2 /* Jim - A small embeddable Tcl interpreter
4 * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5 * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
6 * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
7 * Copyright 2008,2009 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
8 * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
9 * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
10 * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
11 * Copyright 2008 Steve Bennett <steveb@workware.net.au>
12 * Copyright 2009 Nico Coesel <ncoesel@dealogic.nl>
13 * Copyright 2009 Zachary T Welch zw@superlucidity.net
14 * Copyright 2009 David Brownell
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above
23 * copyright notice, this list of conditions and the following
24 * disclaimer in the documentation and/or other materials
25 * provided with the distribution.
27 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
28 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
30 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
31 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
32 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
33 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
36 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
38 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * The views and conclusions contained in the software and documentation
41 * are those of the authors and should not be interpreted as representing
42 * official policies, either expressed or implied, of the Jim Tcl Project.
44 #define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
62 #include "jimautoconf.h"
68 #ifdef HAVE_CRT_EXTERNS_H
69 #include <crt_externs.h>
72 /* For INFINITY, even if math functions are not enabled */
75 /* We may decide to switch to using $[...] after all, so leave it as an option */
76 /*#define EXPRSUGAR_BRACKET*/
78 /* For the no-autoconf case */
80 #define TCL_LIBRARY "."
82 #ifndef TCL_PLATFORM_OS
83 #define TCL_PLATFORM_OS "unknown"
85 #ifndef TCL_PLATFORM_PLATFORM
86 #define TCL_PLATFORM_PLATFORM "unknown"
88 #ifndef TCL_PLATFORM_PATH_SEPARATOR
89 #define TCL_PLATFORM_PATH_SEPARATOR ":"
92 /*#define DEBUG_SHOW_SCRIPT*/
93 /*#define DEBUG_SHOW_SCRIPT_TOKENS*/
94 /*#define DEBUG_SHOW_SUBST*/
95 /*#define DEBUG_SHOW_EXPR*/
96 /*#define DEBUG_SHOW_EXPR_TOKENS*/
97 /*#define JIM_DEBUG_GC*/
99 #define JIM_DEBUG_COMMAND
100 #define JIM_DEBUG_PANIC
103 const char *jim_tt_name(int type
);
105 #ifdef JIM_DEBUG_PANIC
106 static void JimPanicDump(int panic_condition
, const char *fmt
, ...);
107 #define JimPanic(X) JimPanicDump X
112 /* -----------------------------------------------------------------------------
114 * ---------------------------------------------------------------------------*/
116 /* A shared empty string for the objects string representation.
117 * Jim_InvalidateStringRep knows about it and doesn't try to free it. */
118 static char JimEmptyStringRep
[] = "";
120 /* -----------------------------------------------------------------------------
121 * Required prototypes of not exported functions
122 * ---------------------------------------------------------------------------*/
123 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
);
124 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
);
125 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int listindex
, Jim_Obj
*newObjPtr
,
127 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
128 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
129 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
130 const char *prefix
, const char *const *tablePtr
, const char *name
);
131 static void JimDeleteLocalProcs(Jim_Interp
*interp
);
132 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, Jim_Obj
*fileNameObj
, int linenr
,
133 int argc
, Jim_Obj
*const *argv
);
134 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
135 Jim_Obj
*fileNameObj
, int linenr
);
136 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
);
137 static int JimSign(jim_wide w
);
138 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
);
139 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
);
140 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
);
143 static const Jim_HashTableType JimVariablesHashTableType
;
145 /* Fast access to the int (wide) value of an object which is known to be of int type */
146 #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
148 #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
150 static int utf8_tounicode_case(const char *s
, int *uc
, int upper
)
152 int l
= utf8_tounicode(s
, uc
);
154 *uc
= utf8_upper(*uc
);
159 /* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
160 #define JIM_CHARSET_SCAN 2
161 #define JIM_CHARSET_GLOB 0
164 * pattern points to a string like "[^a-z\ub5]"
166 * The pattern may contain trailing chars, which are ignored.
168 * The pattern is matched against unicode char 'c'.
170 * If (flags & JIM_NOCASE), case is ignored when matching.
171 * If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
172 * of the charset, per scan, rather than glob/string match.
174 * If the unicode char 'c' matches that set, returns a pointer to the ']' character,
175 * or the null character if the ']' is missing.
177 * Returns NULL on no match.
179 static const char *JimCharsetMatch(const char *pattern
, int c
, int flags
)
186 if (flags
& JIM_NOCASE
) {
191 if (flags
& JIM_CHARSET_SCAN
) {
192 if (*pattern
== '^') {
197 /* Special case. If the first char is ']', it is part of the set */
198 if (*pattern
== ']') {
203 while (*pattern
&& *pattern
!= ']') {
205 if (pattern
[0] == '\\') {
207 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
210 /* Is this a range? a-z */
214 pattern
+= utf8_tounicode_case(pattern
, &start
, nocase
);
215 if (pattern
[0] == '-' && pattern
[1]) {
217 pattern
+= utf8_tounicode(pattern
, &pchar
);
218 pattern
+= utf8_tounicode_case(pattern
, &end
, nocase
);
220 /* Handle reversed range too */
221 if ((c
>= start
&& c
<= end
) || (c
>= end
&& c
<= start
)) {
237 return match
? pattern
: NULL
;
240 /* Glob-style pattern matching. */
242 /* Note: string *must* be valid UTF-8 sequences
243 * slen is a char length, not byte counts.
245 static int GlobMatch(const char *pattern
, const char *string
, int nocase
)
250 switch (pattern
[0]) {
252 while (pattern
[1] == '*') {
257 return 1; /* match */
260 /* Recursive call - Does the remaining pattern match anywhere? */
261 if (GlobMatch(pattern
, string
, nocase
))
262 return 1; /* match */
263 string
+= utf8_tounicode(string
, &c
);
265 return 0; /* no match */
268 string
+= utf8_tounicode(string
, &c
);
272 string
+= utf8_tounicode(string
, &c
);
273 pattern
= JimCharsetMatch(pattern
+ 1, c
, nocase
? JIM_NOCASE
: 0);
278 /* Ran out of pattern (no ']') */
289 string
+= utf8_tounicode_case(string
, &c
, nocase
);
290 utf8_tounicode_case(pattern
, &pchar
, nocase
);
296 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
298 while (*pattern
== '*') {
304 if (!*pattern
&& !*string
) {
310 static int JimStringMatch(Jim_Interp
*interp
, Jim_Obj
*patternObj
, const char *string
, int nocase
)
312 return GlobMatch(Jim_String(patternObj
), string
, nocase
);
316 * string comparison works on binary data.
318 * Note that the lengths are byte lengths, not char lengths.
320 static int JimStringCompare(const char *s1
, int l1
, const char *s2
, int l2
)
323 return memcmp(s1
, s2
, l1
) <= 0 ? -1 : 1;
326 return memcmp(s1
, s2
, l2
) >= 0 ? 1 : -1;
329 return JimSign(memcmp(s1
, s2
, l1
));
336 * If maxchars is -1, compares to end of string.
337 * Otherwise compares at most 'maxchars' characters.
339 static int JimStringCompareNoCase(const char *s1
, const char *s2
, int maxchars
)
341 while (*s1
&& *s2
&& maxchars
) {
343 s1
+= utf8_tounicode_case(s1
, &c1
, 1);
344 s2
+= utf8_tounicode_case(s2
, &c2
, 1);
346 return JimSign(c1
- c2
);
353 /* One string or both terminated */
363 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
364 * The index of the first occurrence of s1 in s2 is returned.
365 * If s1 is not found inside s2, -1 is returned. */
366 static int JimStringFirst(const char *s1
, int l1
, const char *s2
, int l2
, int idx
)
371 if (!l1
|| !l2
|| l1
> l2
) {
376 s2
+= utf8_index(s2
, idx
);
378 l1bytelen
= utf8_index(s1
, l1
);
380 for (i
= idx
; i
<= l2
- l1
; i
++) {
382 if (memcmp(s2
, s1
, l1bytelen
) == 0) {
385 s2
+= utf8_tounicode(s2
, &c
);
391 * Note: Lengths and return value are in bytes, not chars.
393 static int JimStringLast(const char *s1
, int l1
, const char *s2
, int l2
)
397 if (!l1
|| !l2
|| l1
> l2
)
400 /* Now search for the needle */
401 for (p
= s2
+ l2
- 1; p
!= s2
- 1; p
--) {
402 if (*p
== *s1
&& memcmp(s1
, p
, l1
) == 0) {
411 * Note: Lengths and return value are in chars.
413 static int JimStringLastUtf8(const char *s1
, int l1
, const char *s2
, int l2
)
415 int n
= JimStringLast(s1
, utf8_index(s1
, l1
), s2
, utf8_index(s2
, l2
));
417 n
= utf8_strlen(s2
, n
);
423 int Jim_WideToString(char *buf
, jim_wide wideValue
)
425 const char *fmt
= "%" JIM_WIDE_MODIFIER
;
427 return sprintf(buf
, fmt
, wideValue
);
431 * After an strtol()/strtod()-like conversion,
432 * check whether something was converted and that
433 * the only thing left is white space.
435 * Returns JIM_OK or JIM_ERR.
437 static int JimCheckConversion(const char *str
, const char *endptr
)
439 if (str
[0] == '\0' || str
== endptr
) {
443 if (endptr
[0] != '\0') {
445 if (!isspace(UCHAR(*endptr
))) {
454 int Jim_StringToWide(const char *str
, jim_wide
* widePtr
, int base
)
458 *widePtr
= strtoull(str
, &endptr
, base
);
460 return JimCheckConversion(str
, endptr
);
463 int Jim_DoubleToString(char *buf
, double doubleValue
)
468 len
= sprintf(buf
, "%.12g", doubleValue
);
470 /* Add a final ".0" if it's a number. But not
473 if (*buf
== '.' || isalpha(UCHAR(*buf
))) {
474 /* inf -> Inf, nan -> Nan */
475 if (*buf
== 'i' || *buf
== 'n') {
476 *buf
= toupper(UCHAR(*buf
));
479 /* Infinity -> Inf */
481 len
= buf
- buf0
+ 3;
495 int Jim_StringToDouble(const char *str
, double *doublePtr
)
499 /* Callers can check for underflow via ERANGE */
502 *doublePtr
= strtod(str
, &endptr
);
504 return JimCheckConversion(str
, endptr
);
507 static jim_wide
JimPowWide(jim_wide b
, jim_wide e
)
511 if ((b
== 0 && e
!= 0) || (e
< 0))
513 for (i
= 0; i
< e
; i
++) {
519 /* -----------------------------------------------------------------------------
521 * ---------------------------------------------------------------------------*/
522 #ifdef JIM_DEBUG_PANIC
523 void JimPanicDump(int condition
, const char *fmt
, ...)
533 fprintf(stderr
, JIM_NL
"JIM INTERPRETER PANIC: ");
534 vfprintf(stderr
, fmt
, ap
);
535 fprintf(stderr
, JIM_NL JIM_NL
);
538 #ifdef HAVE_BACKTRACE
544 size
= backtrace(array
, 40);
545 strings
= backtrace_symbols(array
, size
);
546 for (i
= 0; i
< size
; i
++)
547 fprintf(stderr
, "[backtrace] %s" JIM_NL
, strings
[i
]);
548 fprintf(stderr
, "[backtrace] Include the above lines and the output" JIM_NL
);
549 fprintf(stderr
, "[backtrace] of 'nm <executable>' in the bug report." JIM_NL
);
557 /* -----------------------------------------------------------------------------
559 * ---------------------------------------------------------------------------*/
561 void *Jim_Alloc(int size
)
566 void Jim_Free(void *ptr
)
571 void *Jim_Realloc(void *ptr
, int size
)
573 return realloc(ptr
, size
);
576 char *Jim_StrDup(const char *s
)
581 char *Jim_StrDupLen(const char *s
, int l
)
583 char *copy
= Jim_Alloc(l
+ 1);
585 memcpy(copy
, s
, l
+ 1);
586 copy
[l
] = 0; /* Just to be sure, original could be substring */
590 /* -----------------------------------------------------------------------------
591 * Time related functions
592 * ---------------------------------------------------------------------------*/
594 /* Returns microseconds of CPU used since start. */
595 static jim_wide
JimClock(void)
599 gettimeofday(&tv
, NULL
);
600 return (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
;
603 /* -----------------------------------------------------------------------------
605 * ---------------------------------------------------------------------------*/
607 /* -------------------------- private prototypes ---------------------------- */
608 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
);
609 static unsigned int JimHashTableNextPower(unsigned int size
);
610 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
);
612 /* -------------------------- hash functions -------------------------------- */
614 /* Thomas Wang's 32 bit Mix Function */
615 unsigned int Jim_IntHashFunction(unsigned int key
)
626 /* Generic hash function (we are using to multiply by 9 and add the byte
628 unsigned int Jim_GenHashFunction(const unsigned char *buf
, int len
)
633 h
+= (h
<< 3) + *buf
++;
637 /* ----------------------------- API implementation ------------------------- */
639 /* reset a hashtable already initialized with ht_init().
640 * NOTE: This function should only called by ht_destroy(). */
641 static void JimResetHashTable(Jim_HashTable
*ht
)
650 /* Initialize the hash table */
651 int Jim_InitHashTable(Jim_HashTable
*ht
, const Jim_HashTableType
*type
, void *privDataPtr
)
653 JimResetHashTable(ht
);
655 ht
->privdata
= privDataPtr
;
659 /* Resize the table to the minimal size that contains all the elements,
660 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
661 int Jim_ResizeHashTable(Jim_HashTable
*ht
)
663 int minimal
= ht
->used
;
665 if (minimal
< JIM_HT_INITIAL_SIZE
)
666 minimal
= JIM_HT_INITIAL_SIZE
;
667 return Jim_ExpandHashTable(ht
, minimal
);
670 /* Expand or create the hashtable */
671 int Jim_ExpandHashTable(Jim_HashTable
*ht
, unsigned int size
)
673 Jim_HashTable n
; /* the new hashtable */
674 unsigned int realsize
= JimHashTableNextPower(size
), i
;
676 /* the size is invalid if it is smaller than the number of
677 * elements already inside the hashtable */
678 if (ht
->used
>= size
)
681 Jim_InitHashTable(&n
, ht
->type
, ht
->privdata
);
683 n
.sizemask
= realsize
- 1;
684 n
.table
= Jim_Alloc(realsize
* sizeof(Jim_HashEntry
*));
686 /* Initialize all the pointers to NULL */
687 memset(n
.table
, 0, realsize
* sizeof(Jim_HashEntry
*));
689 /* Copy all the elements from the old to the new table:
690 * note that if the old hash table is empty ht->used is zero,
691 * so Jim_ExpandHashTable just creates an empty hash table. */
693 for (i
= 0; ht
->used
> 0; i
++) {
694 Jim_HashEntry
*he
, *nextHe
;
696 if (ht
->table
[i
] == NULL
)
699 /* For each hash entry on this slot... */
705 /* Get the new element index */
706 h
= Jim_HashKey(ht
, he
->key
) & n
.sizemask
;
707 he
->next
= n
.table
[h
];
710 /* Pass to the next element */
714 assert(ht
->used
== 0);
717 /* Remap the new hashtable in the old */
722 /* Add an element to the target hash table */
723 int Jim_AddHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
726 Jim_HashEntry
*entry
;
728 /* Get the index of the new element, or -1 if
729 * the element already exists. */
730 if ((idx
= JimInsertHashEntry(ht
, key
)) == -1)
733 /* Allocates the memory and stores key */
734 entry
= Jim_Alloc(sizeof(*entry
));
735 entry
->next
= ht
->table
[idx
];
736 ht
->table
[idx
] = entry
;
738 /* Set the hash entry fields. */
739 Jim_SetHashKey(ht
, entry
, key
);
740 Jim_SetHashVal(ht
, entry
, val
);
745 /* Add an element, discarding the old if the key already exists */
746 int Jim_ReplaceHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
748 Jim_HashEntry
*entry
;
750 /* Try to add the element. If the key
751 * does not exists Jim_AddHashEntry will suceed. */
752 if (Jim_AddHashEntry(ht
, key
, val
) == JIM_OK
)
754 /* It already exists, get the entry */
755 entry
= Jim_FindHashEntry(ht
, key
);
756 /* Free the old value and set the new one */
757 Jim_FreeEntryVal(ht
, entry
);
758 Jim_SetHashVal(ht
, entry
, val
);
762 /* Search and remove an element */
763 int Jim_DeleteHashEntry(Jim_HashTable
*ht
, const void *key
)
766 Jim_HashEntry
*he
, *prevHe
;
770 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
775 if (Jim_CompareHashKeys(ht
, key
, he
->key
)) {
776 /* Unlink the element from the list */
778 prevHe
->next
= he
->next
;
780 ht
->table
[h
] = he
->next
;
781 Jim_FreeEntryKey(ht
, he
);
782 Jim_FreeEntryVal(ht
, he
);
790 return JIM_ERR
; /* not found */
793 /* Destroy an entire hash table */
794 int Jim_FreeHashTable(Jim_HashTable
*ht
)
798 /* Free all the elements */
799 for (i
= 0; ht
->used
> 0; i
++) {
800 Jim_HashEntry
*he
, *nextHe
;
802 if ((he
= ht
->table
[i
]) == NULL
)
806 Jim_FreeEntryKey(ht
, he
);
807 Jim_FreeEntryVal(ht
, he
);
813 /* Free the table and the allocated cache structure */
815 /* Re-initialize the table */
816 JimResetHashTable(ht
);
817 return JIM_OK
; /* never fails */
820 Jim_HashEntry
*Jim_FindHashEntry(Jim_HashTable
*ht
, const void *key
)
827 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
830 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
837 Jim_HashTableIterator
*Jim_GetHashTableIterator(Jim_HashTable
*ht
)
839 Jim_HashTableIterator
*iter
= Jim_Alloc(sizeof(*iter
));
844 iter
->nextEntry
= NULL
;
848 Jim_HashEntry
*Jim_NextHashEntry(Jim_HashTableIterator
*iter
)
851 if (iter
->entry
== NULL
) {
853 if (iter
->index
>= (signed)iter
->ht
->size
)
855 iter
->entry
= iter
->ht
->table
[iter
->index
];
858 iter
->entry
= iter
->nextEntry
;
861 /* We need to save the 'next' here, the iterator user
862 * may delete the entry we are returning. */
863 iter
->nextEntry
= iter
->entry
->next
;
870 /* ------------------------- private functions ------------------------------ */
872 /* Expand the hash table if needed */
873 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
)
875 /* If the hash table is empty expand it to the intial size,
876 * if the table is "full" dobule its size. */
878 return Jim_ExpandHashTable(ht
, JIM_HT_INITIAL_SIZE
);
879 if (ht
->size
== ht
->used
)
880 return Jim_ExpandHashTable(ht
, ht
->size
* 2);
884 /* Our hash table capability is a power of two */
885 static unsigned int JimHashTableNextPower(unsigned int size
)
887 unsigned int i
= JIM_HT_INITIAL_SIZE
;
889 if (size
>= 2147483648U)
898 /* Returns the index of a free slot that can be populated with
899 * an hash entry for the given 'key'.
900 * If the key already exists, -1 is returned. */
901 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
)
906 /* Expand the hashtable if needed */
907 if (JimExpandHashTableIfNeeded(ht
) == JIM_ERR
)
909 /* Compute the key hash value */
910 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
911 /* Search if this slot does not already contain the given key */
914 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
921 /* ----------------------- StringCopy Hash Table Type ------------------------*/
923 static unsigned int JimStringCopyHTHashFunction(const void *key
)
925 return Jim_GenHashFunction(key
, strlen(key
));
928 static const void *JimStringCopyHTKeyDup(void *privdata
, const void *key
)
930 int len
= strlen(key
);
931 char *copy
= Jim_Alloc(len
+ 1);
933 JIM_NOTUSED(privdata
);
935 memcpy(copy
, key
, len
);
940 static void *JimStringKeyValCopyHTValDup(void *privdata
, const void *val
)
942 int len
= strlen(val
);
943 char *copy
= Jim_Alloc(len
+ 1);
945 JIM_NOTUSED(privdata
);
947 memcpy(copy
, val
, len
);
952 static int JimStringCopyHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
954 JIM_NOTUSED(privdata
);
956 return strcmp(key1
, key2
) == 0;
959 static void JimStringCopyHTKeyDestructor(void *privdata
, const void *key
)
961 JIM_NOTUSED(privdata
);
963 Jim_Free((void *)key
); /* ATTENTION: const cast */
966 static void JimStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
968 JIM_NOTUSED(privdata
);
970 Jim_Free((void *)val
); /* ATTENTION: const cast */
974 static Jim_HashTableType JimStringCopyHashTableType
= {
975 JimStringCopyHTHashFunction
, /* hash function */
976 JimStringCopyHTKeyDup
, /* key dup */
978 JimStringCopyHTKeyCompare
, /* key compare */
979 JimStringCopyHTKeyDestructor
, /* key destructor */
980 NULL
/* val destructor */
984 /* This is like StringCopy but does not auto-duplicate the key.
985 * It's used for intepreter's shared strings. */
986 static const Jim_HashTableType JimSharedStringsHashTableType
= {
987 JimStringCopyHTHashFunction
, /* hash function */
990 JimStringCopyHTKeyCompare
, /* key compare */
991 JimStringCopyHTKeyDestructor
, /* key destructor */
992 NULL
/* val destructor */
995 /* This is like StringCopy but also automatically handle dynamic
996 * allocated C strings as values. */
997 static const Jim_HashTableType JimStringKeyValCopyHashTableType
= {
998 JimStringCopyHTHashFunction
, /* hash function */
999 JimStringCopyHTKeyDup
, /* key dup */
1000 JimStringKeyValCopyHTValDup
, /* val dup */
1001 JimStringCopyHTKeyCompare
, /* key compare */
1002 JimStringCopyHTKeyDestructor
, /* key destructor */
1003 JimStringKeyValCopyHTValDestructor
, /* val destructor */
1006 typedef struct AssocDataValue
1008 Jim_InterpDeleteProc
*delProc
;
1012 static void JimAssocDataHashTableValueDestructor(void *privdata
, void *data
)
1014 AssocDataValue
*assocPtr
= (AssocDataValue
*) data
;
1016 if (assocPtr
->delProc
!= NULL
)
1017 assocPtr
->delProc((Jim_Interp
*)privdata
, assocPtr
->data
);
1021 static const Jim_HashTableType JimAssocDataHashTableType
= {
1022 JimStringCopyHTHashFunction
, /* hash function */
1023 JimStringCopyHTKeyDup
, /* key dup */
1025 JimStringCopyHTKeyCompare
, /* key compare */
1026 JimStringCopyHTKeyDestructor
, /* key destructor */
1027 JimAssocDataHashTableValueDestructor
/* val destructor */
1030 /* -----------------------------------------------------------------------------
1031 * Stack - This is a simple generic stack implementation. It is used for
1032 * example in the 'expr' expression compiler.
1033 * ---------------------------------------------------------------------------*/
1034 void Jim_InitStack(Jim_Stack
*stack
)
1038 stack
->vector
= NULL
;
1041 void Jim_FreeStack(Jim_Stack
*stack
)
1043 Jim_Free(stack
->vector
);
1046 int Jim_StackLen(Jim_Stack
*stack
)
1051 void Jim_StackPush(Jim_Stack
*stack
, void *element
)
1053 int neededLen
= stack
->len
+ 1;
1055 if (neededLen
> stack
->maxlen
) {
1056 stack
->maxlen
= neededLen
< 20 ? 20 : neededLen
* 2;
1057 stack
->vector
= Jim_Realloc(stack
->vector
, sizeof(void *) * stack
->maxlen
);
1059 stack
->vector
[stack
->len
] = element
;
1063 void *Jim_StackPop(Jim_Stack
*stack
)
1065 if (stack
->len
== 0)
1068 return stack
->vector
[stack
->len
];
1071 void *Jim_StackPeek(Jim_Stack
*stack
)
1073 if (stack
->len
== 0)
1075 return stack
->vector
[stack
->len
- 1];
1078 void Jim_FreeStackElements(Jim_Stack
*stack
, void (*freeFunc
) (void *ptr
))
1082 for (i
= 0; i
< stack
->len
; i
++)
1083 freeFunc(stack
->vector
[i
]);
1086 /* -----------------------------------------------------------------------------
1088 * ---------------------------------------------------------------------------*/
1091 #define JIM_TT_NONE 0 /* No token returned */
1092 #define JIM_TT_STR 1 /* simple string */
1093 #define JIM_TT_ESC 2 /* string that needs escape chars conversion */
1094 #define JIM_TT_VAR 3 /* var substitution */
1095 #define JIM_TT_DICTSUGAR 4 /* Syntax sugar for [dict get], $foo(bar) */
1096 #define JIM_TT_CMD 5 /* command substitution */
1097 /* Note: Keep these three together for TOKEN_IS_SEP() */
1098 #define JIM_TT_SEP 6 /* word separator. arg is # of tokens. -ve if {*} */
1099 #define JIM_TT_EOL 7 /* line separator */
1100 #define JIM_TT_EOF 8 /* end of script */
1102 #define JIM_TT_LINE 9 /* special 'start-of-line' token. arg is # of arguments to the command. -ve if {*} */
1103 #define JIM_TT_WORD 10 /* special 'start-of-word' token. arg is # of tokens to combine. -ve if {*} */
1105 /* Additional token types needed for expressions */
1106 #define JIM_TT_SUBEXPR_START 11
1107 #define JIM_TT_SUBEXPR_END 12
1108 #define JIM_TT_EXPR_INT 13
1109 #define JIM_TT_EXPR_DOUBLE 14
1111 #define JIM_TT_EXPRSUGAR 15 /* $(expression) */
1113 /* Operator token types start here */
1114 #define JIM_TT_EXPR_OP 20
1116 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1119 #define JIM_PS_DEF 0 /* Default state */
1120 #define JIM_PS_QUOTE 1 /* Inside "" */
1121 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1123 /* Parser context structure. The same context is used both to parse
1124 * Tcl scripts and lists. */
1127 const char *p
; /* Pointer to the point of the program we are parsing */
1128 int len
; /* Remaining length */
1129 int linenr
; /* Current line number */
1131 const char *tend
; /* Returned token is at tstart-tend in 'prg'. */
1132 int tline
; /* Line number of the returned token */
1133 int tt
; /* Token type */
1134 int eof
; /* Non zero if EOF condition is true. */
1135 int state
; /* Parser state */
1136 int comment
; /* Non zero if the next chars may be a comment. */
1137 char missing
; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1138 int missingline
; /* Line number starting the missing token */
1142 * Results of missing quotes, braces, etc. from parsing.
1144 struct JimParseResult
{
1145 char missing
; /* From JimParserCtx.missing */
1146 int line
; /* From JimParserCtx.missingline */
1149 static int JimParseScript(struct JimParserCtx
*pc
);
1150 static int JimParseSep(struct JimParserCtx
*pc
);
1151 static int JimParseEol(struct JimParserCtx
*pc
);
1152 static int JimParseCmd(struct JimParserCtx
*pc
);
1153 static int JimParseQuote(struct JimParserCtx
*pc
);
1154 static int JimParseVar(struct JimParserCtx
*pc
);
1155 static int JimParseBrace(struct JimParserCtx
*pc
);
1156 static int JimParseStr(struct JimParserCtx
*pc
);
1157 static int JimParseComment(struct JimParserCtx
*pc
);
1158 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1159 static int JimParseSubQuote(struct JimParserCtx
*pc
);
1160 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1161 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
);
1163 /* Initialize a parser context.
1164 * 'prg' is a pointer to the program text, linenr is the line
1165 * number of the first line contained in the program. */
1166 static void JimParserInit(struct JimParserCtx
*pc
, const char *prg
, int len
, int linenr
)
1173 pc
->tt
= JIM_TT_NONE
;
1175 pc
->state
= JIM_PS_DEF
;
1176 pc
->linenr
= linenr
;
1179 pc
->missingline
= linenr
;
1182 static int JimParseScript(struct JimParserCtx
*pc
)
1184 while (1) { /* the while is used to reiterate with continue if needed */
1187 pc
->tend
= pc
->p
- 1;
1188 pc
->tline
= pc
->linenr
;
1189 pc
->tt
= JIM_TT_EOL
;
1195 if (*(pc
->p
+ 1) == '\n' && pc
->state
== JIM_PS_DEF
) {
1196 return JimParseSep(pc
);
1200 return JimParseStr(pc
);
1206 if (pc
->state
== JIM_PS_DEF
)
1207 return JimParseSep(pc
);
1210 return JimParseStr(pc
);
1216 if (pc
->state
== JIM_PS_DEF
)
1217 return JimParseEol(pc
);
1219 return JimParseStr(pc
);
1223 return JimParseCmd(pc
);
1227 if (JimParseVar(pc
) == JIM_ERR
) {
1228 pc
->tstart
= pc
->tend
= pc
->p
++;
1230 pc
->tline
= pc
->linenr
;
1231 pc
->tt
= JIM_TT_STR
;
1239 JimParseComment(pc
);
1243 return JimParseStr(pc
);
1247 return JimParseStr(pc
);
1254 static int JimParseSep(struct JimParserCtx
*pc
)
1257 pc
->tline
= pc
->linenr
;
1258 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' ||
1259 (*pc
->p
== '\\' && *(pc
->p
+ 1) == '\n')) {
1260 if (*pc
->p
== '\\') {
1268 pc
->tend
= pc
->p
- 1;
1269 pc
->tt
= JIM_TT_SEP
;
1273 static int JimParseEol(struct JimParserCtx
*pc
)
1276 pc
->tline
= pc
->linenr
;
1277 while (*pc
->p
== ' ' || *pc
->p
== '\n' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== ';') {
1283 pc
->tend
= pc
->p
- 1;
1284 pc
->tt
= JIM_TT_EOL
;
1289 ** Here are the rules for parsing:
1290 ** {braced expression}
1291 ** - Count open and closing braces
1292 ** - Backslash escapes meaning of braces
1294 ** "quoted expression"
1295 ** - First double quote at start of word terminates the expression
1296 ** - Backslash escapes quote and bracket
1297 ** - [commands brackets] are counted/nested
1298 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1300 ** [command expression]
1301 ** - Count open and closing brackets
1302 ** - Backslash escapes quote, bracket and brace
1303 ** - [commands brackets] are counted/nested
1304 ** - "quoted expressions" are parsed according to quoting rules
1305 ** - {braced expressions} are parsed according to brace rules
1307 ** For everything, backslash escapes the next char, newline increments current line
1311 * Parses a braced expression starting at pc->p.
1313 * Positions the parser at the end of the braced expression,
1314 * sets pc->tend and possibly pc->missing.
1316 static void JimParseSubBrace(struct JimParserCtx
*pc
)
1320 /* Skip the brace */
1327 if (*++pc
->p
== '\n') {
1340 pc
->tend
= pc
->p
- 1;
1355 pc
->missingline
= pc
->tline
;
1356 pc
->tend
= pc
->p
- 1;
1360 * Parses a quoted expression starting at pc->p.
1362 * Positions the parser at the end of the quoted expression,
1363 * sets pc->tend and possibly pc->missing.
1365 * Returns the type of the token of the string,
1366 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1369 static int JimParseSubQuote(struct JimParserCtx
*pc
)
1371 int tt
= JIM_TT_STR
;
1372 int line
= pc
->tline
;
1374 /* Skip the quote */
1381 if (*++pc
->p
== '\n') {
1390 pc
->tend
= pc
->p
- 1;
1412 pc
->missingline
= line
;
1413 pc
->tend
= pc
->p
- 1;
1418 * Parses a [command] expression starting at pc->p.
1420 * Positions the parser at the end of the command expression,
1421 * sets pc->tend and possibly pc->missing.
1423 static void JimParseSubCmd(struct JimParserCtx
*pc
)
1426 int startofword
= 1;
1427 int line
= pc
->tline
;
1429 /* Skip the bracket */
1436 if (*++pc
->p
== '\n') {
1449 pc
->tend
= pc
->p
- 1;
1458 JimParseSubQuote(pc
);
1464 JimParseSubBrace(pc
);
1472 startofword
= isspace(UCHAR(*pc
->p
));
1477 pc
->missingline
= line
;
1478 pc
->tend
= pc
->p
- 1;
1481 static int JimParseBrace(struct JimParserCtx
*pc
)
1483 pc
->tstart
= pc
->p
+ 1;
1484 pc
->tline
= pc
->linenr
;
1485 pc
->tt
= JIM_TT_STR
;
1486 JimParseSubBrace(pc
);
1490 static int JimParseCmd(struct JimParserCtx
*pc
)
1492 pc
->tstart
= pc
->p
+ 1;
1493 pc
->tline
= pc
->linenr
;
1494 pc
->tt
= JIM_TT_CMD
;
1499 static int JimParseQuote(struct JimParserCtx
*pc
)
1501 pc
->tstart
= pc
->p
+ 1;
1502 pc
->tline
= pc
->linenr
;
1503 pc
->tt
= JimParseSubQuote(pc
);
1507 static int JimParseVar(struct JimParserCtx
*pc
)
1513 #ifdef EXPRSUGAR_BRACKET
1514 if (*pc
->p
== '[') {
1515 /* Parse $[...] expr shorthand syntax */
1517 pc
->tt
= JIM_TT_EXPRSUGAR
;
1523 pc
->tt
= JIM_TT_VAR
;
1524 pc
->tline
= pc
->linenr
;
1526 if (*pc
->p
== '{') {
1527 pc
->tstart
= ++pc
->p
;
1530 while (pc
->len
&& *pc
->p
!= '}') {
1531 if (*pc
->p
== '\n') {
1537 pc
->tend
= pc
->p
- 1;
1545 /* Skip double colon, but not single colon! */
1546 if (pc
->p
[0] == ':' && pc
->p
[1] == ':') {
1551 if (isalnum(UCHAR(*pc
->p
)) || *pc
->p
== '_') {
1558 /* Parse [dict get] syntax sugar. */
1559 if (*pc
->p
== '(') {
1561 const char *paren
= NULL
;
1563 pc
->tt
= JIM_TT_DICTSUGAR
;
1565 while (count
&& pc
->len
) {
1568 if (*pc
->p
== '\\' && pc
->len
>= 1) {
1572 else if (*pc
->p
== '(') {
1575 else if (*pc
->p
== ')') {
1585 /* Did not find a matching paren. Back up */
1587 pc
->len
+= (pc
->p
- paren
);
1590 #ifndef EXPRSUGAR_BRACKET
1591 if (*pc
->tstart
== '(') {
1592 pc
->tt
= JIM_TT_EXPRSUGAR
;
1596 pc
->tend
= pc
->p
- 1;
1598 /* Check if we parsed just the '$' character.
1599 * That's not a variable so an error is returned
1600 * to tell the state machine to consider this '$' just
1602 if (pc
->tstart
== pc
->p
) {
1610 static int JimParseStr(struct JimParserCtx
*pc
)
1612 int newword
= (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1613 pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_STR
);
1614 if (newword
&& *pc
->p
== '{') {
1615 return JimParseBrace(pc
);
1617 else if (newword
&& *pc
->p
== '"') {
1618 pc
->state
= JIM_PS_QUOTE
;
1621 /* In case the end quote is missing */
1622 pc
->missingline
= pc
->tline
;
1625 pc
->tline
= pc
->linenr
;
1628 if (pc
->state
== JIM_PS_QUOTE
) {
1631 pc
->tend
= pc
->p
- 1;
1632 pc
->tt
= JIM_TT_ESC
;
1637 if (pc
->state
== JIM_PS_DEF
&& *(pc
->p
+ 1) == '\n') {
1638 pc
->tend
= pc
->p
- 1;
1639 pc
->tt
= JIM_TT_ESC
;
1643 if (*(pc
->p
+ 1) == '\n') {
1651 /* If the following token is not '$' just keep going */
1652 if (pc
->len
> 1 && pc
->p
[1] != '$') {
1656 /* Only need a separate ')' token if the previous was a var */
1657 if (*pc
->p
== '(' || pc
->tt
== JIM_TT_VAR
) {
1658 if (pc
->p
== pc
->tstart
) {
1659 /* At the start of the token, so just return this char */
1663 pc
->tend
= pc
->p
- 1;
1664 pc
->tt
= JIM_TT_ESC
;
1671 pc
->tend
= pc
->p
- 1;
1672 pc
->tt
= JIM_TT_ESC
;
1679 if (pc
->state
== JIM_PS_DEF
) {
1680 pc
->tend
= pc
->p
- 1;
1681 pc
->tt
= JIM_TT_ESC
;
1684 else if (*pc
->p
== '\n') {
1689 if (pc
->state
== JIM_PS_QUOTE
) {
1690 pc
->tend
= pc
->p
- 1;
1691 pc
->tt
= JIM_TT_ESC
;
1694 pc
->state
= JIM_PS_DEF
;
1702 return JIM_OK
; /* unreached */
1705 static int JimParseComment(struct JimParserCtx
*pc
)
1708 if (*pc
->p
== '\n') {
1710 if (*(pc
->p
- 1) != '\\') {
1722 /* xdigitval and odigitval are helper functions for JimEscape() */
1723 static int xdigitval(int c
)
1725 if (c
>= '0' && c
<= '9')
1727 if (c
>= 'a' && c
<= 'f')
1728 return c
- 'a' + 10;
1729 if (c
>= 'A' && c
<= 'F')
1730 return c
- 'A' + 10;
1734 static int odigitval(int c
)
1736 if (c
>= '0' && c
<= '7')
1741 /* Perform Tcl escape substitution of 's', storing the result
1742 * string into 'dest'. The escaped string is guaranteed to
1743 * be the same length or shorted than the source string.
1744 * Slen is the length of the string at 's', if it's -1 the string
1745 * length will be calculated by the function.
1747 * The function returns the length of the resulting string. */
1748 static int JimEscape(char *dest
, const char *s
, int slen
)
1756 for (i
= 0; i
< slen
; i
++) {
1786 /* A unicode or hex sequence.
1787 * \u Expect 1-4 hex chars and convert to utf-8.
1788 * \x Expect 1-2 hex chars and convert to hex.
1789 * An invalid sequence means simply the escaped char.
1797 for (k
= 0; k
< (s
[i
] == 'u' ? 4 : 2); k
++) {
1798 int c
= xdigitval(s
[i
+ k
+ 1]);
1802 val
= (val
<< 4) | c
;
1805 /* Got a valid sequence, so convert */
1807 p
+= utf8_fromunicode(p
, val
);
1815 /* Not a valid codepoint, just an escaped char */
1828 /* Replace all spaces and tabs after backslash newline with a single space*/
1832 } while (s
[i
+ 1] == ' ' || s
[i
+ 1] == '\t');
1845 int c
= odigitval(s
[i
+ 1]);
1848 c
= odigitval(s
[i
+ 2]);
1854 val
= (val
* 8) + c
;
1855 c
= odigitval(s
[i
+ 3]);
1861 val
= (val
* 8) + c
;
1882 /* Returns a dynamically allocated copy of the current token in the
1883 * parser context. The function performs conversion of escapes if
1884 * the token is of type JIM_TT_ESC.
1886 * Note that after the conversion, tokens that are grouped with
1887 * braces in the source code, are always recognizable from the
1888 * identical string obtained in a different way from the type.
1890 * For example the string:
1894 * will return as first token "*", of type JIM_TT_STR
1900 * will return as first token "*", of type JIM_TT_ESC
1902 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
)
1904 const char *start
, *end
;
1912 token
= Jim_Alloc(1);
1916 len
= (end
- start
) + 1;
1917 token
= Jim_Alloc(len
+ 1);
1918 if (pc
->tt
!= JIM_TT_ESC
) {
1919 /* No escape conversion needed? Just copy it. */
1920 memcpy(token
, start
, len
);
1924 /* Else convert the escape chars. */
1925 len
= JimEscape(token
, start
, len
);
1929 return Jim_NewStringObjNoAlloc(interp
, token
, len
);
1932 /* Parses the given string to determine if it represents a complete script.
1934 * This is useful for interactive shells implementation, for [info complete].
1936 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1937 * '{' on scripts incomplete missing one or more '}' to be balanced.
1938 * '[' on scripts incomplete missing one or more ']' to be balanced.
1939 * '"' on scripts incomplete missing a '"' char.
1941 * If the script is complete, 1 is returned, otherwise 0.
1943 int Jim_ScriptIsComplete(const char *s
, int len
, char *stateCharPtr
)
1945 struct JimParserCtx parser
;
1947 JimParserInit(&parser
, s
, len
, 1);
1948 while (!parser
.eof
) {
1949 JimParseScript(&parser
);
1952 *stateCharPtr
= parser
.missing
;
1954 return parser
.missing
== ' ';
1957 /* -----------------------------------------------------------------------------
1959 * ---------------------------------------------------------------------------*/
1960 static int JimParseListSep(struct JimParserCtx
*pc
);
1961 static int JimParseListStr(struct JimParserCtx
*pc
);
1962 static int JimParseListQuote(struct JimParserCtx
*pc
);
1964 static int JimParseList(struct JimParserCtx
*pc
)
1971 return JimParseListSep(pc
);
1974 return JimParseListQuote(pc
);
1977 return JimParseBrace(pc
);
1981 return JimParseListStr(pc
);
1986 pc
->tstart
= pc
->tend
= pc
->p
;
1987 pc
->tline
= pc
->linenr
;
1988 pc
->tt
= JIM_TT_EOL
;
1993 static int JimParseListSep(struct JimParserCtx
*pc
)
1996 pc
->tline
= pc
->linenr
;
1997 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== '\n') {
1998 if (*pc
->p
== '\n') {
2004 pc
->tend
= pc
->p
- 1;
2005 pc
->tt
= JIM_TT_SEP
;
2009 static int JimParseListQuote(struct JimParserCtx
*pc
)
2015 pc
->tline
= pc
->linenr
;
2016 pc
->tt
= JIM_TT_STR
;
2021 pc
->tt
= JIM_TT_ESC
;
2022 if (--pc
->len
== 0) {
2023 /* Trailing backslash */
2033 pc
->tend
= pc
->p
- 1;
2042 pc
->tend
= pc
->p
- 1;
2046 static int JimParseListStr(struct JimParserCtx
*pc
)
2049 pc
->tline
= pc
->linenr
;
2050 pc
->tt
= JIM_TT_STR
;
2055 if (--pc
->len
== 0) {
2056 /* Trailing backslash */
2060 pc
->tt
= JIM_TT_ESC
;
2067 pc
->tend
= pc
->p
- 1;
2073 pc
->tend
= pc
->p
- 1;
2077 /* -----------------------------------------------------------------------------
2078 * Jim_Obj related functions
2079 * ---------------------------------------------------------------------------*/
2081 /* Return a new initialized object. */
2082 Jim_Obj
*Jim_NewObj(Jim_Interp
*interp
)
2086 /* -- Check if there are objects in the free list -- */
2087 if (interp
->freeList
!= NULL
) {
2088 /* -- Unlink the object from the free list -- */
2089 objPtr
= interp
->freeList
;
2090 interp
->freeList
= objPtr
->nextObjPtr
;
2093 /* -- No ready to use objects: allocate a new one -- */
2094 objPtr
= Jim_Alloc(sizeof(*objPtr
));
2097 /* Object is returned with refCount of 0. Every
2098 * kind of GC implemented should take care to don't try
2099 * to scan objects with refCount == 0. */
2100 objPtr
->refCount
= 0;
2101 /* All the other fields are left not initialized to save time.
2102 * The caller will probably want to set them to the right
2105 /* -- Put the object into the live list -- */
2106 objPtr
->prevObjPtr
= NULL
;
2107 objPtr
->nextObjPtr
= interp
->liveList
;
2108 if (interp
->liveList
)
2109 interp
->liveList
->prevObjPtr
= objPtr
;
2110 interp
->liveList
= objPtr
;
2115 /* Free an object. Actually objects are never freed, but
2116 * just moved to the free objects list, where they will be
2117 * reused by Jim_NewObj(). */
2118 void Jim_FreeObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2120 /* Check if the object was already freed, panic. */
2121 JimPanic((objPtr
->refCount
!= 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr
,
2122 objPtr
->refCount
, objPtr
->typePtr
? objPtr
->typePtr
->name
: "<none>"));
2124 /* Free the internal representation */
2125 Jim_FreeIntRep(interp
, objPtr
);
2126 /* Free the string representation */
2127 if (objPtr
->bytes
!= NULL
) {
2128 if (objPtr
->bytes
!= JimEmptyStringRep
)
2129 Jim_Free(objPtr
->bytes
);
2131 /* Unlink the object from the live objects list */
2132 if (objPtr
->prevObjPtr
)
2133 objPtr
->prevObjPtr
->nextObjPtr
= objPtr
->nextObjPtr
;
2134 if (objPtr
->nextObjPtr
)
2135 objPtr
->nextObjPtr
->prevObjPtr
= objPtr
->prevObjPtr
;
2136 if (interp
->liveList
== objPtr
)
2137 interp
->liveList
= objPtr
->nextObjPtr
;
2138 /* Link the object into the free objects list */
2139 objPtr
->prevObjPtr
= NULL
;
2140 objPtr
->nextObjPtr
= interp
->freeList
;
2141 if (interp
->freeList
)
2142 interp
->freeList
->prevObjPtr
= objPtr
;
2143 interp
->freeList
= objPtr
;
2144 objPtr
->refCount
= -1;
2147 /* Invalidate the string representation of an object. */
2148 void Jim_InvalidateStringRep(Jim_Obj
*objPtr
)
2150 if (objPtr
->bytes
!= NULL
) {
2151 if (objPtr
->bytes
!= JimEmptyStringRep
)
2152 Jim_Free(objPtr
->bytes
);
2154 objPtr
->bytes
= NULL
;
2157 #define Jim_SetStringRep(o, b, l) \
2158 do { (o)->bytes = b; (o)->length = l; } while (0)
2160 /* Set the initial string representation for an object.
2161 * Does not try to free an old one. */
2162 void Jim_InitStringRep(Jim_Obj
*objPtr
, const char *bytes
, int length
)
2165 objPtr
->bytes
= JimEmptyStringRep
;
2169 objPtr
->bytes
= Jim_Alloc(length
+ 1);
2170 objPtr
->length
= length
;
2171 memcpy(objPtr
->bytes
, bytes
, length
);
2172 objPtr
->bytes
[length
] = '\0';
2176 /* Duplicate an object. The returned object has refcount = 0. */
2177 Jim_Obj
*Jim_DuplicateObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2181 dupPtr
= Jim_NewObj(interp
);
2182 if (objPtr
->bytes
== NULL
) {
2183 /* Object does not have a valid string representation. */
2184 dupPtr
->bytes
= NULL
;
2187 Jim_InitStringRep(dupPtr
, objPtr
->bytes
, objPtr
->length
);
2190 /* By default, the new object has the same type as the old object */
2191 dupPtr
->typePtr
= objPtr
->typePtr
;
2192 if (objPtr
->typePtr
!= NULL
) {
2193 if (objPtr
->typePtr
->dupIntRepProc
== NULL
) {
2194 dupPtr
->internalRep
= objPtr
->internalRep
;
2197 /* The dup proc may set a different type, e.g. NULL */
2198 objPtr
->typePtr
->dupIntRepProc(interp
, objPtr
, dupPtr
);
2204 /* Return the string representation for objPtr. If the object
2205 * string representation is invalid, calls the method to create
2206 * a new one starting from the internal representation of the object. */
2207 const char *Jim_GetString(Jim_Obj
*objPtr
, int *lenPtr
)
2209 if (objPtr
->bytes
== NULL
) {
2210 /* Invalid string repr. Generate it. */
2211 JimPanic((objPtr
->typePtr
->updateStringProc
== NULL
, "UpdateStringProc called against '%s' type.", objPtr
->typePtr
->name
));
2212 objPtr
->typePtr
->updateStringProc(objPtr
);
2215 *lenPtr
= objPtr
->length
;
2216 return objPtr
->bytes
;
2219 /* Just returns the length of the object's string rep */
2220 int Jim_Length(Jim_Obj
*objPtr
)
2224 Jim_GetString(objPtr
, &len
);
2228 static void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2229 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2231 static const Jim_ObjType dictSubstObjType
= {
2232 "dict-substitution",
2233 FreeDictSubstInternalRep
,
2234 DupDictSubstInternalRep
,
2239 static void FreeInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2241 Jim_DecrRefCount(interp
, (Jim_Obj
*)objPtr
->internalRep
.twoPtrValue
.ptr2
);
2244 static const Jim_ObjType interpolatedObjType
= {
2246 FreeInterpolatedInternalRep
,
2252 /* -----------------------------------------------------------------------------
2254 * ---------------------------------------------------------------------------*/
2255 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2256 static int SetStringFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2258 static const Jim_ObjType stringObjType
= {
2261 DupStringInternalRep
,
2263 JIM_TYPE_REFERENCES
,
2266 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2268 JIM_NOTUSED(interp
);
2270 /* This is a bit subtle: the only caller of this function
2271 * should be Jim_DuplicateObj(), that will copy the
2272 * string representaion. After the copy, the duplicated
2273 * object will not have more room in teh buffer than
2274 * srcPtr->length bytes. So we just set it to length. */
2275 dupPtr
->internalRep
.strValue
.maxLength
= srcPtr
->length
;
2277 dupPtr
->internalRep
.strValue
.charLength
= srcPtr
->internalRep
.strValue
.charLength
;
2280 static int SetStringFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2282 /* Get a fresh string representation. */
2283 (void)Jim_String(objPtr
);
2284 /* Free any other internal representation. */
2285 Jim_FreeIntRep(interp
, objPtr
);
2286 /* Set it as string, i.e. just set the maxLength field. */
2287 objPtr
->typePtr
= &stringObjType
;
2288 objPtr
->internalRep
.strValue
.maxLength
= objPtr
->length
;
2289 /* Don't know the utf-8 length yet */
2290 objPtr
->internalRep
.strValue
.charLength
= -1;
2295 * Returns the length of the object string in chars, not bytes.
2297 * These may be different for a utf-8 string.
2299 int Jim_Utf8Length(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2302 if (objPtr
->typePtr
!= &stringObjType
)
2303 SetStringFromAny(interp
, objPtr
);
2305 if (objPtr
->internalRep
.strValue
.charLength
< 0) {
2306 objPtr
->internalRep
.strValue
.charLength
= utf8_strlen(objPtr
->bytes
, objPtr
->length
);
2308 return objPtr
->internalRep
.strValue
.charLength
;
2310 return Jim_Length(objPtr
);
2314 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2315 Jim_Obj
*Jim_NewStringObj(Jim_Interp
*interp
, const char *s
, int len
)
2317 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2319 /* Need to find out how many bytes the string requires */
2322 /* Alloc/Set the string rep. */
2324 objPtr
->bytes
= JimEmptyStringRep
;
2328 objPtr
->bytes
= Jim_Alloc(len
+ 1);
2329 objPtr
->length
= len
;
2330 memcpy(objPtr
->bytes
, s
, len
);
2331 objPtr
->bytes
[len
] = '\0';
2334 /* No typePtr field for the vanilla string object. */
2335 objPtr
->typePtr
= NULL
;
2339 /* charlen is in characters -- see also Jim_NewStringObj() */
2340 Jim_Obj
*Jim_NewStringObjUtf8(Jim_Interp
*interp
, const char *s
, int charlen
)
2343 /* Need to find out how many bytes the string requires */
2344 int bytelen
= utf8_index(s
, charlen
);
2346 Jim_Obj
*objPtr
= Jim_NewStringObj(interp
, s
, bytelen
);
2348 /* Remember the utf8 length, so set the type */
2349 objPtr
->typePtr
= &stringObjType
;
2350 objPtr
->internalRep
.strValue
.maxLength
= bytelen
;
2351 objPtr
->internalRep
.strValue
.charLength
= charlen
;
2355 return Jim_NewStringObj(interp
, s
, charlen
);
2359 /* This version does not try to duplicate the 's' pointer, but
2360 * use it directly. */
2361 Jim_Obj
*Jim_NewStringObjNoAlloc(Jim_Interp
*interp
, char *s
, int len
)
2363 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2367 Jim_SetStringRep(objPtr
, s
, len
);
2368 objPtr
->typePtr
= NULL
;
2372 /* Low-level string append. Use it only against objects
2373 * of type "string". */
2374 static void StringAppendString(Jim_Obj
*objPtr
, const char *str
, int len
)
2380 needlen
= objPtr
->length
+ len
;
2381 if (objPtr
->internalRep
.strValue
.maxLength
< needlen
||
2382 objPtr
->internalRep
.strValue
.maxLength
== 0) {
2384 /* Inefficient to malloc() for less than 8 bytes */
2388 if (objPtr
->bytes
== JimEmptyStringRep
) {
2389 objPtr
->bytes
= Jim_Alloc(needlen
+ 1);
2392 objPtr
->bytes
= Jim_Realloc(objPtr
->bytes
, needlen
+ 1);
2394 objPtr
->internalRep
.strValue
.maxLength
= needlen
;
2396 memcpy(objPtr
->bytes
+ objPtr
->length
, str
, len
);
2397 objPtr
->bytes
[objPtr
->length
+ len
] = '\0';
2398 if (objPtr
->internalRep
.strValue
.charLength
>= 0) {
2399 /* Update the utf-8 char length */
2400 objPtr
->internalRep
.strValue
.charLength
+= utf8_strlen(objPtr
->bytes
+ objPtr
->length
, len
);
2402 objPtr
->length
+= len
;
2405 /* Higher level API to append strings to objects. */
2406 void Jim_AppendString(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
, int len
)
2408 JimPanic((Jim_IsShared(objPtr
), "Jim_AppendString called with shared object"));
2409 if (objPtr
->typePtr
!= &stringObjType
)
2410 SetStringFromAny(interp
, objPtr
);
2411 StringAppendString(objPtr
, str
, len
);
2414 void Jim_AppendObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*appendObjPtr
)
2419 str
= Jim_GetString(appendObjPtr
, &len
);
2420 Jim_AppendString(interp
, objPtr
, str
, len
);
2423 void Jim_AppendStrings(Jim_Interp
*interp
, Jim_Obj
*objPtr
, ...)
2427 if (objPtr
->typePtr
!= &stringObjType
)
2428 SetStringFromAny(interp
, objPtr
);
2429 va_start(ap
, objPtr
);
2431 char *s
= va_arg(ap
, char *);
2435 Jim_AppendString(interp
, objPtr
, s
, -1);
2440 int Jim_StringEqObj(Jim_Obj
*aObjPtr
, Jim_Obj
*bObjPtr
)
2442 const char *aStr
, *bStr
;
2445 if (aObjPtr
== bObjPtr
)
2447 aStr
= Jim_GetString(aObjPtr
, &aLen
);
2448 bStr
= Jim_GetString(bObjPtr
, &bLen
);
2451 return JimStringCompare(aStr
, aLen
, bStr
, bLen
) == 0;
2454 int Jim_StringMatchObj(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, Jim_Obj
*objPtr
, int nocase
)
2456 return JimStringMatch(interp
, patternObjPtr
, Jim_String(objPtr
), nocase
);
2459 int Jim_StringCompareObj(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*secondObjPtr
, int nocase
)
2461 const char *s1
, *s2
;
2464 s1
= Jim_GetString(firstObjPtr
, &l1
);
2465 s2
= Jim_GetString(secondObjPtr
, &l2
);
2468 return JimStringCompareNoCase(s1
, s2
, -1);
2470 return JimStringCompare(s1
, l1
, s2
, l2
);
2473 /* Convert a range, as returned by Jim_GetRange(), into
2474 * an absolute index into an object of the specified length.
2475 * This function may return negative values, or values
2476 * bigger or equal to the length of the list if the index
2477 * is out of range. */
2478 static int JimRelToAbsIndex(int len
, int idx
)
2485 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2486 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2487 * for implementation of commands like [string range] and [lrange].
2489 * The resulting range is guaranteed to address valid elements of
2491 static void JimRelToAbsRange(int len
, int first
, int last
,
2492 int *firstPtr
, int *lastPtr
, int *rangeLenPtr
)
2500 rangeLen
= last
- first
+ 1;
2507 rangeLen
-= (last
- (len
- 1));
2517 *rangeLenPtr
= rangeLen
;
2520 Jim_Obj
*Jim_StringByteRangeObj(Jim_Interp
*interp
,
2521 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2528 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2529 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2531 str
= Jim_GetString(strObjPtr
, &bytelen
);
2532 first
= JimRelToAbsIndex(bytelen
, first
);
2533 last
= JimRelToAbsIndex(bytelen
, last
);
2534 JimRelToAbsRange(bytelen
, first
, last
, &first
, &last
, &rangeLen
);
2535 if (first
== 0 && rangeLen
== bytelen
) {
2538 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2541 Jim_Obj
*Jim_StringRangeObj(Jim_Interp
*interp
,
2542 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2550 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2551 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2553 str
= Jim_GetString(strObjPtr
, &bytelen
);
2554 len
= Jim_Utf8Length(interp
, strObjPtr
);
2555 first
= JimRelToAbsIndex(len
, first
);
2556 last
= JimRelToAbsIndex(len
, last
);
2557 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
2558 if (first
== 0 && rangeLen
== len
) {
2561 if (len
== bytelen
) {
2562 /* ASCII optimisation */
2563 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2565 return Jim_NewStringObjUtf8(interp
, str
+ utf8_index(str
, first
), rangeLen
);
2567 return Jim_StringByteRangeObj(interp
, strObjPtr
, firstObjPtr
, lastObjPtr
);
2571 static Jim_Obj
*JimStringToLower(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2577 if (strObjPtr
->typePtr
!= &stringObjType
) {
2578 SetStringFromAny(interp
, strObjPtr
);
2581 str
= Jim_GetString(strObjPtr
, &len
);
2583 buf
= p
= Jim_Alloc(len
+ 1);
2586 str
+= utf8_tounicode(str
, &c
);
2587 p
+= utf8_fromunicode(p
, utf8_lower(c
));
2590 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2593 static Jim_Obj
*JimStringToUpper(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2599 if (strObjPtr
->typePtr
!= &stringObjType
) {
2600 SetStringFromAny(interp
, strObjPtr
);
2603 str
= Jim_GetString(strObjPtr
, &len
);
2605 buf
= p
= Jim_Alloc(len
+ 1);
2608 str
+= utf8_tounicode(str
, &c
);
2609 p
+= utf8_fromunicode(p
, utf8_upper(c
));
2612 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2615 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2616 * for unicode character 'c'.
2617 * Returns the position if found or NULL if not
2619 static const char *utf8_memchr(const char *str
, int len
, int c
)
2624 int n
= utf8_tounicode(str
, &sc
);
2633 return memchr(str
, c
, len
);
2638 * Searches for the first non-trim char in string (str, len)
2640 * If none is found, returns just past the last char.
2642 * Lengths are in bytes.
2644 static const char *JimFindTrimLeft(const char *str
, int len
, const char *trimchars
, int trimlen
)
2648 int n
= utf8_tounicode(str
, &c
);
2650 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2651 /* Not a trim char, so stop */
2661 * Searches backwards for a non-trim char in string (str, len).
2663 * Returns a pointer to just after the non-trim char, or NULL if not found.
2665 * Lengths are in bytes.
2667 static const char *JimFindTrimRight(const char *str
, int len
, const char *trimchars
, int trimlen
)
2673 int n
= utf8_prev_len(str
, len
);
2678 n
= utf8_tounicode(str
, &c
);
2680 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2688 static const char default_trim_chars
[] = " \t\n\r";
2689 /* sizeof() here includes the null byte */
2690 static int default_trim_chars_len
= sizeof(default_trim_chars
);
2692 static Jim_Obj
*JimStringTrimLeft(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2695 const char *str
= Jim_GetString(strObjPtr
, &len
);
2696 const char *trimchars
= default_trim_chars
;
2697 int trimcharslen
= default_trim_chars_len
;
2700 if (trimcharsObjPtr
) {
2701 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2704 newstr
= JimFindTrimLeft(str
, len
, trimchars
, trimcharslen
);
2705 if (newstr
== str
) {
2709 return Jim_NewStringObj(interp
, newstr
, len
- (newstr
- str
));
2712 static Jim_Obj
*JimStringTrimRight(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2715 const char *trimchars
= default_trim_chars
;
2716 int trimcharslen
= default_trim_chars_len
;
2717 const char *nontrim
;
2719 if (trimcharsObjPtr
) {
2720 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2723 if (strObjPtr
->typePtr
!= &stringObjType
) {
2724 SetStringFromAny(interp
, strObjPtr
);
2726 Jim_GetString(strObjPtr
, &len
);
2727 nontrim
= JimFindTrimRight(strObjPtr
->bytes
, len
, trimchars
, trimcharslen
);
2729 if (nontrim
== NULL
) {
2730 /* All trim, so return a zero-length string */
2731 return Jim_NewEmptyStringObj(interp
);
2733 if (nontrim
== strObjPtr
->bytes
+ len
) {
2737 if (Jim_IsShared(strObjPtr
)) {
2738 strObjPtr
= Jim_NewStringObj(interp
, strObjPtr
->bytes
, (nontrim
- strObjPtr
->bytes
));
2741 /* Can modify this string in place */
2742 strObjPtr
->bytes
[nontrim
- strObjPtr
->bytes
] = 0;
2743 strObjPtr
->length
= (nontrim
- strObjPtr
->bytes
);
2749 static Jim_Obj
*JimStringTrim(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2751 /* First trim left. */
2752 Jim_Obj
*objPtr
= JimStringTrimLeft(interp
, strObjPtr
, trimcharsObjPtr
);
2754 /* Now trim right */
2755 strObjPtr
= JimStringTrimRight(interp
, objPtr
, trimcharsObjPtr
);
2757 if (objPtr
!= strObjPtr
) {
2758 /* Note that we don't want this object to be leaked */
2759 Jim_IncrRefCount(objPtr
);
2760 Jim_DecrRefCount(interp
, objPtr
);
2767 static int JimStringIs(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*strClass
, int strict
)
2769 static const char * const strclassnames
[] = {
2770 "integer", "alpha", "alnum", "ascii", "digit",
2771 "double", "lower", "upper", "space", "xdigit",
2772 "control", "print", "graph", "punct",
2776 STR_IS_INTEGER
, STR_IS_ALPHA
, STR_IS_ALNUM
, STR_IS_ASCII
, STR_IS_DIGIT
,
2777 STR_IS_DOUBLE
, STR_IS_LOWER
, STR_IS_UPPER
, STR_IS_SPACE
, STR_IS_XDIGIT
,
2778 STR_IS_CONTROL
, STR_IS_PRINT
, STR_IS_GRAPH
, STR_IS_PUNCT
2784 int (*isclassfunc
)(int c
) = NULL
;
2786 if (Jim_GetEnum(interp
, strClass
, strclassnames
, &strclass
, "class", JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
2790 str
= Jim_GetString(strObjPtr
, &len
);
2792 Jim_SetResultInt(interp
, !strict
);
2797 case STR_IS_INTEGER
:
2800 Jim_SetResultInt(interp
, JimGetWideNoErr(interp
, strObjPtr
, &w
) == JIM_OK
);
2807 Jim_SetResultInt(interp
, Jim_GetDouble(interp
, strObjPtr
, &d
) == JIM_OK
&& errno
!= ERANGE
);
2811 case STR_IS_ALPHA
: isclassfunc
= isalpha
; break;
2812 case STR_IS_ALNUM
: isclassfunc
= isalnum
; break;
2813 case STR_IS_ASCII
: isclassfunc
= isascii
; break;
2814 case STR_IS_DIGIT
: isclassfunc
= isdigit
; break;
2815 case STR_IS_LOWER
: isclassfunc
= islower
; break;
2816 case STR_IS_UPPER
: isclassfunc
= isupper
; break;
2817 case STR_IS_SPACE
: isclassfunc
= isspace
; break;
2818 case STR_IS_XDIGIT
: isclassfunc
= isxdigit
; break;
2819 case STR_IS_CONTROL
: isclassfunc
= iscntrl
; break;
2820 case STR_IS_PRINT
: isclassfunc
= isprint
; break;
2821 case STR_IS_GRAPH
: isclassfunc
= isgraph
; break;
2822 case STR_IS_PUNCT
: isclassfunc
= ispunct
; break;
2827 for (i
= 0; i
< len
; i
++) {
2828 if (!isclassfunc(str
[i
])) {
2829 Jim_SetResultInt(interp
, 0);
2833 Jim_SetResultInt(interp
, 1);
2837 /* -----------------------------------------------------------------------------
2838 * Compared String Object
2839 * ---------------------------------------------------------------------------*/
2841 /* This is strange object that allows to compare a C literal string
2842 * with a Jim object in very short time if the same comparison is done
2843 * multiple times. For example every time the [if] command is executed,
2844 * Jim has to check if a given argument is "else". This comparions if
2845 * the code has no errors are true most of the times, so we can cache
2846 * inside the object the pointer of the string of the last matching
2847 * comparison. Because most C compilers perform literal sharing,
2848 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2849 * this works pretty well even if comparisons are at different places
2850 * inside the C code. */
2852 static const Jim_ObjType comparedStringObjType
= {
2857 JIM_TYPE_REFERENCES
,
2860 /* The only way this object is exposed to the API is via the following
2861 * function. Returns true if the string and the object string repr.
2862 * are the same, otherwise zero is returned.
2864 * Note: this isn't binary safe, but it hardly needs to be.*/
2865 int Jim_CompareStringImmediate(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
)
2867 if (objPtr
->typePtr
== &comparedStringObjType
&& objPtr
->internalRep
.ptr
== str
)
2870 const char *objStr
= Jim_String(objPtr
);
2872 if (strcmp(str
, objStr
) != 0)
2874 if (objPtr
->typePtr
!= &comparedStringObjType
) {
2875 Jim_FreeIntRep(interp
, objPtr
);
2876 objPtr
->typePtr
= &comparedStringObjType
;
2878 objPtr
->internalRep
.ptr
= (char *)str
; /*ATTENTION: const cast */
2883 static int qsortCompareStringPointers(const void *a
, const void *b
)
2885 char *const *sa
= (char *const *)a
;
2886 char *const *sb
= (char *const *)b
;
2888 return strcmp(*sa
, *sb
);
2892 /* -----------------------------------------------------------------------------
2895 * This object is just a string from the language point of view, but
2896 * in the internal representation it contains the filename and line number
2897 * where this given token was read. This information is used by
2898 * Jim_EvalObj() if the object passed happens to be of type "source".
2900 * This allows to propagate the information about line numbers and file
2901 * names and give error messages with absolute line numbers.
2903 * Note that this object uses shared strings for filenames, and the
2904 * pointer to the filename together with the line number is taken into
2905 * the space for the "inline" internal representation of the Jim_Object,
2906 * so there is almost memory zero-overhead.
2908 * Also the object will be converted to something else if the given
2909 * token it represents in the source file is not something to be
2910 * evaluated (not a script), and will be specialized in some other way,
2911 * so the time overhead is also null.
2912 * ---------------------------------------------------------------------------*/
2914 static void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2915 static void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2917 static const Jim_ObjType sourceObjType
= {
2919 FreeSourceInternalRep
,
2920 DupSourceInternalRep
,
2922 JIM_TYPE_REFERENCES
,
2925 void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2927 Jim_DecrRefCount(interp
, objPtr
->internalRep
.sourceValue
.fileNameObj
);
2930 void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2932 dupPtr
->internalRep
= srcPtr
->internalRep
;
2933 Jim_IncrRefCount(dupPtr
->internalRep
.sourceValue
.fileNameObj
);
2936 static void JimSetSourceInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2937 Jim_Obj
*fileNameObj
, int lineNumber
)
2939 JimPanic((Jim_IsShared(objPtr
), "JimSetSourceInfo called with shared object"));
2940 JimPanic((objPtr
->typePtr
!= NULL
, "JimSetSourceInfo called with typePtr != NULL"));
2941 Jim_IncrRefCount(fileNameObj
);
2942 objPtr
->internalRep
.sourceValue
.fileNameObj
= fileNameObj
;
2943 objPtr
->internalRep
.sourceValue
.lineNumber
= lineNumber
;
2944 objPtr
->typePtr
= &sourceObjType
;
2947 /* -----------------------------------------------------------------------------
2949 * ---------------------------------------------------------------------------*/
2951 static const Jim_ObjType scriptLineObjType
= {
2959 static Jim_Obj
*JimNewScriptLineObj(Jim_Interp
*interp
, int argc
, int line
)
2963 #ifdef DEBUG_SHOW_SCRIPT
2965 snprintf(buf
, sizeof(buf
), "line=%d, argc=%d", line
, argc
);
2966 objPtr
= Jim_NewStringObj(interp
, buf
, -1);
2968 objPtr
= Jim_NewEmptyStringObj(interp
);
2970 objPtr
->typePtr
= &scriptLineObjType
;
2971 objPtr
->internalRep
.scriptLineValue
.argc
= argc
;
2972 objPtr
->internalRep
.scriptLineValue
.line
= line
;
2977 #define JIM_CMDSTRUCT_EXPAND -1
2979 static void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2980 static void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2981 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
);
2983 static const Jim_ObjType scriptObjType
= {
2985 FreeScriptInternalRep
,
2986 DupScriptInternalRep
,
2988 JIM_TYPE_REFERENCES
,
2991 /* The ScriptToken structure represents every token into a scriptObj.
2992 * Every token contains an associated Jim_Obj that can be specialized
2993 * by commands operating on it. */
2994 typedef struct ScriptToken
3000 /* This is the script object internal representation. An array of
3001 * ScriptToken structures, including a pre-computed representation of the
3002 * command length and arguments.
3004 * For example the script:
3007 * set $i $x$y [foo]BAR
3009 * will produce a ScriptObj with the following Tokens:
3024 * "puts hello" has two args (LIN 2), composed of single tokens.
3025 * (Note that the WRD token is omitted for the common case of a single token.)
3027 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
3028 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
3030 * The precomputation of the command structure makes Jim_Eval() faster,
3031 * and simpler because there aren't dynamic lengths / allocations.
3033 * -- {expand}/{*} handling --
3035 * Expand is handled in a special way.
3037 * If a "word" begins with {*}, the word token count is -ve.
3039 * For example the command:
3043 * Will produce the following cmdstruct array:
3050 * Note that the 'LIN' token also contains the source information for the
3051 * first word of the line for error reporting purposes
3053 * -- the substFlags field of the structure --
3055 * The scriptObj structure is used to represent both "script" objects
3056 * and "subst" objects. In the second case, the there are no LIN and WRD
3057 * tokens. Instead SEP and EOL tokens are added as-is.
3058 * In addition, the field 'substFlags' is used to represent the flags used to turn
3059 * the string into the internal representation used to perform the
3060 * substitution. If this flags are not what the application requires
3061 * the scriptObj is created again. For example the script:
3063 * subst -nocommands $string
3064 * subst -novariables $string
3066 * Will recreate the internal representation of the $string object
3069 typedef struct ScriptObj
3071 int len
; /* Length as number of tokens. */
3072 ScriptToken
*token
; /* Tokens array. */
3073 int substFlags
; /* flags used for the compilation of "subst" objects */
3074 int inUse
; /* Used to share a ScriptObj. Currently
3075 only used by Jim_EvalObj() as protection against
3076 shimmering of the currently evaluated object. */
3077 Jim_Obj
*fileNameObj
;
3078 int line
; /* Line number of the first line */
3081 void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3084 struct ScriptObj
*script
= (void *)objPtr
->internalRep
.ptr
;
3087 if (script
->inUse
!= 0)
3089 for (i
= 0; i
< script
->len
; i
++) {
3090 Jim_DecrRefCount(interp
, script
->token
[i
].objPtr
);
3092 Jim_Free(script
->token
);
3093 Jim_DecrRefCount(interp
, script
->fileNameObj
);
3097 void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
3099 JIM_NOTUSED(interp
);
3100 JIM_NOTUSED(srcPtr
);
3102 /* Just returns an simple string. */
3103 dupPtr
->typePtr
= NULL
;
3106 /* A simple parser token.
3107 * All the simple tokens for the script point into the same script string rep.
3111 const char *token
; /* Pointer to the start of the token */
3112 int len
; /* Length of this token */
3113 int type
; /* Token type */
3114 int line
; /* Line number */
3117 /* A list of parsed tokens representing a script.
3118 * Tokens are added to this list as the script is parsed.
3119 * It grows as needed.
3123 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3124 ParseToken
*list
; /* Array of tokens */
3125 int size
; /* Current size of the list */
3126 int count
; /* Number of entries used */
3127 ParseToken static_list
[20]; /* Small initial token space to avoid allocation */
3130 static void ScriptTokenListInit(ParseTokenList
*tokenlist
)
3132 tokenlist
->list
= tokenlist
->static_list
;
3133 tokenlist
->size
= sizeof(tokenlist
->static_list
) / sizeof(ParseToken
);
3134 tokenlist
->count
= 0;
3137 static void ScriptTokenListFree(ParseTokenList
*tokenlist
)
3139 if (tokenlist
->list
!= tokenlist
->static_list
) {
3140 Jim_Free(tokenlist
->list
);
3145 * Adds the new token to the tokenlist.
3146 * The token has the given length, type and line number.
3147 * The token list is resized as necessary.
3149 static void ScriptAddToken(ParseTokenList
*tokenlist
, const char *token
, int len
, int type
,
3154 if (tokenlist
->count
== tokenlist
->size
) {
3155 /* Resize the list */
3156 tokenlist
->size
*= 2;
3157 if (tokenlist
->list
!= tokenlist
->static_list
) {
3159 Jim_Realloc(tokenlist
->list
, tokenlist
->size
* sizeof(*tokenlist
->list
));
3162 /* The list needs to become allocated */
3163 tokenlist
->list
= Jim_Alloc(tokenlist
->size
* sizeof(*tokenlist
->list
));
3164 memcpy(tokenlist
->list
, tokenlist
->static_list
,
3165 tokenlist
->count
* sizeof(*tokenlist
->list
));
3168 t
= &tokenlist
->list
[tokenlist
->count
++];
3175 /* Counts the number of adjoining non-separator.
3177 * Returns -ve if the first token is the expansion
3178 * operator (in which case the count doesn't include
3181 static int JimCountWordTokens(ParseToken
*t
)
3186 /* Is the first word {*} or {expand}? */
3187 if (t
->type
== JIM_TT_STR
&& !TOKEN_IS_SEP(t
[1].type
)) {
3188 if ((t
->len
== 1 && *t
->token
== '*') || (t
->len
== 6 && strncmp(t
->token
, "expand", 6) == 0)) {
3189 /* Create an expand token */
3195 /* Now count non-separator words */
3196 while (!TOKEN_IS_SEP(t
->type
)) {
3201 return count
* expand
;
3205 * Create a script/subst object from the given token.
3207 static Jim_Obj
*JimMakeScriptObj(Jim_Interp
*interp
, const ParseToken
*t
)
3211 if (t
->type
== JIM_TT_ESC
&& memchr(t
->token
, '\\', t
->len
) != NULL
) {
3212 /* Convert the backlash escapes . */
3214 char *str
= Jim_Alloc(len
+ 1);
3215 len
= JimEscape(str
, t
->token
, len
);
3216 objPtr
= Jim_NewStringObjNoAlloc(interp
, str
, len
);
3219 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3220 * with a single space. This is currently not done.
3222 objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
3228 * Takes a tokenlist and creates the allocated list of script tokens
3229 * in script->token, of length script->len.
3231 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3234 * Also sets script->line to the line number of the first token
3236 static void ScriptObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3237 ParseTokenList
*tokenlist
)
3240 struct ScriptToken
*token
;
3241 /* Number of tokens so far for the current command */
3243 /* This is the first token for the current command */
3244 ScriptToken
*linefirst
;
3248 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3249 printf("==== Tokens ====\n");
3250 for (i
= 0; i
< tokenlist
->count
; i
++) {
3251 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
->list
[i
].line
, jim_tt_name(tokenlist
->list
[i
].type
),
3252 tokenlist
->list
[i
].len
, tokenlist
->list
[i
].token
);
3256 /* May need up to one extra script token for each EOL in the worst case */
3257 count
= tokenlist
->count
;
3258 for (i
= 0; i
< tokenlist
->count
; i
++) {
3259 if (tokenlist
->list
[i
].type
== JIM_TT_EOL
) {
3263 linenr
= script
->line
= tokenlist
->list
[0].line
;
3265 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
3267 /* This is the first token for the current command */
3268 linefirst
= token
++;
3270 for (i
= 0; i
< tokenlist
->count
; ) {
3271 /* Look ahead to find out how many tokens make up the next word */
3274 /* Skip any leading separators */
3275 while (tokenlist
->list
[i
].type
== JIM_TT_SEP
) {
3279 wordtokens
= JimCountWordTokens(tokenlist
->list
+ i
);
3281 if (wordtokens
== 0) {
3282 /* None, so at end of line */
3284 linefirst
->type
= JIM_TT_LINE
;
3285 linefirst
->objPtr
= JimNewScriptLineObj(interp
, lineargs
, linenr
);
3286 Jim_IncrRefCount(linefirst
->objPtr
);
3288 /* Reset for new line */
3290 linefirst
= token
++;
3295 else if (wordtokens
!= 1) {
3296 /* More than 1, or {expand}, so insert a WORD token */
3297 token
->type
= JIM_TT_WORD
;
3298 token
->objPtr
= Jim_NewIntObj(interp
, wordtokens
);
3299 Jim_IncrRefCount(token
->objPtr
);
3301 if (wordtokens
< 0) {
3302 /* Skip the expand token */
3304 wordtokens
= -wordtokens
- 1;
3309 if (lineargs
== 0) {
3310 /* First real token on the line, so record the line number */
3311 linenr
= tokenlist
->list
[i
].line
;
3315 /* Add each non-separator word token to the line */
3316 while (wordtokens
--) {
3317 const ParseToken
*t
= &tokenlist
->list
[i
++];
3319 token
->type
= t
->type
;
3320 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3321 Jim_IncrRefCount(token
->objPtr
);
3323 /* Every object is initially a string, but the
3324 * internal type may be specialized during execution of the
3326 JimSetSourceInfo(interp
, token
->objPtr
, script
->fileNameObj
, t
->line
);
3331 if (lineargs
== 0) {
3335 script
->len
= token
- script
->token
;
3337 assert(script
->len
< count
);
3339 #ifdef DEBUG_SHOW_SCRIPT
3340 printf("==== Script (%s) ====\n", Jim_String(script
->fileNameObj
));
3341 for (i
= 0; i
< script
->len
; i
++) {
3342 const ScriptToken
*t
= &script
->token
[i
];
3343 printf("[%2d] %s %s\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
3350 * Similar to ScriptObjAddTokens(), but for subst objects.
3352 static void SubstObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3353 ParseTokenList
*tokenlist
)
3356 struct ScriptToken
*token
;
3358 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * tokenlist
->count
);
3360 for (i
= 0; i
< tokenlist
->count
; i
++) {
3361 const ParseToken
*t
= &tokenlist
->list
[i
];
3363 /* Create a token for 't' */
3364 token
->type
= t
->type
;
3365 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3366 Jim_IncrRefCount(token
->objPtr
);
3373 /* This method takes the string representation of an object
3374 * as a Tcl script, and generates the pre-parsed internal representation
3376 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
)
3379 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
3380 struct JimParserCtx parser
;
3381 struct ScriptObj
*script
;
3382 ParseTokenList tokenlist
;
3385 /* Try to get information about filename / line number */
3386 if (objPtr
->typePtr
== &sourceObjType
) {
3387 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
3390 /* Initially parse the script into tokens (in tokenlist) */
3391 ScriptTokenListInit(&tokenlist
);
3393 JimParserInit(&parser
, scriptText
, scriptTextLen
, line
);
3394 while (!parser
.eof
) {
3395 JimParseScript(&parser
);
3396 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
3399 if (result
&& parser
.missing
!= ' ') {
3400 ScriptTokenListFree(&tokenlist
);
3401 result
->missing
= parser
.missing
;
3402 result
->line
= parser
.missingline
;
3406 /* Add a final EOF token */
3407 ScriptAddToken(&tokenlist
, scriptText
+ scriptTextLen
, 0, JIM_TT_EOF
, 0);
3409 /* Create the "real" script tokens from the initial token list */
3410 script
= Jim_Alloc(sizeof(*script
));
3411 memset(script
, 0, sizeof(*script
));
3413 script
->line
= line
;
3414 if (objPtr
->typePtr
== &sourceObjType
) {
3415 script
->fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
3418 script
->fileNameObj
= interp
->emptyObj
;
3420 Jim_IncrRefCount(script
->fileNameObj
);
3422 ScriptObjAddTokens(interp
, script
, &tokenlist
);
3424 /* No longer need the token list */
3425 ScriptTokenListFree(&tokenlist
);
3427 /* Free the old internal rep and set the new one. */
3428 Jim_FreeIntRep(interp
, objPtr
);
3429 Jim_SetIntRepPtr(objPtr
, script
);
3430 objPtr
->typePtr
= &scriptObjType
;
3435 ScriptObj
*Jim_GetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3437 struct ScriptObj
*script
= Jim_GetIntRepPtr(objPtr
);
3439 if (objPtr
->typePtr
!= &scriptObjType
|| script
->substFlags
) {
3440 SetScriptFromAny(interp
, objPtr
, NULL
);
3442 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
3445 /* -----------------------------------------------------------------------------
3447 * ---------------------------------------------------------------------------*/
3448 static void JimIncrCmdRefCount(Jim_Cmd
*cmdPtr
)
3453 static void JimDecrCmdRefCount(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
)
3455 if (--cmdPtr
->inUse
== 0) {
3456 if (cmdPtr
->isproc
) {
3457 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.argListObjPtr
);
3458 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.bodyObjPtr
);
3459 if (cmdPtr
->u
.proc
.staticVars
) {
3460 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3461 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3463 if (cmdPtr
->u
.proc
.prevCmd
) {
3464 /* Delete any pushed command too */
3465 JimDecrCmdRefCount(interp
, cmdPtr
->u
.proc
.prevCmd
);
3470 if (cmdPtr
->u
.native
.delProc
) {
3471 cmdPtr
->u
.native
.delProc(interp
, cmdPtr
->u
.native
.privData
);
3478 /* Commands HashTable Type.
3480 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3481 static void JimCommandsHT_ValDestructor(void *interp
, void *val
)
3483 JimDecrCmdRefCount(interp
, val
);
3486 static const Jim_HashTableType JimCommandsHashTableType
= {
3487 JimStringCopyHTHashFunction
, /* hash function */
3488 JimStringCopyHTKeyDup
, /* key dup */
3490 JimStringCopyHTKeyCompare
, /* key compare */
3491 JimStringCopyHTKeyDestructor
, /* key destructor */
3492 JimCommandsHT_ValDestructor
/* val destructor */
3495 /* ------------------------- Commands related functions --------------------- */
3497 int Jim_CreateCommand(Jim_Interp
*interp
, const char *cmdName
,
3498 Jim_CmdProc cmdProc
, void *privData
, Jim_DelCmdProc delProc
)
3502 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) != JIM_ERR
) {
3503 /* Command existed so incr proc epoch */
3504 Jim_InterpIncrProcEpoch(interp
);
3507 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3509 /* Store the new details for this proc */
3510 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3512 cmdPtr
->u
.native
.delProc
= delProc
;
3513 cmdPtr
->u
.native
.cmdProc
= cmdProc
;
3514 cmdPtr
->u
.native
.privData
= privData
;
3516 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3518 /* There is no need to increment the 'proc epoch' because
3519 * creation of a new procedure can never affect existing
3520 * cached commands. We don't do negative caching. */
3524 static int JimCreateProcedure(Jim_Interp
*interp
, Jim_Obj
*cmdName
,
3525 Jim_Obj
*argListObjPtr
, Jim_Obj
*staticsListObjPtr
, Jim_Obj
*bodyObjPtr
)
3532 if (JimValidName(interp
, "procedure", cmdName
) != JIM_OK
) {
3536 argListLen
= Jim_ListLength(interp
, argListObjPtr
);
3538 /* Allocate space for both the command pointer and the arg list */
3539 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
) + sizeof(struct Jim_ProcArg
) * argListLen
);
3540 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3543 cmdPtr
->u
.proc
.argListObjPtr
= argListObjPtr
;
3544 cmdPtr
->u
.proc
.argListLen
= argListLen
;
3545 cmdPtr
->u
.proc
.bodyObjPtr
= bodyObjPtr
;
3546 cmdPtr
->u
.proc
.argsPos
= -1;
3547 cmdPtr
->u
.proc
.arglist
= (struct Jim_ProcArg
*)(cmdPtr
+ 1);
3548 Jim_IncrRefCount(argListObjPtr
);
3549 Jim_IncrRefCount(bodyObjPtr
);
3551 /* Create the statics hash table. */
3552 if (staticsListObjPtr
) {
3555 len
= Jim_ListLength(interp
, staticsListObjPtr
);
3557 cmdPtr
->u
.proc
.staticVars
= Jim_Alloc(sizeof(Jim_HashTable
));
3558 Jim_InitHashTable(cmdPtr
->u
.proc
.staticVars
, &JimVariablesHashTableType
, interp
);
3559 for (i
= 0; i
< len
; i
++) {
3560 Jim_Obj
*objPtr
= 0, *initObjPtr
= 0, *nameObjPtr
= 0;
3564 Jim_ListIndex(interp
, staticsListObjPtr
, i
, &objPtr
, JIM_NONE
);
3565 /* Check if it's composed of two elements. */
3566 subLen
= Jim_ListLength(interp
, objPtr
);
3567 if (subLen
== 1 || subLen
== 2) {
3568 /* Try to get the variable value from the current
3570 Jim_ListIndex(interp
, objPtr
, 0, &nameObjPtr
, JIM_NONE
);
3572 initObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, JIM_NONE
);
3573 if (initObjPtr
== NULL
) {
3574 Jim_SetResultFormatted(interp
,
3575 "variable for initialization of static \"%#s\" not found in the local context",
3581 Jim_ListIndex(interp
, objPtr
, 1, &initObjPtr
, JIM_NONE
);
3583 if (JimValidName(interp
, "static variable", nameObjPtr
) != JIM_OK
) {
3587 varPtr
= Jim_Alloc(sizeof(*varPtr
));
3588 varPtr
->objPtr
= initObjPtr
;
3589 Jim_IncrRefCount(initObjPtr
);
3590 varPtr
->linkFramePtr
= NULL
;
3591 if (Jim_AddHashEntry(cmdPtr
->u
.proc
.staticVars
,
3592 Jim_String(nameObjPtr
), varPtr
) != JIM_OK
) {
3593 Jim_SetResultFormatted(interp
,
3594 "static variable name \"%#s\" duplicated in statics list", nameObjPtr
);
3595 Jim_DecrRefCount(interp
, initObjPtr
);
3601 Jim_SetResultFormatted(interp
, "too many fields in static specifier \"%#s\"",
3609 /* Parse the args out into arglist, validating as we go */
3610 /* Examine the argument list for default parameters and 'args' */
3611 for (i
= 0; i
< argListLen
; i
++) {
3613 Jim_Obj
*nameObjPtr
;
3614 Jim_Obj
*defaultObjPtr
;
3618 /* Examine a parameter */
3619 Jim_ListIndex(interp
, argListObjPtr
, i
, &argPtr
, JIM_NONE
);
3620 len
= Jim_ListLength(interp
, argPtr
);
3622 Jim_SetResultString(interp
, "procedure has argument with no name", -1);
3626 Jim_SetResultString(interp
, "procedure has argument with too many fields", -1);
3631 /* Optional parameter */
3632 Jim_ListIndex(interp
, argPtr
, 0, &nameObjPtr
, JIM_NONE
);
3633 Jim_ListIndex(interp
, argPtr
, 1, &defaultObjPtr
, JIM_NONE
);
3636 /* Required parameter */
3637 nameObjPtr
= argPtr
;
3638 defaultObjPtr
= NULL
;
3642 if (Jim_CompareStringImmediate(interp
, nameObjPtr
, "args")) {
3643 if (cmdPtr
->u
.proc
.argsPos
>= 0) {
3644 Jim_SetResultString(interp
, "procedure has 'args' specified more than once", -1);
3647 cmdPtr
->u
.proc
.argsPos
= i
;
3651 cmdPtr
->u
.proc
.optArity
+= n
;
3654 cmdPtr
->u
.proc
.reqArity
+= n
;
3658 cmdPtr
->u
.proc
.arglist
[i
].nameObjPtr
= nameObjPtr
;
3659 cmdPtr
->u
.proc
.arglist
[i
].defaultObjPtr
= defaultObjPtr
;
3662 /* Add the new command */
3664 /* It may already exist, so we try to delete the old one.
3665 * Note that reference count means that it won't be deleted yet if
3666 * it exists in the call stack.
3668 * BUT, if 'local' is in force, instead of deleting the existing
3669 * proc, we stash a reference to the old proc here.
3671 he
= Jim_FindHashEntry(&interp
->commands
, Jim_String(cmdName
));
3673 /* There was an old procedure with the same name, this requires
3674 * a 'proc epoch' update. */
3676 /* If a procedure with the same name didn't existed there is no need
3677 * to increment the 'proc epoch' because creation of a new procedure
3678 * can never affect existing cached commands. We don't do
3679 * negative caching. */
3680 Jim_InterpIncrProcEpoch(interp
);
3683 if (he
&& interp
->local
) {
3684 /* Just push this proc over the top of the previous one */
3685 cmdPtr
->u
.proc
.prevCmd
= he
->u
.val
;
3690 /* Replace the existing proc */
3691 Jim_DeleteHashEntry(&interp
->commands
, Jim_String(cmdName
));
3694 Jim_AddHashEntry(&interp
->commands
, Jim_String(cmdName
), cmdPtr
);
3697 /* Unlike Tcl, set the name of the proc as the result */
3698 Jim_SetResult(interp
, cmdName
);
3702 if (cmdPtr
->u
.proc
.staticVars
) {
3703 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3705 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3706 Jim_DecrRefCount(interp
, argListObjPtr
);
3707 Jim_DecrRefCount(interp
, bodyObjPtr
);
3712 int Jim_DeleteCommand(Jim_Interp
*interp
, const char *cmdName
)
3714 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) == JIM_ERR
)
3716 Jim_InterpIncrProcEpoch(interp
);
3720 int Jim_RenameCommand(Jim_Interp
*interp
, const char *oldName
, const char *newName
)
3724 /* Does it exist? */
3725 he
= Jim_FindHashEntry(&interp
->commands
, oldName
);
3727 Jim_SetResultFormatted(interp
, "can't %s \"%s\": command doesn't exist",
3728 newName
[0] ? "rename" : "delete", oldName
);
3732 if (newName
[0] == '\0') /* Delete! */
3733 return Jim_DeleteCommand(interp
, oldName
);
3736 if (Jim_FindHashEntry(&interp
->commands
, newName
)) {
3737 Jim_SetResultFormatted(interp
, "can't rename to \"%s\": command already exists", newName
);
3741 /* Add the new name first */
3742 JimIncrCmdRefCount(he
->u
.val
);
3743 Jim_AddHashEntry(&interp
->commands
, newName
, he
->u
.val
);
3745 /* Now remove the old name */
3746 Jim_DeleteHashEntry(&interp
->commands
, oldName
);
3748 /* Increment the epoch */
3749 Jim_InterpIncrProcEpoch(interp
);
3753 /* -----------------------------------------------------------------------------
3755 * ---------------------------------------------------------------------------*/
3757 static int SetCommandFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3759 static const Jim_ObjType commandObjType
= {
3764 JIM_TYPE_REFERENCES
,
3767 int SetCommandFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3770 const char *cmdName
;
3772 /* Get the string representation */
3773 cmdName
= Jim_String(objPtr
);
3774 /* Lookup this name into the commands hash table */
3775 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3779 /* Free the old internal repr and set the new one. */
3780 Jim_FreeIntRep(interp
, objPtr
);
3781 objPtr
->typePtr
= &commandObjType
;
3782 objPtr
->internalRep
.cmdValue
.procEpoch
= interp
->procEpoch
;
3783 objPtr
->internalRep
.cmdValue
.cmdPtr
= (void *)he
->u
.val
;
3787 /* This function returns the command structure for the command name
3788 * stored in objPtr. It tries to specialize the objPtr to contain
3789 * a cached info instead to perform the lookup into the hash table
3790 * every time. The information cached may not be uptodate, in such
3791 * a case the lookup is performed and the cache updated.
3793 * Respects the 'upcall' setting
3795 Jim_Cmd
*Jim_GetCommand(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
3799 if ((objPtr
->typePtr
!= &commandObjType
||
3800 objPtr
->internalRep
.cmdValue
.procEpoch
!= interp
->procEpoch
) &&
3801 SetCommandFromAny(interp
, objPtr
) == JIM_ERR
) {
3802 if (flags
& JIM_ERRMSG
) {
3803 Jim_SetResultFormatted(interp
, "invalid command name \"%#s\"", objPtr
);
3807 cmd
= objPtr
->internalRep
.cmdValue
.cmdPtr
;
3808 while (cmd
->isproc
&& cmd
->u
.proc
.upcall
) {
3809 cmd
= cmd
->u
.proc
.prevCmd
;
3814 /* -----------------------------------------------------------------------------
3816 * ---------------------------------------------------------------------------*/
3818 /* Variables HashTable Type.
3820 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3821 static void JimVariablesHTValDestructor(void *interp
, void *val
)
3823 Jim_Var
*varPtr
= (void *)val
;
3825 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
3829 static const Jim_HashTableType JimVariablesHashTableType
= {
3830 JimStringCopyHTHashFunction
, /* hash function */
3831 JimStringCopyHTKeyDup
, /* key dup */
3833 JimStringCopyHTKeyCompare
, /* key compare */
3834 JimStringCopyHTKeyDestructor
, /* key destructor */
3835 JimVariablesHTValDestructor
/* val destructor */
3838 /* -----------------------------------------------------------------------------
3840 * ---------------------------------------------------------------------------*/
3842 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3844 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3846 static const Jim_ObjType variableObjType
= {
3851 JIM_TYPE_REFERENCES
,
3854 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3855 * is in the form "varname(key)". */
3856 static int JimNameIsDictSugar(const char *str
, int len
)
3858 if (len
&& str
[len
- 1] == ')' && strchr(str
, '(') != NULL
)
3864 * Check that the name does not contain embedded nulls.
3866 * Variable and procedure names are maniplated as null terminated strings, so
3867 * don't allow names with embedded nulls.
3869 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
)
3871 /* Variable names and proc names can't contain embedded nulls */
3872 if (nameObjPtr
->typePtr
!= &variableObjType
) {
3874 const char *str
= Jim_GetString(nameObjPtr
, &len
);
3875 if (memchr(str
, '\0', len
)) {
3876 Jim_SetResultFormatted(interp
, "%s name contains embedded null", type
);
3883 /* This method should be called only by the variable API.
3884 * It returns JIM_OK on success (variable already exists),
3885 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3886 * a variable name, but syntax glue for [dict] i.e. the last
3887 * character is ')' */
3888 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3891 const char *varName
;
3893 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3895 /* Check if the object is already an uptodate variable */
3896 if (objPtr
->typePtr
== &variableObjType
&&
3897 objPtr
->internalRep
.varValue
.callFrameId
== framePtr
->id
) {
3898 return JIM_OK
; /* nothing to do */
3901 if (objPtr
->typePtr
== &dictSubstObjType
) {
3902 return JIM_DICT_SUGAR
;
3905 if (JimValidName(interp
, "variable", objPtr
) != JIM_OK
) {
3909 /* Get the string representation */
3910 varName
= Jim_GetString(objPtr
, &len
);
3912 /* Make sure it's not syntax glue to get/set dict. */
3913 if (JimNameIsDictSugar(varName
, len
)) {
3914 return JIM_DICT_SUGAR
;
3917 if (varName
[0] == ':' && varName
[1] == ':') {
3918 framePtr
= interp
->topFramePtr
;
3919 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
+ 2);
3925 /* Lookup this name into the variables hash table */
3926 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
);
3928 /* Try with static vars. */
3929 if (framePtr
->staticVars
== NULL
)
3931 if (!(he
= Jim_FindHashEntry(framePtr
->staticVars
, varName
)))
3935 /* Free the old internal repr and set the new one. */
3936 Jim_FreeIntRep(interp
, objPtr
);
3937 objPtr
->typePtr
= &variableObjType
;
3938 objPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3939 objPtr
->internalRep
.varValue
.varPtr
= (void *)he
->u
.val
;
3943 /* -------------------- Variables related functions ------------------------- */
3944 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, Jim_Obj
*valObjPtr
);
3945 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, int flags
);
3947 /* For now that's dummy. Variables lookup should be optimized
3948 * in many ways, with caching of lookups, and possibly with
3949 * a table of pre-allocated vars in every CallFrame for local vars.
3950 * All the caching should also have an 'epoch' mechanism similar
3951 * to the one used by Tcl for procedures lookup caching. */
3953 int Jim_SetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
3959 if ((err
= SetVariableFromAny(interp
, nameObjPtr
)) != JIM_OK
) {
3960 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3962 /* Check for [dict] syntax sugar. */
3963 if (err
== JIM_DICT_SUGAR
)
3964 return JimDictSugarSet(interp
, nameObjPtr
, valObjPtr
);
3966 if (JimValidName(interp
, "variable", nameObjPtr
) != JIM_OK
) {
3970 /* New variable to create */
3971 name
= Jim_String(nameObjPtr
);
3973 var
= Jim_Alloc(sizeof(*var
));
3974 var
->objPtr
= valObjPtr
;
3975 Jim_IncrRefCount(valObjPtr
);
3976 var
->linkFramePtr
= NULL
;
3977 /* Insert the new variable */
3978 if (name
[0] == ':' && name
[1] == ':') {
3979 /* Into the top level frame */
3980 framePtr
= interp
->topFramePtr
;
3981 Jim_AddHashEntry(&framePtr
->vars
, name
+ 2, var
);
3984 Jim_AddHashEntry(&framePtr
->vars
, name
, var
);
3986 /* Make the object int rep a variable */
3987 Jim_FreeIntRep(interp
, nameObjPtr
);
3988 nameObjPtr
->typePtr
= &variableObjType
;
3989 nameObjPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3990 nameObjPtr
->internalRep
.varValue
.varPtr
= var
;
3993 var
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3994 if (var
->linkFramePtr
== NULL
) {
3995 Jim_IncrRefCount(valObjPtr
);
3996 Jim_DecrRefCount(interp
, var
->objPtr
);
3997 var
->objPtr
= valObjPtr
;
3999 else { /* Else handle the link */
4000 Jim_CallFrame
*savedCallFrame
;
4002 savedCallFrame
= interp
->framePtr
;
4003 interp
->framePtr
= var
->linkFramePtr
;
4004 err
= Jim_SetVariable(interp
, var
->objPtr
, valObjPtr
);
4005 interp
->framePtr
= savedCallFrame
;
4013 int Jim_SetVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4015 Jim_Obj
*nameObjPtr
;
4018 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4019 Jim_IncrRefCount(nameObjPtr
);
4020 result
= Jim_SetVariable(interp
, nameObjPtr
, objPtr
);
4021 Jim_DecrRefCount(interp
, nameObjPtr
);
4025 int Jim_SetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4027 Jim_CallFrame
*savedFramePtr
;
4030 savedFramePtr
= interp
->framePtr
;
4031 interp
->framePtr
= interp
->topFramePtr
;
4032 result
= Jim_SetVariableStr(interp
, name
, objPtr
);
4033 interp
->framePtr
= savedFramePtr
;
4037 int Jim_SetVariableStrWithStr(Jim_Interp
*interp
, const char *name
, const char *val
)
4039 Jim_Obj
*nameObjPtr
, *valObjPtr
;
4042 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4043 valObjPtr
= Jim_NewStringObj(interp
, val
, -1);
4044 Jim_IncrRefCount(nameObjPtr
);
4045 Jim_IncrRefCount(valObjPtr
);
4046 result
= Jim_SetVariable(interp
, nameObjPtr
, valObjPtr
);
4047 Jim_DecrRefCount(interp
, nameObjPtr
);
4048 Jim_DecrRefCount(interp
, valObjPtr
);
4052 int Jim_SetVariableLink(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
4053 Jim_Obj
*targetNameObjPtr
, Jim_CallFrame
*targetCallFrame
)
4055 const char *varName
;
4058 varName
= Jim_GetString(nameObjPtr
, &len
);
4060 if (varName
[0] == ':' && varName
[1] == ':') {
4061 /* Linking a global var does nothing */
4065 if (JimNameIsDictSugar(varName
, len
)) {
4066 Jim_SetResultString(interp
, "Dict key syntax invalid as link source", -1);
4070 /* Check for an existing variable or link */
4071 if (SetVariableFromAny(interp
, nameObjPtr
) == JIM_OK
) {
4072 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4074 if (varPtr
->linkFramePtr
== NULL
) {
4075 Jim_SetResultFormatted(interp
, "variable \"%#s\" already exists", nameObjPtr
);
4079 /* It exists, but is a link, so delete the link */
4080 varPtr
->linkFramePtr
= NULL
;
4083 /* Check for cycles. */
4084 if (interp
->framePtr
== targetCallFrame
) {
4085 Jim_Obj
*objPtr
= targetNameObjPtr
;
4088 /* Cycles are only possible with 'uplevel 0' */
4090 if (Jim_StringEqObj(objPtr
, nameObjPtr
)) {
4091 Jim_SetResultString(interp
, "can't upvar from variable to itself", -1);
4094 if (SetVariableFromAny(interp
, objPtr
) != JIM_OK
)
4096 varPtr
= objPtr
->internalRep
.varValue
.varPtr
;
4097 if (varPtr
->linkFramePtr
!= targetCallFrame
)
4099 objPtr
= varPtr
->objPtr
;
4103 /* Perform the binding */
4104 Jim_SetVariable(interp
, nameObjPtr
, targetNameObjPtr
);
4105 /* We are now sure 'nameObjPtr' type is variableObjType */
4106 nameObjPtr
->internalRep
.varValue
.varPtr
->linkFramePtr
= targetCallFrame
;
4110 /* Return the Jim_Obj pointer associated with a variable name,
4111 * or NULL if the variable was not found in the current context.
4112 * The same optimization discussed in the comment to the
4113 * 'SetVariable' function should apply here.
4115 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4116 * in a dictionary which is shared, the array variable value is duplicated first.
4117 * This allows the array element to be updated (e.g. append, lappend) without
4118 * affecting other references to the dictionary.
4120 Jim_Obj
*Jim_GetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4122 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4124 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4126 if (varPtr
->linkFramePtr
== NULL
) {
4127 return varPtr
->objPtr
;
4132 /* The variable is a link? Resolve it. */
4133 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
4135 interp
->framePtr
= varPtr
->linkFramePtr
;
4136 objPtr
= Jim_GetVariable(interp
, varPtr
->objPtr
, flags
);
4137 interp
->framePtr
= savedCallFrame
;
4141 /* Error, so fall through to the error message */
4146 case JIM_DICT_SUGAR
:
4147 /* [dict] syntax sugar. */
4148 return JimDictSugarGet(interp
, nameObjPtr
, flags
);
4150 if (flags
& JIM_ERRMSG
) {
4151 Jim_SetResultFormatted(interp
, "can't read \"%#s\": no such variable", nameObjPtr
);
4156 Jim_Obj
*Jim_GetGlobalVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4158 Jim_CallFrame
*savedFramePtr
;
4161 savedFramePtr
= interp
->framePtr
;
4162 interp
->framePtr
= interp
->topFramePtr
;
4163 objPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4164 interp
->framePtr
= savedFramePtr
;
4169 Jim_Obj
*Jim_GetVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4171 Jim_Obj
*nameObjPtr
, *varObjPtr
;
4173 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4174 Jim_IncrRefCount(nameObjPtr
);
4175 varObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4176 Jim_DecrRefCount(interp
, nameObjPtr
);
4180 Jim_Obj
*Jim_GetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4182 Jim_CallFrame
*savedFramePtr
;
4185 savedFramePtr
= interp
->framePtr
;
4186 interp
->framePtr
= interp
->topFramePtr
;
4187 objPtr
= Jim_GetVariableStr(interp
, name
, flags
);
4188 interp
->framePtr
= savedFramePtr
;
4193 /* Unset a variable.
4194 * Note: On success unset invalidates all the variable objects created
4195 * in the current call frame incrementing. */
4196 int Jim_UnsetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4202 retval
= SetVariableFromAny(interp
, nameObjPtr
);
4203 if (retval
== JIM_DICT_SUGAR
) {
4204 /* [dict] syntax sugar. */
4205 return JimDictSugarSet(interp
, nameObjPtr
, NULL
);
4207 else if (retval
== JIM_OK
) {
4208 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4210 /* If it's a link call UnsetVariable recursively */
4211 if (varPtr
->linkFramePtr
) {
4212 Jim_CallFrame
*savedCallFrame
;
4214 savedCallFrame
= interp
->framePtr
;
4215 interp
->framePtr
= varPtr
->linkFramePtr
;
4216 retval
= Jim_UnsetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
4217 interp
->framePtr
= savedCallFrame
;
4220 Jim_CallFrame
*framePtr
= interp
->framePtr
;
4222 name
= Jim_String(nameObjPtr
);
4223 if (name
[0] == ':' && name
[1] == ':') {
4224 framePtr
= interp
->topFramePtr
;
4227 retval
= Jim_DeleteHashEntry(&framePtr
->vars
, name
);
4228 if (retval
== JIM_OK
) {
4229 /* Change the callframe id, invalidating var lookup caching */
4230 JimChangeCallFrameId(interp
, framePtr
);
4234 if (retval
!= JIM_OK
&& (flags
& JIM_ERRMSG
)) {
4235 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such variable", nameObjPtr
);
4240 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4242 /* Given a variable name for [dict] operation syntax sugar,
4243 * this function returns two objects, the first with the name
4244 * of the variable to set, and the second with the rispective key.
4245 * For example "foo(bar)" will return objects with string repr. of
4248 * The returned objects have refcount = 1. The function can't fail. */
4249 static void JimDictSugarParseVarKey(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
4250 Jim_Obj
**varPtrPtr
, Jim_Obj
**keyPtrPtr
)
4252 const char *str
, *p
;
4254 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4256 str
= Jim_GetString(objPtr
, &len
);
4258 p
= strchr(str
, '(');
4259 JimPanic((p
== NULL
, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str
));
4261 varObjPtr
= Jim_NewStringObj(interp
, str
, p
- str
);
4264 keyLen
= (str
+ len
) - p
;
4265 if (str
[len
- 1] == ')') {
4269 /* Create the objects with the variable name and key. */
4270 keyObjPtr
= Jim_NewStringObj(interp
, p
, keyLen
);
4272 Jim_IncrRefCount(varObjPtr
);
4273 Jim_IncrRefCount(keyObjPtr
);
4274 *varPtrPtr
= varObjPtr
;
4275 *keyPtrPtr
= keyObjPtr
;
4278 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4279 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4280 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*valObjPtr
)
4284 SetDictSubstFromAny(interp
, objPtr
);
4286 err
= Jim_SetDictKeysVector(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4287 &objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, 1, valObjPtr
);
4289 if (err
== JIM_OK
) {
4290 /* Don't keep an extra ref to the result */
4291 Jim_SetEmptyResult(interp
);
4295 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4296 if (Jim_GetVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
, JIM_NONE
)) {
4297 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such element in array",
4302 /* Make the error more informative and Tcl-compatible */
4303 Jim_SetResultFormatted(interp
, "can't %s \"%#s\": variable isn't array",
4304 (valObjPtr
? "set" : "unset"), objPtr
);
4310 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4312 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4313 * and stored back to the variable before expansion.
4315 static Jim_Obj
*JimDictExpandArrayVariable(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
,
4316 Jim_Obj
*keyObjPtr
, int flags
)
4318 Jim_Obj
*dictObjPtr
;
4319 Jim_Obj
*resObjPtr
= NULL
;
4322 dictObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
4327 ret
= Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4328 if (ret
!= JIM_OK
) {
4331 Jim_SetResultFormatted(interp
,
4332 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr
, keyObjPtr
);
4335 Jim_SetResultFormatted(interp
,
4336 "can't read \"%#s(%#s)\": no such element in array", varObjPtr
, keyObjPtr
);
4339 else if ((flags
& JIM_UNSHARED
) && Jim_IsShared(dictObjPtr
)) {
4340 dictObjPtr
= Jim_DuplicateObj(interp
, dictObjPtr
);
4341 if (Jim_SetVariable(interp
, varObjPtr
, dictObjPtr
) != JIM_OK
) {
4342 /* This can probably never happen */
4343 JimPanic((1, "SetVariable failed for JIM_UNSHARED"));
4345 /* We know that the key exists. Get the result in the now-unshared dictionary */
4346 Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4352 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4353 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4355 SetDictSubstFromAny(interp
, objPtr
);
4357 return JimDictExpandArrayVariable(interp
,
4358 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4359 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, flags
);
4362 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4364 void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4366 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
4367 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
4370 void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4372 JIM_NOTUSED(interp
);
4374 dupPtr
->internalRep
.dictSubstValue
.varNameObjPtr
=
4375 srcPtr
->internalRep
.dictSubstValue
.varNameObjPtr
;
4376 dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
= srcPtr
->internalRep
.dictSubstValue
.indexObjPtr
;
4377 dupPtr
->typePtr
= &dictSubstObjType
;
4380 /* Note: The object *must* be in dict-sugar format */
4381 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4383 if (objPtr
->typePtr
!= &dictSubstObjType
) {
4384 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4386 if (objPtr
->typePtr
== &interpolatedObjType
) {
4387 /* An interpolated object in dict-sugar form */
4389 const ScriptToken
*token
= objPtr
->internalRep
.twoPtrValue
.ptr1
;
4391 varObjPtr
= token
[0].objPtr
;
4392 keyObjPtr
= objPtr
->internalRep
.twoPtrValue
.ptr2
;
4394 Jim_IncrRefCount(varObjPtr
);
4395 Jim_IncrRefCount(keyObjPtr
);
4398 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
4401 Jim_FreeIntRep(interp
, objPtr
);
4402 objPtr
->typePtr
= &dictSubstObjType
;
4403 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= varObjPtr
;
4404 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= keyObjPtr
;
4408 /* This function is used to expand [dict get] sugar in the form
4409 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4410 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4411 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4412 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4413 * the [dict]ionary contained in variable VARNAME. */
4414 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4416 Jim_Obj
*resObjPtr
= NULL
;
4417 Jim_Obj
*substKeyObjPtr
= NULL
;
4419 SetDictSubstFromAny(interp
, objPtr
);
4421 if (Jim_SubstObj(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
,
4422 &substKeyObjPtr
, JIM_NONE
)
4426 Jim_IncrRefCount(substKeyObjPtr
);
4428 JimDictExpandArrayVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4430 Jim_DecrRefCount(interp
, substKeyObjPtr
);
4435 static Jim_Obj
*JimExpandExprSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4437 Jim_Obj
*resultObjPtr
;
4439 if (Jim_EvalExpression(interp
, objPtr
, &resultObjPtr
) == JIM_OK
) {
4440 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4441 resultObjPtr
->refCount
--;
4442 return resultObjPtr
;
4447 /* -----------------------------------------------------------------------------
4449 * ---------------------------------------------------------------------------*/
4451 static Jim_CallFrame
*JimCreateCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*parent
)
4455 if (interp
->freeFramesList
) {
4456 cf
= interp
->freeFramesList
;
4457 interp
->freeFramesList
= cf
->nextFramePtr
;
4460 cf
= Jim_Alloc(sizeof(*cf
));
4461 cf
->vars
.table
= NULL
;
4464 cf
->id
= interp
->callFrameEpoch
++;
4465 cf
->parentCallFrame
= parent
;
4466 cf
->level
= parent
? parent
->level
+ 1 : 0;
4469 cf
->procArgsObjPtr
= NULL
;
4470 cf
->procBodyObjPtr
= NULL
;
4471 cf
->nextFramePtr
= NULL
;
4472 cf
->staticVars
= NULL
;
4473 if (cf
->vars
.table
== NULL
)
4474 Jim_InitHashTable(&cf
->vars
, &JimVariablesHashTableType
, interp
);
4478 /* Used to invalidate every caching related to callframe stability. */
4479 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
)
4481 cf
->id
= interp
->callFrameEpoch
++;
4484 #define JIM_FCF_NONE 0 /* no flags */
4485 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4486 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
)
4488 if (cf
->procArgsObjPtr
)
4489 Jim_DecrRefCount(interp
, cf
->procArgsObjPtr
);
4490 if (cf
->procBodyObjPtr
)
4491 Jim_DecrRefCount(interp
, cf
->procBodyObjPtr
);
4492 if (!(flags
& JIM_FCF_NOHT
))
4493 Jim_FreeHashTable(&cf
->vars
);
4496 Jim_HashEntry
**table
= cf
->vars
.table
, *he
;
4498 for (i
= 0; i
< JIM_HT_INITIAL_SIZE
; i
++) {
4500 while (he
!= NULL
) {
4501 Jim_HashEntry
*nextEntry
= he
->next
;
4502 Jim_Var
*varPtr
= (void *)he
->u
.val
;
4504 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
4505 Jim_Free(he
->u
.val
);
4506 Jim_Free((void *)he
->key
); /* ATTENTION: const cast */
4514 cf
->nextFramePtr
= interp
->freeFramesList
;
4515 interp
->freeFramesList
= cf
;
4518 /* -----------------------------------------------------------------------------
4520 * ---------------------------------------------------------------------------*/
4521 #ifdef JIM_REFERENCES
4523 /* References HashTable Type.
4525 * Keys are jim_wide integers, dynamically allocated for now but in the
4526 * future it's worth to cache this 8 bytes objects. Values are poitners
4527 * to Jim_References. */
4528 static void JimReferencesHTValDestructor(void *interp
, void *val
)
4530 Jim_Reference
*refPtr
= (void *)val
;
4532 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
4533 if (refPtr
->finalizerCmdNamePtr
!= NULL
) {
4534 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4539 static unsigned int JimReferencesHTHashFunction(const void *key
)
4541 /* Only the least significant bits are used. */
4542 const jim_wide
*widePtr
= key
;
4543 unsigned int intValue
= (unsigned int)*widePtr
;
4545 return Jim_IntHashFunction(intValue
);
4548 static const void *JimReferencesHTKeyDup(void *privdata
, const void *key
)
4550 void *copy
= Jim_Alloc(sizeof(jim_wide
));
4552 JIM_NOTUSED(privdata
);
4554 memcpy(copy
, key
, sizeof(jim_wide
));
4558 static int JimReferencesHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
4560 JIM_NOTUSED(privdata
);
4562 return memcmp(key1
, key2
, sizeof(jim_wide
)) == 0;
4565 static void JimReferencesHTKeyDestructor(void *privdata
, const void *key
)
4567 JIM_NOTUSED(privdata
);
4569 Jim_Free((void *)key
);
4572 static const Jim_HashTableType JimReferencesHashTableType
= {
4573 JimReferencesHTHashFunction
, /* hash function */
4574 JimReferencesHTKeyDup
, /* key dup */
4576 JimReferencesHTKeyCompare
, /* key compare */
4577 JimReferencesHTKeyDestructor
, /* key destructor */
4578 JimReferencesHTValDestructor
/* val destructor */
4581 /* -----------------------------------------------------------------------------
4582 * Reference object type and References API
4583 * ---------------------------------------------------------------------------*/
4585 /* The string representation of references has two features in order
4586 * to make the GC faster. The first is that every reference starts
4587 * with a non common character '<', in order to make the string matching
4588 * faster. The second is that the reference string rep is 42 characters
4589 * in length, this allows to avoid to check every object with a string
4590 * repr < 42, and usually there aren't many of these objects. */
4592 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4594 static int JimFormatReference(char *buf
, Jim_Reference
*refPtr
, jim_wide id
)
4596 const char *fmt
= "<reference.<%s>.%020" JIM_WIDE_MODIFIER
">";
4598 sprintf(buf
, fmt
, refPtr
->tag
, id
);
4599 return JIM_REFERENCE_SPACE
;
4602 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
);
4604 static const Jim_ObjType referenceObjType
= {
4608 UpdateStringOfReference
,
4609 JIM_TYPE_REFERENCES
,
4612 void UpdateStringOfReference(struct Jim_Obj
*objPtr
)
4615 char buf
[JIM_REFERENCE_SPACE
+ 1];
4616 Jim_Reference
*refPtr
;
4618 refPtr
= objPtr
->internalRep
.refValue
.refPtr
;
4619 len
= JimFormatReference(buf
, refPtr
, objPtr
->internalRep
.refValue
.id
);
4620 objPtr
->bytes
= Jim_Alloc(len
+ 1);
4621 memcpy(objPtr
->bytes
, buf
, len
+ 1);
4622 objPtr
->length
= len
;
4625 /* returns true if 'c' is a valid reference tag character.
4626 * i.e. inside the range [_a-zA-Z0-9] */
4627 static int isrefchar(int c
)
4629 return (c
== '_' || isalnum(c
));
4632 static int SetReferenceFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4636 const char *str
, *start
, *end
;
4638 Jim_Reference
*refPtr
;
4641 /* Get the string representation */
4642 str
= Jim_GetString(objPtr
, &len
);
4643 /* Check if it looks like a reference */
4644 if (len
< JIM_REFERENCE_SPACE
)
4648 end
= str
+ len
- 1;
4649 while (*start
== ' ')
4651 while (*end
== ' ' && end
> start
)
4653 if (end
- start
+ 1 != JIM_REFERENCE_SPACE
)
4655 /* <reference.<1234567>.%020> */
4656 if (memcmp(start
, "<reference.<", 12) != 0)
4658 if (start
[12 + JIM_REFERENCE_TAGLEN
] != '>' || end
[0] != '>')
4660 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4661 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4662 if (!isrefchar(start
[12 + i
]))
4665 /* Extract info from the reference. */
4666 memcpy(refId
, start
+ 14 + JIM_REFERENCE_TAGLEN
, 20);
4668 /* Try to convert the ID into a jim_wide */
4669 if (Jim_StringToWide(refId
, &wideValue
, 10) != JIM_OK
)
4671 /* Check if the reference really exists! */
4672 he
= Jim_FindHashEntry(&interp
->references
, &wideValue
);
4674 Jim_SetResultFormatted(interp
, "invalid reference id \"%#s\"", objPtr
);
4678 /* Free the old internal repr and set the new one. */
4679 Jim_FreeIntRep(interp
, objPtr
);
4680 objPtr
->typePtr
= &referenceObjType
;
4681 objPtr
->internalRep
.refValue
.id
= wideValue
;
4682 objPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4686 Jim_SetResultFormatted(interp
, "expected reference but got \"%#s\"", objPtr
);
4690 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4691 * as finalizer command (or NULL if there is no finalizer).
4692 * The returned reference object has refcount = 0. */
4693 Jim_Obj
*Jim_NewReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*tagPtr
, Jim_Obj
*cmdNamePtr
)
4695 struct Jim_Reference
*refPtr
;
4696 jim_wide wideValue
= interp
->referenceNextId
;
4701 /* Perform the Garbage Collection if needed. */
4702 Jim_CollectIfNeeded(interp
);
4704 refPtr
= Jim_Alloc(sizeof(*refPtr
));
4705 refPtr
->objPtr
= objPtr
;
4706 Jim_IncrRefCount(objPtr
);
4707 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4709 Jim_IncrRefCount(cmdNamePtr
);
4710 Jim_AddHashEntry(&interp
->references
, &wideValue
, refPtr
);
4711 refObjPtr
= Jim_NewObj(interp
);
4712 refObjPtr
->typePtr
= &referenceObjType
;
4713 refObjPtr
->bytes
= NULL
;
4714 refObjPtr
->internalRep
.refValue
.id
= interp
->referenceNextId
;
4715 refObjPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4716 interp
->referenceNextId
++;
4717 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4718 * that does not pass the 'isrefchar' test is replaced with '_' */
4719 tag
= Jim_GetString(tagPtr
, &tagLen
);
4720 if (tagLen
> JIM_REFERENCE_TAGLEN
)
4721 tagLen
= JIM_REFERENCE_TAGLEN
;
4722 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4723 if (i
< tagLen
&& isrefchar(tag
[i
]))
4724 refPtr
->tag
[i
] = tag
[i
];
4726 refPtr
->tag
[i
] = '_';
4728 refPtr
->tag
[JIM_REFERENCE_TAGLEN
] = '\0';
4732 Jim_Reference
*Jim_GetReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4734 if (objPtr
->typePtr
!= &referenceObjType
&& SetReferenceFromAny(interp
, objPtr
) == JIM_ERR
)
4736 return objPtr
->internalRep
.refValue
.refPtr
;
4739 int Jim_SetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*cmdNamePtr
)
4741 Jim_Reference
*refPtr
;
4743 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4745 Jim_IncrRefCount(cmdNamePtr
);
4746 if (refPtr
->finalizerCmdNamePtr
)
4747 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4748 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4752 int Jim_GetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
**cmdNamePtrPtr
)
4754 Jim_Reference
*refPtr
;
4756 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4758 *cmdNamePtrPtr
= refPtr
->finalizerCmdNamePtr
;
4762 /* -----------------------------------------------------------------------------
4763 * References Garbage Collection
4764 * ---------------------------------------------------------------------------*/
4766 /* This the hash table type for the "MARK" phase of the GC */
4767 static const Jim_HashTableType JimRefMarkHashTableType
= {
4768 JimReferencesHTHashFunction
, /* hash function */
4769 JimReferencesHTKeyDup
, /* key dup */
4771 JimReferencesHTKeyCompare
, /* key compare */
4772 JimReferencesHTKeyDestructor
, /* key destructor */
4773 NULL
/* val destructor */
4776 /* Performs the garbage collection. */
4777 int Jim_Collect(Jim_Interp
*interp
)
4779 Jim_HashTable marks
;
4780 Jim_HashTableIterator
*htiter
;
4785 /* Avoid recursive calls */
4786 if (interp
->lastCollectId
== -1) {
4787 /* Jim_Collect() already running. Return just now. */
4790 interp
->lastCollectId
= -1;
4792 /* Mark all the references found into the 'mark' hash table.
4793 * The references are searched in every live object that
4794 * is of a type that can contain references. */
4795 Jim_InitHashTable(&marks
, &JimRefMarkHashTableType
, NULL
);
4796 objPtr
= interp
->liveList
;
4798 if (objPtr
->typePtr
== NULL
|| objPtr
->typePtr
->flags
& JIM_TYPE_REFERENCES
) {
4799 const char *str
, *p
;
4802 /* If the object is of type reference, to get the
4803 * Id is simple... */
4804 if (objPtr
->typePtr
== &referenceObjType
) {
4805 Jim_AddHashEntry(&marks
, &objPtr
->internalRep
.refValue
.id
, NULL
);
4807 printf("MARK (reference): %d refcount: %d" JIM_NL
,
4808 (int)objPtr
->internalRep
.refValue
.id
, objPtr
->refCount
);
4810 objPtr
= objPtr
->nextObjPtr
;
4813 /* Get the string repr of the object we want
4814 * to scan for references. */
4815 p
= str
= Jim_GetString(objPtr
, &len
);
4816 /* Skip objects too little to contain references. */
4817 if (len
< JIM_REFERENCE_SPACE
) {
4818 objPtr
= objPtr
->nextObjPtr
;
4821 /* Extract references from the object string repr. */
4827 if ((p
= strstr(p
, "<reference.<")) == NULL
)
4829 /* Check if it's a valid reference. */
4830 if (len
- (p
- str
) < JIM_REFERENCE_SPACE
)
4832 if (p
[41] != '>' || p
[19] != '>' || p
[20] != '.')
4834 for (i
= 21; i
<= 40; i
++)
4835 if (!isdigit(UCHAR(p
[i
])))
4838 memcpy(buf
, p
+ 21, 20);
4840 Jim_StringToWide(buf
, &id
, 10);
4842 /* Ok, a reference for the given ID
4843 * was found. Mark it. */
4844 Jim_AddHashEntry(&marks
, &id
, NULL
);
4846 printf("MARK: %d" JIM_NL
, (int)id
);
4848 p
+= JIM_REFERENCE_SPACE
;
4851 objPtr
= objPtr
->nextObjPtr
;
4854 /* Run the references hash table to destroy every reference that
4855 * is not referenced outside (not present in the mark HT). */
4856 htiter
= Jim_GetHashTableIterator(&interp
->references
);
4857 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
4858 const jim_wide
*refId
;
4859 Jim_Reference
*refPtr
;
4862 /* Check if in the mark phase we encountered
4863 * this reference. */
4864 if (Jim_FindHashEntry(&marks
, refId
) == NULL
) {
4866 printf("COLLECTING %d" JIM_NL
, (int)*refId
);
4869 /* Drop the reference, but call the
4870 * finalizer first if registered. */
4872 if (refPtr
->finalizerCmdNamePtr
) {
4873 char *refstr
= Jim_Alloc(JIM_REFERENCE_SPACE
+ 1);
4874 Jim_Obj
*objv
[3], *oldResult
;
4876 JimFormatReference(refstr
, refPtr
, *refId
);
4878 objv
[0] = refPtr
->finalizerCmdNamePtr
;
4879 objv
[1] = Jim_NewStringObjNoAlloc(interp
, refstr
, 32);
4880 objv
[2] = refPtr
->objPtr
;
4881 Jim_IncrRefCount(objv
[0]);
4882 Jim_IncrRefCount(objv
[1]);
4883 Jim_IncrRefCount(objv
[2]);
4885 /* Drop the reference itself */
4886 Jim_DeleteHashEntry(&interp
->references
, refId
);
4888 /* Call the finalizer. Errors ignored. */
4889 oldResult
= interp
->result
;
4890 Jim_IncrRefCount(oldResult
);
4891 Jim_EvalObjVector(interp
, 3, objv
);
4892 Jim_SetResult(interp
, oldResult
);
4893 Jim_DecrRefCount(interp
, oldResult
);
4895 Jim_DecrRefCount(interp
, objv
[0]);
4896 Jim_DecrRefCount(interp
, objv
[1]);
4897 Jim_DecrRefCount(interp
, objv
[2]);
4900 Jim_DeleteHashEntry(&interp
->references
, refId
);
4904 Jim_FreeHashTableIterator(htiter
);
4905 Jim_FreeHashTable(&marks
);
4906 interp
->lastCollectId
= interp
->referenceNextId
;
4907 interp
->lastCollectTime
= time(NULL
);
4911 #define JIM_COLLECT_ID_PERIOD 5000
4912 #define JIM_COLLECT_TIME_PERIOD 300
4914 void Jim_CollectIfNeeded(Jim_Interp
*interp
)
4919 elapsedId
= interp
->referenceNextId
- interp
->lastCollectId
;
4920 elapsedTime
= time(NULL
) - interp
->lastCollectTime
;
4923 if (elapsedId
> JIM_COLLECT_ID_PERIOD
|| elapsedTime
> JIM_COLLECT_TIME_PERIOD
) {
4924 Jim_Collect(interp
);
4929 static int JimIsBigEndian(void)
4936 return uval
.c
[0] == 1;
4939 /* -----------------------------------------------------------------------------
4940 * Interpreter related functions
4941 * ---------------------------------------------------------------------------*/
4943 Jim_Interp
*Jim_CreateInterp(void)
4945 Jim_Interp
*i
= Jim_Alloc(sizeof(*i
));
4947 memset(i
, 0, sizeof(*i
));
4949 i
->maxNestingDepth
= JIM_MAX_NESTING_DEPTH
;
4950 i
->lastCollectTime
= time(NULL
);
4952 /* Note that we can create objects only after the
4953 * interpreter liveList and freeList pointers are
4954 * initialized to NULL. */
4955 Jim_InitHashTable(&i
->commands
, &JimCommandsHashTableType
, i
);
4956 #ifdef JIM_REFERENCES
4957 Jim_InitHashTable(&i
->references
, &JimReferencesHashTableType
, i
);
4959 Jim_InitHashTable(&i
->assocData
, &JimAssocDataHashTableType
, i
);
4960 Jim_InitHashTable(&i
->packages
, &JimStringKeyValCopyHashTableType
, NULL
);
4961 i
->framePtr
= i
->topFramePtr
= JimCreateCallFrame(i
, NULL
);
4962 i
->emptyObj
= Jim_NewEmptyStringObj(i
);
4963 i
->trueObj
= Jim_NewIntObj(i
, 1);
4964 i
->falseObj
= Jim_NewIntObj(i
, 0);
4965 i
->errorFileNameObj
= i
->emptyObj
;
4966 i
->result
= i
->emptyObj
;
4967 i
->stackTrace
= Jim_NewListObj(i
, NULL
, 0);
4968 i
->unknown
= Jim_NewStringObj(i
, "unknown", -1);
4969 i
->errorProc
= i
->emptyObj
;
4970 i
->currentScriptObj
= Jim_NewEmptyStringObj(i
);
4971 Jim_IncrRefCount(i
->emptyObj
);
4972 Jim_IncrRefCount(i
->errorFileNameObj
);
4973 Jim_IncrRefCount(i
->result
);
4974 Jim_IncrRefCount(i
->stackTrace
);
4975 Jim_IncrRefCount(i
->unknown
);
4976 Jim_IncrRefCount(i
->currentScriptObj
);
4977 Jim_IncrRefCount(i
->errorProc
);
4978 Jim_IncrRefCount(i
->trueObj
);
4979 Jim_IncrRefCount(i
->falseObj
);
4981 /* Initialize key variables every interpreter should contain */
4982 Jim_SetVariableStrWithStr(i
, JIM_LIBPATH
, TCL_LIBRARY
);
4983 Jim_SetVariableStrWithStr(i
, JIM_INTERACTIVE
, "0");
4985 Jim_SetVariableStrWithStr(i
, "tcl_platform(os)", TCL_PLATFORM_OS
);
4986 Jim_SetVariableStrWithStr(i
, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM
);
4987 Jim_SetVariableStrWithStr(i
, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR
);
4988 Jim_SetVariableStrWithStr(i
, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4989 Jim_SetVariableStrWithStr(i
, "tcl_platform(threaded)", "0");
4990 Jim_SetVariableStr(i
, "tcl_platform(pointerSize)", Jim_NewIntObj(i
, sizeof(void *)));
4991 Jim_SetVariableStr(i
, "tcl_platform(wordSize)", Jim_NewIntObj(i
, sizeof(jim_wide
)));
4996 void Jim_FreeInterp(Jim_Interp
*i
)
4998 Jim_CallFrame
*cf
= i
->framePtr
, *prevcf
, *nextcf
;
4999 Jim_Obj
*objPtr
, *nextObjPtr
;
5001 Jim_DecrRefCount(i
, i
->emptyObj
);
5002 Jim_DecrRefCount(i
, i
->trueObj
);
5003 Jim_DecrRefCount(i
, i
->falseObj
);
5004 Jim_DecrRefCount(i
, i
->result
);
5005 Jim_DecrRefCount(i
, i
->stackTrace
);
5006 Jim_DecrRefCount(i
, i
->errorProc
);
5007 Jim_DecrRefCount(i
, i
->unknown
);
5008 Jim_DecrRefCount(i
, i
->errorFileNameObj
);
5009 Jim_DecrRefCount(i
, i
->currentScriptObj
);
5010 Jim_FreeHashTable(&i
->commands
);
5011 #ifdef JIM_REFERENCES
5012 Jim_FreeHashTable(&i
->references
);
5014 Jim_FreeHashTable(&i
->packages
);
5015 Jim_Free(i
->prngState
);
5016 Jim_FreeHashTable(&i
->assocData
);
5017 JimDeleteLocalProcs(i
);
5019 /* Free the call frames list */
5021 prevcf
= cf
->parentCallFrame
;
5022 JimFreeCallFrame(i
, cf
, JIM_FCF_NONE
);
5025 /* Check that the live object list is empty, otherwise
5026 * there is a memory leak. */
5027 if (i
->liveList
!= NULL
) {
5028 objPtr
= i
->liveList
;
5030 printf(JIM_NL
"-------------------------------------" JIM_NL
);
5031 printf("Objects still in the free list:" JIM_NL
);
5033 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "string";
5035 printf("%p (%d) %-10s: '%.20s'" JIM_NL
,
5036 (void *)objPtr
, objPtr
->refCount
, type
, objPtr
->bytes
? objPtr
->bytes
: "(null)");
5037 if (objPtr
->typePtr
== &sourceObjType
) {
5038 printf("FILE %s LINE %d" JIM_NL
,
5039 Jim_String(objPtr
->internalRep
.sourceValue
.fileNameObj
),
5040 objPtr
->internalRep
.sourceValue
.lineNumber
);
5042 objPtr
= objPtr
->nextObjPtr
;
5044 printf("-------------------------------------" JIM_NL JIM_NL
);
5045 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5047 /* Free all the freed objects. */
5048 objPtr
= i
->freeList
;
5050 nextObjPtr
= objPtr
->nextObjPtr
;
5052 objPtr
= nextObjPtr
;
5054 /* Free cached CallFrame structures */
5055 cf
= i
->freeFramesList
;
5057 nextcf
= cf
->nextFramePtr
;
5058 if (cf
->vars
.table
!= NULL
)
5059 Jim_Free(cf
->vars
.table
);
5064 Jim_FreeLoadHandles(i
);
5067 /* Free the interpreter structure. */
5071 /* Returns the call frame relative to the level represented by
5072 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5074 * This function accepts the 'level' argument in the form
5075 * of the commands [uplevel] and [upvar].
5077 * For a function accepting a relative integer as level suitable
5078 * for implementation of [info level ?level?] check the
5079 * JimGetCallFrameByInteger() function.
5081 * Returns NULL on error.
5083 Jim_CallFrame
*Jim_GetCallFrameByLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5087 Jim_CallFrame
*framePtr
;
5090 str
= Jim_String(levelObjPtr
);
5091 if (str
[0] == '#') {
5094 level
= strtol(str
+ 1, &endptr
, 0);
5095 if (str
[1] == '\0' || endptr
[0] != '\0') {
5100 if (Jim_GetLong(interp
, levelObjPtr
, &level
) != JIM_OK
|| level
< 0) {
5104 /* Convert from a relative to an absolute level */
5105 level
= interp
->framePtr
->level
- level
;
5110 str
= "1"; /* Needed to format the error message. */
5111 level
= interp
->framePtr
->level
- 1;
5115 return interp
->topFramePtr
;
5119 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5120 if (framePtr
->level
== level
) {
5126 Jim_SetResultFormatted(interp
, "bad level \"%s\"", str
);
5130 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5131 * as a relative integer like in the [info level ?level?] command.
5133 static Jim_CallFrame
*JimGetCallFrameByInteger(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5136 Jim_CallFrame
*framePtr
;
5138 if (Jim_GetLong(interp
, levelObjPtr
, &level
) == JIM_OK
) {
5140 /* Convert from a relative to an absolute level */
5141 level
= interp
->framePtr
->level
+ level
;
5145 return interp
->topFramePtr
;
5149 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5150 if (framePtr
->level
== level
) {
5156 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
5160 static void JimResetStackTrace(Jim_Interp
*interp
)
5162 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5163 interp
->stackTrace
= Jim_NewListObj(interp
, NULL
, 0);
5164 Jim_IncrRefCount(interp
->stackTrace
);
5167 static void JimSetStackTrace(Jim_Interp
*interp
, Jim_Obj
*stackTraceObj
)
5171 /* Increment reference first in case these are the same object */
5172 Jim_IncrRefCount(stackTraceObj
);
5173 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5174 interp
->stackTrace
= stackTraceObj
;
5175 interp
->errorFlag
= 1;
5177 /* This is a bit ugly.
5178 * If the filename of the last entry of the stack trace is empty,
5179 * the next stack level should be added.
5181 len
= Jim_ListLength(interp
, interp
->stackTrace
);
5183 Jim_Obj
*filenameObj
;
5185 Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &filenameObj
, JIM_NONE
);
5187 Jim_GetString(filenameObj
, &len
);
5190 interp
->addStackTrace
= 1;
5195 /* Returns 1 if the stack trace information was used or 0 if not */
5196 static void JimAppendStackTrace(Jim_Interp
*interp
, const char *procname
,
5197 Jim_Obj
*fileNameObj
, int linenr
)
5199 if (strcmp(procname
, "unknown") == 0) {
5202 if (!*procname
&& !Jim_Length(fileNameObj
)) {
5203 /* No useful info here */
5207 if (Jim_IsShared(interp
->stackTrace
)) {
5208 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5209 interp
->stackTrace
= Jim_DuplicateObj(interp
, interp
->stackTrace
);
5210 Jim_IncrRefCount(interp
->stackTrace
);
5213 /* If we have no procname but the previous element did, merge with that frame */
5214 if (!*procname
&& Jim_Length(fileNameObj
)) {
5215 /* Just a filename. Check the previous entry */
5216 int len
= Jim_ListLength(interp
, interp
->stackTrace
);
5220 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 3, &objPtr
, JIM_NONE
) == JIM_OK
&& Jim_Length(objPtr
)) {
5221 /* Yes, the previous level had procname */
5222 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &objPtr
, JIM_NONE
) == JIM_OK
&& !Jim_Length(objPtr
)) {
5223 /* But no filename, so merge the new info with that frame */
5224 ListSetIndex(interp
, interp
->stackTrace
, len
- 2, fileNameObj
, 0);
5225 ListSetIndex(interp
, interp
->stackTrace
, len
- 1, Jim_NewIntObj(interp
, linenr
), 0);
5232 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewStringObj(interp
, procname
, -1));
5233 Jim_ListAppendElement(interp
, interp
->stackTrace
, fileNameObj
);
5234 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewIntObj(interp
, linenr
));
5237 int Jim_SetAssocData(Jim_Interp
*interp
, const char *key
, Jim_InterpDeleteProc
* delProc
,
5240 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) Jim_Alloc(sizeof(AssocDataValue
));
5242 assocEntryPtr
->delProc
= delProc
;
5243 assocEntryPtr
->data
= data
;
5244 return Jim_AddHashEntry(&interp
->assocData
, key
, assocEntryPtr
);
5247 void *Jim_GetAssocData(Jim_Interp
*interp
, const char *key
)
5249 Jim_HashEntry
*entryPtr
= Jim_FindHashEntry(&interp
->assocData
, key
);
5251 if (entryPtr
!= NULL
) {
5252 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) entryPtr
->u
.val
;
5254 return assocEntryPtr
->data
;
5259 int Jim_DeleteAssocData(Jim_Interp
*interp
, const char *key
)
5261 return Jim_DeleteHashEntry(&interp
->assocData
, key
);
5264 int Jim_GetExitCode(Jim_Interp
*interp
)
5266 return interp
->exitCode
;
5269 /* -----------------------------------------------------------------------------
5271 * ---------------------------------------------------------------------------*/
5272 #define JIM_INTEGER_SPACE 24
5274 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
);
5275 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
5277 static const Jim_ObjType intObjType
= {
5285 /* A coerced double is closer to an int than a double.
5286 * It is an int value temporarily masquerading as a double value.
5287 * i.e. it has the same string value as an int and Jim_GetWide()
5288 * succeeds, but also Jim_GetDouble() returns the value directly.
5290 static const Jim_ObjType coercedDoubleObjType
= {
5299 void UpdateStringOfInt(struct Jim_Obj
*objPtr
)
5302 char buf
[JIM_INTEGER_SPACE
+ 1];
5304 len
= Jim_WideToString(buf
, JimWideValue(objPtr
));
5305 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5306 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5307 objPtr
->length
= len
;
5310 int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
5315 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5316 /* Simple switcheroo */
5317 objPtr
->typePtr
= &intObjType
;
5321 /* Get the string representation */
5322 str
= Jim_String(objPtr
);
5323 /* Try to convert into a jim_wide */
5324 if (Jim_StringToWide(str
, &wideValue
, 0) != JIM_OK
) {
5325 if (flags
& JIM_ERRMSG
) {
5326 Jim_SetResultFormatted(interp
, "expected integer but got \"%#s\"", objPtr
);
5330 if ((wideValue
== JIM_WIDE_MIN
|| wideValue
== JIM_WIDE_MAX
) && errno
== ERANGE
) {
5331 Jim_SetResultString(interp
, "Integer value too big to be represented", -1);
5334 /* Free the old internal repr and set the new one. */
5335 Jim_FreeIntRep(interp
, objPtr
);
5336 objPtr
->typePtr
= &intObjType
;
5337 objPtr
->internalRep
.wideValue
= wideValue
;
5341 #ifdef JIM_OPTIMIZATION
5342 static int JimIsWide(Jim_Obj
*objPtr
)
5344 return objPtr
->typePtr
== &intObjType
;
5348 int Jim_GetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5350 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
5352 *widePtr
= JimWideValue(objPtr
);
5356 /* Get a wide but does not set an error if the format is bad. */
5357 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5359 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_NONE
) == JIM_ERR
)
5361 *widePtr
= JimWideValue(objPtr
);
5365 int Jim_GetLong(Jim_Interp
*interp
, Jim_Obj
*objPtr
, long *longPtr
)
5370 retval
= Jim_GetWide(interp
, objPtr
, &wideValue
);
5371 if (retval
== JIM_OK
) {
5372 *longPtr
= (long)wideValue
;
5378 Jim_Obj
*Jim_NewIntObj(Jim_Interp
*interp
, jim_wide wideValue
)
5382 objPtr
= Jim_NewObj(interp
);
5383 objPtr
->typePtr
= &intObjType
;
5384 objPtr
->bytes
= NULL
;
5385 objPtr
->internalRep
.wideValue
= wideValue
;
5389 /* -----------------------------------------------------------------------------
5391 * ---------------------------------------------------------------------------*/
5392 #define JIM_DOUBLE_SPACE 30
5394 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
);
5395 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5397 static const Jim_ObjType doubleObjType
= {
5401 UpdateStringOfDouble
,
5405 void UpdateStringOfDouble(struct Jim_Obj
*objPtr
)
5408 char buf
[JIM_DOUBLE_SPACE
+ 1];
5410 len
= Jim_DoubleToString(buf
, objPtr
->internalRep
.doubleValue
);
5411 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5412 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5413 objPtr
->length
= len
;
5416 int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5422 /* Preserve the string representation.
5423 * Needed so we can convert back to int without loss
5425 str
= Jim_String(objPtr
);
5427 #ifdef HAVE_LONG_LONG
5428 /* Assume a 53 bit mantissa */
5429 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5430 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5432 if (objPtr
->typePtr
== &intObjType
5433 && JimWideValue(objPtr
) >= MIN_INT_IN_DOUBLE
5434 && JimWideValue(objPtr
) <= MAX_INT_IN_DOUBLE
) {
5436 /* Direct conversion to coerced double */
5437 objPtr
->typePtr
= &coercedDoubleObjType
;
5442 if (Jim_StringToWide(str
, &wideValue
, 10) == JIM_OK
) {
5443 /* Managed to convert to an int, so we can use this as a cooerced double */
5444 Jim_FreeIntRep(interp
, objPtr
);
5445 objPtr
->typePtr
= &coercedDoubleObjType
;
5446 objPtr
->internalRep
.wideValue
= wideValue
;
5450 /* Try to convert into a double */
5451 if (Jim_StringToDouble(str
, &doubleValue
) != JIM_OK
) {
5452 Jim_SetResultFormatted(interp
, "expected number but got \"%#s\"", objPtr
);
5455 /* Free the old internal repr and set the new one. */
5456 Jim_FreeIntRep(interp
, objPtr
);
5458 objPtr
->typePtr
= &doubleObjType
;
5459 objPtr
->internalRep
.doubleValue
= doubleValue
;
5463 int Jim_GetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double *doublePtr
)
5465 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5466 *doublePtr
= JimWideValue(objPtr
);
5469 if (objPtr
->typePtr
!= &doubleObjType
&& SetDoubleFromAny(interp
, objPtr
) == JIM_ERR
)
5472 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5473 *doublePtr
= JimWideValue(objPtr
);
5476 *doublePtr
= objPtr
->internalRep
.doubleValue
;
5481 Jim_Obj
*Jim_NewDoubleObj(Jim_Interp
*interp
, double doubleValue
)
5485 objPtr
= Jim_NewObj(interp
);
5486 objPtr
->typePtr
= &doubleObjType
;
5487 objPtr
->bytes
= NULL
;
5488 objPtr
->internalRep
.doubleValue
= doubleValue
;
5492 /* -----------------------------------------------------------------------------
5494 * ---------------------------------------------------------------------------*/
5495 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
);
5496 static void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5497 static void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
5498 static void UpdateStringOfList(struct Jim_Obj
*objPtr
);
5499 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
5501 /* Note that while the elements of the list may contain references,
5502 * the list object itself can't. This basically means that the
5503 * list object string representation as a whole can't contain references
5504 * that are not presents in the single elements. */
5505 static const Jim_ObjType listObjType
= {
5507 FreeListInternalRep
,
5513 void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5517 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5518 Jim_DecrRefCount(interp
, objPtr
->internalRep
.listValue
.ele
[i
]);
5520 Jim_Free(objPtr
->internalRep
.listValue
.ele
);
5523 void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
5527 JIM_NOTUSED(interp
);
5529 dupPtr
->internalRep
.listValue
.len
= srcPtr
->internalRep
.listValue
.len
;
5530 dupPtr
->internalRep
.listValue
.maxLen
= srcPtr
->internalRep
.listValue
.maxLen
;
5531 dupPtr
->internalRep
.listValue
.ele
=
5532 Jim_Alloc(sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.maxLen
);
5533 memcpy(dupPtr
->internalRep
.listValue
.ele
, srcPtr
->internalRep
.listValue
.ele
,
5534 sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.len
);
5535 for (i
= 0; i
< dupPtr
->internalRep
.listValue
.len
; i
++) {
5536 Jim_IncrRefCount(dupPtr
->internalRep
.listValue
.ele
[i
]);
5538 dupPtr
->typePtr
= &listObjType
;
5541 /* The following function checks if a given string can be encoded
5542 * into a list element without any kind of quoting, surrounded by braces,
5543 * or using escapes to quote. */
5544 #define JIM_ELESTR_SIMPLE 0
5545 #define JIM_ELESTR_BRACE 1
5546 #define JIM_ELESTR_QUOTE 2
5547 static int ListElementQuotingType(const char *s
, int len
)
5549 int i
, level
, blevel
, trySimple
= 1;
5551 /* Try with the SIMPLE case */
5553 return JIM_ELESTR_BRACE
;
5555 return JIM_ELESTR_BRACE
;
5556 if (s
[0] == '"' || s
[0] == '{') {
5560 for (i
= 0; i
< len
; i
++) {
5580 return JIM_ELESTR_SIMPLE
;
5583 /* Test if it's possible to do with braces */
5584 if (s
[len
- 1] == '\\')
5585 return JIM_ELESTR_QUOTE
;
5588 for (i
= 0; i
< len
; i
++) {
5596 return JIM_ELESTR_QUOTE
;
5605 if (s
[i
+ 1] == '\n')
5606 return JIM_ELESTR_QUOTE
;
5607 else if (s
[i
+ 1] != '\0')
5613 return JIM_ELESTR_QUOTE
;
5618 return JIM_ELESTR_BRACE
;
5619 for (i
= 0; i
< len
; i
++) {
5633 return JIM_ELESTR_BRACE
;
5637 return JIM_ELESTR_SIMPLE
;
5639 return JIM_ELESTR_QUOTE
;
5642 /* Returns the malloc-ed representation of a string
5643 * using backslash to quote special chars. */
5644 static char *BackslashQuoteString(const char *s
, int len
, int *qlenPtr
)
5646 char *q
= Jim_Alloc(len
* 2 + 1), *p
;
5698 static void UpdateStringOfList(struct Jim_Obj
*objPtr
)
5700 int i
, bufLen
, realLength
;
5704 Jim_Obj
**ele
= objPtr
->internalRep
.listValue
.ele
;
5706 /* (Over) Estimate the space needed. */
5707 quotingType
= Jim_Alloc(sizeof(int) * objPtr
->internalRep
.listValue
.len
+ 1);
5709 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5712 strRep
= Jim_GetString(ele
[i
], &len
);
5713 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
5714 switch (quotingType
[i
]) {
5715 case JIM_ELESTR_SIMPLE
:
5718 case JIM_ELESTR_BRACE
:
5721 case JIM_ELESTR_QUOTE
:
5725 bufLen
++; /* elements separator. */
5729 /* Generate the string rep. */
5730 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
5732 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5736 strRep
= Jim_GetString(ele
[i
], &len
);
5738 switch (quotingType
[i
]) {
5739 case JIM_ELESTR_SIMPLE
:
5740 memcpy(p
, strRep
, len
);
5744 case JIM_ELESTR_BRACE
:
5746 memcpy(p
, strRep
, len
);
5749 realLength
+= len
+ 2;
5751 case JIM_ELESTR_QUOTE
:
5752 q
= BackslashQuoteString(strRep
, len
, &qlen
);
5759 /* Add a separating space */
5760 if (i
+ 1 != objPtr
->internalRep
.listValue
.len
) {
5765 *p
= '\0'; /* nul term. */
5766 objPtr
->length
= realLength
;
5767 Jim_Free(quotingType
);
5770 int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
5772 struct JimParserCtx parser
;
5775 Jim_Obj
*fileNameObj
;
5778 /* Try to preserve information about filename / line number */
5779 if (objPtr
->typePtr
== &sourceObjType
) {
5780 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
5781 linenr
= objPtr
->internalRep
.sourceValue
.lineNumber
;
5784 fileNameObj
= interp
->emptyObj
;
5787 Jim_IncrRefCount(fileNameObj
);
5788 //printf("%s:%d incr %s\n", __FILE__, __LINE__, Jim_String(fileNameObj));
5790 /* Get the string representation */
5791 str
= Jim_GetString(objPtr
, &strLen
);
5793 /* Free the old internal repr just now and initialize the
5794 * new one just now. The string->list conversion can't fail. */
5795 Jim_FreeIntRep(interp
, objPtr
);
5796 objPtr
->typePtr
= &listObjType
;
5797 objPtr
->internalRep
.listValue
.len
= 0;
5798 objPtr
->internalRep
.listValue
.maxLen
= 0;
5799 objPtr
->internalRep
.listValue
.ele
= NULL
;
5801 /* Convert into a list */
5802 JimParserInit(&parser
, str
, strLen
, linenr
);
5803 while (!parser
.eof
) {
5804 Jim_Obj
*elementPtr
;
5806 JimParseList(&parser
);
5807 if (parser
.tt
!= JIM_TT_STR
&& parser
.tt
!= JIM_TT_ESC
)
5809 elementPtr
= JimParserGetTokenObj(interp
, &parser
);
5810 JimSetSourceInfo(interp
, elementPtr
, fileNameObj
, parser
.tline
);
5811 ListAppendElement(objPtr
, elementPtr
);
5813 Jim_DecrRefCount(interp
, fileNameObj
);
5817 Jim_Obj
*Jim_NewListObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
5822 objPtr
= Jim_NewObj(interp
);
5823 objPtr
->typePtr
= &listObjType
;
5824 objPtr
->bytes
= NULL
;
5825 objPtr
->internalRep
.listValue
.ele
= NULL
;
5826 objPtr
->internalRep
.listValue
.len
= 0;
5827 objPtr
->internalRep
.listValue
.maxLen
= 0;
5828 for (i
= 0; i
< len
; i
++) {
5829 ListAppendElement(objPtr
, elements
[i
]);
5834 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5835 * length of the vector. Note that the user of this function should make
5836 * sure that the list object can't shimmer while the vector returned
5837 * is in use, this vector is the one stored inside the internal representation
5838 * of the list object. This function is not exported, extensions should
5839 * always access to the List object elements using Jim_ListIndex(). */
5840 static void JimListGetElements(Jim_Interp
*interp
, Jim_Obj
*listObj
, int *listLen
,
5843 *listLen
= Jim_ListLength(interp
, listObj
);
5844 *listVec
= listObj
->internalRep
.listValue
.ele
;
5847 /* Sorting uses ints, but commands may return wide */
5848 static int JimSign(jim_wide w
)
5859 /* ListSortElements type values */
5873 int (*subfn
)(Jim_Obj
**, Jim_Obj
**);
5876 static struct lsort_info
*sort_info
;
5878 static int ListSortIndexHelper(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5880 Jim_Obj
*lObj
, *rObj
;
5882 if (Jim_ListIndex(sort_info
->interp
, *lhsObj
, sort_info
->index
, &lObj
, JIM_ERRMSG
) != JIM_OK
||
5883 Jim_ListIndex(sort_info
->interp
, *rhsObj
, sort_info
->index
, &rObj
, JIM_ERRMSG
) != JIM_OK
) {
5884 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5886 return sort_info
->subfn(&lObj
, &rObj
);
5889 /* Sort the internal rep of a list. */
5890 static int ListSortString(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5892 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 0) * sort_info
->order
;
5895 static int ListSortStringNoCase(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5897 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 1) * sort_info
->order
;
5900 static int ListSortInteger(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5902 jim_wide lhs
= 0, rhs
= 0;
5904 if (Jim_GetWide(sort_info
->interp
, *lhsObj
, &lhs
) != JIM_OK
||
5905 Jim_GetWide(sort_info
->interp
, *rhsObj
, &rhs
) != JIM_OK
) {
5906 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5909 return JimSign(lhs
- rhs
) * sort_info
->order
;
5912 static int ListSortCommand(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5914 Jim_Obj
*compare_script
;
5919 /* This must be a valid list */
5920 compare_script
= Jim_DuplicateObj(sort_info
->interp
, sort_info
->command
);
5921 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *lhsObj
);
5922 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *rhsObj
);
5924 rc
= Jim_EvalObj(sort_info
->interp
, compare_script
);
5926 if (rc
!= JIM_OK
|| Jim_GetWide(sort_info
->interp
, Jim_GetResult(sort_info
->interp
), &ret
) != JIM_OK
) {
5927 longjmp(sort_info
->jmpbuf
, rc
);
5930 return JimSign(ret
) * sort_info
->order
;
5933 /* Sort a list *in place*. MUST be called with non-shared objects. */
5934 static int ListSortElements(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, struct lsort_info
*info
)
5936 struct lsort_info
*prev_info
;
5938 typedef int (qsort_comparator
) (const void *, const void *);
5939 int (*fn
) (Jim_Obj
**, Jim_Obj
**);
5944 JimPanic((Jim_IsShared(listObjPtr
), "Jim_ListSortElements called with shared object"));
5945 if (!Jim_IsList(listObjPtr
))
5946 SetListFromAny(interp
, listObjPtr
);
5948 /* Allow lsort to be called reentrantly */
5949 prev_info
= sort_info
;
5952 vector
= listObjPtr
->internalRep
.listValue
.ele
;
5953 len
= listObjPtr
->internalRep
.listValue
.len
;
5954 switch (info
->type
) {
5955 case JIM_LSORT_ASCII
:
5956 fn
= ListSortString
;
5958 case JIM_LSORT_NOCASE
:
5959 fn
= ListSortStringNoCase
;
5961 case JIM_LSORT_INTEGER
:
5962 fn
= ListSortInteger
;
5964 case JIM_LSORT_COMMAND
:
5965 fn
= ListSortCommand
;
5968 fn
= NULL
; /* avoid warning */
5969 JimPanic((1, "ListSort called with invalid sort type"));
5972 if (info
->indexed
) {
5973 /* Need to interpose a "list index" function */
5975 fn
= ListSortIndexHelper
;
5978 if ((rc
= setjmp(info
->jmpbuf
)) == 0) {
5979 qsort(vector
, len
, sizeof(Jim_Obj
*), (qsort_comparator
*) fn
);
5981 Jim_InvalidateStringRep(listObjPtr
);
5982 sort_info
= prev_info
;
5987 /* This is the low-level function to insert elements into a list.
5988 * The higher-level Jim_ListInsertElements() performs shared object
5989 * check and invalidate the string repr. This version is used
5990 * in the internals of the List Object and is not exported.
5992 * NOTE: this function can be called only against objects
5993 * with internal type of List. */
5994 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
)
5996 int currentLen
= listPtr
->internalRep
.listValue
.len
;
5997 int requiredLen
= currentLen
+ elemc
;
6001 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
6002 int maxLen
= requiredLen
* 2;
6004 listPtr
->internalRep
.listValue
.ele
=
6005 Jim_Realloc(listPtr
->internalRep
.listValue
.ele
, sizeof(Jim_Obj
*) * maxLen
);
6006 listPtr
->internalRep
.listValue
.maxLen
= maxLen
;
6008 point
= listPtr
->internalRep
.listValue
.ele
+ idx
;
6009 memmove(point
+ elemc
, point
, (currentLen
- idx
) * sizeof(Jim_Obj
*));
6010 for (i
= 0; i
< elemc
; ++i
) {
6011 point
[i
] = elemVec
[i
];
6012 Jim_IncrRefCount(point
[i
]);
6014 listPtr
->internalRep
.listValue
.len
+= elemc
;
6017 /* Convenience call to ListInsertElements() to append a single element.
6019 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6021 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
, 1, &objPtr
);
6025 /* Appends every element of appendListPtr into listPtr.
6026 * Both have to be of the list type.
6027 * Convenience call to ListInsertElements()
6029 static void ListAppendList(Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6031 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
,
6032 appendListPtr
->internalRep
.listValue
.len
, appendListPtr
->internalRep
.listValue
.ele
);
6035 void Jim_ListAppendElement(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6037 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendElement called with shared object"));
6038 if (!Jim_IsList(listPtr
))
6039 SetListFromAny(interp
, listPtr
);
6040 Jim_InvalidateStringRep(listPtr
);
6041 ListAppendElement(listPtr
, objPtr
);
6044 void Jim_ListAppendList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6046 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendList called with shared object"));
6047 if (!Jim_IsList(listPtr
))
6048 SetListFromAny(interp
, listPtr
);
6049 Jim_InvalidateStringRep(listPtr
);
6050 ListAppendList(listPtr
, appendListPtr
);
6053 int Jim_ListLength(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6055 if (!Jim_IsList(objPtr
))
6056 SetListFromAny(interp
, objPtr
);
6057 return objPtr
->internalRep
.listValue
.len
;
6060 void Jim_ListInsertElements(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6061 int objc
, Jim_Obj
*const *objVec
)
6063 JimPanic((Jim_IsShared(listPtr
), "Jim_ListInsertElement called with shared object"));
6064 if (!Jim_IsList(listPtr
))
6065 SetListFromAny(interp
, listPtr
);
6066 if (idx
>= 0 && idx
> listPtr
->internalRep
.listValue
.len
)
6067 idx
= listPtr
->internalRep
.listValue
.len
;
6070 Jim_InvalidateStringRep(listPtr
);
6071 ListInsertElements(listPtr
, idx
, objc
, objVec
);
6074 int Jim_ListIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
, Jim_Obj
**objPtrPtr
, int flags
)
6076 if (!Jim_IsList(listPtr
))
6077 SetListFromAny(interp
, listPtr
);
6078 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6079 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6080 if (flags
& JIM_ERRMSG
) {
6081 Jim_SetResultString(interp
, "list index out of range", -1);
6087 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6088 *objPtrPtr
= listPtr
->internalRep
.listValue
.ele
[idx
];
6092 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6093 Jim_Obj
*newObjPtr
, int flags
)
6095 if (!Jim_IsList(listPtr
))
6096 SetListFromAny(interp
, listPtr
);
6097 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6098 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6099 if (flags
& JIM_ERRMSG
) {
6100 Jim_SetResultString(interp
, "list index out of range", -1);
6105 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6106 Jim_DecrRefCount(interp
, listPtr
->internalRep
.listValue
.ele
[idx
]);
6107 listPtr
->internalRep
.listValue
.ele
[idx
] = newObjPtr
;
6108 Jim_IncrRefCount(newObjPtr
);
6112 /* Modify the list stored into the variable named 'varNamePtr'
6113 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6114 * with the new element 'newObjptr'. */
6115 int Jim_SetListIndex(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6116 Jim_Obj
*const *indexv
, int indexc
, Jim_Obj
*newObjPtr
)
6118 Jim_Obj
*varObjPtr
, *objPtr
, *listObjPtr
;
6121 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
| JIM_UNSHARED
);
6124 if ((shared
= Jim_IsShared(objPtr
)))
6125 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6126 for (i
= 0; i
< indexc
- 1; i
++) {
6127 listObjPtr
= objPtr
;
6128 if (Jim_GetIndex(interp
, indexv
[i
], &idx
) != JIM_OK
)
6130 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_ERRMSG
) != JIM_OK
) {
6133 if (Jim_IsShared(objPtr
)) {
6134 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6135 ListSetIndex(interp
, listObjPtr
, idx
, objPtr
, JIM_NONE
);
6137 Jim_InvalidateStringRep(listObjPtr
);
6139 if (Jim_GetIndex(interp
, indexv
[indexc
- 1], &idx
) != JIM_OK
)
6141 if (ListSetIndex(interp
, objPtr
, idx
, newObjPtr
, JIM_ERRMSG
) == JIM_ERR
)
6143 Jim_InvalidateStringRep(objPtr
);
6144 Jim_InvalidateStringRep(varObjPtr
);
6145 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
6147 Jim_SetResult(interp
, varObjPtr
);
6151 Jim_FreeNewObj(interp
, varObjPtr
);
6156 Jim_Obj
*Jim_ConcatObj(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
6160 /* If all the objects in objv are lists,
6161 * it's possible to return a list as result, that's the
6162 * concatenation of all the lists. */
6163 for (i
= 0; i
< objc
; i
++) {
6164 if (!Jim_IsList(objv
[i
]))
6168 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
6170 for (i
= 0; i
< objc
; i
++)
6171 Jim_ListAppendList(interp
, objPtr
, objv
[i
]);
6175 /* Else... we have to glue strings together */
6176 int len
= 0, objLen
;
6179 /* Compute the length */
6180 for (i
= 0; i
< objc
; i
++) {
6181 Jim_GetString(objv
[i
], &objLen
);
6186 /* Create the string rep, and a string object holding it. */
6187 p
= bytes
= Jim_Alloc(len
+ 1);
6188 for (i
= 0; i
< objc
; i
++) {
6189 const char *s
= Jim_GetString(objv
[i
], &objLen
);
6191 /* Remove leading space */
6192 while (objLen
&& (*s
== ' ' || *s
== '\t' || *s
== '\n')) {
6197 /* And trailing space */
6198 while (objLen
&& (s
[objLen
- 1] == ' ' ||
6199 s
[objLen
- 1] == '\n' || s
[objLen
- 1] == '\t')) {
6200 /* Handle trailing backslash-space case */
6201 if (objLen
> 1 && s
[objLen
- 2] == '\\') {
6207 memcpy(p
, s
, objLen
);
6209 if (objLen
&& i
+ 1 != objc
) {
6212 else if (i
+ 1 != objc
) {
6213 /* Drop the space calcuated for this
6214 * element that is instead null. */
6219 return Jim_NewStringObjNoAlloc(interp
, bytes
, len
);
6223 /* Returns a list composed of the elements in the specified range.
6224 * first and start are directly accepted as Jim_Objects and
6225 * processed for the end?-index? case. */
6226 Jim_Obj
*Jim_ListRange(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*firstObjPtr
,
6227 Jim_Obj
*lastObjPtr
)
6232 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
6233 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
6235 len
= Jim_ListLength(interp
, listObjPtr
); /* will convert into list */
6236 first
= JimRelToAbsIndex(len
, first
);
6237 last
= JimRelToAbsIndex(len
, last
);
6238 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
6239 if (first
== 0 && last
== len
) {
6242 return Jim_NewListObj(interp
, listObjPtr
->internalRep
.listValue
.ele
+ first
, rangeLen
);
6245 /* -----------------------------------------------------------------------------
6247 * ---------------------------------------------------------------------------*/
6248 static void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6249 static void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
6250 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
);
6251 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6253 /* Dict HashTable Type.
6255 * Keys and Values are Jim objects. */
6257 static unsigned int JimObjectHTHashFunction(const void *key
)
6260 Jim_Obj
*objPtr
= (Jim_Obj
*)key
;
6263 str
= Jim_GetString(objPtr
, &len
);
6264 h
= Jim_GenHashFunction((unsigned char *)str
, len
);
6268 static int JimObjectHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
6270 JIM_NOTUSED(privdata
);
6272 return Jim_StringEqObj((Jim_Obj
*)key1
, (Jim_Obj
*)key2
);
6275 static void JimObjectHTKeyValDestructor(void *interp
, void *val
)
6277 Jim_Obj
*objPtr
= val
;
6279 Jim_DecrRefCount(interp
, objPtr
);
6282 static const Jim_HashTableType JimDictHashTableType
= {
6283 JimObjectHTHashFunction
, /* hash function */
6286 JimObjectHTKeyCompare
, /* key compare */
6287 (void (*)(void *, const void *)) /* ATTENTION: const cast */
6288 JimObjectHTKeyValDestructor
, /* key destructor */
6289 JimObjectHTKeyValDestructor
/* val destructor */
6292 /* Note that while the elements of the dict may contain references,
6293 * the list object itself can't. This basically means that the
6294 * dict object string representation as a whole can't contain references
6295 * that are not presents in the single elements. */
6296 static const Jim_ObjType dictObjType
= {
6298 FreeDictInternalRep
,
6304 void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6306 JIM_NOTUSED(interp
);
6308 Jim_FreeHashTable(objPtr
->internalRep
.ptr
);
6309 Jim_Free(objPtr
->internalRep
.ptr
);
6312 void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
6314 Jim_HashTable
*ht
, *dupHt
;
6315 Jim_HashTableIterator
*htiter
;
6318 /* Create a new hash table */
6319 ht
= srcPtr
->internalRep
.ptr
;
6320 dupHt
= Jim_Alloc(sizeof(*dupHt
));
6321 Jim_InitHashTable(dupHt
, &JimDictHashTableType
, interp
);
6323 Jim_ExpandHashTable(dupHt
, ht
->size
);
6324 /* Copy every element from the source to the dup hash table */
6325 htiter
= Jim_GetHashTableIterator(ht
);
6326 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6327 const Jim_Obj
*keyObjPtr
= he
->key
;
6328 Jim_Obj
*valObjPtr
= he
->u
.val
;
6330 Jim_IncrRefCount((Jim_Obj
*)keyObjPtr
); /* ATTENTION: const cast */
6331 Jim_IncrRefCount(valObjPtr
);
6332 Jim_AddHashEntry(dupHt
, keyObjPtr
, valObjPtr
);
6334 Jim_FreeHashTableIterator(htiter
);
6336 dupPtr
->internalRep
.ptr
= dupHt
;
6337 dupPtr
->typePtr
= &dictObjType
;
6340 void UpdateStringOfDict(struct Jim_Obj
*objPtr
)
6342 int i
, bufLen
, realLength
;
6345 int *quotingType
, objc
;
6347 Jim_HashTableIterator
*htiter
;
6351 /* Trun the hash table into a flat vector of Jim_Objects. */
6352 ht
= objPtr
->internalRep
.ptr
;
6353 objc
= ht
->used
* 2;
6354 objv
= Jim_Alloc(objc
* sizeof(Jim_Obj
*));
6355 htiter
= Jim_GetHashTableIterator(ht
);
6357 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6358 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6359 objv
[i
++] = he
->u
.val
;
6361 Jim_FreeHashTableIterator(htiter
);
6362 /* (Over) Estimate the space needed. */
6363 quotingType
= Jim_Alloc(sizeof(int) * objc
);
6365 for (i
= 0; i
< objc
; i
++) {
6368 strRep
= Jim_GetString(objv
[i
], &len
);
6369 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
6370 switch (quotingType
[i
]) {
6371 case JIM_ELESTR_SIMPLE
:
6374 case JIM_ELESTR_BRACE
:
6377 case JIM_ELESTR_QUOTE
:
6381 bufLen
++; /* elements separator. */
6385 /* Generate the string rep. */
6386 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
6388 for (i
= 0; i
< objc
; i
++) {
6392 strRep
= Jim_GetString(objv
[i
], &len
);
6394 switch (quotingType
[i
]) {
6395 case JIM_ELESTR_SIMPLE
:
6396 memcpy(p
, strRep
, len
);
6400 case JIM_ELESTR_BRACE
:
6402 memcpy(p
, strRep
, len
);
6405 realLength
+= len
+ 2;
6407 case JIM_ELESTR_QUOTE
:
6408 q
= BackslashQuoteString(strRep
, len
, &qlen
);
6415 /* Add a separating space */
6416 if (i
+ 1 != objc
) {
6421 *p
= '\0'; /* nul term. */
6422 objPtr
->length
= realLength
;
6423 Jim_Free(quotingType
);
6427 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
6431 /* Get the string representation. Do this first so we don't
6432 * change order in case of fast conversion to dict.
6436 /* For simplicity, convert a non-list object to a list and then to a dict */
6437 listlen
= Jim_ListLength(interp
, objPtr
);
6439 Jim_SetResultString(interp
,
6440 "invalid dictionary value: must be a list with an even number of elements", -1);
6444 /* Now it is easy to convert to a dict from a list, and it can't fail */
6448 ht
= Jim_Alloc(sizeof(*ht
));
6449 Jim_InitHashTable(ht
, &JimDictHashTableType
, interp
);
6451 for (i
= 0; i
< listlen
; i
+= 2) {
6455 Jim_ListIndex(interp
, objPtr
, i
, &keyObjPtr
, JIM_NONE
);
6456 Jim_ListIndex(interp
, objPtr
, i
+ 1, &valObjPtr
, JIM_NONE
);
6458 Jim_IncrRefCount(keyObjPtr
);
6459 Jim_IncrRefCount(valObjPtr
);
6461 if (Jim_AddHashEntry(ht
, keyObjPtr
, valObjPtr
) != JIM_OK
) {
6464 he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6465 Jim_DecrRefCount(interp
, keyObjPtr
);
6466 /* ATTENTION: const cast */
6467 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6468 he
->u
.val
= valObjPtr
;
6472 Jim_FreeIntRep(interp
, objPtr
);
6473 objPtr
->typePtr
= &dictObjType
;
6474 objPtr
->internalRep
.ptr
= ht
;
6480 /* Dict object API */
6482 /* Add an element to a dict. objPtr must be of the "dict" type.
6483 * The higer-level exported function is Jim_DictAddElement().
6484 * If an element with the specified key already exists, the value
6485 * associated is replaced with the new one.
6487 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6488 static int DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6489 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6491 Jim_HashTable
*ht
= objPtr
->internalRep
.ptr
;
6493 if (valueObjPtr
== NULL
) { /* unset */
6494 return Jim_DeleteHashEntry(ht
, keyObjPtr
);
6496 Jim_IncrRefCount(keyObjPtr
);
6497 Jim_IncrRefCount(valueObjPtr
);
6498 if (Jim_AddHashEntry(ht
, keyObjPtr
, valueObjPtr
) != JIM_OK
) {
6499 Jim_HashEntry
*he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6501 Jim_DecrRefCount(interp
, keyObjPtr
);
6502 /* ATTENTION: const cast */
6503 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6504 he
->u
.val
= valueObjPtr
;
6509 /* Add an element, higher-level interface for DictAddElement().
6510 * If valueObjPtr == NULL, the key is removed if it exists. */
6511 int Jim_DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6512 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6516 JimPanic((Jim_IsShared(objPtr
), "Jim_DictAddElement called with shared object"));
6517 if (objPtr
->typePtr
!= &dictObjType
) {
6518 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
)
6521 retcode
= DictAddElement(interp
, objPtr
, keyObjPtr
, valueObjPtr
);
6522 Jim_InvalidateStringRep(objPtr
);
6526 Jim_Obj
*Jim_NewDictObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
6531 JimPanic((len
% 2, "Jim_NewDictObj() 'len' argument must be even"));
6533 objPtr
= Jim_NewObj(interp
);
6534 objPtr
->typePtr
= &dictObjType
;
6535 objPtr
->bytes
= NULL
;
6536 objPtr
->internalRep
.ptr
= Jim_Alloc(sizeof(Jim_HashTable
));
6537 Jim_InitHashTable(objPtr
->internalRep
.ptr
, &JimDictHashTableType
, interp
);
6538 for (i
= 0; i
< len
; i
+= 2)
6539 DictAddElement(interp
, objPtr
, elements
[i
], elements
[i
+ 1]);
6543 /* Return the value associated to the specified dict key
6544 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6546 int Jim_DictKey(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
*keyPtr
,
6547 Jim_Obj
**objPtrPtr
, int flags
)
6552 if (dictPtr
->typePtr
!= &dictObjType
) {
6553 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6556 ht
= dictPtr
->internalRep
.ptr
;
6557 if ((he
= Jim_FindHashEntry(ht
, keyPtr
)) == NULL
) {
6558 if (flags
& JIM_ERRMSG
) {
6559 Jim_SetResultFormatted(interp
, "key \"%#s\" not found in dictionary", keyPtr
);
6563 *objPtrPtr
= he
->u
.val
;
6567 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6568 int Jim_DictPairs(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
***objPtrPtr
, int *len
)
6571 Jim_HashTableIterator
*htiter
;
6576 if (dictPtr
->typePtr
!= &dictObjType
) {
6577 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6580 ht
= dictPtr
->internalRep
.ptr
;
6582 /* Turn the hash table into a flat vector of Jim_Objects. */
6583 objv
= Jim_Alloc((ht
->used
* 2) * sizeof(Jim_Obj
*));
6584 htiter
= Jim_GetHashTableIterator(ht
);
6586 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6587 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6588 objv
[i
++] = he
->u
.val
;
6591 Jim_FreeHashTableIterator(htiter
);
6597 /* Return the value associated to the specified dict keys */
6598 int Jim_DictKeysVector(Jim_Interp
*interp
, Jim_Obj
*dictPtr
,
6599 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
**objPtrPtr
, int flags
)
6604 *objPtrPtr
= dictPtr
;
6608 for (i
= 0; i
< keyc
; i
++) {
6611 if (Jim_DictKey(interp
, dictPtr
, keyv
[i
], &objPtr
, flags
)
6616 *objPtrPtr
= dictPtr
;
6620 /* Modify the dict stored into the variable named 'varNamePtr'
6621 * setting the element specified by the 'keyc' keys objects in 'keyv',
6622 * with the new value of the element 'newObjPtr'.
6624 * If newObjPtr == NULL the operation is to remove the given key
6625 * from the dictionary. */
6626 int Jim_SetDictKeysVector(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6627 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*newObjPtr
)
6629 Jim_Obj
*varObjPtr
, *objPtr
, *dictObjPtr
;
6632 varObjPtr
= objPtr
=
6633 Jim_GetVariable(interp
, varNamePtr
, newObjPtr
== NULL
? JIM_ERRMSG
: JIM_NONE
);
6634 if (objPtr
== NULL
) {
6635 if (newObjPtr
== NULL
) /* Cannot remove a key from non existing var */
6637 varObjPtr
= objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6638 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
6639 Jim_FreeNewObj(interp
, varObjPtr
);
6643 if ((shared
= Jim_IsShared(objPtr
)))
6644 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6645 for (i
= 0; i
< keyc
- 1; i
++) {
6646 dictObjPtr
= objPtr
;
6648 /* Check if it's a valid dictionary */
6649 if (dictObjPtr
->typePtr
!= &dictObjType
) {
6650 if (SetDictFromAny(interp
, dictObjPtr
) != JIM_OK
)
6653 /* Check if the given key exists. */
6654 Jim_InvalidateStringRep(dictObjPtr
);
6655 if (Jim_DictKey(interp
, dictObjPtr
, keyv
[i
], &objPtr
,
6656 newObjPtr
? JIM_NONE
: JIM_ERRMSG
) == JIM_OK
) {
6657 /* This key exists at the current level.
6658 * Make sure it's not shared!. */
6659 if (Jim_IsShared(objPtr
)) {
6660 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6661 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6665 /* Key not found. If it's an [unset] operation
6666 * this is an error. Only the last key may not
6668 if (newObjPtr
== NULL
)
6670 /* Otherwise set an empty dictionary
6671 * as key's value. */
6672 objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6673 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6676 if (Jim_DictAddElement(interp
, objPtr
, keyv
[keyc
- 1], newObjPtr
) != JIM_OK
) {
6679 Jim_InvalidateStringRep(objPtr
);
6680 Jim_InvalidateStringRep(varObjPtr
);
6681 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
6683 Jim_SetResult(interp
, varObjPtr
);
6687 Jim_FreeNewObj(interp
, varObjPtr
);
6692 /* -----------------------------------------------------------------------------
6694 * ---------------------------------------------------------------------------*/
6695 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
);
6696 static int SetIndexFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6698 static const Jim_ObjType indexObjType
= {
6702 UpdateStringOfIndex
,
6706 void UpdateStringOfIndex(struct Jim_Obj
*objPtr
)
6709 char buf
[JIM_INTEGER_SPACE
+ 1];
6711 if (objPtr
->internalRep
.indexValue
>= 0)
6712 len
= sprintf(buf
, "%d", objPtr
->internalRep
.indexValue
);
6713 else if (objPtr
->internalRep
.indexValue
== -1)
6714 len
= sprintf(buf
, "end");
6716 len
= sprintf(buf
, "end%d", objPtr
->internalRep
.indexValue
+ 1);
6718 objPtr
->bytes
= Jim_Alloc(len
+ 1);
6719 memcpy(objPtr
->bytes
, buf
, len
+ 1);
6720 objPtr
->length
= len
;
6723 int SetIndexFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6729 /* Get the string representation */
6730 str
= Jim_String(objPtr
);
6732 /* Try to convert into an index */
6733 if (strncmp(str
, "end", 3) == 0) {
6739 idx
= strtol(str
, &endptr
, 10);
6741 if (endptr
== str
) {
6747 /* Now str may include or +<num> or -<num> */
6748 if (*str
== '+' || *str
== '-') {
6749 int sign
= (*str
== '+' ? 1 : -1);
6751 idx
+= sign
* strtol(++str
, &endptr
, 10);
6752 if (str
== endptr
|| *endptr
) {
6757 /* The only thing left should be spaces */
6758 while (isspace(UCHAR(*str
))) {
6769 /* end-1 is repesented as -2 */
6777 /* Free the old internal repr and set the new one. */
6778 Jim_FreeIntRep(interp
, objPtr
);
6779 objPtr
->typePtr
= &indexObjType
;
6780 objPtr
->internalRep
.indexValue
= idx
;
6784 Jim_SetResultFormatted(interp
,
6785 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr
);
6789 int Jim_GetIndex(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *indexPtr
)
6791 /* Avoid shimmering if the object is an integer. */
6792 if (objPtr
->typePtr
== &intObjType
) {
6793 jim_wide val
= JimWideValue(objPtr
);
6795 if (!(val
< LONG_MIN
) && !(val
> LONG_MAX
)) {
6796 *indexPtr
= (val
< 0) ? -INT_MAX
: (long)val
;;
6800 if (objPtr
->typePtr
!= &indexObjType
&& SetIndexFromAny(interp
, objPtr
) == JIM_ERR
)
6802 *indexPtr
= objPtr
->internalRep
.indexValue
;
6806 /* -----------------------------------------------------------------------------
6807 * Return Code Object.
6808 * ---------------------------------------------------------------------------*/
6810 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6811 static const char * const jimReturnCodes
[] = {
6813 [JIM_ERR
] = "error",
6814 [JIM_RETURN
] = "return",
6815 [JIM_BREAK
] = "break",
6816 [JIM_CONTINUE
] = "continue",
6817 [JIM_SIGNAL
] = "signal",
6818 [JIM_EXIT
] = "exit",
6819 [JIM_EVAL
] = "eval",
6823 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6825 static int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6827 static const Jim_ObjType returnCodeObjType
= {
6835 /* Converts a (standard) return code to a string. Returns "?" for
6836 * non-standard return codes.
6838 const char *Jim_ReturnCode(int code
)
6840 if (code
< 0 || code
>= (int)jimReturnCodesSize
) {
6844 return jimReturnCodes
[code
];
6848 int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6853 /* Try to convert into an integer */
6854 if (JimGetWideNoErr(interp
, objPtr
, &wideValue
) != JIM_ERR
)
6855 returnCode
= (int)wideValue
;
6856 else if (Jim_GetEnum(interp
, objPtr
, jimReturnCodes
, &returnCode
, NULL
, JIM_NONE
) != JIM_OK
) {
6857 Jim_SetResultFormatted(interp
, "expected return code but got \"%#s\"", objPtr
);
6860 /* Free the old internal repr and set the new one. */
6861 Jim_FreeIntRep(interp
, objPtr
);
6862 objPtr
->typePtr
= &returnCodeObjType
;
6863 objPtr
->internalRep
.returnCode
= returnCode
;
6867 int Jim_GetReturnCode(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *intPtr
)
6869 if (objPtr
->typePtr
!= &returnCodeObjType
&& SetReturnCodeFromAny(interp
, objPtr
) == JIM_ERR
)
6871 *intPtr
= objPtr
->internalRep
.returnCode
;
6875 /* -----------------------------------------------------------------------------
6876 * Expression Parsing
6877 * ---------------------------------------------------------------------------*/
6878 static int JimParseExprOperator(struct JimParserCtx
*pc
);
6879 static int JimParseExprNumber(struct JimParserCtx
*pc
);
6880 static int JimParseExprIrrational(struct JimParserCtx
*pc
);
6882 /* Exrp's Stack machine operators opcodes. */
6884 /* Binary operators (numbers) */
6887 /* Continues on from the JIM_TT_ space */
6889 JIM_EXPROP_MUL
= JIM_TT_EXPR_OP
, /* 15 */
6904 JIM_EXPROP_BITAND
, /* 30 */
6908 /* Note must keep these together */
6909 JIM_EXPROP_LOGICAND
, /* 33 */
6910 JIM_EXPROP_LOGICAND_LEFT
,
6911 JIM_EXPROP_LOGICAND_RIGHT
,
6914 JIM_EXPROP_LOGICOR
, /* 36 */
6915 JIM_EXPROP_LOGICOR_LEFT
,
6916 JIM_EXPROP_LOGICOR_RIGHT
,
6919 /* Ternary operators */
6920 JIM_EXPROP_TERNARY
, /* 39 */
6921 JIM_EXPROP_TERNARY_LEFT
,
6922 JIM_EXPROP_TERNARY_RIGHT
,
6925 JIM_EXPROP_COLON
, /* 42 */
6926 JIM_EXPROP_COLON_LEFT
,
6927 JIM_EXPROP_COLON_RIGHT
,
6929 JIM_EXPROP_POW
, /* 45 */
6931 /* Binary operators (strings) */
6937 /* Unary operators (numbers) */
6940 JIM_EXPROP_UNARYMINUS
,
6941 JIM_EXPROP_UNARYPLUS
,
6944 JIM_EXPROP_FUNC_FIRST
,
6945 JIM_EXPROP_FUNC_INT
= JIM_EXPROP_FUNC_FIRST
,
6946 JIM_EXPROP_FUNC_ABS
,
6947 JIM_EXPROP_FUNC_DOUBLE
,
6948 JIM_EXPROP_FUNC_ROUND
,
6949 JIM_EXPROP_FUNC_RAND
,
6950 JIM_EXPROP_FUNC_SRAND
,
6952 #ifdef JIM_MATH_FUNCTIONS
6953 /* math functions from libm */
6954 JIM_EXPROP_FUNC_SIN
,
6955 JIM_EXPROP_FUNC_COS
,
6956 JIM_EXPROP_FUNC_TAN
,
6957 JIM_EXPROP_FUNC_ASIN
,
6958 JIM_EXPROP_FUNC_ACOS
,
6959 JIM_EXPROP_FUNC_ATAN
,
6960 JIM_EXPROP_FUNC_SINH
,
6961 JIM_EXPROP_FUNC_COSH
,
6962 JIM_EXPROP_FUNC_TANH
,
6963 JIM_EXPROP_FUNC_CEIL
,
6964 JIM_EXPROP_FUNC_FLOOR
,
6965 JIM_EXPROP_FUNC_EXP
,
6966 JIM_EXPROP_FUNC_LOG
,
6967 JIM_EXPROP_FUNC_LOG10
,
6968 JIM_EXPROP_FUNC_SQRT
,
6980 /* Operators table */
6981 typedef struct Jim_ExprOperator
6986 int (*funcop
) (Jim_Interp
*interp
, struct JimExprState
* e
);
6990 static void ExprPush(struct JimExprState
*e
, Jim_Obj
*obj
)
6992 Jim_IncrRefCount(obj
);
6993 e
->stack
[e
->stacklen
++] = obj
;
6996 static Jim_Obj
*ExprPop(struct JimExprState
*e
)
6998 return e
->stack
[--e
->stacklen
];
7001 static int JimExprOpNumUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7005 Jim_Obj
*A
= ExprPop(e
);
7007 jim_wide wA
, wC
= 0;
7009 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) && JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
) {
7012 switch (e
->opcode
) {
7013 case JIM_EXPROP_FUNC_INT
:
7016 case JIM_EXPROP_FUNC_ROUND
:
7019 case JIM_EXPROP_FUNC_DOUBLE
:
7023 case JIM_EXPROP_FUNC_ABS
:
7024 wC
= wA
>= 0 ? wA
: -wA
;
7026 case JIM_EXPROP_UNARYMINUS
:
7029 case JIM_EXPROP_UNARYPLUS
:
7032 case JIM_EXPROP_NOT
:
7039 else if ((rc
= Jim_GetDouble(interp
, A
, &dA
)) == JIM_OK
) {
7040 switch (e
->opcode
) {
7041 case JIM_EXPROP_FUNC_INT
:
7045 case JIM_EXPROP_FUNC_ROUND
:
7046 wC
= dA
< 0 ? (dA
- 0.5) : (dA
+ 0.5);
7049 case JIM_EXPROP_FUNC_DOUBLE
:
7052 case JIM_EXPROP_FUNC_ABS
:
7053 dC
= dA
>= 0 ? dA
: -dA
;
7055 case JIM_EXPROP_UNARYMINUS
:
7058 case JIM_EXPROP_UNARYPLUS
:
7061 case JIM_EXPROP_NOT
:
7072 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7075 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7079 Jim_DecrRefCount(interp
, A
);
7084 static double JimRandDouble(Jim_Interp
*interp
)
7087 JimRandomBytes(interp
, &x
, sizeof(x
));
7089 return (double)x
/ (unsigned long)~0;
7092 static int JimExprOpIntUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7094 Jim_Obj
*A
= ExprPop(e
);
7097 int rc
= Jim_GetWide(interp
, A
, &wA
);
7099 switch (e
->opcode
) {
7100 case JIM_EXPROP_BITNOT
:
7101 ExprPush(e
, Jim_NewIntObj(interp
, ~wA
));
7103 case JIM_EXPROP_FUNC_SRAND
:
7104 JimPrngSeed(interp
, (unsigned char *)&wA
, sizeof(wA
));
7105 ExprPush(e
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7112 Jim_DecrRefCount(interp
, A
);
7117 static int JimExprOpNone(Jim_Interp
*interp
, struct JimExprState
*e
)
7119 JimPanic((e
->opcode
!= JIM_EXPROP_FUNC_RAND
, "JimExprOpNone only support rand()"));
7121 ExprPush(e
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7126 #ifdef JIM_MATH_FUNCTIONS
7127 static int JimExprOpDoubleUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7130 Jim_Obj
*A
= ExprPop(e
);
7133 rc
= Jim_GetDouble(interp
, A
, &dA
);
7135 switch (e
->opcode
) {
7136 case JIM_EXPROP_FUNC_SIN
:
7139 case JIM_EXPROP_FUNC_COS
:
7142 case JIM_EXPROP_FUNC_TAN
:
7145 case JIM_EXPROP_FUNC_ASIN
:
7148 case JIM_EXPROP_FUNC_ACOS
:
7151 case JIM_EXPROP_FUNC_ATAN
:
7154 case JIM_EXPROP_FUNC_SINH
:
7157 case JIM_EXPROP_FUNC_COSH
:
7160 case JIM_EXPROP_FUNC_TANH
:
7163 case JIM_EXPROP_FUNC_CEIL
:
7166 case JIM_EXPROP_FUNC_FLOOR
:
7169 case JIM_EXPROP_FUNC_EXP
:
7172 case JIM_EXPROP_FUNC_LOG
:
7175 case JIM_EXPROP_FUNC_LOG10
:
7178 case JIM_EXPROP_FUNC_SQRT
:
7184 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7187 Jim_DecrRefCount(interp
, A
);
7193 /* A binary operation on two ints */
7194 static int JimExprOpIntBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7196 Jim_Obj
*B
= ExprPop(e
);
7197 Jim_Obj
*A
= ExprPop(e
);
7201 if (Jim_GetWide(interp
, A
, &wA
) == JIM_OK
&& Jim_GetWide(interp
, B
, &wB
) == JIM_OK
) {
7206 switch (e
->opcode
) {
7207 case JIM_EXPROP_LSHIFT
:
7210 case JIM_EXPROP_RSHIFT
:
7213 case JIM_EXPROP_BITAND
:
7216 case JIM_EXPROP_BITXOR
:
7219 case JIM_EXPROP_BITOR
:
7222 case JIM_EXPROP_MOD
:
7225 Jim_SetResultString(interp
, "Division by zero", -1);
7232 * This code is tricky: C doesn't guarantee much
7233 * about the quotient or remainder, but Tcl does.
7234 * The remainder always has the same sign as the
7235 * divisor and a smaller absolute value.
7253 case JIM_EXPROP_ROTL
:
7254 case JIM_EXPROP_ROTR
:{
7255 /* uint32_t would be better. But not everyone has inttypes.h? */
7256 unsigned long uA
= (unsigned long)wA
;
7257 unsigned long uB
= (unsigned long)wB
;
7258 const unsigned int S
= sizeof(unsigned long) * 8;
7260 /* Shift left by the word size or more is undefined. */
7263 if (e
->opcode
== JIM_EXPROP_ROTR
) {
7266 wC
= (unsigned long)(uA
<< uB
) | (uA
>> (S
- uB
));
7272 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7276 Jim_DecrRefCount(interp
, A
);
7277 Jim_DecrRefCount(interp
, B
);
7283 /* A binary operation on two ints or two doubles (or two strings for some ops) */
7284 static int JimExprOpBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7288 double dA
, dB
, dC
= 0;
7289 jim_wide wA
, wB
, wC
= 0;
7291 Jim_Obj
*B
= ExprPop(e
);
7292 Jim_Obj
*A
= ExprPop(e
);
7294 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) &&
7295 (B
->typePtr
!= &doubleObjType
|| B
->bytes
) &&
7296 JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
&& JimGetWideNoErr(interp
, B
, &wB
) == JIM_OK
) {
7302 switch (e
->opcode
) {
7303 case JIM_EXPROP_POW
:
7304 wC
= JimPowWide(wA
, wB
);
7306 case JIM_EXPROP_ADD
:
7309 case JIM_EXPROP_SUB
:
7312 case JIM_EXPROP_MUL
:
7315 case JIM_EXPROP_DIV
:
7317 Jim_SetResultString(interp
, "Division by zero", -1);
7324 * This code is tricky: C doesn't guarantee much
7325 * about the quotient or remainder, but Tcl does.
7326 * The remainder always has the same sign as the
7327 * divisor and a smaller absolute value.
7345 case JIM_EXPROP_LTE
:
7348 case JIM_EXPROP_GTE
:
7351 case JIM_EXPROP_NUMEQ
:
7354 case JIM_EXPROP_NUMNE
:
7361 else if (Jim_GetDouble(interp
, A
, &dA
) == JIM_OK
&& Jim_GetDouble(interp
, B
, &dB
) == JIM_OK
) {
7362 switch (e
->opcode
) {
7363 case JIM_EXPROP_POW
:
7364 #ifdef JIM_MATH_FUNCTIONS
7367 Jim_SetResultString(interp
, "unsupported", -1);
7371 case JIM_EXPROP_ADD
:
7374 case JIM_EXPROP_SUB
:
7377 case JIM_EXPROP_MUL
:
7380 case JIM_EXPROP_DIV
:
7383 dC
= dA
< 0 ? -INFINITY
: INFINITY
;
7385 dC
= (dA
< 0 ? -1.0 : 1.0) * strtod("Inf", NULL
);
7400 case JIM_EXPROP_LTE
:
7404 case JIM_EXPROP_GTE
:
7408 case JIM_EXPROP_NUMEQ
:
7412 case JIM_EXPROP_NUMNE
:
7421 /* Handle the string case */
7423 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7424 int i
= Jim_StringCompareObj(interp
, A
, B
, 0);
7428 switch (e
->opcode
) {
7435 case JIM_EXPROP_LTE
:
7438 case JIM_EXPROP_GTE
:
7441 case JIM_EXPROP_NUMEQ
:
7444 case JIM_EXPROP_NUMNE
:
7455 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7458 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7462 Jim_DecrRefCount(interp
, A
);
7463 Jim_DecrRefCount(interp
, B
);
7468 static int JimSearchList(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*valObj
)
7473 listlen
= Jim_ListLength(interp
, listObjPtr
);
7474 for (i
= 0; i
< listlen
; i
++) {
7477 Jim_ListIndex(interp
, listObjPtr
, i
, &objPtr
, JIM_NONE
);
7479 if (Jim_StringEqObj(objPtr
, valObj
)) {
7486 static int JimExprOpStrBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7488 Jim_Obj
*B
= ExprPop(e
);
7489 Jim_Obj
*A
= ExprPop(e
);
7493 switch (e
->opcode
) {
7494 case JIM_EXPROP_STREQ
:
7495 case JIM_EXPROP_STRNE
: {
7497 const char *sA
= Jim_GetString(A
, &Alen
);
7498 const char *sB
= Jim_GetString(B
, &Blen
);
7500 if (e
->opcode
== JIM_EXPROP_STREQ
) {
7501 wC
= (Alen
== Blen
&& memcmp(sA
, sB
, Alen
) == 0);
7504 wC
= (Alen
!= Blen
|| memcmp(sA
, sB
, Alen
) != 0);
7508 case JIM_EXPROP_STRIN
:
7509 wC
= JimSearchList(interp
, B
, A
);
7511 case JIM_EXPROP_STRNI
:
7512 wC
= !JimSearchList(interp
, B
, A
);
7517 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7519 Jim_DecrRefCount(interp
, A
);
7520 Jim_DecrRefCount(interp
, B
);
7525 static int ExprBool(Jim_Interp
*interp
, Jim_Obj
*obj
)
7530 if (Jim_GetLong(interp
, obj
, &l
) == JIM_OK
) {
7533 if (Jim_GetDouble(interp
, obj
, &d
) == JIM_OK
) {
7539 static int JimExprOpAndLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7541 Jim_Obj
*skip
= ExprPop(e
);
7542 Jim_Obj
*A
= ExprPop(e
);
7545 switch (ExprBool(interp
, A
)) {
7547 /* false, so skip RHS opcodes with a 0 result */
7548 e
->skip
= JimWideValue(skip
);
7549 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7553 /* true so continue */
7560 Jim_DecrRefCount(interp
, A
);
7561 Jim_DecrRefCount(interp
, skip
);
7566 static int JimExprOpOrLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7568 Jim_Obj
*skip
= ExprPop(e
);
7569 Jim_Obj
*A
= ExprPop(e
);
7572 switch (ExprBool(interp
, A
)) {
7574 /* false, so do nothing */
7578 /* true so skip RHS opcodes with a 1 result */
7579 e
->skip
= JimWideValue(skip
);
7580 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7588 Jim_DecrRefCount(interp
, A
);
7589 Jim_DecrRefCount(interp
, skip
);
7594 static int JimExprOpAndOrRight(Jim_Interp
*interp
, struct JimExprState
*e
)
7596 Jim_Obj
*A
= ExprPop(e
);
7599 switch (ExprBool(interp
, A
)) {
7601 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7605 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7613 Jim_DecrRefCount(interp
, A
);
7618 static int JimExprOpTernaryLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7620 Jim_Obj
*skip
= ExprPop(e
);
7621 Jim_Obj
*A
= ExprPop(e
);
7627 switch (ExprBool(interp
, A
)) {
7629 /* false, skip RHS opcodes */
7630 e
->skip
= JimWideValue(skip
);
7631 /* Push a dummy value */
7632 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7636 /* true so do nothing */
7644 Jim_DecrRefCount(interp
, A
);
7645 Jim_DecrRefCount(interp
, skip
);
7650 static int JimExprOpColonLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7652 Jim_Obj
*skip
= ExprPop(e
);
7653 Jim_Obj
*B
= ExprPop(e
);
7654 Jim_Obj
*A
= ExprPop(e
);
7656 /* No need to check for A as non-boolean */
7657 if (ExprBool(interp
, A
)) {
7658 /* true, so skip RHS opcodes */
7659 e
->skip
= JimWideValue(skip
);
7660 /* Repush B as the answer */
7664 Jim_DecrRefCount(interp
, skip
);
7665 Jim_DecrRefCount(interp
, A
);
7666 Jim_DecrRefCount(interp
, B
);
7670 static int JimExprOpNull(Jim_Interp
*interp
, struct JimExprState
*e
)
7683 /* name - precedence - arity - opcode */
7684 static const struct Jim_ExprOperator Jim_ExprOperators
[] = {
7685 [JIM_EXPROP_FUNC_INT
] = {"int", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7686 [JIM_EXPROP_FUNC_DOUBLE
] = {"double", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7687 [JIM_EXPROP_FUNC_ABS
] = {"abs", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7688 [JIM_EXPROP_FUNC_ROUND
] = {"round", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7689 [JIM_EXPROP_FUNC_RAND
] = {"rand", 400, 0, JimExprOpNone
, LAZY_NONE
},
7690 [JIM_EXPROP_FUNC_SRAND
] = {"srand", 400, 1, JimExprOpIntUnary
, LAZY_NONE
},
7692 #ifdef JIM_MATH_FUNCTIONS
7693 [JIM_EXPROP_FUNC_SIN
] = {"sin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7694 [JIM_EXPROP_FUNC_COS
] = {"cos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7695 [JIM_EXPROP_FUNC_TAN
] = {"tan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7696 [JIM_EXPROP_FUNC_ASIN
] = {"asin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7697 [JIM_EXPROP_FUNC_ACOS
] = {"acos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7698 [JIM_EXPROP_FUNC_ATAN
] = {"atan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7699 [JIM_EXPROP_FUNC_SINH
] = {"sinh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7700 [JIM_EXPROP_FUNC_COSH
] = {"cosh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7701 [JIM_EXPROP_FUNC_TANH
] = {"tanh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7702 [JIM_EXPROP_FUNC_CEIL
] = {"ceil", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7703 [JIM_EXPROP_FUNC_FLOOR
] = {"floor", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7704 [JIM_EXPROP_FUNC_EXP
] = {"exp", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7705 [JIM_EXPROP_FUNC_LOG
] = {"log", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7706 [JIM_EXPROP_FUNC_LOG10
] = {"log10", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7707 [JIM_EXPROP_FUNC_SQRT
] = {"sqrt", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7710 [JIM_EXPROP_NOT
] = {"!", 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7711 [JIM_EXPROP_BITNOT
] = {"~", 300, 1, JimExprOpIntUnary
, LAZY_NONE
},
7712 [JIM_EXPROP_UNARYMINUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7713 [JIM_EXPROP_UNARYPLUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7715 [JIM_EXPROP_POW
] = {"**", 250, 2, JimExprOpBin
, LAZY_NONE
},
7717 [JIM_EXPROP_MUL
] = {"*", 200, 2, JimExprOpBin
, LAZY_NONE
},
7718 [JIM_EXPROP_DIV
] = {"/", 200, 2, JimExprOpBin
, LAZY_NONE
},
7719 [JIM_EXPROP_MOD
] = {"%", 200, 2, JimExprOpIntBin
, LAZY_NONE
},
7721 [JIM_EXPROP_SUB
] = {"-", 100, 2, JimExprOpBin
, LAZY_NONE
},
7722 [JIM_EXPROP_ADD
] = {"+", 100, 2, JimExprOpBin
, LAZY_NONE
},
7724 [JIM_EXPROP_ROTL
] = {"<<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7725 [JIM_EXPROP_ROTR
] = {">>>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7726 [JIM_EXPROP_LSHIFT
] = {"<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7727 [JIM_EXPROP_RSHIFT
] = {">>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7729 [JIM_EXPROP_LT
] = {"<", 80, 2, JimExprOpBin
, LAZY_NONE
},
7730 [JIM_EXPROP_GT
] = {">", 80, 2, JimExprOpBin
, LAZY_NONE
},
7731 [JIM_EXPROP_LTE
] = {"<=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7732 [JIM_EXPROP_GTE
] = {">=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7734 [JIM_EXPROP_NUMEQ
] = {"==", 70, 2, JimExprOpBin
, LAZY_NONE
},
7735 [JIM_EXPROP_NUMNE
] = {"!=", 70, 2, JimExprOpBin
, LAZY_NONE
},
7737 [JIM_EXPROP_STREQ
] = {"eq", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7738 [JIM_EXPROP_STRNE
] = {"ne", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7740 [JIM_EXPROP_STRIN
] = {"in", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7741 [JIM_EXPROP_STRNI
] = {"ni", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7743 [JIM_EXPROP_BITAND
] = {"&", 50, 2, JimExprOpIntBin
, LAZY_NONE
},
7744 [JIM_EXPROP_BITXOR
] = {"^", 49, 2, JimExprOpIntBin
, LAZY_NONE
},
7745 [JIM_EXPROP_BITOR
] = {"|", 48, 2, JimExprOpIntBin
, LAZY_NONE
},
7747 [JIM_EXPROP_LOGICAND
] = {"&&", 10, 2, NULL
, LAZY_OP
},
7748 [JIM_EXPROP_LOGICOR
] = {"||", 9, 2, NULL
, LAZY_OP
},
7750 [JIM_EXPROP_TERNARY
] = {"?", 5, 2, JimExprOpNull
, LAZY_OP
},
7751 [JIM_EXPROP_COLON
] = {":", 5, 2, JimExprOpNull
, LAZY_OP
},
7753 /* private operators */
7754 [JIM_EXPROP_TERNARY_LEFT
] = {NULL
, 5, 2, JimExprOpTernaryLeft
, LAZY_LEFT
},
7755 [JIM_EXPROP_TERNARY_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7756 [JIM_EXPROP_COLON_LEFT
] = {NULL
, 5, 2, JimExprOpColonLeft
, LAZY_LEFT
},
7757 [JIM_EXPROP_COLON_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7758 [JIM_EXPROP_LOGICAND_LEFT
] = {NULL
, 10, 2, JimExprOpAndLeft
, LAZY_LEFT
},
7759 [JIM_EXPROP_LOGICAND_RIGHT
] = {NULL
, 10, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7760 [JIM_EXPROP_LOGICOR_LEFT
] = {NULL
, 9, 2, JimExprOpOrLeft
, LAZY_LEFT
},
7761 [JIM_EXPROP_LOGICOR_RIGHT
] = {NULL
, 9, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7764 #define JIM_EXPR_OPERATORS_NUM \
7765 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7767 static int JimParseExpression(struct JimParserCtx
*pc
)
7769 /* Discard spaces and quoted newline */
7770 while (isspace(UCHAR(*pc
->p
)) || (*(pc
->p
) == '\\' && *(pc
->p
+ 1) == '\n')) {
7771 if (*pc
->p
== '\n') {
7779 pc
->tstart
= pc
->tend
= pc
->p
;
7780 pc
->tline
= pc
->linenr
;
7781 pc
->tt
= JIM_TT_EOL
;
7787 pc
->tstart
= pc
->tend
= pc
->p
;
7788 pc
->tline
= pc
->linenr
;
7789 pc
->tt
= JIM_TT_SUBEXPR_START
;
7794 pc
->tstart
= pc
->tend
= pc
->p
;
7795 pc
->tline
= pc
->linenr
;
7796 pc
->tt
= JIM_TT_SUBEXPR_END
;
7801 return JimParseCmd(pc
);
7803 if (JimParseVar(pc
) == JIM_ERR
)
7804 return JimParseExprOperator(pc
);
7806 /* Don't allow expr sugar in expressions */
7807 if (pc
->tt
== JIM_TT_EXPRSUGAR
) {
7824 return JimParseExprNumber(pc
);
7826 return JimParseQuote(pc
);
7828 return JimParseBrace(pc
);
7834 if (JimParseExprIrrational(pc
) == JIM_ERR
)
7835 return JimParseExprOperator(pc
);
7838 return JimParseExprOperator(pc
);
7844 static int JimParseExprNumber(struct JimParserCtx
*pc
)
7849 /* Assume an integer for now */
7850 pc
->tt
= JIM_TT_EXPR_INT
;
7852 pc
->tline
= pc
->linenr
;
7853 while (isdigit(UCHAR(*pc
->p
))
7854 || (allowhex
&& isxdigit(UCHAR(*pc
->p
)))
7855 || (allowdot
&& *pc
->p
== '.')
7856 || (pc
->p
- pc
->tstart
== 1 && *pc
->tstart
== '0' && (*pc
->p
== 'x' || *pc
->p
== 'X'))
7858 if ((*pc
->p
== 'x') || (*pc
->p
== 'X')) {
7862 if (*pc
->p
== '.') {
7864 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7868 if (!allowhex
&& (*pc
->p
== 'e' || *pc
->p
== 'E') && (pc
->p
[1] == '-' || pc
->p
[1] == '+'
7869 || isdigit(UCHAR(pc
->p
[1])))) {
7872 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7875 pc
->tend
= pc
->p
- 1;
7879 static int JimParseExprIrrational(struct JimParserCtx
*pc
)
7881 const char *Tokens
[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL
};
7884 for (token
= Tokens
; *token
!= NULL
; token
++) {
7885 int len
= strlen(*token
);
7887 if (strncmp(*token
, pc
->p
, len
) == 0) {
7889 pc
->tend
= pc
->p
+ len
- 1;
7892 pc
->tline
= pc
->linenr
;
7893 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7900 static int JimParseExprOperator(struct JimParserCtx
*pc
)
7903 int bestIdx
= -1, bestLen
= 0;
7905 /* Try to get the longest match. */
7906 for (i
= JIM_TT_EXPR_OP
; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++) {
7910 opname
= Jim_ExprOperators
[i
].name
;
7911 if (opname
== NULL
) {
7914 oplen
= strlen(opname
);
7916 if (strncmp(opname
, pc
->p
, oplen
) == 0 && oplen
> bestLen
) {
7921 if (bestIdx
== -1) {
7925 /* Validate paretheses around function arguments */
7926 if (bestIdx
>= JIM_EXPROP_FUNC_FIRST
) {
7927 const char *p
= pc
->p
+ bestLen
;
7928 int len
= pc
->len
- bestLen
;
7930 while (len
&& isspace(UCHAR(*p
))) {
7939 pc
->tend
= pc
->p
+ bestLen
- 1;
7942 pc
->tline
= pc
->linenr
;
7948 static const struct Jim_ExprOperator
*JimExprOperatorInfoByOpcode(int opcode
)
7950 return &Jim_ExprOperators
[opcode
];
7953 const char *jim_tt_name(int type
)
7955 static const char * const tt_names
[JIM_TT_EXPR_OP
] =
7956 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", "INT",
7958 if (type
< JIM_TT_EXPR_OP
) {
7959 return tt_names
[type
];
7962 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(type
);
7963 static char buf
[20];
7965 if (op
&& op
->name
) {
7968 sprintf(buf
, "(%d)", type
);
7973 /* -----------------------------------------------------------------------------
7975 * ---------------------------------------------------------------------------*/
7976 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
7977 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
7978 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
7980 static const Jim_ObjType exprObjType
= {
7982 FreeExprInternalRep
,
7985 JIM_TYPE_REFERENCES
,
7988 /* Expr bytecode structure */
7989 typedef struct ExprByteCode
7991 int len
; /* Length as number of tokens. */
7992 ScriptToken
*token
; /* Tokens array. */
7993 int inUse
; /* Used for sharing. */
7996 static void ExprFreeByteCode(Jim_Interp
*interp
, ExprByteCode
* expr
)
8000 for (i
= 0; i
< expr
->len
; i
++) {
8001 Jim_DecrRefCount(interp
, expr
->token
[i
].objPtr
);
8003 Jim_Free(expr
->token
);
8007 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8009 ExprByteCode
*expr
= (void *)objPtr
->internalRep
.ptr
;
8012 if (--expr
->inUse
!= 0) {
8016 ExprFreeByteCode(interp
, expr
);
8020 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8022 JIM_NOTUSED(interp
);
8023 JIM_NOTUSED(srcPtr
);
8025 /* Just returns an simple string. */
8026 dupPtr
->typePtr
= NULL
;
8029 /* Check if an expr program looks correct. */
8030 static int ExprCheckCorrectness(ExprByteCode
* expr
)
8036 /* Try to check if there are stack underflows,
8037 * and make sure at the end of the program there is
8038 * a single result on the stack. */
8039 for (i
= 0; i
< expr
->len
; i
++) {
8040 ScriptToken
*t
= &expr
->token
[i
];
8041 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8044 stacklen
-= op
->arity
;
8048 if (t
->type
== JIM_EXPROP_TERNARY
|| t
->type
== JIM_EXPROP_TERNARY_LEFT
) {
8051 else if (t
->type
== JIM_EXPROP_COLON
|| t
->type
== JIM_EXPROP_COLON_LEFT
) {
8056 /* All operations and operands add one to the stack */
8059 if (stacklen
!= 1 || ternary
!= 0) {
8065 /* This procedure converts every occurrence of || and && opereators
8066 * in lazy unary versions.
8068 * a b || is converted into:
8070 * a <offset> |L b |R
8072 * a b && is converted into:
8074 * a <offset> &L b &R
8076 * "|L" checks if 'a' is true:
8077 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8078 * the opcode just after |R.
8079 * 2) if it is false does nothing.
8080 * "|R" checks if 'b' is true:
8081 * 1) if it is true pushes 1, otherwise pushes 0.
8083 * "&L" checks if 'a' is true:
8084 * 1) if it is true does nothing.
8085 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8086 * the opcode just after &R
8087 * "&R" checks if 'a' is true:
8088 * if it is true pushes 1, otherwise pushes 0.
8090 static int ExprAddLazyOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8094 int leftindex
, arity
, offset
;
8096 /* Search for the end of the first operator */
8097 leftindex
= expr
->len
- 1;
8101 ScriptToken
*tt
= &expr
->token
[leftindex
];
8103 if (tt
->type
>= JIM_TT_EXPR_OP
) {
8104 arity
+= JimExprOperatorInfoByOpcode(tt
->type
)->arity
;
8107 if (--leftindex
< 0) {
8114 memmove(&expr
->token
[leftindex
+ 2], &expr
->token
[leftindex
],
8115 sizeof(*expr
->token
) * (expr
->len
- leftindex
));
8117 offset
= (expr
->len
- leftindex
) - 1;
8119 /* Now we rely on the fact the the left and right version have opcodes
8120 * 1 and 2 after the main opcode respectively
8122 expr
->token
[leftindex
+ 1].type
= t
->type
+ 1;
8123 expr
->token
[leftindex
+ 1].objPtr
= interp
->emptyObj
;
8125 expr
->token
[leftindex
].type
= JIM_TT_EXPR_INT
;
8126 expr
->token
[leftindex
].objPtr
= Jim_NewIntObj(interp
, offset
);
8128 /* Now add the 'R' operator */
8129 expr
->token
[expr
->len
].objPtr
= interp
->emptyObj
;
8130 expr
->token
[expr
->len
].type
= t
->type
+ 2;
8133 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8134 for (i
= leftindex
- 1; i
> 0; i
--) {
8135 if (JimExprOperatorInfoByOpcode(expr
->token
[i
].type
)->lazy
== LAZY_LEFT
) {
8136 if (JimWideValue(expr
->token
[i
- 1].objPtr
) + i
- 1 >= leftindex
) {
8137 JimWideValue(expr
->token
[i
- 1].objPtr
) += 2;
8144 static int ExprAddOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8146 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8147 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8149 if (op
->lazy
== LAZY_OP
) {
8150 if (ExprAddLazyOperator(interp
, expr
, t
) != JIM_OK
) {
8151 Jim_SetResultFormatted(interp
, "Expression has bad operands to %s", op
->name
);
8156 token
->objPtr
= interp
->emptyObj
;
8157 token
->type
= t
->type
;
8164 * Returns the index of the COLON_LEFT to the left of 'right_index'
8165 * taking into account nesting.
8167 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8169 static int ExprTernaryGetColonLeftIndex(ExprByteCode
*expr
, int right_index
)
8171 int ternary_count
= 1;
8175 while (right_index
> 1) {
8176 if (expr
->token
[right_index
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8179 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_RIGHT
) {
8182 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_LEFT
&& ternary_count
== 1) {
8193 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8195 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8196 * Otherwise returns 0.
8198 static int ExprTernaryGetMoveIndices(ExprByteCode
*expr
, int right_index
, int *prev_right_index
, int *prev_left_index
)
8200 int i
= right_index
- 1;
8201 int ternary_count
= 1;
8204 if (expr
->token
[i
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8205 if (--ternary_count
== 0 && expr
->token
[i
- 2].type
== JIM_EXPROP_COLON_RIGHT
) {
8206 *prev_right_index
= i
- 2;
8207 *prev_left_index
= ExprTernaryGetColonLeftIndex(expr
, *prev_right_index
);
8211 else if (expr
->token
[i
].type
== JIM_EXPROP_COLON_RIGHT
) {
8212 if (ternary_count
== 0) {
8223 * ExprTernaryReorderExpression description
8224 * ========================================
8226 * ?: is right-to-left associative which doesn't work with the stack-based
8227 * expression engine. The fix is to reorder the bytecode.
8233 * Has initial bytecode:
8235 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8236 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8238 * The fix involves simulating this expression instead:
8242 * With the following bytecode:
8244 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8245 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8247 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8248 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8249 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8250 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8252 * ExprTernaryReorderExpression works thus as follows :
8253 * - start from the end of the stack
8254 * - while walking towards the beginning of the stack
8255 * if token=JIM_EXPROP_COLON_RIGHT then
8256 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8257 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8258 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8260 * perform the rotation
8261 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8265 * Note: care has to be taken for nested ternary constructs!!!
8267 static void ExprTernaryReorderExpression(Jim_Interp
*interp
, ExprByteCode
*expr
)
8271 for (i
= expr
->len
- 1; i
> 1; i
--) {
8272 int prev_right_index
;
8273 int prev_left_index
;
8277 if (expr
->token
[i
].type
!= JIM_EXPROP_COLON_RIGHT
) {
8281 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8282 if (ExprTernaryGetMoveIndices(expr
, i
, &prev_right_index
, &prev_left_index
) == 0) {
8287 ** rotate tokens down
8289 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8298 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8300 tmp
= expr
->token
[prev_right_index
];
8301 for (j
= prev_right_index
; j
< i
; j
++) {
8302 expr
->token
[j
] = expr
->token
[j
+ 1];
8304 expr
->token
[i
] = tmp
;
8306 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8308 * This is 'colon left increment' = i - prev_right_index
8310 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8311 * [prev_left_index-1] : skip_count
8314 JimWideValue(expr
->token
[prev_left_index
-1].objPtr
) += (i
- prev_right_index
);
8316 /* Adjust for i-- in the loop */
8321 static ExprByteCode
*ExprCreateByteCode(Jim_Interp
*interp
, const ParseTokenList
*tokenlist
, Jim_Obj
*fileNameObj
)
8327 int prevtt
= JIM_TT_NONE
;
8328 int have_ternary
= 0;
8331 int count
= tokenlist
->count
- 1;
8333 expr
= Jim_Alloc(sizeof(*expr
));
8337 Jim_InitStack(&stack
);
8339 /* Need extra bytecodes for lazy operators.
8340 * Also check for the ternary operator
8342 for (i
= 0; i
< tokenlist
->count
; i
++) {
8343 ParseToken
*t
= &tokenlist
->list
[i
];
8345 if (JimExprOperatorInfoByOpcode(t
->type
)->lazy
== LAZY_OP
) {
8347 /* Ternary is a lazy op but also needs reordering */
8348 if (t
->type
== JIM_EXPROP_TERNARY
) {
8354 expr
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
8356 for (i
= 0; i
< tokenlist
->count
&& ok
; i
++) {
8357 ParseToken
*t
= &tokenlist
->list
[i
];
8359 /* Next token will be stored here */
8360 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8362 if (t
->type
== JIM_TT_EOL
) {
8370 case JIM_TT_DICTSUGAR
:
8371 case JIM_TT_EXPRSUGAR
:
8373 token
->objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
8374 token
->type
= t
->type
;
8375 if (t
->type
== JIM_TT_CMD
) {
8376 /* Only commands need source info */
8377 JimSetSourceInfo(interp
, token
->objPtr
, fileNameObj
, t
->line
);
8382 case JIM_TT_EXPR_INT
:
8383 token
->objPtr
= Jim_NewIntObj(interp
, strtoull(t
->token
, NULL
, 0));
8384 token
->type
= t
->type
;
8388 case JIM_TT_EXPR_DOUBLE
:
8389 token
->objPtr
= Jim_NewDoubleObj(interp
, strtod(t
->token
, NULL
));
8390 token
->type
= t
->type
;
8394 case JIM_TT_SUBEXPR_START
:
8395 Jim_StackPush(&stack
, t
);
8396 prevtt
= JIM_TT_NONE
;
8399 case JIM_TT_SUBEXPR_END
:
8401 while (Jim_StackLen(&stack
)) {
8402 ParseToken
*tt
= Jim_StackPop(&stack
);
8404 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8409 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8414 Jim_SetResultString(interp
, "Unexpected close parenthesis", -1);
8421 /* Must be an operator */
8422 const struct Jim_ExprOperator
*op
;
8425 /* Convert -/+ to unary minus or unary plus if necessary */
8426 if (prevtt
== JIM_TT_NONE
|| prevtt
>= JIM_TT_EXPR_OP
) {
8427 if (t
->type
== JIM_EXPROP_SUB
) {
8428 t
->type
= JIM_EXPROP_UNARYMINUS
;
8430 else if (t
->type
== JIM_EXPROP_ADD
) {
8431 t
->type
= JIM_EXPROP_UNARYPLUS
;
8435 op
= JimExprOperatorInfoByOpcode(t
->type
);
8437 /* Now handle precedence */
8438 while ((tt
= Jim_StackPeek(&stack
)) != NULL
) {
8439 const struct Jim_ExprOperator
*tt_op
=
8440 JimExprOperatorInfoByOpcode(tt
->type
);
8442 /* Note that right-to-left associativity of ?: operator is handled later */
8444 if (op
->arity
!= 1 && tt_op
->precedence
>= op
->precedence
) {
8445 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8449 Jim_StackPop(&stack
);
8455 Jim_StackPush(&stack
, t
);
8462 /* Reduce any remaining subexpr */
8463 while (Jim_StackLen(&stack
)) {
8464 ParseToken
*tt
= Jim_StackPop(&stack
);
8466 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8468 Jim_SetResultString(interp
, "Missing close parenthesis", -1);
8471 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8478 ExprTernaryReorderExpression(interp
, expr
);
8482 /* Free the stack used for the compilation. */
8483 Jim_FreeStack(&stack
);
8485 for (i
= 0; i
< expr
->len
; i
++) {
8486 Jim_IncrRefCount(expr
->token
[i
].objPtr
);
8490 ExprFreeByteCode(interp
, expr
);
8498 /* This method takes the string representation of an expression
8499 * and generates a program for the Expr's stack-based VM. */
8500 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
8503 const char *exprText
;
8504 struct JimParserCtx parser
;
8505 struct ExprByteCode
*expr
;
8506 ParseTokenList tokenlist
;
8508 Jim_Obj
*fileNameObj
;
8511 /* Try to get information about filename / line number */
8512 if (objPtr
->typePtr
== &sourceObjType
) {
8513 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
8514 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
8517 fileNameObj
= interp
->emptyObj
;
8520 Jim_IncrRefCount(fileNameObj
);
8522 exprText
= Jim_GetString(objPtr
, &exprTextLen
);
8524 /* Initially tokenise the expression into tokenlist */
8525 ScriptTokenListInit(&tokenlist
);
8527 JimParserInit(&parser
, exprText
, exprTextLen
, line
);
8528 while (!parser
.eof
) {
8529 if (JimParseExpression(&parser
) != JIM_OK
) {
8530 ScriptTokenListFree(&tokenlist
);
8532 Jim_SetResultFormatted(interp
, "syntax error in expression: \"%#s\"", objPtr
);
8537 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
8541 #ifdef DEBUG_SHOW_EXPR_TOKENS
8544 printf("==== Expr Tokens ====\n");
8545 for (i
= 0; i
< tokenlist
.count
; i
++) {
8546 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
.list
[i
].line
, jim_tt_name(tokenlist
.list
[i
].type
),
8547 tokenlist
.list
[i
].len
, tokenlist
.list
[i
].token
);
8552 /* Now create the expression bytecode from the tokenlist */
8553 expr
= ExprCreateByteCode(interp
, &tokenlist
, fileNameObj
);
8555 /* No longer need the token list */
8556 ScriptTokenListFree(&tokenlist
);
8562 #ifdef DEBUG_SHOW_EXPR
8566 printf("==== Expr ====\n");
8567 for (i
= 0; i
< expr
->len
; i
++) {
8568 ScriptToken
*t
= &expr
->token
[i
];
8570 printf("[%2d] %s '%s'\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
8575 /* Check program correctness. */
8576 if (ExprCheckCorrectness(expr
) != JIM_OK
) {
8577 ExprFreeByteCode(interp
, expr
);
8584 /* Free the old internal rep and set the new one. */
8585 Jim_DecrRefCount(interp
, fileNameObj
);
8586 Jim_FreeIntRep(interp
, objPtr
);
8587 Jim_SetIntRepPtr(objPtr
, expr
);
8588 objPtr
->typePtr
= &exprObjType
;
8592 static ExprByteCode
*JimGetExpression(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8594 if (objPtr
->typePtr
!= &exprObjType
) {
8595 if (SetExprFromAny(interp
, objPtr
) != JIM_OK
) {
8599 return (ExprByteCode
*) Jim_GetIntRepPtr(objPtr
);
8602 /* -----------------------------------------------------------------------------
8603 * Expressions evaluation.
8604 * Jim uses a specialized stack-based virtual machine for expressions,
8605 * that takes advantage of the fact that expr's operators
8606 * can't be redefined.
8608 * Jim_EvalExpression() uses the bytecode compiled by
8609 * SetExprFromAny() method of the "expression" object.
8611 * On success a Tcl Object containing the result of the evaluation
8612 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8614 * On error the function returns a retcode != to JIM_OK and set a suitable
8615 * error on the interp.
8616 * ---------------------------------------------------------------------------*/
8617 #define JIM_EE_STATICSTACK_LEN 10
8619 int Jim_EvalExpression(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, Jim_Obj
**exprResultPtrPtr
)
8622 Jim_Obj
*staticStack
[JIM_EE_STATICSTACK_LEN
];
8624 int retcode
= JIM_OK
;
8625 struct JimExprState e
;
8627 expr
= JimGetExpression(interp
, exprObjPtr
);
8629 return JIM_ERR
; /* error in expression. */
8632 #ifdef JIM_OPTIMIZATION
8633 /* Check for one of the following common expressions used by while/for
8638 * $a < CONST, $a < $b
8639 * $a <= CONST, $a <= $b
8640 * $a > CONST, $a > $b
8641 * $a >= CONST, $a >= $b
8642 * $a != CONST, $a != $b
8643 * $a == CONST, $a == $b
8648 /* STEP 1 -- Check if there are the conditions to run the specialized
8649 * version of while */
8651 switch (expr
->len
) {
8653 if (expr
->token
[0].type
== JIM_TT_EXPR_INT
) {
8654 *exprResultPtrPtr
= expr
->token
[0].objPtr
;
8655 Jim_IncrRefCount(*exprResultPtrPtr
);
8658 if (expr
->token
[0].type
== JIM_TT_VAR
) {
8659 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_ERRMSG
);
8661 *exprResultPtrPtr
= objPtr
;
8662 Jim_IncrRefCount(*exprResultPtrPtr
);
8669 if (expr
->token
[1].type
== JIM_EXPROP_NOT
&& expr
->token
[0].type
== JIM_TT_VAR
) {
8672 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8673 if (objPtr
&& JimIsWide(objPtr
)
8674 && Jim_GetWide(interp
, objPtr
, &wideValue
) == JIM_OK
) {
8675 *exprResultPtrPtr
= wideValue
? interp
->falseObj
: interp
->trueObj
;
8676 Jim_IncrRefCount(*exprResultPtrPtr
);
8683 if (expr
->token
[0].type
== JIM_TT_VAR
&& (expr
->token
[1].type
== JIM_TT_EXPR_INT
8684 || expr
->token
[1].type
== JIM_TT_VAR
)) {
8685 switch (expr
->token
[2].type
) {
8687 case JIM_EXPROP_LTE
:
8689 case JIM_EXPROP_GTE
:
8690 case JIM_EXPROP_NUMEQ
:
8691 case JIM_EXPROP_NUMNE
:{
8693 jim_wide wideValueA
;
8694 jim_wide wideValueB
;
8696 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8697 if (objPtr
&& JimIsWide(objPtr
)
8698 && Jim_GetWide(interp
, objPtr
, &wideValueA
) == JIM_OK
) {
8699 if (expr
->token
[1].type
== JIM_TT_VAR
) {
8701 Jim_GetVariable(interp
, expr
->token
[1].objPtr
,
8705 objPtr
= expr
->token
[1].objPtr
;
8707 if (objPtr
&& JimIsWide(objPtr
)
8708 && Jim_GetWide(interp
, objPtr
, &wideValueB
) == JIM_OK
) {
8711 switch (expr
->token
[2].type
) {
8713 cmpRes
= wideValueA
< wideValueB
;
8715 case JIM_EXPROP_LTE
:
8716 cmpRes
= wideValueA
<= wideValueB
;
8719 cmpRes
= wideValueA
> wideValueB
;
8721 case JIM_EXPROP_GTE
:
8722 cmpRes
= wideValueA
>= wideValueB
;
8724 case JIM_EXPROP_NUMEQ
:
8725 cmpRes
= wideValueA
== wideValueB
;
8727 case JIM_EXPROP_NUMNE
:
8728 cmpRes
= wideValueA
!= wideValueB
;
8730 default: /*notreached */
8734 cmpRes
? interp
->trueObj
: interp
->falseObj
;
8735 Jim_IncrRefCount(*exprResultPtrPtr
);
8747 /* In order to avoid that the internal repr gets freed due to
8748 * shimmering of the exprObjPtr's object, we make the internal rep
8752 /* The stack-based expr VM itself */
8754 /* Stack allocation. Expr programs have the feature that
8755 * a program of length N can't require a stack longer than
8757 if (expr
->len
> JIM_EE_STATICSTACK_LEN
)
8758 e
.stack
= Jim_Alloc(sizeof(Jim_Obj
*) * expr
->len
);
8760 e
.stack
= staticStack
;
8764 /* Execute every instruction */
8765 for (i
= 0; i
< expr
->len
&& retcode
== JIM_OK
; i
++) {
8768 switch (expr
->token
[i
].type
) {
8769 case JIM_TT_EXPR_INT
:
8770 case JIM_TT_EXPR_DOUBLE
:
8772 ExprPush(&e
, expr
->token
[i
].objPtr
);
8776 objPtr
= Jim_GetVariable(interp
, expr
->token
[i
].objPtr
, JIM_ERRMSG
);
8778 ExprPush(&e
, objPtr
);
8785 case JIM_TT_DICTSUGAR
:
8786 objPtr
= JimExpandDictSugar(interp
, expr
->token
[i
].objPtr
);
8788 ExprPush(&e
, objPtr
);
8796 retcode
= Jim_SubstObj(interp
, expr
->token
[i
].objPtr
, &objPtr
, JIM_NONE
);
8797 if (retcode
== JIM_OK
) {
8798 ExprPush(&e
, objPtr
);
8803 retcode
= Jim_EvalObj(interp
, expr
->token
[i
].objPtr
);
8804 if (retcode
== JIM_OK
) {
8805 ExprPush(&e
, Jim_GetResult(interp
));
8810 /* Find and execute the operation */
8812 e
.opcode
= expr
->token
[i
].type
;
8814 retcode
= JimExprOperatorInfoByOpcode(e
.opcode
)->funcop(interp
, &e
);
8815 /* Skip some opcodes if necessary */
8824 if (retcode
== JIM_OK
) {
8825 *exprResultPtrPtr
= ExprPop(&e
);
8828 for (i
= 0; i
< e
.stacklen
; i
++) {
8829 Jim_DecrRefCount(interp
, e
.stack
[i
]);
8832 if (e
.stack
!= staticStack
) {
8838 int Jim_GetBoolFromExpr(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, int *boolPtr
)
8843 Jim_Obj
*exprResultPtr
;
8845 retcode
= Jim_EvalExpression(interp
, exprObjPtr
, &exprResultPtr
);
8846 if (retcode
!= JIM_OK
)
8849 if (JimGetWideNoErr(interp
, exprResultPtr
, &wideValue
) != JIM_OK
) {
8850 if (Jim_GetDouble(interp
, exprResultPtr
, &doubleValue
) != JIM_OK
) {
8851 Jim_DecrRefCount(interp
, exprResultPtr
);
8855 Jim_DecrRefCount(interp
, exprResultPtr
);
8856 *boolPtr
= doubleValue
!= 0;
8860 *boolPtr
= wideValue
!= 0;
8862 Jim_DecrRefCount(interp
, exprResultPtr
);
8866 /* -----------------------------------------------------------------------------
8867 * ScanFormat String Object
8868 * ---------------------------------------------------------------------------*/
8870 /* This Jim_Obj will held a parsed representation of a format string passed to
8871 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8872 * to be parsed in its entirely first and then, if correct, can be used for
8873 * scanning. To avoid endless re-parsing, the parsed representation will be
8874 * stored in an internal representation and re-used for performance reason. */
8876 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8877 * scanformat string. This part will later be used to extract information
8878 * out from the string to be parsed by Jim_ScanString */
8880 typedef struct ScanFmtPartDescr
8882 char type
; /* Type of conversion (e.g. c, d, f) */
8883 char modifier
; /* Modify type (e.g. l - long, h - short */
8884 size_t width
; /* Maximal width of input to be converted */
8885 int pos
; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8886 char *arg
; /* Specification of a CHARSET conversion */
8887 char *prefix
; /* Prefix to be scanned literally before conversion */
8890 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8891 * string parsed and separated in part descriptions. Furthermore it contains
8892 * the original string representation of the scanformat string to allow for
8893 * fast update of the Jim_Obj's string representation part.
8895 * As an add-on the internal object representation adds some scratch pad area
8896 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8897 * memory for purpose of string scanning.
8899 * The error member points to a static allocated string in case of a mal-
8900 * formed scanformat string or it contains '0' (NULL) in case of a valid
8901 * parse representation.
8903 * The whole memory of the internal representation is allocated as a single
8904 * area of memory that will be internally separated. So freeing and duplicating
8905 * of such an object is cheap */
8907 typedef struct ScanFmtStringObj
8909 jim_wide size
; /* Size of internal repr in bytes */
8910 char *stringRep
; /* Original string representation */
8911 size_t count
; /* Number of ScanFmtPartDescr contained */
8912 size_t convCount
; /* Number of conversions that will assign */
8913 size_t maxPos
; /* Max position index if XPG3 is used */
8914 const char *error
; /* Ptr to error text (NULL if no error */
8915 char *scratch
; /* Some scratch pad used by Jim_ScanString */
8916 ScanFmtPartDescr descr
[1]; /* The vector of partial descriptions */
8920 static void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
8921 static void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
8922 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
);
8924 static const Jim_ObjType scanFmtStringObjType
= {
8926 FreeScanFmtInternalRep
,
8927 DupScanFmtInternalRep
,
8928 UpdateStringOfScanFmt
,
8932 void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8934 JIM_NOTUSED(interp
);
8935 Jim_Free((char *)objPtr
->internalRep
.ptr
);
8936 objPtr
->internalRep
.ptr
= 0;
8939 void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8941 size_t size
= (size_t) ((ScanFmtStringObj
*) srcPtr
->internalRep
.ptr
)->size
;
8942 ScanFmtStringObj
*newVec
= (ScanFmtStringObj
*) Jim_Alloc(size
);
8944 JIM_NOTUSED(interp
);
8945 memcpy(newVec
, srcPtr
->internalRep
.ptr
, size
);
8946 dupPtr
->internalRep
.ptr
= newVec
;
8947 dupPtr
->typePtr
= &scanFmtStringObjType
;
8950 void UpdateStringOfScanFmt(Jim_Obj
*objPtr
)
8952 char *bytes
= ((ScanFmtStringObj
*) objPtr
->internalRep
.ptr
)->stringRep
;
8954 objPtr
->bytes
= Jim_StrDup(bytes
);
8955 objPtr
->length
= strlen(bytes
);
8958 /* SetScanFmtFromAny will parse a given string and create the internal
8959 * representation of the format specification. In case of an error
8960 * the error data member of the internal representation will be set
8961 * to an descriptive error text and the function will be left with
8962 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
8965 static int SetScanFmtFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8967 ScanFmtStringObj
*fmtObj
;
8969 int maxCount
, i
, approxSize
, lastPos
= -1;
8970 const char *fmt
= objPtr
->bytes
;
8971 int maxFmtLen
= objPtr
->length
;
8972 const char *fmtEnd
= fmt
+ maxFmtLen
;
8975 Jim_FreeIntRep(interp
, objPtr
);
8976 /* Count how many conversions could take place maximally */
8977 for (i
= 0, maxCount
= 0; i
< maxFmtLen
; ++i
)
8980 /* Calculate an approximation of the memory necessary */
8981 approxSize
= sizeof(ScanFmtStringObj
) /* Size of the container */
8982 +(maxCount
+ 1) * sizeof(ScanFmtPartDescr
) /* Size of all partials */
8983 +maxFmtLen
* sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
8984 + maxFmtLen
* sizeof(char) + 1 /* Original stringrep */
8985 + maxFmtLen
* sizeof(char) /* Arg for CHARSETs */
8986 +(maxCount
+ 1) * sizeof(char) /* '\0' for every partial */
8987 +1; /* safety byte */
8988 fmtObj
= (ScanFmtStringObj
*) Jim_Alloc(approxSize
);
8989 memset(fmtObj
, 0, approxSize
);
8990 fmtObj
->size
= approxSize
;
8992 fmtObj
->scratch
= (char *)&fmtObj
->descr
[maxCount
+ 1];
8993 fmtObj
->stringRep
= fmtObj
->scratch
+ maxFmtLen
+ 3 + 1;
8994 memcpy(fmtObj
->stringRep
, fmt
, maxFmtLen
);
8995 buffer
= fmtObj
->stringRep
+ maxFmtLen
+ 1;
8996 objPtr
->internalRep
.ptr
= fmtObj
;
8997 objPtr
->typePtr
= &scanFmtStringObjType
;
8998 for (i
= 0, curr
= 0; fmt
< fmtEnd
; ++fmt
) {
8999 int width
= 0, skip
;
9000 ScanFmtPartDescr
*descr
= &fmtObj
->descr
[curr
];
9003 descr
->width
= 0; /* Assume width unspecified */
9004 /* Overread and store any "literal" prefix */
9005 if (*fmt
!= '%' || fmt
[1] == '%') {
9007 descr
->prefix
= &buffer
[i
];
9008 for (; fmt
< fmtEnd
; ++fmt
) {
9018 /* Skip the conversion introducing '%' sign */
9020 /* End reached due to non-conversion literal only? */
9023 descr
->pos
= 0; /* Assume "natural" positioning */
9025 descr
->pos
= -1; /* Okay, conversion will not be assigned */
9029 fmtObj
->convCount
++; /* Otherwise count as assign-conversion */
9030 /* Check if next token is a number (could be width or pos */
9031 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9033 /* Was the number a XPG3 position specifier? */
9034 if (descr
->pos
!= -1 && *fmt
== '$') {
9040 /* Look if "natural" postioning and XPG3 one was mixed */
9041 if ((lastPos
== 0 && descr
->pos
> 0)
9042 || (lastPos
> 0 && descr
->pos
== 0)) {
9043 fmtObj
->error
= "cannot mix \"%\" and \"%n$\" conversion specifiers";
9046 /* Look if this position was already used */
9047 for (prev
= 0; prev
< curr
; ++prev
) {
9048 if (fmtObj
->descr
[prev
].pos
== -1)
9050 if (fmtObj
->descr
[prev
].pos
== descr
->pos
) {
9052 "variable is assigned by multiple \"%n$\" conversion specifiers";
9056 /* Try to find a width after the XPG3 specifier */
9057 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9058 descr
->width
= width
;
9061 if (descr
->pos
> 0 && (size_t) descr
->pos
> fmtObj
->maxPos
)
9062 fmtObj
->maxPos
= descr
->pos
;
9065 /* Number was not a XPG3, so it has to be a width */
9066 descr
->width
= width
;
9069 /* If positioning mode was undetermined yet, fix this */
9071 lastPos
= descr
->pos
;
9072 /* Handle CHARSET conversion type ... */
9074 int swapped
= 1, beg
= i
, end
, j
;
9077 descr
->arg
= &buffer
[i
];
9080 buffer
[i
++] = *fmt
++;
9082 buffer
[i
++] = *fmt
++;
9083 while (*fmt
&& *fmt
!= ']')
9084 buffer
[i
++] = *fmt
++;
9086 fmtObj
->error
= "unmatched [ in format string";
9091 /* In case a range fence was given "backwards", swap it */
9094 for (j
= beg
+ 1; j
< end
- 1; ++j
) {
9095 if (buffer
[j
] == '-' && buffer
[j
- 1] > buffer
[j
+ 1]) {
9096 char tmp
= buffer
[j
- 1];
9098 buffer
[j
- 1] = buffer
[j
+ 1];
9099 buffer
[j
+ 1] = tmp
;
9106 /* Remember any valid modifier if given */
9107 if (strchr("hlL", *fmt
) != 0)
9108 descr
->modifier
= tolower((int)*fmt
++);
9111 if (strchr("efgcsndoxui", *fmt
) == 0) {
9112 fmtObj
->error
= "bad scan conversion character";
9115 else if (*fmt
== 'c' && descr
->width
!= 0) {
9116 fmtObj
->error
= "field width may not be specified in %c " "conversion";
9119 else if (*fmt
== 'u' && descr
->modifier
== 'l') {
9120 fmtObj
->error
= "unsigned wide not supported";
9130 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9132 #define FormatGetCnvCount(_fo_) \
9133 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9134 #define FormatGetMaxPos(_fo_) \
9135 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9136 #define FormatGetError(_fo_) \
9137 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9139 /* JimScanAString is used to scan an unspecified string that ends with
9140 * next WS, or a string that is specified via a charset.
9143 static Jim_Obj
*JimScanAString(Jim_Interp
*interp
, const char *sdescr
, const char *str
)
9145 char *buffer
= Jim_StrDup(str
);
9152 if (!sdescr
&& isspace(UCHAR(*str
)))
9153 break; /* EOS via WS if unspecified */
9155 n
= utf8_tounicode(str
, &c
);
9156 if (sdescr
&& !JimCharsetMatch(sdescr
, c
, JIM_CHARSET_SCAN
))
9162 return Jim_NewStringObjNoAlloc(interp
, buffer
, p
- buffer
);
9165 /* ScanOneEntry will scan one entry out of the string passed as argument.
9166 * It use the sscanf() function for this task. After extracting and
9167 * converting of the value, the count of scanned characters will be
9168 * returned of -1 in case of no conversion tool place and string was
9169 * already scanned thru */
9171 static int ScanOneEntry(Jim_Interp
*interp
, const char *str
, int pos
, int strLen
,
9172 ScanFmtStringObj
* fmtObj
, long idx
, Jim_Obj
**valObjPtr
)
9175 const ScanFmtPartDescr
*descr
= &fmtObj
->descr
[idx
];
9177 size_t anchor
= pos
;
9179 Jim_Obj
*tmpObj
= NULL
;
9181 /* First pessimistically assume, we will not scan anything :-) */
9183 if (descr
->prefix
) {
9184 /* There was a prefix given before the conversion, skip it and adjust
9185 * the string-to-be-parsed accordingly */
9186 /* XXX: Should be checking strLen, not str[pos] */
9187 for (i
= 0; pos
< strLen
&& descr
->prefix
[i
]; ++i
) {
9188 /* If prefix require, skip WS */
9189 if (isspace(UCHAR(descr
->prefix
[i
])))
9190 while (pos
< strLen
&& isspace(UCHAR(str
[pos
])))
9192 else if (descr
->prefix
[i
] != str
[pos
])
9193 break; /* Prefix do not match here, leave the loop */
9195 ++pos
; /* Prefix matched so far, next round */
9197 if (pos
>= strLen
) {
9198 return -1; /* All of str consumed: EOF condition */
9200 else if (descr
->prefix
[i
] != 0)
9201 return 0; /* Not whole prefix consumed, no conversion possible */
9203 /* For all but following conversion, skip leading WS */
9204 if (descr
->type
!= 'c' && descr
->type
!= '[' && descr
->type
!= 'n')
9205 while (isspace(UCHAR(str
[pos
])))
9207 /* Determine how much skipped/scanned so far */
9208 scanned
= pos
- anchor
;
9210 /* %c is a special, simple case. no width */
9211 if (descr
->type
== 'n') {
9212 /* Return pseudo conversion means: how much scanned so far? */
9213 *valObjPtr
= Jim_NewIntObj(interp
, anchor
+ scanned
);
9215 else if (pos
>= strLen
) {
9216 /* Cannot scan anything, as str is totally consumed */
9219 else if (descr
->type
== 'c') {
9221 scanned
+= utf8_tounicode(&str
[pos
], &c
);
9222 *valObjPtr
= Jim_NewIntObj(interp
, c
);
9226 /* Processing of conversions follows ... */
9227 if (descr
->width
> 0) {
9228 /* Do not try to scan as fas as possible but only the given width.
9229 * To ensure this, we copy the part that should be scanned. */
9230 size_t sLen
= utf8_strlen(&str
[pos
], strLen
- pos
);
9231 size_t tLen
= descr
->width
> sLen
? sLen
: descr
->width
;
9233 tmpObj
= Jim_NewStringObjUtf8(interp
, str
+ pos
, tLen
);
9234 tok
= tmpObj
->bytes
;
9237 /* As no width was given, simply refer to the original string */
9240 switch (descr
->type
) {
9246 char *endp
; /* Position where the number finished */
9249 int base
= descr
->type
== 'o' ? 8
9250 : descr
->type
== 'x' ? 16 : descr
->type
== 'i' ? 0 : 10;
9252 /* Try to scan a number with the given base */
9253 w
= strtoull(tok
, &endp
, base
);
9254 if (endp
== tok
&& base
== 0) {
9255 /* If scanning failed, and base was undetermined, simply
9256 * put it to 10 and try once more. This should catch the
9257 * case where %i begin to parse a number prefix (e.g.
9258 * '0x' but no further digits follows. This will be
9259 * handled as a ZERO followed by a char 'x' by Tcl */
9260 w
= strtoull(tok
, &endp
, 10);
9264 /* There was some number sucessfully scanned! */
9265 *valObjPtr
= Jim_NewIntObj(interp
, w
);
9267 /* Adjust the number-of-chars scanned so far */
9268 scanned
+= endp
- tok
;
9271 /* Nothing was scanned. We have to determine if this
9272 * happened due to e.g. prefix mismatch or input str
9274 scanned
= *tok
? 0 : -1;
9280 *valObjPtr
= JimScanAString(interp
, descr
->arg
, tok
);
9281 scanned
+= Jim_Length(*valObjPtr
);
9288 double value
= strtod(tok
, &endp
);
9291 /* There was some number sucessfully scanned! */
9292 *valObjPtr
= Jim_NewDoubleObj(interp
, value
);
9293 /* Adjust the number-of-chars scanned so far */
9294 scanned
+= endp
- tok
;
9297 /* Nothing was scanned. We have to determine if this
9298 * happened due to e.g. prefix mismatch or input str
9300 scanned
= *tok
? 0 : -1;
9305 /* If a substring was allocated (due to pre-defined width) do not
9306 * forget to free it */
9308 Jim_FreeNewObj(interp
, tmpObj
);
9314 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9315 * string and returns all converted (and not ignored) values in a list back
9316 * to the caller. If an error occured, a NULL pointer will be returned */
9318 Jim_Obj
*Jim_ScanString(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*fmtObjPtr
, int flags
)
9322 const char *str
= Jim_String(strObjPtr
);
9323 int strLen
= Jim_Utf8Length(interp
, strObjPtr
);
9324 Jim_Obj
*resultList
= 0;
9325 Jim_Obj
**resultVec
= 0;
9327 Jim_Obj
*emptyStr
= 0;
9328 ScanFmtStringObj
*fmtObj
;
9330 /* This should never happen. The format object should already be of the correct type */
9331 JimPanic((fmtObjPtr
->typePtr
!= &scanFmtStringObjType
, "Jim_ScanString() for non-scan format"));
9333 fmtObj
= (ScanFmtStringObj
*) fmtObjPtr
->internalRep
.ptr
;
9334 /* Check if format specification was valid */
9335 if (fmtObj
->error
!= 0) {
9336 if (flags
& JIM_ERRMSG
)
9337 Jim_SetResultString(interp
, fmtObj
->error
, -1);
9340 /* Allocate a new "shared" empty string for all unassigned conversions */
9341 emptyStr
= Jim_NewEmptyStringObj(interp
);
9342 Jim_IncrRefCount(emptyStr
);
9343 /* Create a list and fill it with empty strings up to max specified XPG3 */
9344 resultList
= Jim_NewListObj(interp
, 0, 0);
9345 if (fmtObj
->maxPos
> 0) {
9346 for (i
= 0; i
< fmtObj
->maxPos
; ++i
)
9347 Jim_ListAppendElement(interp
, resultList
, emptyStr
);
9348 JimListGetElements(interp
, resultList
, &resultc
, &resultVec
);
9350 /* Now handle every partial format description */
9351 for (i
= 0, pos
= 0; i
< fmtObj
->count
; ++i
) {
9352 ScanFmtPartDescr
*descr
= &(fmtObj
->descr
[i
]);
9355 /* Only last type may be "literal" w/o conversion - skip it! */
9356 if (descr
->type
== 0)
9358 /* As long as any conversion could be done, we will proceed */
9360 scanned
= ScanOneEntry(interp
, str
, pos
, strLen
, fmtObj
, i
, &value
);
9361 /* In case our first try results in EOF, we will leave */
9362 if (scanned
== -1 && i
== 0)
9364 /* Advance next pos-to-be-scanned for the amount scanned already */
9367 /* value == 0 means no conversion took place so take empty string */
9369 value
= Jim_NewEmptyStringObj(interp
);
9370 /* If value is a non-assignable one, skip it */
9371 if (descr
->pos
== -1) {
9372 Jim_FreeNewObj(interp
, value
);
9374 else if (descr
->pos
== 0)
9375 /* Otherwise append it to the result list if no XPG3 was given */
9376 Jim_ListAppendElement(interp
, resultList
, value
);
9377 else if (resultVec
[descr
->pos
- 1] == emptyStr
) {
9378 /* But due to given XPG3, put the value into the corr. slot */
9379 Jim_DecrRefCount(interp
, resultVec
[descr
->pos
- 1]);
9380 Jim_IncrRefCount(value
);
9381 resultVec
[descr
->pos
- 1] = value
;
9384 /* Otherwise, the slot was already used - free obj and ERROR */
9385 Jim_FreeNewObj(interp
, value
);
9389 Jim_DecrRefCount(interp
, emptyStr
);
9392 Jim_DecrRefCount(interp
, emptyStr
);
9393 Jim_FreeNewObj(interp
, resultList
);
9394 return (Jim_Obj
*)EOF
;
9396 Jim_DecrRefCount(interp
, emptyStr
);
9397 Jim_FreeNewObj(interp
, resultList
);
9401 /* -----------------------------------------------------------------------------
9402 * Pseudo Random Number Generation
9403 * ---------------------------------------------------------------------------*/
9404 /* Initialize the sbox with the numbers from 0 to 255 */
9405 static void JimPrngInit(Jim_Interp
*interp
)
9407 #define PRNG_SEED_SIZE 256
9410 time_t t
= time(NULL
);
9412 interp
->prngState
= Jim_Alloc(sizeof(Jim_PrngState
));
9414 seed
= Jim_Alloc(PRNG_SEED_SIZE
* sizeof(*seed
));
9415 for (i
= 0; i
< PRNG_SEED_SIZE
; i
++) {
9416 seed
[i
] = (rand() ^ t
^ clock());
9418 JimPrngSeed(interp
, (unsigned char *)seed
, PRNG_SEED_SIZE
* sizeof(*seed
));
9422 /* Generates N bytes of random data */
9423 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
)
9425 Jim_PrngState
*prng
;
9426 unsigned char *destByte
= (unsigned char *)dest
;
9427 unsigned int si
, sj
, x
;
9429 /* initialization, only needed the first time */
9430 if (interp
->prngState
== NULL
)
9431 JimPrngInit(interp
);
9432 prng
= interp
->prngState
;
9433 /* generates 'len' bytes of pseudo-random numbers */
9434 for (x
= 0; x
< len
; x
++) {
9435 prng
->i
= (prng
->i
+ 1) & 0xff;
9436 si
= prng
->sbox
[prng
->i
];
9437 prng
->j
= (prng
->j
+ si
) & 0xff;
9438 sj
= prng
->sbox
[prng
->j
];
9439 prng
->sbox
[prng
->i
] = sj
;
9440 prng
->sbox
[prng
->j
] = si
;
9441 *destByte
++ = prng
->sbox
[(si
+ sj
) & 0xff];
9445 /* Re-seed the generator with user-provided bytes */
9446 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
)
9449 Jim_PrngState
*prng
;
9451 /* initialization, only needed the first time */
9452 if (interp
->prngState
== NULL
)
9453 JimPrngInit(interp
);
9454 prng
= interp
->prngState
;
9456 /* Set the sbox[i] with i */
9457 for (i
= 0; i
< 256; i
++)
9459 /* Now use the seed to perform a random permutation of the sbox */
9460 for (i
= 0; i
< seedLen
; i
++) {
9463 t
= prng
->sbox
[i
& 0xFF];
9464 prng
->sbox
[i
& 0xFF] = prng
->sbox
[seed
[i
]];
9465 prng
->sbox
[seed
[i
]] = t
;
9467 prng
->i
= prng
->j
= 0;
9469 /* discard at least the first 256 bytes of stream.
9470 * borrow the seed buffer for this
9472 for (i
= 0; i
< 256; i
+= seedLen
) {
9473 JimRandomBytes(interp
, seed
, seedLen
);
9478 static int Jim_IncrCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
9480 jim_wide wideValue
, increment
= 1;
9483 if (argc
!= 2 && argc
!= 3) {
9484 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?increment?");
9488 if (Jim_GetWide(interp
, argv
[2], &increment
) != JIM_OK
)
9491 intObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
9493 /* Set missing variable to 0 */
9496 else if (Jim_GetWide(interp
, intObjPtr
, &wideValue
) != JIM_OK
) {
9499 if (!intObjPtr
|| Jim_IsShared(intObjPtr
)) {
9500 intObjPtr
= Jim_NewIntObj(interp
, wideValue
+ increment
);
9501 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
9502 Jim_FreeNewObj(interp
, intObjPtr
);
9507 /* Can do it the quick way */
9508 Jim_InvalidateStringRep(intObjPtr
);
9509 JimWideValue(intObjPtr
) = wideValue
+ increment
;
9511 /* The following step is required in order to invalidate the
9512 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9513 if (argv
[1]->typePtr
!= &variableObjType
) {
9514 /* Note that this can't fail since GetVariable already succeeded */
9515 Jim_SetVariable(interp
, argv
[1], intObjPtr
);
9518 Jim_SetResult(interp
, intObjPtr
);
9523 /* -----------------------------------------------------------------------------
9525 * ---------------------------------------------------------------------------*/
9526 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9527 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9529 /* Handle calls to the [unknown] command */
9530 static int JimUnknown(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, Jim_Obj
*fileNameObj
,
9533 Jim_Obj
**v
, *sv
[JIM_EVAL_SARGV_LEN
];
9536 /* If JimUnknown() is recursively called too many times...
9539 if (interp
->unknown_called
> 50) {
9543 /* If the [unknown] command does not exists returns
9545 if (Jim_GetCommand(interp
, interp
->unknown
, JIM_NONE
) == NULL
)
9548 /* The object interp->unknown just contains
9549 * the "unknown" string, it is used in order to
9550 * avoid to lookup the unknown command every time
9551 * but instread to cache the result. */
9552 if (argc
+ 1 <= JIM_EVAL_SARGV_LEN
)
9555 v
= Jim_Alloc(sizeof(Jim_Obj
*) * (argc
+ 1));
9556 /* Make a copy of the arguments vector, but shifted on
9557 * the right of one position. The command name of the
9558 * command will be instead the first argument of the
9559 * [unknown] call. */
9560 memcpy(v
+ 1, argv
, sizeof(Jim_Obj
*) * argc
);
9561 v
[0] = interp
->unknown
;
9563 interp
->unknown_called
++;
9564 retCode
= JimEvalObjVector(interp
, argc
+ 1, v
, fileNameObj
, linenr
);
9565 interp
->unknown_called
--;
9573 /* Eval the object vector 'objv' composed of 'objc' elements.
9574 * Every element is used as single argument.
9575 * Jim_EvalObj() will call this function every time its object
9576 * argument is of "list" type, with no string representation.
9578 * This is possible because the string representation of a
9579 * list object generated by the UpdateStringOfList is made
9580 * in a way that ensures that every list element is a different
9581 * command argument. */
9582 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
9583 Jim_Obj
*fileNameObj
, int linenr
)
9588 /* Incr refcount of arguments. */
9589 for (i
= 0; i
< objc
; i
++)
9590 Jim_IncrRefCount(objv
[i
]);
9591 /* Command lookup */
9592 cmdPtr
= Jim_GetCommand(interp
, objv
[0], JIM_ERRMSG
);
9593 if (cmdPtr
== NULL
) {
9594 retcode
= JimUnknown(interp
, objc
, objv
, fileNameObj
, linenr
);
9597 /* Call it -- Make sure result is an empty object. */
9598 JimIncrCmdRefCount(cmdPtr
);
9599 Jim_SetEmptyResult(interp
);
9600 if (cmdPtr
->isproc
) {
9601 retcode
= JimCallProcedure(interp
, cmdPtr
, fileNameObj
, linenr
, objc
, objv
);
9604 interp
->cmdPrivData
= cmdPtr
->u
.native
.privData
;
9605 retcode
= cmdPtr
->u
.native
.cmdProc(interp
, objc
, objv
);
9607 JimDecrCmdRefCount(interp
, cmdPtr
);
9609 /* Decr refcount of arguments and return the retcode */
9610 for (i
= 0; i
< objc
; i
++)
9611 Jim_DecrRefCount(interp
, objv
[i
]);
9616 int Jim_EvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
9618 return JimEvalObjVector(interp
, objc
, objv
, NULL
, 0);
9622 * Invokes 'prefix' as a command with the objv array as arguments.
9624 int Jim_EvalObjPrefix(Jim_Interp
*interp
, const char *prefix
, int objc
, Jim_Obj
*const *objv
)
9628 Jim_Obj
**nargv
= Jim_Alloc((objc
+ 1) * sizeof(*nargv
));
9630 nargv
[0] = Jim_NewStringObj(interp
, prefix
, -1);
9631 for (i
= 0; i
< objc
; i
++) {
9632 nargv
[i
+ 1] = objv
[i
];
9634 ret
= Jim_EvalObjVector(interp
, objc
+ 1, nargv
);
9639 static void JimAddErrorToStack(Jim_Interp
*interp
, int retcode
, Jim_Obj
*fileNameObj
, int line
)
9643 if (rc
== JIM_ERR
&& !interp
->errorFlag
) {
9644 /* This is the first error, so save the file/line information and reset the stack */
9645 interp
->errorFlag
= 1;
9646 Jim_IncrRefCount(fileNameObj
);
9647 Jim_DecrRefCount(interp
, interp
->errorFileNameObj
);
9648 interp
->errorFileNameObj
= fileNameObj
;
9649 interp
->errorLine
= line
;
9651 JimResetStackTrace(interp
);
9652 /* Always add a level where the error first occurs */
9653 interp
->addStackTrace
++;
9656 /* Now if this is an "interesting" level, add it to the stack trace */
9657 if (rc
== JIM_ERR
&& interp
->addStackTrace
> 0) {
9658 /* Add the stack info for the current level */
9660 JimAppendStackTrace(interp
, Jim_String(interp
->errorProc
), fileNameObj
, line
);
9662 /* Note: if we didn't have a filename for this level,
9663 * don't clear the addStackTrace flag
9664 * so we can pick it up at the next level
9666 if (Jim_Length(fileNameObj
)) {
9667 interp
->addStackTrace
= 0;
9670 Jim_DecrRefCount(interp
, interp
->errorProc
);
9671 interp
->errorProc
= interp
->emptyObj
;
9672 Jim_IncrRefCount(interp
->errorProc
);
9674 else if (rc
== JIM_RETURN
&& interp
->returnCode
== JIM_ERR
) {
9675 /* Propagate the addStackTrace value through 'return -code error' */
9678 interp
->addStackTrace
= 0;
9682 /* And delete any local procs */
9683 static void JimDeleteLocalProcs(Jim_Interp
*interp
)
9685 if (interp
->localProcs
) {
9688 while ((procname
= Jim_StackPop(interp
->localProcs
)) != NULL
) {
9689 /* If there is a pushed command, find it */
9690 Jim_Cmd
*prevCmd
= NULL
;
9691 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->commands
, procname
);
9693 Jim_Cmd
*cmd
= (Jim_Cmd
*)he
->u
.val
;
9694 if (cmd
->isproc
&& cmd
->u
.proc
.prevCmd
) {
9695 prevCmd
= cmd
->u
.proc
.prevCmd
;
9696 cmd
->u
.proc
.prevCmd
= NULL
;
9700 /* Delete the local proc */
9701 Jim_DeleteCommand(interp
, procname
);
9704 /* And restore the pushed command */
9705 Jim_AddHashEntry(&interp
->commands
, procname
, prevCmd
);
9709 Jim_FreeStack(interp
->localProcs
);
9710 Jim_Free(interp
->localProcs
);
9711 interp
->localProcs
= NULL
;
9715 static int JimSubstOneToken(Jim_Interp
*interp
, const ScriptToken
*token
, Jim_Obj
**objPtrPtr
)
9719 switch (token
->type
) {
9722 objPtr
= token
->objPtr
;
9725 objPtr
= Jim_GetVariable(interp
, token
->objPtr
, JIM_ERRMSG
);
9727 case JIM_TT_DICTSUGAR
:
9728 objPtr
= JimExpandDictSugar(interp
, token
->objPtr
);
9730 case JIM_TT_EXPRSUGAR
:
9731 objPtr
= JimExpandExprSugar(interp
, token
->objPtr
);
9734 switch (Jim_EvalObj(interp
, token
->objPtr
)) {
9737 objPtr
= interp
->result
;
9740 /* Stop substituting */
9743 /* just skip this one */
9744 return JIM_CONTINUE
;
9751 "default token type (%d) reached " "in Jim_SubstObj().", token
->type
));
9756 *objPtrPtr
= objPtr
;
9762 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9763 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9764 * The returned object has refcount = 0.
9766 static Jim_Obj
*JimInterpolateTokens(Jim_Interp
*interp
, const ScriptToken
* token
, int tokens
, int flags
)
9770 Jim_Obj
*sintv
[JIM_EVAL_SINTV_LEN
];
9774 if (tokens
<= JIM_EVAL_SINTV_LEN
)
9777 intv
= Jim_Alloc(sizeof(Jim_Obj
*) * tokens
);
9779 /* Compute every token forming the argument
9780 * in the intv objects vector. */
9781 for (i
= 0; i
< tokens
; i
++) {
9782 switch (JimSubstOneToken(interp
, &token
[i
], &intv
[i
])) {
9787 if (flags
& JIM_SUBST_FLAG
) {
9792 /* XXX: Should probably set an error about break outside loop */
9793 /* fall through to error */
9795 if (flags
& JIM_SUBST_FLAG
) {
9799 /* XXX: Ditto continue outside loop */
9800 /* fall through to error */
9803 Jim_DecrRefCount(interp
, intv
[i
]);
9805 if (intv
!= sintv
) {
9810 Jim_IncrRefCount(intv
[i
]);
9811 Jim_String(intv
[i
]);
9812 totlen
+= intv
[i
]->length
;
9815 /* Fast path return for a single token */
9816 if (tokens
== 1 && intv
[0] && intv
== sintv
) {
9817 Jim_DecrRefCount(interp
, intv
[0]);
9821 /* Concatenate every token in an unique
9823 objPtr
= Jim_NewStringObjNoAlloc(interp
, NULL
, 0);
9825 if (tokens
== 4 && token
[0].type
== JIM_TT_ESC
&& token
[1].type
== JIM_TT_ESC
9826 && token
[2].type
== JIM_TT_VAR
) {
9827 /* May be able to do fast interpolated object -> dictSubst */
9828 objPtr
->typePtr
= &interpolatedObjType
;
9829 objPtr
->internalRep
.twoPtrValue
.ptr1
= (void *)token
;
9830 objPtr
->internalRep
.twoPtrValue
.ptr2
= intv
[2];
9831 Jim_IncrRefCount(intv
[2]);
9834 s
= objPtr
->bytes
= Jim_Alloc(totlen
+ 1);
9835 objPtr
->length
= totlen
;
9836 for (i
= 0; i
< tokens
; i
++) {
9838 memcpy(s
, intv
[i
]->bytes
, intv
[i
]->length
);
9839 s
+= intv
[i
]->length
;
9840 Jim_DecrRefCount(interp
, intv
[i
]);
9843 objPtr
->bytes
[totlen
] = '\0';
9844 /* Free the intv vector if not static. */
9845 if (intv
!= sintv
) {
9853 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9854 * Otherwise eval with Jim_EvalObj()
9856 static int JimEvalObjList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*fileNameObj
, int linenr
)
9858 if (!Jim_IsList(listPtr
)) {
9859 return Jim_EvalObj(interp
, listPtr
);
9862 int retcode
= JIM_OK
;
9864 if (listPtr
->internalRep
.listValue
.len
) {
9865 Jim_IncrRefCount(listPtr
);
9866 retcode
= JimEvalObjVector(interp
,
9867 listPtr
->internalRep
.listValue
.len
,
9868 listPtr
->internalRep
.listValue
.ele
, fileNameObj
, linenr
);
9869 Jim_DecrRefCount(interp
, listPtr
);
9875 int Jim_EvalObj(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
9880 int retcode
= JIM_OK
;
9881 Jim_Obj
*sargv
[JIM_EVAL_SARGV_LEN
], **argv
= NULL
;
9884 interp
->errorFlag
= 0;
9886 /* If the object is of type "list", we can call
9887 * a specialized version of Jim_EvalObj() */
9888 if (Jim_IsList(scriptObjPtr
)) {
9889 return JimEvalObjList(interp
, scriptObjPtr
, NULL
, 0);
9892 Jim_IncrRefCount(scriptObjPtr
); /* Make sure it's shared. */
9893 script
= Jim_GetScript(interp
, scriptObjPtr
);
9895 /* Reset the interpreter result. This is useful to
9896 * return the empty result in the case of empty program. */
9897 Jim_SetEmptyResult(interp
);
9899 #ifdef JIM_OPTIMIZATION
9900 /* Check for one of the following common scripts used by for, while
9905 if (script
->len
== 0) {
9906 Jim_DecrRefCount(interp
, scriptObjPtr
);
9909 if (script
->len
== 3
9910 && script
->token
[1].objPtr
->typePtr
== &commandObjType
9911 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->isproc
== 0
9912 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->u
.native
.cmdProc
== Jim_IncrCoreCommand
9913 && script
->token
[2].objPtr
->typePtr
== &variableObjType
) {
9915 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, script
->token
[2].objPtr
, JIM_NONE
);
9917 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
9918 JimWideValue(objPtr
)++;
9919 Jim_InvalidateStringRep(objPtr
);
9920 Jim_DecrRefCount(interp
, scriptObjPtr
);
9921 Jim_SetResult(interp
, objPtr
);
9927 /* Now we have to make sure the internal repr will not be
9928 * freed on shimmering.
9930 * Think for example to this:
9932 * set x {llength $x; ... some more code ...}; eval $x
9934 * In order to preserve the internal rep, we increment the
9935 * inUse field of the script internal rep structure. */
9938 token
= script
->token
;
9941 /* Execute every command sequentially until the end of the script
9942 * or an error occurs.
9944 for (i
= 0; i
< script
->len
&& retcode
== JIM_OK
; ) {
9949 /* First token of the line is always JIM_TT_LINE */
9950 argc
= token
[i
].objPtr
->internalRep
.scriptLineValue
.argc
;
9951 linenr
= token
[i
].objPtr
->internalRep
.scriptLineValue
.line
;
9953 /* Allocate the arguments vector if required */
9954 if (argc
> JIM_EVAL_SARGV_LEN
)
9955 argv
= Jim_Alloc(sizeof(Jim_Obj
*) * argc
);
9957 /* Skip the JIM_TT_LINE token */
9960 /* Populate the arguments objects.
9961 * If an error occurs, retcode will be set and
9962 * 'j' will be set to the number of args expanded
9964 for (j
= 0; j
< argc
; j
++) {
9965 long wordtokens
= 1;
9967 Jim_Obj
*wordObjPtr
= NULL
;
9969 if (token
[i
].type
== JIM_TT_WORD
) {
9970 wordtokens
= JimWideValue(token
[i
++].objPtr
);
9971 if (wordtokens
< 0) {
9973 wordtokens
= -wordtokens
;
9977 if (wordtokens
== 1) {
9978 /* Fast path if the token does not
9979 * need interpolation */
9981 switch (token
[i
].type
) {
9984 wordObjPtr
= token
[i
].objPtr
;
9987 wordObjPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
9989 case JIM_TT_EXPRSUGAR
:
9990 wordObjPtr
= JimExpandExprSugar(interp
, token
[i
].objPtr
);
9992 case JIM_TT_DICTSUGAR
:
9993 wordObjPtr
= JimExpandDictSugar(interp
, token
[i
].objPtr
);
9996 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
9997 if (retcode
== JIM_OK
) {
9998 wordObjPtr
= Jim_GetResult(interp
);
10002 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10006 /* For interpolation we call a helper
10007 * function to do the work for us. */
10008 wordObjPtr
= JimInterpolateTokens(interp
, token
+ i
, wordtokens
, JIM_NONE
);
10012 if (retcode
== JIM_OK
) {
10018 Jim_IncrRefCount(wordObjPtr
);
10022 argv
[j
] = wordObjPtr
;
10025 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10026 int len
= Jim_ListLength(interp
, wordObjPtr
);
10027 int newargc
= argc
+ len
- 1;
10031 if (argv
== sargv
) {
10032 if (newargc
> JIM_EVAL_SARGV_LEN
) {
10033 argv
= Jim_Alloc(sizeof(*argv
) * newargc
);
10034 memcpy(argv
, sargv
, sizeof(*argv
) * j
);
10038 /* Need to realloc to make room for (len - 1) more entries */
10039 argv
= Jim_Realloc(argv
, sizeof(*argv
) * newargc
);
10043 /* Now copy in the expanded version */
10044 for (k
= 0; k
< len
; k
++) {
10045 argv
[j
++] = wordObjPtr
->internalRep
.listValue
.ele
[k
];
10046 Jim_IncrRefCount(wordObjPtr
->internalRep
.listValue
.ele
[k
]);
10049 /* The original object reference is no longer needed,
10050 * after the expansion it is no longer present on
10051 * the argument vector, but the single elements are
10053 Jim_DecrRefCount(interp
, wordObjPtr
);
10055 /* And update the indexes */
10061 if (retcode
== JIM_OK
&& argc
) {
10062 /* Lookup the command to call */
10063 cmd
= Jim_GetCommand(interp
, argv
[0], JIM_ERRMSG
);
10065 /* Call it -- Make sure result is an empty object. */
10066 JimIncrCmdRefCount(cmd
);
10067 Jim_SetEmptyResult(interp
);
10070 JimCallProcedure(interp
, cmd
, script
->fileNameObj
, linenr
, argc
, argv
);
10072 interp
->cmdPrivData
= cmd
->u
.native
.privData
;
10073 retcode
= cmd
->u
.native
.cmdProc(interp
, argc
, argv
);
10075 JimDecrCmdRefCount(interp
, cmd
);
10078 /* Call [unknown] */
10079 retcode
= JimUnknown(interp
, argc
, argv
, script
->fileNameObj
, linenr
);
10081 if (interp
->signal_level
&& interp
->sigmask
) {
10082 /* Check for a signal after each command */
10083 retcode
= JIM_SIGNAL
;
10087 /* Finished with the command, so decrement ref counts of each argument */
10089 Jim_DecrRefCount(interp
, argv
[j
]);
10092 if (argv
!= sargv
) {
10098 /* Possibly add to the error stack trace */
10099 JimAddErrorToStack(interp
, retcode
, script
->fileNameObj
, linenr
);
10101 /* Note that we don't have to decrement inUse, because the
10102 * following code transfers our use of the reference again to
10103 * the script object. */
10104 Jim_FreeIntRep(interp
, scriptObjPtr
);
10105 scriptObjPtr
->typePtr
= &scriptObjType
;
10106 Jim_SetIntRepPtr(scriptObjPtr
, script
);
10107 Jim_DecrRefCount(interp
, scriptObjPtr
);
10112 static int JimSetProcArg(Jim_Interp
*interp
, Jim_Obj
*argNameObj
, Jim_Obj
*argValObj
)
10115 /* If argObjPtr begins with '&', do an automatic upvar */
10116 const char *varname
= Jim_String(argNameObj
);
10117 if (*varname
== '&') {
10118 /* First check that the target variable exists */
10120 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
10122 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10123 objPtr
= Jim_GetVariable(interp
, argValObj
, JIM_ERRMSG
);
10124 interp
->framePtr
= savedCallFrame
;
10129 /* It exists, so perform the binding. */
10130 objPtr
= Jim_NewStringObj(interp
, varname
+ 1, -1);
10131 Jim_IncrRefCount(objPtr
);
10132 retcode
= Jim_SetVariableLink(interp
, objPtr
, argValObj
, interp
->framePtr
->parentCallFrame
);
10133 Jim_DecrRefCount(interp
, objPtr
);
10136 retcode
= Jim_SetVariable(interp
, argNameObj
, argValObj
);
10142 * Sets the interp result to be an error message indicating the required proc args.
10144 static void JimSetProcWrongArgs(Jim_Interp
*interp
, Jim_Obj
*procNameObj
, Jim_Cmd
*cmd
)
10146 /* Create a nice error message, consistent with Tcl 8.5 */
10147 Jim_Obj
*argmsg
= Jim_NewStringObj(interp
, "", 0);
10150 for (i
= 0; i
< cmd
->u
.proc
.argListLen
; i
++) {
10151 Jim_AppendString(interp
, argmsg
, " ", 1);
10153 if (i
== cmd
->u
.proc
.argsPos
) {
10154 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10156 Jim_AppendString(interp
, argmsg
, "?", 1);
10157 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].defaultObjPtr
);
10158 Jim_AppendString(interp
, argmsg
, " ...?", -1);
10161 /* We have plain args */
10162 Jim_AppendString(interp
, argmsg
, "?argument ...?", -1);
10166 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10167 Jim_AppendString(interp
, argmsg
, "?", 1);
10168 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10169 Jim_AppendString(interp
, argmsg
, "?", 1);
10172 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10176 Jim_SetResultFormatted(interp
, "wrong # args: should be \"%#s%#s\"", procNameObj
, argmsg
);
10177 Jim_FreeNewObj(interp
, argmsg
);
10180 /* Call a procedure implemented in Tcl.
10181 * It's possible to speed-up a lot this function, currently
10182 * the callframes are not cached, but allocated and
10183 * destroied every time. What is expecially costly is
10184 * to create/destroy the local vars hash table every time.
10186 * This can be fixed just implementing callframes caching
10187 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10188 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, Jim_Obj
*fileNameObj
, int linenr
, int argc
,
10189 Jim_Obj
*const *argv
)
10191 Jim_CallFrame
*callFramePtr
;
10192 Jim_Stack
*prevLocalProcs
;
10193 int i
, d
, retcode
, optargs
;
10196 if (argc
- 1 < cmd
->u
.proc
.reqArity
||
10197 (cmd
->u
.proc
.argsPos
< 0 && argc
- 1 > cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
)) {
10198 JimSetProcWrongArgs(interp
, argv
[0], cmd
);
10202 /* Check if there are too nested calls */
10203 if (interp
->framePtr
->level
== interp
->maxNestingDepth
) {
10204 Jim_SetResultString(interp
, "Too many nested calls. Infinite recursion?", -1);
10208 /* Create a new callframe */
10209 callFramePtr
= JimCreateCallFrame(interp
, interp
->framePtr
);
10210 callFramePtr
->argv
= argv
;
10211 callFramePtr
->argc
= argc
;
10212 callFramePtr
->procArgsObjPtr
= cmd
->u
.proc
.argListObjPtr
;
10213 callFramePtr
->procBodyObjPtr
= cmd
->u
.proc
.bodyObjPtr
;
10214 callFramePtr
->staticVars
= cmd
->u
.proc
.staticVars
;
10215 callFramePtr
->fileNameObj
= fileNameObj
;
10216 callFramePtr
->line
= linenr
;
10217 Jim_IncrRefCount(cmd
->u
.proc
.argListObjPtr
);
10218 Jim_IncrRefCount(cmd
->u
.proc
.bodyObjPtr
);
10219 interp
->framePtr
= callFramePtr
;
10221 /* How many optional args are available */
10222 optargs
= (argc
- 1 - cmd
->u
.proc
.reqArity
);
10224 /* Step 'i' along the actual args, and step 'd' along the formal args */
10226 for (d
= 0; d
< cmd
->u
.proc
.argListLen
; d
++) {
10227 Jim_Obj
*nameObjPtr
= cmd
->u
.proc
.arglist
[d
].nameObjPtr
;
10228 if (d
== cmd
->u
.proc
.argsPos
) {
10230 Jim_Obj
*listObjPtr
;
10232 if (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
< argc
- 1) {
10233 argsLen
= argc
- 1 - (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
);
10235 listObjPtr
= Jim_NewListObj(interp
, &argv
[i
], argsLen
);
10237 /* It is possible to rename args. */
10238 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
) {
10239 nameObjPtr
=cmd
->u
.proc
.arglist
[d
].defaultObjPtr
;
10241 retcode
= Jim_SetVariable(interp
, nameObjPtr
, listObjPtr
);
10242 if (retcode
!= JIM_OK
) {
10250 /* Optional or required? */
10251 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
== NULL
|| optargs
-- > 0) {
10252 retcode
= JimSetProcArg(interp
, nameObjPtr
, argv
[i
++]);
10255 /* Ran out, so use the default */
10256 retcode
= Jim_SetVariable(interp
, nameObjPtr
, cmd
->u
.proc
.arglist
[d
].defaultObjPtr
);
10258 if (retcode
!= JIM_OK
) {
10263 /* Install a new stack for local procs */
10264 prevLocalProcs
= interp
->localProcs
;
10265 interp
->localProcs
= NULL
;
10267 /* Eval the body */
10268 retcode
= Jim_EvalObj(interp
, cmd
->u
.proc
.bodyObjPtr
);
10270 /* Delete any local procs */
10271 JimDeleteLocalProcs(interp
);
10272 interp
->localProcs
= prevLocalProcs
;
10275 /* Destroy the callframe */
10276 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10277 if (callFramePtr
->vars
.size
!= JIM_HT_INITIAL_SIZE
) {
10278 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NONE
);
10281 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NOHT
);
10283 /* Handle the JIM_EVAL return code */
10284 while (retcode
== JIM_EVAL
) {
10285 Jim_Obj
*resultScriptObjPtr
= Jim_GetResult(interp
);
10287 Jim_IncrRefCount(resultScriptObjPtr
);
10288 /* Should be a list! */
10289 retcode
= JimEvalObjList(interp
, resultScriptObjPtr
, fileNameObj
, linenr
);
10290 Jim_DecrRefCount(interp
, resultScriptObjPtr
);
10292 /* Handle the JIM_RETURN return code */
10293 if (retcode
== JIM_RETURN
) {
10294 if (--interp
->returnLevel
<= 0) {
10295 retcode
= interp
->returnCode
;
10296 interp
->returnCode
= JIM_OK
;
10297 interp
->returnLevel
= 0;
10300 else if (retcode
== JIM_ERR
) {
10301 interp
->addStackTrace
++;
10302 Jim_DecrRefCount(interp
, interp
->errorProc
);
10303 interp
->errorProc
= argv
[0];
10304 Jim_IncrRefCount(interp
->errorProc
);
10309 int Jim_Eval_Named(Jim_Interp
*interp
, const char *script
, const char *filename
, int lineno
)
10312 Jim_Obj
*scriptObjPtr
;
10314 scriptObjPtr
= Jim_NewStringObj(interp
, script
, -1);
10315 Jim_IncrRefCount(scriptObjPtr
);
10319 Jim_Obj
*prevScriptObj
;
10321 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), lineno
);
10323 prevScriptObj
= interp
->currentScriptObj
;
10324 interp
->currentScriptObj
= scriptObjPtr
;
10326 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10328 interp
->currentScriptObj
= prevScriptObj
;
10331 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10333 Jim_DecrRefCount(interp
, scriptObjPtr
);
10337 int Jim_Eval(Jim_Interp
*interp
, const char *script
)
10339 return Jim_Eval_Named(interp
, script
, NULL
, 0);
10342 /* Execute script in the scope of the global level */
10343 int Jim_EvalGlobal(Jim_Interp
*interp
, const char *script
)
10346 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10348 interp
->framePtr
= interp
->topFramePtr
;
10349 retval
= Jim_Eval(interp
, script
);
10350 interp
->framePtr
= savedFramePtr
;
10355 int Jim_EvalFileGlobal(Jim_Interp
*interp
, const char *filename
)
10358 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10360 interp
->framePtr
= interp
->topFramePtr
;
10361 retval
= Jim_EvalFile(interp
, filename
);
10362 interp
->framePtr
= savedFramePtr
;
10367 #include <sys/stat.h>
10369 int Jim_EvalFile(Jim_Interp
*interp
, const char *filename
)
10373 Jim_Obj
*scriptObjPtr
;
10374 Jim_Obj
*prevScriptObj
;
10378 struct JimParseResult result
;
10380 if (stat(filename
, &sb
) != 0 || (fp
= fopen(filename
, "rt")) == NULL
) {
10381 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", filename
, strerror(errno
));
10384 if (sb
.st_size
== 0) {
10389 buf
= Jim_Alloc(sb
.st_size
+ 1);
10390 readlen
= fread(buf
, 1, sb
.st_size
, fp
);
10394 Jim_SetResultFormatted(interp
, "failed to load file \"%s\": %s", filename
, strerror(errno
));
10400 scriptObjPtr
= Jim_NewStringObjNoAlloc(interp
, buf
, readlen
);
10401 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), 1);
10402 Jim_IncrRefCount(scriptObjPtr
);
10404 /* Now check the script for unmatched braces, etc. */
10405 if (SetScriptFromAny(interp
, scriptObjPtr
, &result
) == JIM_ERR
) {
10409 switch (result
.missing
) {
10411 msg
= "unmatched \"[\"";
10414 msg
= "missing close-brace";
10418 msg
= "missing quote";
10422 snprintf(linebuf
, sizeof(linebuf
), "%d", result
.line
);
10424 Jim_SetResultFormatted(interp
, "%s in \"%s\" at line %s",
10425 msg
, filename
, linebuf
);
10426 Jim_DecrRefCount(interp
, scriptObjPtr
);
10430 prevScriptObj
= interp
->currentScriptObj
;
10431 interp
->currentScriptObj
= scriptObjPtr
;
10433 retcode
= Jim_EvalObj(interp
, scriptObjPtr
);
10435 /* Handle the JIM_RETURN return code */
10436 if (retcode
== JIM_RETURN
) {
10437 if (--interp
->returnLevel
<= 0) {
10438 retcode
= interp
->returnCode
;
10439 interp
->returnCode
= JIM_OK
;
10440 interp
->returnLevel
= 0;
10443 if (retcode
== JIM_ERR
) {
10444 /* EvalFile changes context, so add a stack frame here */
10445 interp
->addStackTrace
++;
10448 interp
->currentScriptObj
= prevScriptObj
;
10450 Jim_DecrRefCount(interp
, scriptObjPtr
);
10455 /* -----------------------------------------------------------------------------
10457 * ---------------------------------------------------------------------------*/
10458 static int JimParseSubstStr(struct JimParserCtx
*pc
)
10460 pc
->tstart
= pc
->p
;
10461 pc
->tline
= pc
->linenr
;
10462 while (pc
->len
&& *pc
->p
!= '$' && *pc
->p
!= '[') {
10463 if (*pc
->p
== '\\' && pc
->len
> 1) {
10470 pc
->tend
= pc
->p
- 1;
10471 pc
->tt
= JIM_TT_ESC
;
10475 static int JimParseSubst(struct JimParserCtx
*pc
, int flags
)
10479 if (pc
->len
== 0) {
10480 pc
->tstart
= pc
->tend
= pc
->p
;
10481 pc
->tline
= pc
->linenr
;
10482 pc
->tt
= JIM_TT_EOL
;
10488 retval
= JimParseCmd(pc
);
10489 if (flags
& JIM_SUBST_NOCMD
) {
10492 pc
->tt
= (flags
& JIM_SUBST_NOESC
) ? JIM_TT_STR
: JIM_TT_ESC
;
10497 if (JimParseVar(pc
) == JIM_ERR
) {
10498 pc
->tstart
= pc
->tend
= pc
->p
++;
10500 pc
->tline
= pc
->linenr
;
10501 pc
->tt
= JIM_TT_STR
;
10504 if (flags
& JIM_SUBST_NOVAR
) {
10506 if (flags
& JIM_SUBST_NOESC
)
10507 pc
->tt
= JIM_TT_STR
;
10509 pc
->tt
= JIM_TT_ESC
;
10510 if (*pc
->tstart
== '{') {
10512 if (*(pc
->tend
+ 1))
10519 retval
= JimParseSubstStr(pc
);
10520 if (flags
& JIM_SUBST_NOESC
)
10521 pc
->tt
= JIM_TT_STR
;
10528 /* The subst object type reuses most of the data structures and functions
10529 * of the script object. Script's data structures are a bit more complex
10530 * for what is needed for [subst]itution tasks, but the reuse helps to
10531 * deal with a single data structure at the cost of some more memory
10532 * usage for substitutions. */
10534 /* This method takes the string representation of an object
10535 * as a Tcl string where to perform [subst]itution, and generates
10536 * the pre-parsed internal representation. */
10537 static int SetSubstFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, int flags
)
10540 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
10541 struct JimParserCtx parser
;
10542 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
10543 ParseTokenList tokenlist
;
10545 /* Initially parse the subst into tokens (in tokenlist) */
10546 ScriptTokenListInit(&tokenlist
);
10548 JimParserInit(&parser
, scriptText
, scriptTextLen
, 1);
10550 JimParseSubst(&parser
, flags
);
10552 /* Note that subst doesn't need the EOL token */
10555 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
10559 /* Create the "real" subst/script tokens from the initial token list */
10561 script
->substFlags
= flags
;
10562 script
->fileNameObj
= interp
->emptyObj
;
10563 Jim_IncrRefCount(script
->fileNameObj
);
10564 SubstObjAddTokens(interp
, script
, &tokenlist
);
10566 /* No longer need the token list */
10567 ScriptTokenListFree(&tokenlist
);
10569 #ifdef DEBUG_SHOW_SUBST
10573 printf("==== Subst ====\n");
10574 for (i
= 0; i
< script
->len
; i
++) {
10575 printf("[%2d] %s '%s'\n", i
, jim_tt_name(script
->token
[i
].type
),
10576 Jim_String(script
->token
[i
].objPtr
));
10581 /* Free the old internal rep and set the new one. */
10582 Jim_FreeIntRep(interp
, objPtr
);
10583 Jim_SetIntRepPtr(objPtr
, script
);
10584 objPtr
->typePtr
= &scriptObjType
;
10588 static ScriptObj
*Jim_GetSubst(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
10590 if (objPtr
->typePtr
!= &scriptObjType
|| ((ScriptObj
*)Jim_GetIntRepPtr(objPtr
))->substFlags
!= flags
)
10591 SetSubstFromAny(interp
, objPtr
, flags
);
10592 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
10595 /* Performs commands,variables,blackslashes substitution,
10596 * storing the result object (with refcount 0) into
10598 int Jim_SubstObj(Jim_Interp
*interp
, Jim_Obj
*substObjPtr
, Jim_Obj
**resObjPtrPtr
, int flags
)
10600 ScriptObj
*script
= Jim_GetSubst(interp
, substObjPtr
, flags
);
10602 Jim_IncrRefCount(substObjPtr
); /* Make sure it's shared. */
10603 /* In order to preserve the internal rep, we increment the
10604 * inUse field of the script internal rep structure. */
10607 *resObjPtrPtr
= JimInterpolateTokens(interp
, script
->token
, script
->len
, flags
);
10610 Jim_DecrRefCount(interp
, substObjPtr
);
10611 if (*resObjPtrPtr
== NULL
) {
10617 /* -----------------------------------------------------------------------------
10618 * Core commands utility functions
10619 * ---------------------------------------------------------------------------*/
10620 void Jim_WrongNumArgs(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, const char *msg
)
10623 Jim_Obj
*objPtr
= Jim_NewEmptyStringObj(interp
);
10625 Jim_AppendString(interp
, objPtr
, "wrong # args: should be \"", -1);
10626 for (i
= 0; i
< argc
; i
++) {
10627 Jim_AppendObj(interp
, objPtr
, argv
[i
]);
10628 if (!(i
+ 1 == argc
&& msg
[0] == '\0'))
10629 Jim_AppendString(interp
, objPtr
, " ", 1);
10631 Jim_AppendString(interp
, objPtr
, msg
, -1);
10632 Jim_AppendString(interp
, objPtr
, "\"", 1);
10633 Jim_SetResult(interp
, objPtr
);
10636 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10638 /* type is: 0=commands, 1=procs, 2=channels */
10639 static Jim_Obj
*JimCommandsList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int type
)
10641 Jim_HashTableIterator
*htiter
;
10643 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10645 /* Check for the non-pattern case. We can do this much more efficiently. */
10646 if (patternObjPtr
&& JimTrivialMatch(Jim_String(patternObjPtr
))) {
10647 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, patternObjPtr
, JIM_NONE
);
10649 if (type
== 1 && !cmdPtr
->isproc
) {
10652 else if (type
== 2 && !Jim_AioFilehandle(interp
, patternObjPtr
)) {
10653 /* not a channel */
10656 Jim_ListAppendElement(interp
, listObjPtr
, patternObjPtr
);
10662 htiter
= Jim_GetHashTableIterator(&interp
->commands
);
10663 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10664 Jim_Cmd
*cmdPtr
= he
->u
.val
;
10665 Jim_Obj
*cmdNameObj
;
10667 if (type
== 1 && !cmdPtr
->isproc
) {
10671 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10674 cmdNameObj
= Jim_NewStringObj(interp
, he
->key
, -1);
10676 /* Is it a channel? */
10677 if (type
== 2 && !Jim_AioFilehandle(interp
, cmdNameObj
)) {
10678 Jim_FreeNewObj(interp
, cmdNameObj
);
10682 Jim_ListAppendElement(interp
, listObjPtr
, cmdNameObj
);
10684 Jim_FreeHashTableIterator(htiter
);
10688 /* Keep this in order */
10689 #define JIM_VARLIST_GLOBALS 0
10690 #define JIM_VARLIST_LOCALS 1
10691 #define JIM_VARLIST_VARS 2
10693 static Jim_Obj
*JimVariablesList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int mode
)
10695 Jim_HashTableIterator
*htiter
;
10697 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10699 if (mode
== JIM_VARLIST_GLOBALS
) {
10700 htiter
= Jim_GetHashTableIterator(&interp
->topFramePtr
->vars
);
10703 /* For [info locals], if we are at top level an emtpy list
10704 * is returned. I don't agree, but we aim at compatibility (SS) */
10705 if (mode
== JIM_VARLIST_LOCALS
&& interp
->framePtr
== interp
->topFramePtr
)
10707 htiter
= Jim_GetHashTableIterator(&interp
->framePtr
->vars
);
10709 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10710 Jim_Var
*varPtr
= (Jim_Var
*)he
->u
.val
;
10712 if (mode
== JIM_VARLIST_LOCALS
) {
10713 if (varPtr
->linkFramePtr
!= NULL
)
10716 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10718 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, he
->key
, -1));
10720 Jim_FreeHashTableIterator(htiter
);
10724 static int JimInfoLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
10725 Jim_Obj
**objPtrPtr
, int info_level_cmd
)
10727 Jim_CallFrame
*targetCallFrame
;
10729 targetCallFrame
= JimGetCallFrameByInteger(interp
, levelObjPtr
);
10730 if (targetCallFrame
== NULL
) {
10733 /* No proc call at toplevel callframe */
10734 if (targetCallFrame
== interp
->topFramePtr
) {
10735 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
10738 if (info_level_cmd
) {
10739 *objPtrPtr
= Jim_NewListObj(interp
, targetCallFrame
->argv
, targetCallFrame
->argc
);
10742 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
10744 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->argv
[0]);
10745 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->fileNameObj
);
10746 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, targetCallFrame
->line
));
10747 *objPtrPtr
= listObj
;
10752 /* -----------------------------------------------------------------------------
10754 * ---------------------------------------------------------------------------*/
10756 /* fake [puts] -- not the real puts, just for debugging. */
10757 static int Jim_PutsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10759 if (argc
!= 2 && argc
!= 3) {
10760 Jim_WrongNumArgs(interp
, 1, argv
, "?-nonewline? string");
10764 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-nonewline")) {
10765 Jim_SetResultString(interp
, "The second argument must " "be -nonewline", -1);
10769 fputs(Jim_String(argv
[2]), stdout
);
10773 puts(Jim_String(argv
[1]));
10778 /* Helper for [+] and [*] */
10779 static int JimAddMulHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10781 jim_wide wideValue
, res
;
10782 double doubleValue
, doubleRes
;
10785 res
= (op
== JIM_EXPROP_ADD
) ? 0 : 1;
10787 for (i
= 1; i
< argc
; i
++) {
10788 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
)
10790 if (op
== JIM_EXPROP_ADD
)
10795 Jim_SetResultInt(interp
, res
);
10798 doubleRes
= (double)res
;
10799 for (; i
< argc
; i
++) {
10800 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10802 if (op
== JIM_EXPROP_ADD
)
10803 doubleRes
+= doubleValue
;
10805 doubleRes
*= doubleValue
;
10807 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10811 /* Helper for [-] and [/] */
10812 static int JimSubDivHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10814 jim_wide wideValue
, res
= 0;
10815 double doubleValue
, doubleRes
= 0;
10819 Jim_WrongNumArgs(interp
, 1, argv
, "number ?number ... number?");
10822 else if (argc
== 2) {
10823 /* The arity = 2 case is different. For [- x] returns -x,
10824 * while [/ x] returns 1/x. */
10825 if (Jim_GetWide(interp
, argv
[1], &wideValue
) != JIM_OK
) {
10826 if (Jim_GetDouble(interp
, argv
[1], &doubleValue
) != JIM_OK
) {
10830 if (op
== JIM_EXPROP_SUB
)
10831 doubleRes
= -doubleValue
;
10833 doubleRes
= 1.0 / doubleValue
;
10834 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10838 if (op
== JIM_EXPROP_SUB
) {
10840 Jim_SetResultInt(interp
, res
);
10843 doubleRes
= 1.0 / wideValue
;
10844 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10849 if (Jim_GetWide(interp
, argv
[1], &res
) != JIM_OK
) {
10850 if (Jim_GetDouble(interp
, argv
[1], &doubleRes
)
10859 for (i
= 2; i
< argc
; i
++) {
10860 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
) {
10861 doubleRes
= (double)res
;
10864 if (op
== JIM_EXPROP_SUB
)
10869 Jim_SetResultInt(interp
, res
);
10872 for (; i
< argc
; i
++) {
10873 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10875 if (op
== JIM_EXPROP_SUB
)
10876 doubleRes
-= doubleValue
;
10878 doubleRes
/= doubleValue
;
10880 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10886 static int Jim_AddCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10888 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_ADD
);
10892 static int Jim_MulCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10894 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_MUL
);
10898 static int Jim_SubCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10900 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_SUB
);
10904 static int Jim_DivCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10906 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_DIV
);
10910 static int Jim_SetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10912 if (argc
!= 2 && argc
!= 3) {
10913 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?newValue?");
10919 objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
10922 Jim_SetResult(interp
, objPtr
);
10925 /* argc == 3 case. */
10926 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
10928 Jim_SetResult(interp
, argv
[2]);
10934 * unset ?-nocomplain? ?--? ?varName ...?
10936 static int Jim_UnsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10942 if (Jim_CompareStringImmediate(interp
, argv
[i
], "--")) {
10946 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-nocomplain")) {
10955 if (Jim_UnsetVariable(interp
, argv
[i
], complain
? JIM_ERRMSG
: JIM_NONE
) != JIM_OK
10965 static int Jim_WhileCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10968 Jim_WrongNumArgs(interp
, 1, argv
, "condition body");
10972 /* The general purpose implementation of while starts here */
10974 int boolean
, retval
;
10976 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[1], &boolean
)) != JIM_OK
)
10981 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
10995 Jim_SetEmptyResult(interp
);
11000 static int Jim_ForCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11004 Jim_Obj
*varNamePtr
= NULL
;
11005 Jim_Obj
*stopVarNamePtr
= NULL
;
11008 Jim_WrongNumArgs(interp
, 1, argv
, "start test next body");
11012 /* Do the initialisation */
11013 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
) {
11017 /* And do the first test now. Better for optimisation
11018 * if we can do next/test at the bottom of the loop
11020 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11022 /* Ready to do the body as follows:
11024 * body // check retcode
11025 * next // check retcode
11026 * test // check retcode/test bool
11030 #ifdef JIM_OPTIMIZATION
11031 /* Check if the for is on the form:
11032 * for ... {$i < CONST} {incr i}
11033 * for ... {$i < $j} {incr i}
11035 if (retval
== JIM_OK
&& boolean
) {
11036 ScriptObj
*incrScript
;
11037 ExprByteCode
*expr
;
11038 jim_wide stop
, currentVal
;
11039 unsigned jim_wide procEpoch
;
11043 /* Do it only if there aren't shared arguments */
11044 expr
= JimGetExpression(interp
, argv
[2]);
11045 incrScript
= Jim_GetScript(interp
, argv
[3]);
11047 /* Ensure proper lengths to start */
11048 if (incrScript
->len
!= 3 || !expr
|| expr
->len
!= 3) {
11051 /* Ensure proper token types. */
11052 if (incrScript
->token
[1].type
!= JIM_TT_ESC
||
11053 expr
->token
[0].type
!= JIM_TT_VAR
||
11054 (expr
->token
[1].type
!= JIM_TT_EXPR_INT
&& expr
->token
[1].type
!= JIM_TT_VAR
)) {
11058 if (expr
->token
[2].type
== JIM_EXPROP_LT
) {
11061 else if (expr
->token
[2].type
== JIM_EXPROP_LTE
) {
11068 /* Update command must be incr */
11069 if (!Jim_CompareStringImmediate(interp
, incrScript
->token
[1].objPtr
, "incr")) {
11073 /* incr, expression must be about the same variable */
11074 if (!Jim_StringEqObj(incrScript
->token
[2].objPtr
, expr
->token
[0].objPtr
)) {
11078 /* Get the stop condition (must be a variable or integer) */
11079 if (expr
->token
[1].type
== JIM_TT_EXPR_INT
) {
11080 if (Jim_GetWide(interp
, expr
->token
[1].objPtr
, &stop
) == JIM_ERR
) {
11085 stopVarNamePtr
= expr
->token
[1].objPtr
;
11086 Jim_IncrRefCount(stopVarNamePtr
);
11087 /* Keep the compiler happy */
11091 /* Initialization */
11092 procEpoch
= interp
->procEpoch
;
11093 varNamePtr
= expr
->token
[0].objPtr
;
11094 Jim_IncrRefCount(varNamePtr
);
11096 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_NONE
);
11097 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
) {
11101 /* --- OPTIMIZED FOR --- */
11102 while (retval
== JIM_OK
) {
11103 /* === Check condition === */
11104 /* Note that currentVal is already set here */
11106 /* Immediate or Variable? get the 'stop' value if the latter. */
11107 if (stopVarNamePtr
) {
11108 objPtr
= Jim_GetVariable(interp
, stopVarNamePtr
, JIM_NONE
);
11109 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, &stop
) != JIM_OK
) {
11114 if (currentVal
>= stop
+ cmpOffset
) {
11119 retval
= Jim_EvalObj(interp
, argv
[4]);
11120 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11122 /* If there was a change in procedures/command continue
11123 * with the usual [for] command implementation */
11124 if (procEpoch
!= interp
->procEpoch
) {
11128 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
11131 if (objPtr
== NULL
) {
11135 if (!Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11136 currentVal
= ++JimWideValue(objPtr
);
11137 Jim_InvalidateStringRep(objPtr
);
11140 if (Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
||
11141 Jim_SetVariable(interp
, varNamePtr
, Jim_NewIntObj(interp
,
11142 ++currentVal
)) != JIM_OK
) {
11153 while (boolean
&& (retval
== JIM_OK
|| retval
== JIM_CONTINUE
)) {
11155 retval
= Jim_EvalObj(interp
, argv
[4]);
11157 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11160 retval
= Jim_EvalObj(interp
, argv
[3]);
11161 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11164 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11169 if (stopVarNamePtr
) {
11170 Jim_DecrRefCount(interp
, stopVarNamePtr
);
11173 Jim_DecrRefCount(interp
, varNamePtr
);
11176 if (retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
|| retval
== JIM_OK
) {
11177 Jim_SetEmptyResult(interp
);
11185 static int Jim_LoopCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11191 Jim_Obj
*bodyObjPtr
;
11193 if (argc
!= 5 && argc
!= 6) {
11194 Jim_WrongNumArgs(interp
, 1, argv
, "var first limit ?incr? body");
11198 if (Jim_GetWide(interp
, argv
[2], &i
) != JIM_OK
||
11199 Jim_GetWide(interp
, argv
[3], &limit
) != JIM_OK
||
11200 (argc
== 6 && Jim_GetWide(interp
, argv
[4], &incr
) != JIM_OK
)) {
11203 bodyObjPtr
= (argc
== 5) ? argv
[4] : argv
[5];
11205 retval
= Jim_SetVariable(interp
, argv
[1], argv
[2]);
11207 while (((i
< limit
&& incr
> 0) || (i
> limit
&& incr
< 0)) && retval
== JIM_OK
) {
11208 retval
= Jim_EvalObj(interp
, bodyObjPtr
);
11209 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11210 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11217 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11218 if (argv
[1]->typePtr
!= &variableObjType
) {
11219 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11223 JimWideValue(objPtr
) = i
;
11224 Jim_InvalidateStringRep(objPtr
);
11226 /* The following step is required in order to invalidate the
11227 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11228 if (argv
[1]->typePtr
!= &variableObjType
) {
11229 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11236 objPtr
= Jim_NewIntObj(interp
, i
);
11237 retval
= Jim_SetVariable(interp
, argv
[1], objPtr
);
11238 if (retval
!= JIM_OK
) {
11239 Jim_FreeNewObj(interp
, objPtr
);
11245 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
) {
11246 Jim_SetEmptyResult(interp
);
11252 /* foreach + lmap implementation. */
11253 static int JimForeachMapHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int doMap
)
11255 int result
= JIM_ERR
, i
, nbrOfLists
, *listsIdx
, *listsEnd
;
11256 int nbrOfLoops
= 0;
11257 Jim_Obj
*emptyStr
, *script
, *mapRes
= NULL
;
11259 if (argc
< 4 || argc
% 2 != 0) {
11260 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varList list ...? script");
11264 mapRes
= Jim_NewListObj(interp
, NULL
, 0);
11265 Jim_IncrRefCount(mapRes
);
11267 emptyStr
= Jim_NewEmptyStringObj(interp
);
11268 Jim_IncrRefCount(emptyStr
);
11269 script
= argv
[argc
- 1]; /* Last argument is a script */
11270 nbrOfLists
= (argc
- 1 - 1) / 2; /* argc - 'foreach' - script */
11271 listsIdx
= (int *)Jim_Alloc(nbrOfLists
* sizeof(int));
11272 listsEnd
= (int *)Jim_Alloc(nbrOfLists
* 2 * sizeof(int));
11273 /* Initialize iterators and remember max nbr elements each list */
11274 memset(listsIdx
, 0, nbrOfLists
* sizeof(int));
11275 /* Remember lengths of all lists and calculate how much rounds to loop */
11276 for (i
= 0; i
< nbrOfLists
* 2; i
+= 2) {
11280 listsEnd
[i
] = Jim_ListLength(interp
, argv
[i
+ 1]);
11281 listsEnd
[i
+ 1] = Jim_ListLength(interp
, argv
[i
+ 2]);
11282 if (listsEnd
[i
] == 0) {
11283 Jim_SetResultString(interp
, "foreach varlist is empty", -1);
11286 cnt
= div(listsEnd
[i
+ 1], listsEnd
[i
]);
11287 count
= cnt
.quot
+ (cnt
.rem
? 1 : 0);
11288 if (count
> nbrOfLoops
)
11289 nbrOfLoops
= count
;
11291 for (; nbrOfLoops
-- > 0;) {
11292 for (i
= 0; i
< nbrOfLists
; ++i
) {
11293 int varIdx
= 0, var
= i
* 2;
11295 while (varIdx
< listsEnd
[var
]) {
11296 Jim_Obj
*varName
, *ele
;
11297 int lst
= i
* 2 + 1;
11299 /* List index operations below can't fail */
11300 Jim_ListIndex(interp
, argv
[var
+ 1], varIdx
, &varName
, JIM_NONE
);
11301 if (listsIdx
[i
] < listsEnd
[lst
]) {
11302 Jim_ListIndex(interp
, argv
[lst
+ 1], listsIdx
[i
], &ele
, JIM_NONE
);
11303 /* Avoid shimmering */
11304 Jim_IncrRefCount(ele
);
11305 result
= Jim_SetVariable(interp
, varName
, ele
);
11306 Jim_DecrRefCount(interp
, ele
);
11307 if (result
== JIM_OK
) {
11308 ++listsIdx
[i
]; /* Remember next iterator of current list */
11309 ++varIdx
; /* Next variable */
11313 else if (Jim_SetVariable(interp
, varName
, emptyStr
) == JIM_OK
) {
11314 ++varIdx
; /* Next variable */
11320 switch (result
= Jim_EvalObj(interp
, script
)) {
11323 Jim_ListAppendElement(interp
, mapRes
, interp
->result
);
11337 Jim_SetResult(interp
, mapRes
);
11339 Jim_SetEmptyResult(interp
);
11342 Jim_DecrRefCount(interp
, mapRes
);
11343 Jim_DecrRefCount(interp
, emptyStr
);
11344 Jim_Free(listsIdx
);
11345 Jim_Free(listsEnd
);
11350 static int Jim_ForeachCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11352 return JimForeachMapHelper(interp
, argc
, argv
, 0);
11356 static int Jim_LmapCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11358 return JimForeachMapHelper(interp
, argc
, argv
, 1);
11362 static int Jim_IfCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11364 int boolean
, retval
, current
= 1, falsebody
= 0;
11368 /* Far not enough arguments given! */
11369 if (current
>= argc
)
11371 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[current
++], &boolean
))
11374 /* There lacks something, isn't it? */
11375 if (current
>= argc
)
11377 if (Jim_CompareStringImmediate(interp
, argv
[current
], "then"))
11379 /* Tsk tsk, no then-clause? */
11380 if (current
>= argc
)
11383 return Jim_EvalObj(interp
, argv
[current
]);
11384 /* Ok: no else-clause follows */
11385 if (++current
>= argc
) {
11386 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11389 falsebody
= current
++;
11390 if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "else")) {
11391 /* IIICKS - else-clause isn't last cmd? */
11392 if (current
!= argc
- 1)
11394 return Jim_EvalObj(interp
, argv
[current
]);
11396 else if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "elseif"))
11397 /* Ok: elseif follows meaning all the stuff
11398 * again (how boring...) */
11400 /* OOPS - else-clause is not last cmd? */
11401 else if (falsebody
!= argc
- 1)
11403 return Jim_EvalObj(interp
, argv
[falsebody
]);
11408 Jim_WrongNumArgs(interp
, 1, argv
, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11413 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11414 int Jim_CommandMatchObj(Jim_Interp
*interp
, Jim_Obj
*commandObj
, Jim_Obj
*patternObj
,
11415 Jim_Obj
*stringObj
, int nocase
)
11422 parms
[argc
++] = commandObj
;
11424 parms
[argc
++] = Jim_NewStringObj(interp
, "-nocase", -1);
11426 parms
[argc
++] = patternObj
;
11427 parms
[argc
++] = stringObj
;
11429 rc
= Jim_EvalObjVector(interp
, argc
, parms
);
11431 if (rc
!= JIM_OK
|| Jim_GetLong(interp
, Jim_GetResult(interp
), &eq
) != JIM_OK
) {
11439 { SWITCH_EXACT
, SWITCH_GLOB
, SWITCH_RE
, SWITCH_CMD
};
11442 static int Jim_SwitchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11444 int matchOpt
= SWITCH_EXACT
, opt
= 1, patCount
, i
;
11445 Jim_Obj
*command
= 0, *const *caseList
= 0, *strObj
;
11446 Jim_Obj
*script
= 0;
11450 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string "
11451 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11454 for (opt
= 1; opt
< argc
; ++opt
) {
11455 const char *option
= Jim_GetString(argv
[opt
], 0);
11457 if (*option
!= '-')
11459 else if (strncmp(option
, "--", 2) == 0) {
11463 else if (strncmp(option
, "-exact", 2) == 0)
11464 matchOpt
= SWITCH_EXACT
;
11465 else if (strncmp(option
, "-glob", 2) == 0)
11466 matchOpt
= SWITCH_GLOB
;
11467 else if (strncmp(option
, "-regexp", 2) == 0)
11468 matchOpt
= SWITCH_RE
;
11469 else if (strncmp(option
, "-command", 2) == 0) {
11470 matchOpt
= SWITCH_CMD
;
11471 if ((argc
- opt
) < 2)
11473 command
= argv
[++opt
];
11476 Jim_SetResultFormatted(interp
,
11477 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11481 if ((argc
- opt
) < 2)
11484 strObj
= argv
[opt
++];
11485 patCount
= argc
- opt
;
11486 if (patCount
== 1) {
11489 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11493 caseList
= &argv
[opt
];
11494 if (patCount
== 0 || patCount
% 2 != 0)
11496 for (i
= 0; script
== 0 && i
< patCount
; i
+= 2) {
11497 Jim_Obj
*patObj
= caseList
[i
];
11499 if (!Jim_CompareStringImmediate(interp
, patObj
, "default")
11500 || i
< (patCount
- 2)) {
11501 switch (matchOpt
) {
11503 if (Jim_StringEqObj(strObj
, patObj
))
11504 script
= caseList
[i
+ 1];
11507 if (Jim_StringMatchObj(interp
, patObj
, strObj
, 0))
11508 script
= caseList
[i
+ 1];
11511 command
= Jim_NewStringObj(interp
, "regexp", -1);
11512 /* Fall thru intentionally */
11514 int rc
= Jim_CommandMatchObj(interp
, command
, patObj
, strObj
, 0);
11516 /* After the execution of a command we need to
11517 * make sure to reconvert the object into a list
11518 * again. Only for the single-list style [switch]. */
11519 if (argc
- opt
== 1) {
11522 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11525 /* command is here already decref'd */
11530 script
= caseList
[i
+ 1];
11536 script
= caseList
[i
+ 1];
11539 for (; i
< patCount
&& Jim_CompareStringImmediate(interp
, script
, "-"); i
+= 2)
11540 script
= caseList
[i
+ 1];
11541 if (script
&& Jim_CompareStringImmediate(interp
, script
, "-")) {
11542 Jim_SetResultFormatted(interp
, "no body specified for pattern \"%#s\"", caseList
[i
- 2]);
11545 Jim_SetEmptyResult(interp
);
11547 return Jim_EvalObj(interp
, script
);
11553 static int Jim_ListCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11555 Jim_Obj
*listObjPtr
;
11557 listObjPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
11558 Jim_SetResult(interp
, listObjPtr
);
11563 static int Jim_LindexCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11565 Jim_Obj
*objPtr
, *listObjPtr
;
11570 Jim_WrongNumArgs(interp
, 1, argv
, "list index ?...?");
11574 Jim_IncrRefCount(objPtr
);
11575 for (i
= 2; i
< argc
; i
++) {
11576 listObjPtr
= objPtr
;
11577 if (Jim_GetIndex(interp
, argv
[i
], &idx
) != JIM_OK
) {
11578 Jim_DecrRefCount(interp
, listObjPtr
);
11581 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_NONE
) != JIM_OK
) {
11582 /* Returns an empty object if the index
11583 * is out of range. */
11584 Jim_DecrRefCount(interp
, listObjPtr
);
11585 Jim_SetEmptyResult(interp
);
11588 Jim_IncrRefCount(objPtr
);
11589 Jim_DecrRefCount(interp
, listObjPtr
);
11591 Jim_SetResult(interp
, objPtr
);
11592 Jim_DecrRefCount(interp
, objPtr
);
11597 static int Jim_LlengthCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11600 Jim_WrongNumArgs(interp
, 1, argv
, "list");
11603 Jim_SetResultInt(interp
, Jim_ListLength(interp
, argv
[1]));
11608 static int Jim_LsearchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11610 static const char * const options
[] = {
11611 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11615 { OPT_BOOL
, OPT_NOT
, OPT_NOCASE
, OPT_EXACT
, OPT_GLOB
, OPT_REGEXP
, OPT_ALL
, OPT_INLINE
,
11620 int opt_nocase
= 0;
11622 int opt_inline
= 0;
11623 int opt_match
= OPT_EXACT
;
11626 Jim_Obj
*listObjPtr
= NULL
;
11627 Jim_Obj
*commandObj
= NULL
;
11631 Jim_WrongNumArgs(interp
, 1, argv
,
11632 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11636 for (i
= 1; i
< argc
- 2; i
++) {
11639 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
11661 if (i
>= argc
- 2) {
11664 commandObj
= argv
[++i
];
11669 opt_match
= option
;
11677 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11679 if (opt_match
== OPT_REGEXP
) {
11680 commandObj
= Jim_NewStringObj(interp
, "regexp", -1);
11683 Jim_IncrRefCount(commandObj
);
11686 listlen
= Jim_ListLength(interp
, argv
[0]);
11687 for (i
= 0; i
< listlen
; i
++) {
11691 Jim_ListIndex(interp
, argv
[0], i
, &objPtr
, JIM_NONE
);
11692 switch (opt_match
) {
11694 eq
= Jim_StringCompareObj(interp
, objPtr
, argv
[1], opt_nocase
) == 0;
11698 eq
= Jim_StringMatchObj(interp
, argv
[1], objPtr
, opt_nocase
);
11703 eq
= Jim_CommandMatchObj(interp
, commandObj
, argv
[1], objPtr
, opt_nocase
);
11706 Jim_FreeNewObj(interp
, listObjPtr
);
11714 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11715 if (!eq
&& opt_bool
&& opt_not
&& !opt_all
) {
11719 if ((!opt_bool
&& eq
== !opt_not
) || (opt_bool
&& (eq
|| opt_all
))) {
11720 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11721 Jim_Obj
*resultObj
;
11724 resultObj
= Jim_NewIntObj(interp
, eq
^ opt_not
);
11726 else if (!opt_inline
) {
11727 resultObj
= Jim_NewIntObj(interp
, i
);
11730 resultObj
= objPtr
;
11734 Jim_ListAppendElement(interp
, listObjPtr
, resultObj
);
11737 Jim_SetResult(interp
, resultObj
);
11744 Jim_SetResult(interp
, listObjPtr
);
11749 Jim_SetResultBool(interp
, opt_not
);
11751 else if (!opt_inline
) {
11752 Jim_SetResultInt(interp
, -1);
11758 Jim_DecrRefCount(interp
, commandObj
);
11764 static int Jim_LappendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11766 Jim_Obj
*listObjPtr
;
11770 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
11773 listObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
11775 /* Create the list if it does not exists */
11776 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11777 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11778 Jim_FreeNewObj(interp
, listObjPtr
);
11782 shared
= Jim_IsShared(listObjPtr
);
11784 listObjPtr
= Jim_DuplicateObj(interp
, listObjPtr
);
11785 for (i
= 2; i
< argc
; i
++)
11786 Jim_ListAppendElement(interp
, listObjPtr
, argv
[i
]);
11787 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11789 Jim_FreeNewObj(interp
, listObjPtr
);
11792 Jim_SetResult(interp
, listObjPtr
);
11797 static int Jim_LinsertCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11803 Jim_WrongNumArgs(interp
, 1, argv
, "list index element " "?element ...?");
11807 if (Jim_IsShared(listPtr
))
11808 listPtr
= Jim_DuplicateObj(interp
, listPtr
);
11809 if (Jim_GetIndex(interp
, argv
[2], &idx
) != JIM_OK
)
11811 len
= Jim_ListLength(interp
, listPtr
);
11815 idx
= len
+ idx
+ 1;
11816 Jim_ListInsertElements(interp
, listPtr
, idx
, argc
- 3, &argv
[3]);
11817 Jim_SetResult(interp
, listPtr
);
11820 if (listPtr
!= argv
[1]) {
11821 Jim_FreeNewObj(interp
, listPtr
);
11827 static int Jim_LreplaceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11829 int first
, last
, len
, rangeLen
;
11831 Jim_Obj
*newListObj
;
11836 Jim_WrongNumArgs(interp
, 1, argv
, "list first last ?element element ...?");
11839 if (Jim_GetIndex(interp
, argv
[2], &first
) != JIM_OK
||
11840 Jim_GetIndex(interp
, argv
[3], &last
) != JIM_OK
) {
11845 len
= Jim_ListLength(interp
, listObj
);
11847 first
= JimRelToAbsIndex(len
, first
);
11848 last
= JimRelToAbsIndex(len
, last
);
11849 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
11851 /* Now construct a new list which consists of:
11852 * <elements before first> <supplied elements> <elements after last>
11855 /* Check to see if trying to replace past the end of the list */
11857 /* OK. Not past the end */
11859 else if (len
== 0) {
11860 /* Special for empty list, adjust first to 0 */
11864 Jim_SetResultString(interp
, "list doesn't contain element ", -1);
11865 Jim_AppendObj(interp
, Jim_GetResult(interp
), argv
[2]);
11869 newListObj
= Jim_NewListObj(interp
, NULL
, 0);
11871 shared
= Jim_IsShared(listObj
);
11873 listObj
= Jim_DuplicateObj(interp
, listObj
);
11876 /* Add the first set of elements */
11877 for (i
= 0; i
< first
; i
++) {
11878 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11881 /* Add supplied elements */
11882 for (i
= 4; i
< argc
; i
++) {
11883 Jim_ListAppendElement(interp
, newListObj
, argv
[i
]);
11886 /* Add the remaining elements */
11887 for (i
= first
+ rangeLen
; i
< len
; i
++) {
11888 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11890 Jim_SetResult(interp
, newListObj
);
11892 Jim_FreeNewObj(interp
, listObj
);
11898 static int Jim_LsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11901 Jim_WrongNumArgs(interp
, 1, argv
, "listVar ?index...? newVal");
11904 else if (argc
== 3) {
11905 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
11907 Jim_SetResult(interp
, argv
[2]);
11910 if (Jim_SetListIndex(interp
, argv
[1], argv
+ 2, argc
- 3, argv
[argc
- 1])
11917 static int Jim_LsortCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const argv
[])
11919 static const char * const options
[] = {
11920 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11923 { OPT_ASCII
, OPT_NOCASE
, OPT_INCREASING
, OPT_DECREASING
, OPT_COMMAND
, OPT_INTEGER
, OPT_INDEX
};
11928 struct lsort_info info
;
11931 Jim_WrongNumArgs(interp
, 1, argv
, "?options? list");
11935 info
.type
= JIM_LSORT_ASCII
;
11938 info
.command
= NULL
;
11939 info
.interp
= interp
;
11941 for (i
= 1; i
< (argc
- 1); i
++) {
11944 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
)
11949 info
.type
= JIM_LSORT_ASCII
;
11952 info
.type
= JIM_LSORT_NOCASE
;
11955 info
.type
= JIM_LSORT_INTEGER
;
11957 case OPT_INCREASING
:
11960 case OPT_DECREASING
:
11964 if (i
>= (argc
- 2)) {
11965 Jim_SetResultString(interp
, "\"-command\" option must be followed by comparison command", -1);
11968 info
.type
= JIM_LSORT_COMMAND
;
11969 info
.command
= argv
[i
+ 1];
11973 if (i
>= (argc
- 2)) {
11974 Jim_SetResultString(interp
, "\"-index\" option must be followed by list index", -1);
11977 if (Jim_GetIndex(interp
, argv
[i
+ 1], &info
.index
) != JIM_OK
) {
11985 resObj
= Jim_DuplicateObj(interp
, argv
[argc
- 1]);
11986 retCode
= ListSortElements(interp
, resObj
, &info
);
11987 if (retCode
== JIM_OK
) {
11988 Jim_SetResult(interp
, resObj
);
11991 Jim_FreeNewObj(interp
, resObj
);
11997 static int Jim_AppendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11999 Jim_Obj
*stringObjPtr
;
12003 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
12007 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
12013 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
12014 if (!stringObjPtr
) {
12015 /* Create the string if it doesn't exist */
12016 stringObjPtr
= Jim_NewEmptyStringObj(interp
);
12019 else if (Jim_IsShared(stringObjPtr
)) {
12021 stringObjPtr
= Jim_DuplicateObj(interp
, stringObjPtr
);
12023 for (i
= 2; i
< argc
; i
++) {
12024 Jim_AppendObj(interp
, stringObjPtr
, argv
[i
]);
12026 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
) != JIM_OK
) {
12028 Jim_FreeNewObj(interp
, stringObjPtr
);
12033 Jim_SetResult(interp
, stringObjPtr
);
12038 static int Jim_DebugCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12040 #ifdef JIM_DEBUG_COMMAND
12041 static const char * const options
[] = {
12042 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12048 OPT_REFCOUNT
, OPT_OBJCOUNT
, OPT_OBJECTS
, OPT_INVSTR
, OPT_SCRIPTLEN
,
12049 OPT_EXPRLEN
, OPT_EXPRBC
, OPT_SHOW
,
12054 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?...?");
12057 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
)
12059 if (option
== OPT_REFCOUNT
) {
12061 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12064 Jim_SetResultInt(interp
, argv
[2]->refCount
);
12067 else if (option
== OPT_OBJCOUNT
) {
12068 int freeobj
= 0, liveobj
= 0;
12073 Jim_WrongNumArgs(interp
, 2, argv
, "");
12076 /* Count the number of free objects. */
12077 objPtr
= interp
->freeList
;
12080 objPtr
= objPtr
->nextObjPtr
;
12082 /* Count the number of live objects. */
12083 objPtr
= interp
->liveList
;
12086 objPtr
= objPtr
->nextObjPtr
;
12088 /* Set the result string and return. */
12089 sprintf(buf
, "free %d used %d", freeobj
, liveobj
);
12090 Jim_SetResultString(interp
, buf
, -1);
12093 else if (option
== OPT_OBJECTS
) {
12094 Jim_Obj
*objPtr
, *listObjPtr
, *subListObjPtr
;
12096 /* Count the number of live objects. */
12097 objPtr
= interp
->liveList
;
12098 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12101 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "";
12103 subListObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12104 sprintf(buf
, "%p", objPtr
);
12105 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
12106 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, type
, -1));
12107 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewIntObj(interp
, objPtr
->refCount
));
12108 Jim_ListAppendElement(interp
, subListObjPtr
, objPtr
);
12109 Jim_ListAppendElement(interp
, listObjPtr
, subListObjPtr
);
12110 objPtr
= objPtr
->nextObjPtr
;
12112 Jim_SetResult(interp
, listObjPtr
);
12115 else if (option
== OPT_INVSTR
) {
12119 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12123 if (objPtr
->typePtr
!= NULL
)
12124 Jim_InvalidateStringRep(objPtr
);
12125 Jim_SetEmptyResult(interp
);
12128 else if (option
== OPT_SHOW
) {
12133 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12136 s
= Jim_GetString(argv
[2], &len
);
12137 charlen
= Jim_Utf8Length(interp
, argv
[2]);
12138 printf("refcount: %d, type: %s\n", argv
[2]->refCount
, JimObjTypeName(argv
[2]));
12139 printf("chars (%d): <<%s>>\n", charlen
, s
);
12140 printf("bytes (%d):", len
);
12142 printf(" %02x", (unsigned char)*s
++);
12147 else if (option
== OPT_SCRIPTLEN
) {
12151 Jim_WrongNumArgs(interp
, 2, argv
, "script");
12154 script
= Jim_GetScript(interp
, argv
[2]);
12155 Jim_SetResultInt(interp
, script
->len
);
12158 else if (option
== OPT_EXPRLEN
) {
12159 ExprByteCode
*expr
;
12162 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12165 expr
= JimGetExpression(interp
, argv
[2]);
12168 Jim_SetResultInt(interp
, expr
->len
);
12171 else if (option
== OPT_EXPRBC
) {
12173 ExprByteCode
*expr
;
12177 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12180 expr
= JimGetExpression(interp
, argv
[2]);
12183 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
12184 for (i
= 0; i
< expr
->len
; i
++) {
12186 const Jim_ExprOperator
*op
;
12187 Jim_Obj
*obj
= expr
->token
[i
].objPtr
;
12189 switch (expr
->token
[i
].type
) {
12190 case JIM_TT_EXPR_INT
:
12193 case JIM_TT_EXPR_DOUBLE
:
12202 case JIM_TT_DICTSUGAR
:
12203 type
= "dictsugar";
12205 case JIM_TT_EXPRSUGAR
:
12206 type
= "exprsugar";
12215 op
= JimExprOperatorInfoByOpcode(expr
->token
[i
].type
);
12222 obj
= Jim_NewStringObj(interp
, op
? op
->name
: "", -1);
12225 Jim_ListAppendElement(interp
, objPtr
, Jim_NewStringObj(interp
, type
, -1));
12226 Jim_ListAppendElement(interp
, objPtr
, obj
);
12228 Jim_SetResult(interp
, objPtr
);
12232 Jim_SetResultString(interp
,
12233 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12238 Jim_SetResultString(interp
, "unsupported", -1);
12244 static int Jim_EvalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12249 Jim_WrongNumArgs(interp
, 1, argv
, "script ?...?");
12254 rc
= Jim_EvalObj(interp
, argv
[1]);
12257 rc
= Jim_EvalObj(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12260 if (rc
== JIM_ERR
) {
12261 /* eval is "interesting", so add a stack frame here */
12262 interp
->addStackTrace
++;
12268 static int Jim_UplevelCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12272 Jim_CallFrame
*savedCallFrame
, *targetCallFrame
;
12276 /* Save the old callframe pointer */
12277 savedCallFrame
= interp
->framePtr
;
12279 /* Lookup the target frame pointer */
12280 str
= Jim_String(argv
[1]);
12281 if ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#') {
12282 targetCallFrame
=Jim_GetCallFrameByLevel(interp
, argv
[1]);
12287 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12289 if (targetCallFrame
== NULL
) {
12294 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12297 /* Eval the code in the target callframe. */
12298 interp
->framePtr
= targetCallFrame
;
12300 retcode
= Jim_EvalObj(interp
, argv
[1]);
12303 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12304 Jim_IncrRefCount(objPtr
);
12305 retcode
= Jim_EvalObj(interp
, objPtr
);
12306 Jim_DecrRefCount(interp
, objPtr
);
12308 interp
->framePtr
= savedCallFrame
;
12312 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12318 static int Jim_ExprCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12320 Jim_Obj
*exprResultPtr
;
12324 retcode
= Jim_EvalExpression(interp
, argv
[1], &exprResultPtr
);
12326 else if (argc
> 2) {
12329 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12330 Jim_IncrRefCount(objPtr
);
12331 retcode
= Jim_EvalExpression(interp
, objPtr
, &exprResultPtr
);
12332 Jim_DecrRefCount(interp
, objPtr
);
12335 Jim_WrongNumArgs(interp
, 1, argv
, "expression ?...?");
12338 if (retcode
!= JIM_OK
)
12340 Jim_SetResult(interp
, exprResultPtr
);
12341 Jim_DecrRefCount(interp
, exprResultPtr
);
12346 static int Jim_BreakCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12349 Jim_WrongNumArgs(interp
, 1, argv
, "");
12356 static int Jim_ContinueCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12359 Jim_WrongNumArgs(interp
, 1, argv
, "");
12362 return JIM_CONTINUE
;
12366 static int Jim_ReturnCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12369 Jim_Obj
*stackTraceObj
= NULL
;
12370 Jim_Obj
*errorCodeObj
= NULL
;
12371 int returnCode
= JIM_OK
;
12374 for (i
= 1; i
< argc
- 1; i
+= 2) {
12375 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-code")) {
12376 if (Jim_GetReturnCode(interp
, argv
[i
+ 1], &returnCode
) == JIM_ERR
) {
12380 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorinfo")) {
12381 stackTraceObj
= argv
[i
+ 1];
12383 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorcode")) {
12384 errorCodeObj
= argv
[i
+ 1];
12386 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-level")) {
12387 if (Jim_GetLong(interp
, argv
[i
+ 1], &level
) != JIM_OK
|| level
< 0) {
12388 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", argv
[i
+ 1]);
12397 if (i
!= argc
- 1 && i
!= argc
) {
12398 Jim_WrongNumArgs(interp
, 1, argv
,
12399 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12402 /* If a stack trace is supplied and code is error, set the stack trace */
12403 if (stackTraceObj
&& returnCode
== JIM_ERR
) {
12404 JimSetStackTrace(interp
, stackTraceObj
);
12406 /* If an error code list is supplied, set the global $errorCode */
12407 if (errorCodeObj
&& returnCode
== JIM_ERR
) {
12408 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCodeObj
);
12410 interp
->returnCode
= returnCode
;
12411 interp
->returnLevel
= level
;
12413 if (i
== argc
- 1) {
12414 Jim_SetResult(interp
, argv
[i
]);
12420 static int Jim_TailcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12424 objPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
12425 Jim_SetResult(interp
, objPtr
);
12430 static int Jim_ProcCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12432 if (argc
!= 4 && argc
!= 5) {
12433 Jim_WrongNumArgs(interp
, 1, argv
, "name arglist ?statics? body");
12438 return JimCreateProcedure(interp
, argv
[1], argv
[2], NULL
, argv
[3]);
12441 return JimCreateProcedure(interp
, argv
[1], argv
[2], argv
[3], argv
[4]);
12446 static int Jim_LocalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12450 /* Evaluate the arguments with 'local' in force */
12452 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12456 /* If OK, and the result is a proc, add it to the list of local procs */
12457 if (retcode
== 0) {
12458 const char *procname
= Jim_String(Jim_GetResult(interp
));
12460 if (Jim_FindHashEntry(&interp
->commands
, procname
) == NULL
) {
12461 Jim_SetResultFormatted(interp
, "not a proc: \"%s\"", procname
);
12464 if (interp
->localProcs
== NULL
) {
12465 interp
->localProcs
= Jim_Alloc(sizeof(*interp
->localProcs
));
12466 Jim_InitStack(interp
->localProcs
);
12468 Jim_StackPush(interp
->localProcs
, Jim_StrDup(procname
));
12475 static int Jim_UpcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12478 Jim_WrongNumArgs(interp
, 1, argv
, "cmd ?args ...?");
12484 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, argv
[1], JIM_ERRMSG
);
12485 if (cmdPtr
== NULL
|| !cmdPtr
->isproc
|| !cmdPtr
->u
.proc
.prevCmd
) {
12486 Jim_SetResultFormatted(interp
, "no previous proc: \"%#s\"", argv
[1]);
12489 /* OK. Mark this command as being in an upcall */
12490 cmdPtr
->u
.proc
.upcall
++;
12491 JimIncrCmdRefCount(cmdPtr
);
12493 /* Invoke the command as normal */
12494 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12496 /* No longer in an upcall */
12497 cmdPtr
->u
.proc
.upcall
--;
12498 JimDecrCmdRefCount(interp
, cmdPtr
);
12505 static int Jim_ConcatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12507 Jim_SetResult(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12512 static int Jim_UpvarCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12515 Jim_CallFrame
*targetCallFrame
;
12517 /* Lookup the target frame pointer */
12518 if (argc
> 3 && (argc
% 2 == 0)) {
12519 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, argv
[1]);
12524 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12526 if (targetCallFrame
== NULL
) {
12530 /* Check for arity */
12532 Jim_WrongNumArgs(interp
, 1, argv
, "?level? otherVar localVar ?otherVar localVar ...?");
12536 /* Now... for every other/local couple: */
12537 for (i
= 1; i
< argc
; i
+= 2) {
12538 if (Jim_SetVariableLink(interp
, argv
[i
+ 1], argv
[i
], targetCallFrame
) != JIM_OK
)
12545 static int Jim_GlobalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12550 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
12553 /* Link every var to the toplevel having the same name */
12554 if (interp
->framePtr
->level
== 0)
12555 return JIM_OK
; /* global at toplevel... */
12556 for (i
= 1; i
< argc
; i
++) {
12557 if (Jim_SetVariableLink(interp
, argv
[i
], argv
[i
], interp
->topFramePtr
) != JIM_OK
)
12563 /* does the [string map] operation. On error NULL is returned,
12564 * otherwise a new string object with the result, having refcount = 0,
12566 static Jim_Obj
*JimStringMap(Jim_Interp
*interp
, Jim_Obj
*mapListObjPtr
,
12567 Jim_Obj
*objPtr
, int nocase
)
12570 const char *str
, *noMatchStart
= NULL
;
12572 Jim_Obj
*resultObjPtr
;
12574 numMaps
= Jim_ListLength(interp
, mapListObjPtr
);
12576 Jim_SetResultString(interp
, "list must contain an even number of elements", -1);
12580 str
= Jim_String(objPtr
);
12581 strLen
= Jim_Utf8Length(interp
, objPtr
);
12584 resultObjPtr
= Jim_NewStringObj(interp
, "", 0);
12586 for (i
= 0; i
< numMaps
; i
+= 2) {
12591 Jim_ListIndex(interp
, mapListObjPtr
, i
, &objPtr
, JIM_NONE
);
12592 k
= Jim_String(objPtr
);
12593 kl
= Jim_Utf8Length(interp
, objPtr
);
12595 if (strLen
>= kl
&& kl
) {
12598 rc
= JimStringCompareNoCase(str
, k
, kl
);
12601 rc
= JimStringCompare(str
, kl
, k
, kl
);
12604 if (noMatchStart
) {
12605 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12606 noMatchStart
= NULL
;
12608 Jim_ListIndex(interp
, mapListObjPtr
, i
+ 1, &objPtr
, JIM_NONE
);
12609 Jim_AppendObj(interp
, resultObjPtr
, objPtr
);
12610 str
+= utf8_index(str
, kl
);
12616 if (i
== numMaps
) { /* no match */
12618 if (noMatchStart
== NULL
)
12619 noMatchStart
= str
;
12620 str
+= utf8_tounicode(str
, &c
);
12624 if (noMatchStart
) {
12625 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12627 return resultObjPtr
;
12631 static int Jim_StringCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12636 static const char * const options
[] = {
12637 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12638 "repeat", "reverse", "index", "first", "last",
12639 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12643 OPT_BYTELENGTH
, OPT_LENGTH
, OPT_COMPARE
, OPT_MATCH
, OPT_EQUAL
, OPT_IS
, OPT_BYTERANGE
, OPT_RANGE
, OPT_MAP
,
12644 OPT_REPEAT
, OPT_REVERSE
, OPT_INDEX
, OPT_FIRST
, OPT_LAST
,
12645 OPT_TRIM
, OPT_TRIMLEFT
, OPT_TRIMRIGHT
, OPT_TOLOWER
, OPT_TOUPPER
12647 static const char * const nocase_options
[] = {
12652 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
12655 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
,
12656 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
)
12661 case OPT_BYTELENGTH
:
12663 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12666 if (option
== OPT_LENGTH
) {
12667 len
= Jim_Utf8Length(interp
, argv
[2]);
12670 len
= Jim_Length(argv
[2]);
12672 Jim_SetResultInt(interp
, len
);
12679 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12680 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12681 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? string1 string2");
12684 if (opt_case
== 0) {
12687 if (option
== OPT_COMPARE
|| !opt_case
) {
12688 Jim_SetResultInt(interp
, Jim_StringCompareObj(interp
, argv
[2], argv
[3], !opt_case
));
12691 Jim_SetResultBool(interp
, Jim_StringEqObj(argv
[2], argv
[3]));
12698 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12699 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12700 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? pattern string");
12703 if (opt_case
== 0) {
12706 Jim_SetResultBool(interp
, Jim_StringMatchObj(interp
, argv
[2], argv
[3], !opt_case
));
12714 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12715 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12716 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? mapList string");
12720 if (opt_case
== 0) {
12723 objPtr
= JimStringMap(interp
, argv
[2], argv
[3], !opt_case
);
12724 if (objPtr
== NULL
) {
12727 Jim_SetResult(interp
, objPtr
);
12732 case OPT_BYTERANGE
:{
12736 Jim_WrongNumArgs(interp
, 2, argv
, "string first last");
12739 if (option
== OPT_RANGE
) {
12740 objPtr
= Jim_StringRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12744 objPtr
= Jim_StringByteRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12747 if (objPtr
== NULL
) {
12750 Jim_SetResult(interp
, objPtr
);
12759 Jim_WrongNumArgs(interp
, 2, argv
, "string count");
12762 if (Jim_GetWide(interp
, argv
[3], &count
) != JIM_OK
) {
12765 objPtr
= Jim_NewStringObj(interp
, "", 0);
12768 Jim_AppendObj(interp
, objPtr
, argv
[2]);
12771 Jim_SetResult(interp
, objPtr
);
12782 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12786 str
= Jim_GetString(argv
[2], &len
);
12791 buf
= Jim_Alloc(len
+ 1);
12794 for (i
= 0; i
< len
; ) {
12796 int l
= utf8_tounicode(str
, &c
);
12797 memcpy(p
- l
, str
, l
);
12802 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
12811 Jim_WrongNumArgs(interp
, 2, argv
, "string index");
12814 if (Jim_GetIndex(interp
, argv
[3], &idx
) != JIM_OK
) {
12817 str
= Jim_String(argv
[2]);
12818 len
= Jim_Utf8Length(interp
, argv
[2]);
12819 if (idx
!= INT_MIN
&& idx
!= INT_MAX
) {
12820 idx
= JimRelToAbsIndex(len
, idx
);
12822 if (idx
< 0 || idx
>= len
|| str
== NULL
) {
12823 Jim_SetResultString(interp
, "", 0);
12825 else if (len
== Jim_Length(argv
[2])) {
12826 /* ASCII optimisation */
12827 Jim_SetResultString(interp
, str
+ idx
, 1);
12831 int i
= utf8_index(str
, idx
);
12832 Jim_SetResultString(interp
, str
+ i
, utf8_tounicode(str
+ i
, &c
));
12839 int idx
= 0, l1
, l2
;
12840 const char *s1
, *s2
;
12842 if (argc
!= 4 && argc
!= 5) {
12843 Jim_WrongNumArgs(interp
, 2, argv
, "subString string ?index?");
12846 s1
= Jim_String(argv
[2]);
12847 s2
= Jim_String(argv
[3]);
12848 l1
= Jim_Utf8Length(interp
, argv
[2]);
12849 l2
= Jim_Utf8Length(interp
, argv
[3]);
12851 if (Jim_GetIndex(interp
, argv
[4], &idx
) != JIM_OK
) {
12854 idx
= JimRelToAbsIndex(l2
, idx
);
12856 else if (option
== OPT_LAST
) {
12859 if (option
== OPT_FIRST
) {
12860 Jim_SetResultInt(interp
, JimStringFirst(s1
, l1
, s2
, l2
, idx
));
12864 Jim_SetResultInt(interp
, JimStringLastUtf8(s1
, l1
, s2
, idx
));
12866 Jim_SetResultInt(interp
, JimStringLast(s1
, l1
, s2
, idx
));
12874 case OPT_TRIMRIGHT
:{
12875 Jim_Obj
*trimchars
;
12877 if (argc
!= 3 && argc
!= 4) {
12878 Jim_WrongNumArgs(interp
, 2, argv
, "string ?trimchars?");
12881 trimchars
= (argc
== 4 ? argv
[3] : NULL
);
12882 if (option
== OPT_TRIM
) {
12883 Jim_SetResult(interp
, JimStringTrim(interp
, argv
[2], trimchars
));
12885 else if (option
== OPT_TRIMLEFT
) {
12886 Jim_SetResult(interp
, JimStringTrimLeft(interp
, argv
[2], trimchars
));
12888 else if (option
== OPT_TRIMRIGHT
) {
12889 Jim_SetResult(interp
, JimStringTrimRight(interp
, argv
[2], trimchars
));
12897 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12900 if (option
== OPT_TOLOWER
) {
12901 Jim_SetResult(interp
, JimStringToLower(interp
, argv
[2]));
12904 Jim_SetResult(interp
, JimStringToUpper(interp
, argv
[2]));
12909 if (argc
== 4 || (argc
== 5 && Jim_CompareStringImmediate(interp
, argv
[3], "-strict"))) {
12910 return JimStringIs(interp
, argv
[argc
- 1], argv
[2], argc
== 5);
12912 Jim_WrongNumArgs(interp
, 2, argv
, "class ?-strict? str");
12919 static int Jim_TimeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12922 jim_wide start
, elapsed
;
12924 const char *fmt
= "%" JIM_WIDE_MODIFIER
" microseconds per iteration";
12927 Jim_WrongNumArgs(interp
, 1, argv
, "script ?count?");
12931 if (Jim_GetLong(interp
, argv
[2], &count
) != JIM_OK
)
12937 start
= JimClock();
12941 retval
= Jim_EvalObj(interp
, argv
[1]);
12942 if (retval
!= JIM_OK
) {
12946 elapsed
= JimClock() - start
;
12947 sprintf(buf
, fmt
, count
== 0 ? 0 : elapsed
/ count
);
12948 Jim_SetResultString(interp
, buf
, -1);
12953 static int Jim_ExitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12958 Jim_WrongNumArgs(interp
, 1, argv
, "?exitCode?");
12962 if (Jim_GetLong(interp
, argv
[1], &exitCode
) != JIM_OK
)
12965 interp
->exitCode
= exitCode
;
12970 static int Jim_CatchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12976 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
12977 jim_wide ignore_mask
= (1 << JIM_EXIT
) | (1 << JIM_EVAL
) | (1 << JIM_SIGNAL
);
12978 static const int max_ignore_code
= sizeof(ignore_mask
) * 8;
12980 /* Reset the error code before catch.
12981 * Note that this is not strictly correct.
12983 Jim_SetGlobalVariableStr(interp
, "errorCode", Jim_NewStringObj(interp
, "NONE", -1));
12985 for (i
= 1; i
< argc
- 1; i
++) {
12986 const char *arg
= Jim_String(argv
[i
]);
12990 /* It's a pity we can't use Jim_GetEnum here :-( */
12991 if (strcmp(arg
, "--") == 0) {
12999 if (strncmp(arg
, "-no", 3) == 0) {
13008 if (Jim_StringToWide(arg
, &option
, 10) != JIM_OK
) {
13012 option
= Jim_FindByName(arg
, jimReturnCodes
, jimReturnCodesSize
);
13019 ignore_mask
|= (1 << option
);
13022 ignore_mask
&= ~(1 << option
);
13027 if (argc
< 1 || argc
> 3) {
13029 Jim_WrongNumArgs(interp
, 1, argv
,
13030 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13035 if ((ignore_mask
& (1 << JIM_SIGNAL
)) == 0) {
13039 interp
->signal_level
+= sig
;
13040 if (interp
->signal_level
&& interp
->sigmask
) {
13041 /* If a signal is set, don't even try to execute the body */
13042 exitCode
= JIM_SIGNAL
;
13045 exitCode
= Jim_EvalObj(interp
, argv
[0]);
13047 interp
->signal_level
-= sig
;
13049 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13050 if (exitCode
>= 0 && exitCode
< max_ignore_code
&& ((1 << exitCode
) & ignore_mask
)) {
13051 /* Not caught, pass it up */
13055 if (sig
&& exitCode
== JIM_SIGNAL
) {
13056 /* Catch the signal at this level */
13057 if (interp
->signal_set_result
) {
13058 interp
->signal_set_result(interp
, interp
->sigmask
);
13061 Jim_SetResultInt(interp
, interp
->sigmask
);
13063 interp
->sigmask
= 0;
13067 if (Jim_SetVariable(interp
, argv
[1], Jim_GetResult(interp
)) != JIM_OK
) {
13071 Jim_Obj
*optListObj
= Jim_NewListObj(interp
, NULL
, 0);
13073 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-code", -1));
13074 Jim_ListAppendElement(interp
, optListObj
,
13075 Jim_NewIntObj(interp
, exitCode
== JIM_RETURN
? interp
->returnCode
: exitCode
));
13076 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-level", -1));
13077 Jim_ListAppendElement(interp
, optListObj
, Jim_NewIntObj(interp
, interp
->returnLevel
));
13078 if (exitCode
== JIM_ERR
) {
13079 Jim_Obj
*errorCode
;
13080 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorinfo",
13082 Jim_ListAppendElement(interp
, optListObj
, interp
->stackTrace
);
13084 errorCode
= Jim_GetGlobalVariableStr(interp
, "errorCode", JIM_NONE
);
13086 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorcode", -1));
13087 Jim_ListAppendElement(interp
, optListObj
, errorCode
);
13090 if (Jim_SetVariable(interp
, argv
[2], optListObj
) != JIM_OK
) {
13095 Jim_SetResultInt(interp
, exitCode
);
13099 #ifdef JIM_REFERENCES
13102 static int Jim_RefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13104 if (argc
!= 3 && argc
!= 4) {
13105 Jim_WrongNumArgs(interp
, 1, argv
, "string tag ?finalizer?");
13109 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], NULL
));
13112 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], argv
[3]));
13118 static int Jim_GetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13120 Jim_Reference
*refPtr
;
13123 Jim_WrongNumArgs(interp
, 1, argv
, "reference");
13126 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13128 Jim_SetResult(interp
, refPtr
->objPtr
);
13133 static int Jim_SetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13135 Jim_Reference
*refPtr
;
13138 Jim_WrongNumArgs(interp
, 1, argv
, "reference newValue");
13141 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13143 Jim_IncrRefCount(argv
[2]);
13144 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
13145 refPtr
->objPtr
= argv
[2];
13146 Jim_SetResult(interp
, argv
[2]);
13151 static int Jim_CollectCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13154 Jim_WrongNumArgs(interp
, 1, argv
, "");
13157 Jim_SetResultInt(interp
, Jim_Collect(interp
));
13159 /* Free all the freed objects. */
13160 while (interp
->freeList
) {
13161 Jim_Obj
*nextObjPtr
= interp
->freeList
->nextObjPtr
;
13162 Jim_Free(interp
->freeList
);
13163 interp
->freeList
= nextObjPtr
;
13169 /* [finalize] reference ?newValue? */
13170 static int Jim_FinalizeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13172 if (argc
!= 2 && argc
!= 3) {
13173 Jim_WrongNumArgs(interp
, 1, argv
, "reference ?finalizerProc?");
13177 Jim_Obj
*cmdNamePtr
;
13179 if (Jim_GetFinalizer(interp
, argv
[1], &cmdNamePtr
) != JIM_OK
)
13181 if (cmdNamePtr
!= NULL
) /* otherwise the null string is returned. */
13182 Jim_SetResult(interp
, cmdNamePtr
);
13185 if (Jim_SetFinalizer(interp
, argv
[1], argv
[2]) != JIM_OK
)
13187 Jim_SetResult(interp
, argv
[2]);
13192 /* [info references] */
13193 static int JimInfoReferences(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13195 Jim_Obj
*listObjPtr
;
13196 Jim_HashTableIterator
*htiter
;
13199 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13201 htiter
= Jim_GetHashTableIterator(&interp
->references
);
13202 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
13203 char buf
[JIM_REFERENCE_SPACE
];
13204 Jim_Reference
*refPtr
= he
->u
.val
;
13205 const jim_wide
*refId
= he
->key
;
13207 JimFormatReference(buf
, refPtr
, *refId
);
13208 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
13210 Jim_FreeHashTableIterator(htiter
);
13211 Jim_SetResult(interp
, listObjPtr
);
13217 static int Jim_RenameCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13219 const char *oldName
, *newName
;
13222 Jim_WrongNumArgs(interp
, 1, argv
, "oldName newName");
13226 if (JimValidName(interp
, "new procedure", argv
[2])) {
13230 oldName
= Jim_String(argv
[1]);
13231 newName
= Jim_String(argv
[2]);
13232 return Jim_RenameCommand(interp
, oldName
, newName
);
13235 int Jim_DictKeys(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*patternObj
)
13239 Jim_Obj
*resultObj
;
13241 Jim_Obj
**dictValuesObj
;
13243 if (Jim_DictKeysVector(interp
, objPtr
, NULL
, 0, &dictObj
, JIM_ERRMSG
) != JIM_OK
) {
13247 /* XXX: Could make the exact-match case much more efficient here.
13248 * See JimCommandsList()
13250 if (Jim_DictPairs(interp
, dictObj
, &dictValuesObj
, &len
) != JIM_OK
) {
13254 /* Only return the matching values */
13255 resultObj
= Jim_NewListObj(interp
, NULL
, 0);
13257 for (i
= 0; i
< len
; i
+= 2) {
13258 if (patternObj
== NULL
|| Jim_StringMatchObj(interp
, patternObj
, dictValuesObj
[i
], 0)) {
13259 Jim_ListAppendElement(interp
, resultObj
, dictValuesObj
[i
]);
13262 Jim_Free(dictValuesObj
);
13264 Jim_SetResult(interp
, resultObj
);
13268 int Jim_DictSize(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
13270 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
13273 return ((Jim_HashTable
*)objPtr
->internalRep
.ptr
)->used
;
13277 static int Jim_DictCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13281 static const char * const options
[] = {
13282 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13286 OPT_CREATE
, OPT_GET
, OPT_SET
, OPT_UNSET
, OPT_EXIST
, OPT_KEYS
, OPT_MERGE
, OPT_SIZE
, OPT_WITH
,
13290 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?arguments ...?");
13294 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
) {
13301 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13304 if (Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, &objPtr
,
13305 JIM_ERRMSG
) != JIM_OK
) {
13308 Jim_SetResult(interp
, objPtr
);
13313 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...? value");
13316 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 4, argv
[argc
- 1]);
13320 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13323 Jim_SetResultBool(interp
, Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3,
13324 &objPtr
, JIM_ERRMSG
) == JIM_OK
);
13329 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...?");
13332 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, NULL
);
13335 if (argc
!= 3 && argc
!= 4) {
13336 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?pattern?");
13339 return Jim_DictKeys(interp
, argv
[2], argc
== 4 ? argv
[3] : NULL
);
13345 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar");
13349 size
= Jim_DictSize(interp
, argv
[2]);
13353 Jim_SetResultInt(interp
, size
);
13361 else if (argv
[2]->typePtr
!= &dictObjType
&& SetDictFromAny(interp
, argv
[2]) != JIM_OK
) {
13365 return Jim_EvalObjPrefix(interp
, "dict merge", argc
- 2, argv
+ 2);
13370 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?key ...? script");
13373 else if (Jim_GetVariable(interp
, argv
[2], JIM_ERRMSG
) == NULL
) {
13377 return Jim_EvalObjPrefix(interp
, "dict with", argc
- 2, argv
+ 2);
13382 Jim_WrongNumArgs(interp
, 2, argv
, "?key value ...?");
13385 objPtr
= Jim_NewDictObj(interp
, argv
+ 2, argc
- 2);
13386 Jim_SetResult(interp
, objPtr
);
13395 static int Jim_SubstCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13397 static const char * const options
[] = {
13398 "-nobackslashes", "-nocommands", "-novariables", NULL
13401 { OPT_NOBACKSLASHES
, OPT_NOCOMMANDS
, OPT_NOVARIABLES
};
13403 int flags
= JIM_SUBST_FLAG
;
13407 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string");
13410 for (i
= 1; i
< (argc
- 1); i
++) {
13413 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
,
13414 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13418 case OPT_NOBACKSLASHES
:
13419 flags
|= JIM_SUBST_NOESC
;
13421 case OPT_NOCOMMANDS
:
13422 flags
|= JIM_SUBST_NOCMD
;
13424 case OPT_NOVARIABLES
:
13425 flags
|= JIM_SUBST_NOVAR
;
13429 if (Jim_SubstObj(interp
, argv
[argc
- 1], &objPtr
, flags
) != JIM_OK
) {
13432 Jim_SetResult(interp
, objPtr
);
13437 static int Jim_InfoCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13443 static const char * const commands
[] = {
13444 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13445 "vars", "version", "patchlevel", "complete", "args", "hostname",
13446 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13450 { INFO_BODY
, INFO_COMMANDS
, INFO_PROCS
, INFO_CHANNELS
, INFO_EXISTS
, INFO_GLOBALS
, INFO_LEVEL
,
13451 INFO_FRAME
, INFO_LOCALS
, INFO_VARS
, INFO_VERSION
, INFO_PATCHLEVEL
, INFO_COMPLETE
, INFO_ARGS
,
13452 INFO_HOSTNAME
, INFO_SCRIPT
, INFO_SOURCE
, INFO_STACKTRACE
, INFO_NAMEOFEXECUTABLE
,
13453 INFO_RETURNCODES
, INFO_REFERENCES
,
13457 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?args ...?");
13460 if (Jim_GetEnum(interp
, argv
[1], commands
, &cmd
, "subcommand", JIM_ERRMSG
| JIM_ENUM_ABBREV
)
13465 /* Test for the the most common commands first, just in case it makes a difference */
13469 Jim_WrongNumArgs(interp
, 2, argv
, "varName");
13472 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, argv
[2], 0) != NULL
);
13476 case INFO_CHANNELS
:
13477 #ifndef jim_ext_aio
13478 Jim_SetResultString(interp
, "aio not enabled", -1);
13481 case INFO_COMMANDS
:
13483 if (argc
!= 2 && argc
!= 3) {
13484 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13487 Jim_SetResult(interp
, JimCommandsList(interp
, (argc
== 3) ? argv
[2] : NULL
,
13488 (cmd
- INFO_COMMANDS
)));
13492 mode
++; /* JIM_VARLIST_VARS */
13494 mode
++; /* JIM_VARLIST_LOCALS */
13496 /* mode 0 => JIM_VARLIST_GLOBALS */
13497 if (argc
!= 2 && argc
!= 3) {
13498 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13501 Jim_SetResult(interp
, JimVariablesList(interp
, argc
== 3 ? argv
[2] : NULL
, mode
));
13506 Jim_WrongNumArgs(interp
, 2, argv
, "");
13509 Jim_SetResult(interp
, Jim_GetScript(interp
, interp
->currentScriptObj
)->fileNameObj
);
13514 Jim_Obj
*resObjPtr
;
13515 Jim_Obj
*fileNameObj
;
13518 Jim_WrongNumArgs(interp
, 2, argv
, "source");
13521 if (argv
[2]->typePtr
== &sourceObjType
) {
13522 fileNameObj
= argv
[2]->internalRep
.sourceValue
.fileNameObj
;
13523 line
= argv
[2]->internalRep
.sourceValue
.lineNumber
;
13525 else if (argv
[2]->typePtr
== &scriptObjType
) {
13526 ScriptObj
*script
= Jim_GetScript(interp
, argv
[2]);
13527 fileNameObj
= script
->fileNameObj
;
13528 line
= script
->line
;
13531 fileNameObj
= interp
->emptyObj
;
13534 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13535 Jim_ListAppendElement(interp
, resObjPtr
, fileNameObj
);
13536 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewIntObj(interp
, line
));
13537 Jim_SetResult(interp
, resObjPtr
);
13541 case INFO_STACKTRACE
:
13542 Jim_SetResult(interp
, interp
->stackTrace
);
13549 Jim_SetResultInt(interp
, interp
->framePtr
->level
);
13553 if (JimInfoLevel(interp
, argv
[2], &objPtr
, cmd
== INFO_LEVEL
) != JIM_OK
) {
13556 Jim_SetResult(interp
, objPtr
);
13560 Jim_WrongNumArgs(interp
, 2, argv
, "?levelNum?");
13570 Jim_WrongNumArgs(interp
, 2, argv
, "procname");
13573 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
) {
13576 if (!cmdPtr
->isproc
) {
13577 Jim_SetResultFormatted(interp
, "command \"%#s\" is not a procedure", argv
[2]);
13580 Jim_SetResult(interp
,
13581 cmd
== INFO_BODY
? cmdPtr
->u
.proc
.bodyObjPtr
: cmdPtr
->u
.proc
.argListObjPtr
);
13586 case INFO_PATCHLEVEL
:{
13587 char buf
[(JIM_INTEGER_SPACE
* 2) + 1];
13589 sprintf(buf
, "%d.%d", JIM_VERSION
/ 100, JIM_VERSION
% 100);
13590 Jim_SetResultString(interp
, buf
, -1);
13594 case INFO_COMPLETE
:
13595 if (argc
!= 3 && argc
!= 4) {
13596 Jim_WrongNumArgs(interp
, 2, argv
, "script ?missing?");
13601 const char *s
= Jim_GetString(argv
[2], &len
);
13604 Jim_SetResultBool(interp
, Jim_ScriptIsComplete(s
, len
, &missing
));
13605 if (missing
!= ' ' && argc
== 4) {
13606 Jim_SetVariable(interp
, argv
[3], Jim_NewStringObj(interp
, &missing
, 1));
13611 case INFO_HOSTNAME
:
13612 /* Redirect to os.gethostname if it exists */
13613 return Jim_Eval(interp
, "os.gethostname");
13615 case INFO_NAMEOFEXECUTABLE
:
13616 /* Redirect to Tcl proc */
13617 return Jim_Eval(interp
, "{info nameofexecutable}");
13619 case INFO_RETURNCODES
:
13622 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13624 for (i
= 0; jimReturnCodes
[i
]; i
++) {
13625 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewIntObj(interp
, i
));
13626 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
,
13627 jimReturnCodes
[i
], -1));
13630 Jim_SetResult(interp
, listObjPtr
);
13632 else if (argc
== 3) {
13636 if (Jim_GetLong(interp
, argv
[2], &code
) != JIM_OK
) {
13639 name
= Jim_ReturnCode(code
);
13640 if (*name
== '?') {
13641 Jim_SetResultInt(interp
, code
);
13644 Jim_SetResultString(interp
, name
, -1);
13648 Jim_WrongNumArgs(interp
, 2, argv
, "?code?");
13652 case INFO_REFERENCES
:
13653 #ifdef JIM_REFERENCES
13654 return JimInfoReferences(interp
, argc
, argv
);
13656 Jim_SetResultString(interp
, "not supported", -1);
13664 static int Jim_ExistsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13668 static const char * const options
[] = {
13669 "-command", "-proc", "-var", NULL
13673 OPT_COMMAND
, OPT_PROC
, OPT_VAR
13681 else if (argc
== 3) {
13682 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13688 Jim_WrongNumArgs(interp
, 1, argv
, "?option? name");
13692 /* Test for the the most common commands first, just in case it makes a difference */
13695 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, objPtr
, 0) != NULL
);
13700 Jim_Cmd
*cmd
= Jim_GetCommand(interp
, objPtr
, JIM_NONE
);
13701 Jim_SetResultBool(interp
, cmd
!= NULL
&& (option
== OPT_COMMAND
|| cmd
->isproc
));
13709 static int Jim_SplitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13711 const char *str
, *splitChars
, *noMatchStart
;
13712 int splitLen
, strLen
;
13713 Jim_Obj
*resObjPtr
;
13717 if (argc
!= 2 && argc
!= 3) {
13718 Jim_WrongNumArgs(interp
, 1, argv
, "string ?splitChars?");
13722 str
= Jim_GetString(argv
[1], &len
);
13726 strLen
= Jim_Utf8Length(interp
, argv
[1]);
13730 splitChars
= " \n\t\r";
13734 splitChars
= Jim_String(argv
[2]);
13735 splitLen
= Jim_Utf8Length(interp
, argv
[2]);
13738 noMatchStart
= str
;
13739 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13745 const char *sc
= splitChars
;
13746 int scLen
= splitLen
;
13747 int sl
= utf8_tounicode(str
, &c
);
13750 sc
+= utf8_tounicode(sc
, &pc
);
13752 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13753 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13754 noMatchStart
= str
+ sl
;
13760 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13761 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13764 /* This handles the special case of splitchars eq {}
13765 * Optimise by sharing common (ASCII) characters
13767 Jim_Obj
**commonObj
= NULL
;
13768 #define NUM_COMMON (128 - 9)
13770 int n
= utf8_tounicode(str
, &c
);
13771 #ifdef JIM_OPTIMIZATION
13772 if (c
>= 9 && c
< 128) {
13773 /* Common ASCII char. Note that 9 is the tab character */
13776 commonObj
= Jim_Alloc(sizeof(*commonObj
) * NUM_COMMON
);
13777 memset(commonObj
, 0, sizeof(*commonObj
) * NUM_COMMON
);
13779 if (!commonObj
[c
]) {
13780 commonObj
[c
] = Jim_NewStringObj(interp
, str
, 1);
13782 Jim_ListAppendElement(interp
, resObjPtr
, commonObj
[c
]);
13787 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewStringObjUtf8(interp
, str
, 1));
13790 Jim_Free(commonObj
);
13793 Jim_SetResult(interp
, resObjPtr
);
13798 static int Jim_JoinCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13800 const char *joinStr
;
13801 int joinStrLen
, i
, listLen
;
13802 Jim_Obj
*resObjPtr
;
13804 if (argc
!= 2 && argc
!= 3) {
13805 Jim_WrongNumArgs(interp
, 1, argv
, "list ?joinString?");
13814 joinStr
= Jim_GetString(argv
[2], &joinStrLen
);
13816 listLen
= Jim_ListLength(interp
, argv
[1]);
13817 resObjPtr
= Jim_NewStringObj(interp
, NULL
, 0);
13819 for (i
= 0; i
< listLen
; i
++) {
13820 Jim_Obj
*objPtr
= 0;
13822 Jim_ListIndex(interp
, argv
[1], i
, &objPtr
, JIM_NONE
);
13823 Jim_AppendObj(interp
, resObjPtr
, objPtr
);
13824 if (i
+ 1 != listLen
) {
13825 Jim_AppendString(interp
, resObjPtr
, joinStr
, joinStrLen
);
13828 Jim_SetResult(interp
, resObjPtr
);
13833 static int Jim_FormatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13838 Jim_WrongNumArgs(interp
, 1, argv
, "formatString ?arg arg ...?");
13841 objPtr
= Jim_FormatString(interp
, argv
[1], argc
- 2, argv
+ 2);
13842 if (objPtr
== NULL
)
13844 Jim_SetResult(interp
, objPtr
);
13849 static int Jim_ScanCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13851 Jim_Obj
*listPtr
, **outVec
;
13855 Jim_WrongNumArgs(interp
, 1, argv
, "string format ?varName varName ...?");
13858 if (argv
[2]->typePtr
!= &scanFmtStringObjType
)
13859 SetScanFmtFromAny(interp
, argv
[2]);
13860 if (FormatGetError(argv
[2]) != 0) {
13861 Jim_SetResultString(interp
, FormatGetError(argv
[2]), -1);
13865 int maxPos
= FormatGetMaxPos(argv
[2]);
13866 int count
= FormatGetCnvCount(argv
[2]);
13868 if (maxPos
> argc
- 3) {
13869 Jim_SetResultString(interp
, "\"%n$\" argument index out of range", -1);
13872 else if (count
> argc
- 3) {
13873 Jim_SetResultString(interp
, "different numbers of variable names and "
13874 "field specifiers", -1);
13877 else if (count
< argc
- 3) {
13878 Jim_SetResultString(interp
, "variable is not assigned by any "
13879 "conversion specifiers", -1);
13883 listPtr
= Jim_ScanString(interp
, argv
[1], argv
[2], JIM_ERRMSG
);
13890 if (listPtr
!= 0 && listPtr
!= (Jim_Obj
*)EOF
) {
13891 int len
= Jim_ListLength(interp
, listPtr
);
13894 JimListGetElements(interp
, listPtr
, &outc
, &outVec
);
13895 for (i
= 0; i
< outc
; ++i
) {
13896 if (Jim_Length(outVec
[i
]) > 0) {
13898 if (Jim_SetVariable(interp
, argv
[3 + i
], outVec
[i
]) != JIM_OK
) {
13904 Jim_FreeNewObj(interp
, listPtr
);
13909 if (rc
== JIM_OK
) {
13910 Jim_SetResultInt(interp
, count
);
13915 if (listPtr
== (Jim_Obj
*)EOF
) {
13916 Jim_SetResult(interp
, Jim_NewListObj(interp
, 0, 0));
13919 Jim_SetResult(interp
, listPtr
);
13925 static int Jim_ErrorCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13927 if (argc
!= 2 && argc
!= 3) {
13928 Jim_WrongNumArgs(interp
, 1, argv
, "message ?stacktrace?");
13931 Jim_SetResult(interp
, argv
[1]);
13933 JimSetStackTrace(interp
, argv
[2]);
13936 interp
->addStackTrace
++;
13941 static int Jim_LrangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13946 Jim_WrongNumArgs(interp
, 1, argv
, "list first last");
13949 if ((objPtr
= Jim_ListRange(interp
, argv
[1], argv
[2], argv
[3])) == NULL
)
13951 Jim_SetResult(interp
, objPtr
);
13956 static int Jim_LrepeatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13961 if (argc
< 2 || Jim_GetLong(interp
, argv
[1], &count
) != JIM_OK
|| count
< 0) {
13962 Jim_WrongNumArgs(interp
, 1, argv
, "count ?value ...?");
13966 if (count
== 0 || argc
== 2) {
13973 objPtr
= Jim_NewListObj(interp
, argv
, argc
);
13977 for (i
= 0; i
< argc
; i
++) {
13978 ListAppendElement(objPtr
, argv
[i
]);
13982 Jim_SetResult(interp
, objPtr
);
13986 char **Jim_GetEnviron(void)
13988 #if defined(HAVE__NSGETENVIRON)
13989 return *_NSGetEnviron();
13991 #if !defined(NO_ENVIRON_EXTERN)
13992 extern char **environ
;
13999 void Jim_SetEnviron(char **env
)
14001 #if defined(HAVE__NSGETENVIRON)
14002 *_NSGetEnviron() = env
;
14004 #if !defined(NO_ENVIRON_EXTERN)
14005 extern char **environ
;
14013 static int Jim_EnvCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14019 char **e
= Jim_GetEnviron();
14022 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14024 for (i
= 0; e
[i
]; i
++) {
14025 const char *equals
= strchr(e
[i
], '=');
14028 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, e
[i
],
14030 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, equals
+ 1, -1));
14034 Jim_SetResult(interp
, listObjPtr
);
14039 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?default?");
14042 key
= Jim_String(argv
[1]);
14046 Jim_SetResultFormatted(interp
, "environment variable \"%#s\" does not exist", argv
[1]);
14049 val
= Jim_String(argv
[2]);
14051 Jim_SetResult(interp
, Jim_NewStringObj(interp
, val
, -1));
14056 static int Jim_SourceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14061 Jim_WrongNumArgs(interp
, 1, argv
, "fileName");
14064 retval
= Jim_EvalFile(interp
, Jim_String(argv
[1]));
14065 if (retval
== JIM_RETURN
)
14071 static int Jim_LreverseCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14073 Jim_Obj
*revObjPtr
, **ele
;
14077 Jim_WrongNumArgs(interp
, 1, argv
, "list");
14080 JimListGetElements(interp
, argv
[1], &len
, &ele
);
14082 revObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14084 ListAppendElement(revObjPtr
, ele
[len
--]);
14085 Jim_SetResult(interp
, revObjPtr
);
14089 static int JimRangeLen(jim_wide start
, jim_wide end
, jim_wide step
)
14097 else if (step
> 0 && start
> end
)
14099 else if (step
< 0 && end
> start
)
14103 len
= -len
; /* abs(len) */
14105 step
= -step
; /* abs(step) */
14106 len
= 1 + ((len
- 1) / step
);
14107 /* We can truncate safely to INT_MAX, the range command
14108 * will always return an error for a such long range
14109 * because Tcl lists can't be so long. */
14112 return (int)((len
< 0) ? -1 : len
);
14116 static int Jim_RangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14118 jim_wide start
= 0, end
, step
= 1;
14122 if (argc
< 2 || argc
> 4) {
14123 Jim_WrongNumArgs(interp
, 1, argv
, "?start? end ?step?");
14127 if (Jim_GetWide(interp
, argv
[1], &end
) != JIM_OK
)
14131 if (Jim_GetWide(interp
, argv
[1], &start
) != JIM_OK
||
14132 Jim_GetWide(interp
, argv
[2], &end
) != JIM_OK
)
14134 if (argc
== 4 && Jim_GetWide(interp
, argv
[3], &step
) != JIM_OK
)
14137 if ((len
= JimRangeLen(start
, end
, step
)) == -1) {
14138 Jim_SetResultString(interp
, "Invalid (infinite?) range specified", -1);
14141 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
14142 for (i
= 0; i
< len
; i
++)
14143 ListAppendElement(objPtr
, Jim_NewIntObj(interp
, start
+ i
* step
));
14144 Jim_SetResult(interp
, objPtr
);
14149 static int Jim_RandCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14151 jim_wide min
= 0, max
= 0, len
, maxMul
;
14153 if (argc
< 1 || argc
> 3) {
14154 Jim_WrongNumArgs(interp
, 1, argv
, "?min? max");
14158 max
= JIM_WIDE_MAX
;
14159 } else if (argc
== 2) {
14160 if (Jim_GetWide(interp
, argv
[1], &max
) != JIM_OK
)
14162 } else if (argc
== 3) {
14163 if (Jim_GetWide(interp
, argv
[1], &min
) != JIM_OK
||
14164 Jim_GetWide(interp
, argv
[2], &max
) != JIM_OK
)
14169 Jim_SetResultString(interp
, "Invalid arguments (max < min)", -1);
14172 maxMul
= JIM_WIDE_MAX
- (len
? (JIM_WIDE_MAX
%len
) : 0);
14176 JimRandomBytes(interp
, &r
, sizeof(jim_wide
));
14177 if (r
< 0 || r
>= maxMul
) continue;
14178 r
= (len
== 0) ? 0 : r
%len
;
14179 Jim_SetResultInt(interp
, min
+r
);
14184 static const struct {
14186 Jim_CmdProc cmdProc
;
14187 } Jim_CoreCommandsTable
[] = {
14188 {"set", Jim_SetCoreCommand
},
14189 {"unset", Jim_UnsetCoreCommand
},
14190 {"puts", Jim_PutsCoreCommand
},
14191 {"+", Jim_AddCoreCommand
},
14192 {"*", Jim_MulCoreCommand
},
14193 {"-", Jim_SubCoreCommand
},
14194 {"/", Jim_DivCoreCommand
},
14195 {"incr", Jim_IncrCoreCommand
},
14196 {"while", Jim_WhileCoreCommand
},
14197 {"loop", Jim_LoopCoreCommand
},
14198 {"for", Jim_ForCoreCommand
},
14199 {"foreach", Jim_ForeachCoreCommand
},
14200 {"lmap", Jim_LmapCoreCommand
},
14201 {"if", Jim_IfCoreCommand
},
14202 {"switch", Jim_SwitchCoreCommand
},
14203 {"list", Jim_ListCoreCommand
},
14204 {"lindex", Jim_LindexCoreCommand
},
14205 {"lset", Jim_LsetCoreCommand
},
14206 {"lsearch", Jim_LsearchCoreCommand
},
14207 {"llength", Jim_LlengthCoreCommand
},
14208 {"lappend", Jim_LappendCoreCommand
},
14209 {"linsert", Jim_LinsertCoreCommand
},
14210 {"lreplace", Jim_LreplaceCoreCommand
},
14211 {"lsort", Jim_LsortCoreCommand
},
14212 {"append", Jim_AppendCoreCommand
},
14213 {"debug", Jim_DebugCoreCommand
},
14214 {"eval", Jim_EvalCoreCommand
},
14215 {"uplevel", Jim_UplevelCoreCommand
},
14216 {"expr", Jim_ExprCoreCommand
},
14217 {"break", Jim_BreakCoreCommand
},
14218 {"continue", Jim_ContinueCoreCommand
},
14219 {"proc", Jim_ProcCoreCommand
},
14220 {"concat", Jim_ConcatCoreCommand
},
14221 {"return", Jim_ReturnCoreCommand
},
14222 {"upvar", Jim_UpvarCoreCommand
},
14223 {"global", Jim_GlobalCoreCommand
},
14224 {"string", Jim_StringCoreCommand
},
14225 {"time", Jim_TimeCoreCommand
},
14226 {"exit", Jim_ExitCoreCommand
},
14227 {"catch", Jim_CatchCoreCommand
},
14228 #ifdef JIM_REFERENCES
14229 {"ref", Jim_RefCoreCommand
},
14230 {"getref", Jim_GetrefCoreCommand
},
14231 {"setref", Jim_SetrefCoreCommand
},
14232 {"finalize", Jim_FinalizeCoreCommand
},
14233 {"collect", Jim_CollectCoreCommand
},
14235 {"rename", Jim_RenameCoreCommand
},
14236 {"dict", Jim_DictCoreCommand
},
14237 {"subst", Jim_SubstCoreCommand
},
14238 {"info", Jim_InfoCoreCommand
},
14239 {"exists", Jim_ExistsCoreCommand
},
14240 {"split", Jim_SplitCoreCommand
},
14241 {"join", Jim_JoinCoreCommand
},
14242 {"format", Jim_FormatCoreCommand
},
14243 {"scan", Jim_ScanCoreCommand
},
14244 {"error", Jim_ErrorCoreCommand
},
14245 {"lrange", Jim_LrangeCoreCommand
},
14246 {"lrepeat", Jim_LrepeatCoreCommand
},
14247 {"env", Jim_EnvCoreCommand
},
14248 {"source", Jim_SourceCoreCommand
},
14249 {"lreverse", Jim_LreverseCoreCommand
},
14250 {"range", Jim_RangeCoreCommand
},
14251 {"rand", Jim_RandCoreCommand
},
14252 {"tailcall", Jim_TailcallCoreCommand
},
14253 {"local", Jim_LocalCoreCommand
},
14254 {"upcall", Jim_UpcallCoreCommand
},
14258 void Jim_RegisterCoreCommands(Jim_Interp
*interp
)
14262 while (Jim_CoreCommandsTable
[i
].name
!= NULL
) {
14263 Jim_CreateCommand(interp
,
14264 Jim_CoreCommandsTable
[i
].name
, Jim_CoreCommandsTable
[i
].cmdProc
, NULL
, NULL
);
14269 /* -----------------------------------------------------------------------------
14270 * Interactive prompt
14271 * ---------------------------------------------------------------------------*/
14272 void Jim_MakeErrorMessage(Jim_Interp
*interp
)
14276 argv
[0] = Jim_NewStringObj(interp
, "errorInfo", -1);
14277 argv
[1] = interp
->result
;
14279 Jim_EvalObjVector(interp
, 2, argv
);
14282 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
14283 const char *prefix
, const char *const *tablePtr
, const char *name
)
14286 char **tablePtrSorted
;
14289 for (count
= 0; tablePtr
[count
]; count
++) {
14292 if (name
== NULL
) {
14296 Jim_SetResultFormatted(interp
, "%s%s \"%s\": must be ", badtype
, name
, arg
);
14297 tablePtrSorted
= Jim_Alloc(sizeof(char *) * count
);
14298 memcpy(tablePtrSorted
, tablePtr
, sizeof(char *) * count
);
14299 qsort(tablePtrSorted
, count
, sizeof(char *), qsortCompareStringPointers
);
14300 for (i
= 0; i
< count
; i
++) {
14301 if (i
+ 1 == count
&& count
> 1) {
14302 Jim_AppendString(interp
, Jim_GetResult(interp
), "or ", -1);
14304 Jim_AppendStrings(interp
, Jim_GetResult(interp
), prefix
, tablePtrSorted
[i
], NULL
);
14305 if (i
+ 1 != count
) {
14306 Jim_AppendString(interp
, Jim_GetResult(interp
), ", ", -1);
14309 Jim_Free(tablePtrSorted
);
14312 int Jim_GetEnum(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
14313 const char *const *tablePtr
, int *indexPtr
, const char *name
, int flags
)
14315 const char *bad
= "bad ";
14316 const char *const *entryPtr
= NULL
;
14320 const char *arg
= Jim_GetString(objPtr
, &arglen
);
14324 for (entryPtr
= tablePtr
, i
= 0; *entryPtr
!= NULL
; entryPtr
++, i
++) {
14325 if (Jim_CompareStringImmediate(interp
, objPtr
, *entryPtr
)) {
14326 /* Found an exact match */
14330 if (flags
& JIM_ENUM_ABBREV
) {
14331 /* Accept an unambiguous abbreviation.
14332 * Note that '-' doesnt' consitute a valid abbreviation
14334 if (strncmp(arg
, *entryPtr
, arglen
) == 0) {
14335 if (*arg
== '-' && arglen
== 1) {
14339 bad
= "ambiguous ";
14347 /* If we had an unambiguous partial match */
14354 if (flags
& JIM_ERRMSG
) {
14355 JimSetFailedEnumResult(interp
, arg
, bad
, "", tablePtr
, name
);
14360 int Jim_FindByName(const char *name
, const char * const array
[], size_t len
)
14364 for (i
= 0; i
< (int)len
; i
++) {
14365 if (array
[i
] && strcmp(array
[i
], name
) == 0) {
14372 int Jim_IsDict(Jim_Obj
*objPtr
)
14374 return objPtr
->typePtr
== &dictObjType
;
14377 int Jim_IsList(Jim_Obj
*objPtr
)
14379 return objPtr
->typePtr
== &listObjType
;
14383 * Very simple printf-like formatting, designed for error messages.
14385 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14386 * The resulting string is created and set as the result.
14388 * Each '%s' should correspond to a regular string parameter.
14389 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14390 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14392 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14394 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14396 void Jim_SetResultFormatted(Jim_Interp
*interp
, const char *format
, ...)
14398 /* Initial space needed */
14399 int len
= strlen(format
);
14402 const char *params
[5];
14407 va_start(args
, format
);
14409 for (i
= 0; i
< len
&& n
< 5; i
++) {
14412 if (strncmp(format
+ i
, "%s", 2) == 0) {
14413 params
[n
] = va_arg(args
, char *);
14415 l
= strlen(params
[n
]);
14417 else if (strncmp(format
+ i
, "%#s", 3) == 0) {
14418 Jim_Obj
*objPtr
= va_arg(args
, Jim_Obj
*);
14420 params
[n
] = Jim_GetString(objPtr
, &l
);
14423 if (format
[i
] == '%') {
14433 buf
= Jim_Alloc(len
+ 1);
14434 len
= snprintf(buf
, len
+ 1, format
, params
[0], params
[1], params
[2], params
[3], params
[4]);
14436 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
14440 #ifndef jim_ext_package
14441 int Jim_PackageProvide(Jim_Interp
*interp
, const char *name
, const char *ver
, int flags
)
14446 #ifndef jim_ext_aio
14447 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*fhObj
)
14449 Jim_SetResultString(interp
, "aio not enabled", -1);
14456 * Local Variables: ***
14457 * c-basic-offset: 4 ***