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 /* For the no-autoconf case */
77 #define TCL_LIBRARY "."
79 #ifndef TCL_PLATFORM_OS
80 #define TCL_PLATFORM_OS "unknown"
82 #ifndef TCL_PLATFORM_PLATFORM
83 #define TCL_PLATFORM_PLATFORM "unknown"
86 /*#define DEBUG_SHOW_SCRIPT*/
87 /*#define DEBUG_SHOW_SCRIPT_TOKENS*/
88 /*#define DEBUG_SHOW_SUBST*/
89 /*#define DEBUG_SHOW_EXPR*/
90 /*#define DEBUG_SHOW_EXPR_TOKENS*/
91 /*#define JIM_DEBUG_GC*/
93 #define JIM_DEBUG_COMMAND
94 #define JIM_DEBUG_PANIC
97 const char *jim_tt_name(int type
);
99 #ifdef JIM_DEBUG_PANIC
100 static void JimPanicDump(int panic_condition
, Jim_Interp
*interp
, const char *fmt
, ...);
101 #define JimPanic(X) JimPanicDump X
106 /* -----------------------------------------------------------------------------
108 * ---------------------------------------------------------------------------*/
110 /* A shared empty string for the objects string representation.
111 * Jim_InvalidateStringRep knows about it and doesn't try to free it. */
112 static char JimEmptyStringRep
[] = "";
114 /* -----------------------------------------------------------------------------
115 * Required prototypes of not exported functions
116 * ---------------------------------------------------------------------------*/
117 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
);
118 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
);
119 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int listindex
, Jim_Obj
*newObjPtr
,
121 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
122 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
123 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
124 const char *prefix
, const char *const *tablePtr
, const char *name
);
125 static void JimDeleteLocalProcs(Jim_Interp
*interp
);
126 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, const char *filename
, int linenr
,
127 int argc
, Jim_Obj
*const *argv
);
128 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
129 const char *filename
, int linenr
);
130 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
);
131 static int JimSign(jim_wide w
);
132 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
);
134 static const Jim_HashTableType JimVariablesHashTableType
;
136 /* Fast access to the int (wide) value of an object which is known to be of int type */
137 #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
139 #define JimObjTypeName(O) (objPtr->typePtr ? objPtr->typePtr->name : "none")
141 static int utf8_tounicode_case(const char *s
, int *uc
, int upper
)
143 int l
= utf8_tounicode(s
, uc
);
145 *uc
= utf8_upper(*uc
);
150 /* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
151 #define JIM_CHARSET_SCAN 2
152 #define JIM_CHARSET_GLOB 0
155 * pattern points to a string like "[^a-z\ub5]"
157 * The pattern may contain trailing chars, which are ignored.
159 * The pattern is matched against unicode char 'c'.
161 * If (flags & JIM_NOCASE), case is ignored when matching.
162 * If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
163 * of the charset, per scan, rather than glob/string match.
165 * If the unicode char 'c' matches that set, returns a pointer to the ']' character,
166 * or the null character if the ']' is missing.
168 * Returns NULL on no match.
170 static const char *JimCharsetMatch(const char *pattern
, int c
, int flags
)
177 if (flags
& JIM_NOCASE
) {
182 if (flags
& JIM_CHARSET_SCAN
) {
183 if (*pattern
== '^') {
188 /* Special case. If the first char is ']', it is part of the set */
189 if (*pattern
== ']') {
194 while (*pattern
&& *pattern
!= ']') {
196 if (pattern
[0] == '\\') {
198 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
201 /* Is this a range? a-z */
205 pattern
+= utf8_tounicode_case(pattern
, &start
, nocase
);
206 if (pattern
[0] == '-' && pattern
[1]) {
208 pattern
+= utf8_tounicode(pattern
, &pchar
);
209 pattern
+= utf8_tounicode_case(pattern
, &end
, nocase
);
211 /* Handle reversed range too */
212 if ((c
>= start
&& c
<= end
) || (c
>= end
&& c
<= start
)) {
228 return match
? pattern
: NULL
;
231 /* Glob-style pattern matching. */
233 /* Note: string *must* be valid UTF-8 sequences
234 * slen is a char length, not byte counts.
236 static int GlobMatch(const char *pattern
, const char *string
, int nocase
)
241 switch (pattern
[0]) {
243 while (pattern
[1] == '*') {
248 return 1; /* match */
251 /* Recursive call - Does the remaining pattern match anywhere? */
252 if (GlobMatch(pattern
, string
, nocase
))
253 return 1; /* match */
254 string
+= utf8_tounicode(string
, &c
);
256 return 0; /* no match */
259 string
+= utf8_tounicode(string
, &c
);
263 string
+= utf8_tounicode(string
, &c
);
264 pattern
= JimCharsetMatch(pattern
+ 1, c
, nocase
? JIM_NOCASE
: 0);
269 /* Ran out of pattern (no ']') */
280 string
+= utf8_tounicode_case(string
, &c
, nocase
);
281 utf8_tounicode_case(pattern
, &pchar
, nocase
);
287 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
289 while (*pattern
== '*') {
295 if (!*pattern
&& !*string
) {
301 static int JimStringMatch(Jim_Interp
*interp
, Jim_Obj
*patternObj
, const char *string
, int nocase
)
303 return GlobMatch(Jim_String(patternObj
), string
, nocase
);
307 * string comparison works on binary data.
309 * Note that the lengths are byte lengths, not char lengths.
311 static int JimStringCompare(const char *s1
, int l1
, const char *s2
, int l2
)
314 return memcmp(s1
, s2
, l1
) <= 0 ? -1 : 1;
317 return memcmp(s1
, s2
, l2
) >= 0 ? 1 : -1;
320 return JimSign(memcmp(s1
, s2
, l1
));
327 * If maxchars is -1, compares to end of string.
328 * Otherwise compares at most 'maxchars' characters.
330 static int JimStringCompareNoCase(const char *s1
, const char *s2
, int maxchars
)
332 while (*s1
&& *s2
&& maxchars
) {
334 s1
+= utf8_tounicode_case(s1
, &c1
, 1);
335 s2
+= utf8_tounicode_case(s2
, &c2
, 1);
337 return JimSign(c1
- c2
);
344 /* One string or both terminated */
354 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
355 * The index of the first occurrence of s1 in s2 is returned.
356 * If s1 is not found inside s2, -1 is returned. */
357 static int JimStringFirst(const char *s1
, int l1
, const char *s2
, int l2
, int idx
)
362 if (!l1
|| !l2
|| l1
> l2
) {
367 s2
+= utf8_index(s2
, idx
);
369 l1bytelen
= utf8_index(s1
, l1
);
371 for (i
= idx
; i
<= l2
- l1
; i
++) {
373 if (memcmp(s2
, s1
, l1bytelen
) == 0) {
376 s2
+= utf8_tounicode(s2
, &c
);
382 * Note: Lengths and return value are in bytes, not chars.
384 static int JimStringLast(const char *s1
, int l1
, const char *s2
, int l2
)
388 if (!l1
|| !l2
|| l1
> l2
)
391 /* Now search for the needle */
392 for (p
= s2
+ l2
- 1; p
!= s2
- 1; p
--) {
393 if (*p
== *s1
&& memcmp(s1
, p
, l1
) == 0) {
402 * Note: Lengths and return value are in chars.
404 static int JimStringLastUtf8(const char *s1
, int l1
, const char *s2
, int l2
)
406 int n
= JimStringLast(s1
, utf8_index(s1
, l1
), s2
, utf8_index(s2
, l2
));
408 n
= utf8_strlen(s2
, n
);
414 int Jim_WideToString(char *buf
, jim_wide wideValue
)
416 const char *fmt
= "%" JIM_WIDE_MODIFIER
;
418 return sprintf(buf
, fmt
, wideValue
);
422 * After an strtol()/strtod()-like conversion,
423 * check whether something was converted and that
424 * the only thing left is white space.
426 * Returns JIM_OK or JIM_ERR.
428 static int JimCheckConversion(const char *str
, const char *endptr
)
430 if (str
[0] == '\0' || str
== endptr
) {
434 if (endptr
[0] != '\0') {
436 if (!isspace(UCHAR(*endptr
))) {
445 int Jim_StringToWide(const char *str
, jim_wide
* widePtr
, int base
)
449 *widePtr
= strtoull(str
, &endptr
, base
);
451 return JimCheckConversion(str
, endptr
);
454 int Jim_DoubleToString(char *buf
, double doubleValue
)
459 len
= sprintf(buf
, "%.12g", doubleValue
);
461 /* Add a final ".0" if it's a number. But not
464 if (*buf
== '.' || isalpha(UCHAR(*buf
))) {
465 /* inf -> Inf, nan -> Nan */
466 if (*buf
== 'i' || *buf
== 'n') {
467 *buf
= toupper(UCHAR(*buf
));
470 /* Infinity -> Inf */
472 len
= buf
- buf0
+ 3;
486 int Jim_StringToDouble(const char *str
, double *doublePtr
)
490 /* Callers can check for underflow via ERANGE */
493 *doublePtr
= strtod(str
, &endptr
);
495 return JimCheckConversion(str
, endptr
);
498 static jim_wide
JimPowWide(jim_wide b
, jim_wide e
)
502 if ((b
== 0 && e
!= 0) || (e
< 0))
504 for (i
= 0; i
< e
; i
++) {
510 /* -----------------------------------------------------------------------------
512 * ---------------------------------------------------------------------------*/
513 #ifdef JIM_DEBUG_PANIC
514 /* Note that 'interp' may be NULL if not available in the
515 * context of the panic. It's only useful to get the error
516 * file descriptor, it will default to stderr otherwise. */
517 void JimPanicDump(int condition
, Jim_Interp
*interp
, const char *fmt
, ...)
527 * Send it here first.. Assuming STDIO still works
529 fprintf(stderr
, JIM_NL
"JIM INTERPRETER PANIC: ");
530 vfprintf(stderr
, fmt
, ap
);
531 fprintf(stderr
, JIM_NL JIM_NL
);
534 #ifdef HAVE_BACKTRACE
540 size
= backtrace(array
, 40);
541 strings
= backtrace_symbols(array
, size
);
542 for (i
= 0; i
< size
; i
++)
543 fprintf(stderr
, "[backtrace] %s" JIM_NL
, strings
[i
]);
544 fprintf(stderr
, "[backtrace] Include the above lines and the output" JIM_NL
);
545 fprintf(stderr
, "[backtrace] of 'nm <executable>' in the bug report." JIM_NL
);
553 /* -----------------------------------------------------------------------------
555 * ---------------------------------------------------------------------------*/
557 void *Jim_Alloc(int size
)
562 void Jim_Free(void *ptr
)
567 void *Jim_Realloc(void *ptr
, int size
)
569 return realloc(ptr
, size
);
572 char *Jim_StrDup(const char *s
)
577 char *Jim_StrDupLen(const char *s
, int l
)
579 char *copy
= Jim_Alloc(l
+ 1);
581 memcpy(copy
, s
, l
+ 1);
582 copy
[l
] = 0; /* Just to be sure, original could be substring */
586 /* -----------------------------------------------------------------------------
587 * Time related functions
588 * ---------------------------------------------------------------------------*/
590 /* Returns microseconds of CPU used since start. */
591 static jim_wide
JimClock(void)
595 gettimeofday(&tv
, NULL
);
596 return (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
;
599 /* -----------------------------------------------------------------------------
601 * ---------------------------------------------------------------------------*/
603 /* -------------------------- private prototypes ---------------------------- */
604 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
);
605 static unsigned int JimHashTableNextPower(unsigned int size
);
606 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
);
608 /* -------------------------- hash functions -------------------------------- */
610 /* Thomas Wang's 32 bit Mix Function */
611 unsigned int Jim_IntHashFunction(unsigned int key
)
622 /* Generic hash function (we are using to multiply by 9 and add the byte
624 unsigned int Jim_GenHashFunction(const unsigned char *buf
, int len
)
629 h
+= (h
<< 3) + *buf
++;
633 /* ----------------------------- API implementation ------------------------- */
635 /* reset a hashtable already initialized with ht_init().
636 * NOTE: This function should only called by ht_destroy(). */
637 static void JimResetHashTable(Jim_HashTable
*ht
)
646 /* Initialize the hash table */
647 int Jim_InitHashTable(Jim_HashTable
*ht
, const Jim_HashTableType
*type
, void *privDataPtr
)
649 JimResetHashTable(ht
);
651 ht
->privdata
= privDataPtr
;
655 /* Resize the table to the minimal size that contains all the elements,
656 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
657 int Jim_ResizeHashTable(Jim_HashTable
*ht
)
659 int minimal
= ht
->used
;
661 if (minimal
< JIM_HT_INITIAL_SIZE
)
662 minimal
= JIM_HT_INITIAL_SIZE
;
663 return Jim_ExpandHashTable(ht
, minimal
);
666 /* Expand or create the hashtable */
667 int Jim_ExpandHashTable(Jim_HashTable
*ht
, unsigned int size
)
669 Jim_HashTable n
; /* the new hashtable */
670 unsigned int realsize
= JimHashTableNextPower(size
), i
;
672 /* the size is invalid if it is smaller than the number of
673 * elements already inside the hashtable */
674 if (ht
->used
>= size
)
677 Jim_InitHashTable(&n
, ht
->type
, ht
->privdata
);
679 n
.sizemask
= realsize
- 1;
680 n
.table
= Jim_Alloc(realsize
* sizeof(Jim_HashEntry
*));
682 /* Initialize all the pointers to NULL */
683 memset(n
.table
, 0, realsize
* sizeof(Jim_HashEntry
*));
685 /* Copy all the elements from the old to the new table:
686 * note that if the old hash table is empty ht->size is zero,
687 * so Jim_ExpandHashTable just creates an hash table. */
689 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
690 Jim_HashEntry
*he
, *nextHe
;
692 if (ht
->table
[i
] == NULL
)
695 /* For each hash entry on this slot... */
701 /* Get the new element index */
702 h
= Jim_HashKey(ht
, he
->key
) & n
.sizemask
;
703 he
->next
= n
.table
[h
];
706 /* Pass to the next element */
710 assert(ht
->used
== 0);
713 /* Remap the new hashtable in the old */
718 /* Add an element to the target hash table */
719 int Jim_AddHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
722 Jim_HashEntry
*entry
;
724 /* Get the index of the new element, or -1 if
725 * the element already exists. */
726 if ((idx
= JimInsertHashEntry(ht
, key
)) == -1)
729 /* Allocates the memory and stores key */
730 entry
= Jim_Alloc(sizeof(*entry
));
731 entry
->next
= ht
->table
[idx
];
732 ht
->table
[idx
] = entry
;
734 /* Set the hash entry fields. */
735 Jim_SetHashKey(ht
, entry
, key
);
736 Jim_SetHashVal(ht
, entry
, val
);
741 /* Add an element, discarding the old if the key already exists */
742 int Jim_ReplaceHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
744 Jim_HashEntry
*entry
;
746 /* Try to add the element. If the key
747 * does not exists Jim_AddHashEntry will suceed. */
748 if (Jim_AddHashEntry(ht
, key
, val
) == JIM_OK
)
750 /* It already exists, get the entry */
751 entry
= Jim_FindHashEntry(ht
, key
);
752 /* Free the old value and set the new one */
753 Jim_FreeEntryVal(ht
, entry
);
754 Jim_SetHashVal(ht
, entry
, val
);
758 /* Search and remove an element */
759 int Jim_DeleteHashEntry(Jim_HashTable
*ht
, const void *key
)
762 Jim_HashEntry
*he
, *prevHe
;
766 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
771 if (Jim_CompareHashKeys(ht
, key
, he
->key
)) {
772 /* Unlink the element from the list */
774 prevHe
->next
= he
->next
;
776 ht
->table
[h
] = he
->next
;
777 Jim_FreeEntryKey(ht
, he
);
778 Jim_FreeEntryVal(ht
, he
);
786 return JIM_ERR
; /* not found */
789 /* Destroy an entire hash table */
790 int Jim_FreeHashTable(Jim_HashTable
*ht
)
794 /* Free all the elements */
795 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
796 Jim_HashEntry
*he
, *nextHe
;
798 if ((he
= ht
->table
[i
]) == NULL
)
802 Jim_FreeEntryKey(ht
, he
);
803 Jim_FreeEntryVal(ht
, he
);
809 /* Free the table and the allocated cache structure */
811 /* Re-initialize the table */
812 JimResetHashTable(ht
);
813 return JIM_OK
; /* never fails */
816 Jim_HashEntry
*Jim_FindHashEntry(Jim_HashTable
*ht
, const void *key
)
823 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
826 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
833 Jim_HashTableIterator
*Jim_GetHashTableIterator(Jim_HashTable
*ht
)
835 Jim_HashTableIterator
*iter
= Jim_Alloc(sizeof(*iter
));
840 iter
->nextEntry
= NULL
;
844 Jim_HashEntry
*Jim_NextHashEntry(Jim_HashTableIterator
*iter
)
847 if (iter
->entry
== NULL
) {
849 if (iter
->index
>= (signed)iter
->ht
->size
)
851 iter
->entry
= iter
->ht
->table
[iter
->index
];
854 iter
->entry
= iter
->nextEntry
;
857 /* We need to save the 'next' here, the iterator user
858 * may delete the entry we are returning. */
859 iter
->nextEntry
= iter
->entry
->next
;
866 /* ------------------------- private functions ------------------------------ */
868 /* Expand the hash table if needed */
869 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
)
871 /* If the hash table is empty expand it to the intial size,
872 * if the table is "full" dobule its size. */
874 return Jim_ExpandHashTable(ht
, JIM_HT_INITIAL_SIZE
);
875 if (ht
->size
== ht
->used
)
876 return Jim_ExpandHashTable(ht
, ht
->size
* 2);
880 /* Our hash table capability is a power of two */
881 static unsigned int JimHashTableNextPower(unsigned int size
)
883 unsigned int i
= JIM_HT_INITIAL_SIZE
;
885 if (size
>= 2147483648U)
894 /* Returns the index of a free slot that can be populated with
895 * an hash entry for the given 'key'.
896 * If the key already exists, -1 is returned. */
897 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
)
902 /* Expand the hashtable if needed */
903 if (JimExpandHashTableIfNeeded(ht
) == JIM_ERR
)
905 /* Compute the key hash value */
906 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
907 /* Search if this slot does not already contain the given key */
910 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
917 /* ----------------------- StringCopy Hash Table Type ------------------------*/
919 static unsigned int JimStringCopyHTHashFunction(const void *key
)
921 return Jim_GenHashFunction(key
, strlen(key
));
924 static const void *JimStringCopyHTKeyDup(void *privdata
, const void *key
)
926 int len
= strlen(key
);
927 char *copy
= Jim_Alloc(len
+ 1);
929 JIM_NOTUSED(privdata
);
931 memcpy(copy
, key
, len
);
936 static void *JimStringKeyValCopyHTValDup(void *privdata
, const void *val
)
938 int len
= strlen(val
);
939 char *copy
= Jim_Alloc(len
+ 1);
941 JIM_NOTUSED(privdata
);
943 memcpy(copy
, val
, len
);
948 static int JimStringCopyHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
950 JIM_NOTUSED(privdata
);
952 return strcmp(key1
, key2
) == 0;
955 static void JimStringCopyHTKeyDestructor(void *privdata
, const void *key
)
957 JIM_NOTUSED(privdata
);
959 Jim_Free((void *)key
); /* ATTENTION: const cast */
962 static void JimStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
964 JIM_NOTUSED(privdata
);
966 Jim_Free((void *)val
); /* ATTENTION: const cast */
970 static Jim_HashTableType JimStringCopyHashTableType
= {
971 JimStringCopyHTHashFunction
, /* hash function */
972 JimStringCopyHTKeyDup
, /* key dup */
974 JimStringCopyHTKeyCompare
, /* key compare */
975 JimStringCopyHTKeyDestructor
, /* key destructor */
976 NULL
/* val destructor */
980 /* This is like StringCopy but does not auto-duplicate the key.
981 * It's used for intepreter's shared strings. */
982 static const Jim_HashTableType JimSharedStringsHashTableType
= {
983 JimStringCopyHTHashFunction
, /* hash function */
986 JimStringCopyHTKeyCompare
, /* key compare */
987 JimStringCopyHTKeyDestructor
, /* key destructor */
988 NULL
/* val destructor */
991 /* This is like StringCopy but also automatically handle dynamic
992 * allocated C strings as values. */
993 static const Jim_HashTableType JimStringKeyValCopyHashTableType
= {
994 JimStringCopyHTHashFunction
, /* hash function */
995 JimStringCopyHTKeyDup
, /* key dup */
996 JimStringKeyValCopyHTValDup
, /* val dup */
997 JimStringCopyHTKeyCompare
, /* key compare */
998 JimStringCopyHTKeyDestructor
, /* key destructor */
999 JimStringKeyValCopyHTValDestructor
, /* val destructor */
1002 typedef struct AssocDataValue
1004 Jim_InterpDeleteProc
*delProc
;
1008 static void JimAssocDataHashTableValueDestructor(void *privdata
, void *data
)
1010 AssocDataValue
*assocPtr
= (AssocDataValue
*) data
;
1012 if (assocPtr
->delProc
!= NULL
)
1013 assocPtr
->delProc((Jim_Interp
*)privdata
, assocPtr
->data
);
1017 static const Jim_HashTableType JimAssocDataHashTableType
= {
1018 JimStringCopyHTHashFunction
, /* hash function */
1019 JimStringCopyHTKeyDup
, /* key dup */
1021 JimStringCopyHTKeyCompare
, /* key compare */
1022 JimStringCopyHTKeyDestructor
, /* key destructor */
1023 JimAssocDataHashTableValueDestructor
/* val destructor */
1026 /* -----------------------------------------------------------------------------
1027 * Stack - This is a simple generic stack implementation. It is used for
1028 * example in the 'expr' expression compiler.
1029 * ---------------------------------------------------------------------------*/
1030 void Jim_InitStack(Jim_Stack
*stack
)
1034 stack
->vector
= NULL
;
1037 void Jim_FreeStack(Jim_Stack
*stack
)
1039 Jim_Free(stack
->vector
);
1042 int Jim_StackLen(Jim_Stack
*stack
)
1047 void Jim_StackPush(Jim_Stack
*stack
, void *element
)
1049 int neededLen
= stack
->len
+ 1;
1051 if (neededLen
> stack
->maxlen
) {
1052 stack
->maxlen
= neededLen
< 20 ? 20 : neededLen
* 2;
1053 stack
->vector
= Jim_Realloc(stack
->vector
, sizeof(void *) * stack
->maxlen
);
1055 stack
->vector
[stack
->len
] = element
;
1059 void *Jim_StackPop(Jim_Stack
*stack
)
1061 if (stack
->len
== 0)
1064 return stack
->vector
[stack
->len
];
1067 void *Jim_StackPeek(Jim_Stack
*stack
)
1069 if (stack
->len
== 0)
1071 return stack
->vector
[stack
->len
- 1];
1074 void Jim_FreeStackElements(Jim_Stack
*stack
, void (*freeFunc
) (void *ptr
))
1078 for (i
= 0; i
< stack
->len
; i
++)
1079 freeFunc(stack
->vector
[i
]);
1082 /* -----------------------------------------------------------------------------
1084 * ---------------------------------------------------------------------------*/
1087 #define JIM_TT_NONE 0 /* No token returned */
1088 #define JIM_TT_STR 1 /* simple string */
1089 #define JIM_TT_ESC 2 /* string that needs escape chars conversion */
1090 #define JIM_TT_VAR 3 /* var substitution */
1091 #define JIM_TT_DICTSUGAR 4 /* Syntax sugar for [dict get], $foo(bar) */
1092 #define JIM_TT_CMD 5 /* command substitution */
1093 /* Note: Keep these three together for TOKEN_IS_SEP() */
1094 #define JIM_TT_SEP 6 /* word separator. arg is # of tokens. -ve if {*} */
1095 #define JIM_TT_EOL 7 /* line separator */
1096 #define JIM_TT_EOF 8 /* end of script */
1098 #define JIM_TT_LINE 9 /* special 'start-of-line' token. arg is # of arguments to the command. -ve if {*} */
1099 #define JIM_TT_WORD 10 /* special 'start-of-word' token. arg is # of tokens to combine. -ve if {*} */
1101 /* Additional token types needed for expressions */
1102 #define JIM_TT_SUBEXPR_START 11
1103 #define JIM_TT_SUBEXPR_END 12
1104 #define JIM_TT_EXPR_INT 13
1105 #define JIM_TT_EXPR_DOUBLE 14
1107 #define JIM_TT_EXPRSUGAR 15 /* $(expression) */
1109 /* Operator token types start here */
1110 #define JIM_TT_EXPR_OP 20
1112 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1115 #define JIM_PS_DEF 0 /* Default state */
1116 #define JIM_PS_QUOTE 1 /* Inside "" */
1117 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1119 /* Parser context structure. The same context is used both to parse
1120 * Tcl scripts and lists. */
1123 const char *prg
; /* Program text */
1124 const char *p
; /* Pointer to the point of the program we are parsing */
1125 int len
; /* Left length of 'prg' */
1126 int linenr
; /* Current line number */
1128 const char *tend
; /* Returned token is at tstart-tend in 'prg'. */
1129 int tline
; /* Line number of the returned token */
1130 int tt
; /* Token type */
1131 int eof
; /* Non zero if EOF condition is true. */
1132 int state
; /* Parser state */
1133 int comment
; /* Non zero if the next chars may be a comment. */
1134 char missing
; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1137 static int JimParseScript(struct JimParserCtx
*pc
);
1138 static int JimParseSep(struct JimParserCtx
*pc
);
1139 static int JimParseEol(struct JimParserCtx
*pc
);
1140 static int JimParseCmd(struct JimParserCtx
*pc
);
1141 static int JimParseQuote(struct JimParserCtx
*pc
);
1142 static int JimParseVar(struct JimParserCtx
*pc
);
1143 static int JimParseBrace(struct JimParserCtx
*pc
);
1144 static int JimParseStr(struct JimParserCtx
*pc
);
1145 static int JimParseComment(struct JimParserCtx
*pc
);
1146 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1147 static int JimParseSubQuote(struct JimParserCtx
*pc
);
1148 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1149 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
);
1151 /* Initialize a parser context.
1152 * 'prg' is a pointer to the program text, linenr is the line
1153 * number of the first line contained in the program. */
1154 static void JimParserInit(struct JimParserCtx
*pc
, const char *prg
, int len
, int linenr
)
1162 pc
->tt
= JIM_TT_NONE
;
1164 pc
->state
= JIM_PS_DEF
;
1165 pc
->linenr
= linenr
;
1170 static int JimParseScript(struct JimParserCtx
*pc
)
1172 while (1) { /* the while is used to reiterate with continue if needed */
1175 pc
->tend
= pc
->p
- 1;
1176 pc
->tline
= pc
->linenr
;
1177 pc
->tt
= JIM_TT_EOL
;
1183 if (*(pc
->p
+ 1) == '\n' && pc
->state
== JIM_PS_DEF
) {
1184 return JimParseSep(pc
);
1188 return JimParseStr(pc
);
1194 if (pc
->state
== JIM_PS_DEF
)
1195 return JimParseSep(pc
);
1198 return JimParseStr(pc
);
1204 if (pc
->state
== JIM_PS_DEF
)
1205 return JimParseEol(pc
);
1207 return JimParseStr(pc
);
1211 return JimParseCmd(pc
);
1215 if (JimParseVar(pc
) == JIM_ERR
) {
1216 pc
->tstart
= pc
->tend
= pc
->p
++;
1218 pc
->tline
= pc
->linenr
;
1219 pc
->tt
= JIM_TT_STR
;
1227 JimParseComment(pc
);
1231 return JimParseStr(pc
);
1235 return JimParseStr(pc
);
1242 static int JimParseSep(struct JimParserCtx
*pc
)
1245 pc
->tline
= pc
->linenr
;
1246 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' ||
1247 (*pc
->p
== '\\' && *(pc
->p
+ 1) == '\n')) {
1248 if (*pc
->p
== '\\') {
1256 pc
->tend
= pc
->p
- 1;
1257 pc
->tt
= JIM_TT_SEP
;
1261 static int JimParseEol(struct JimParserCtx
*pc
)
1264 pc
->tline
= pc
->linenr
;
1265 while (*pc
->p
== ' ' || *pc
->p
== '\n' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== ';') {
1271 pc
->tend
= pc
->p
- 1;
1272 pc
->tt
= JIM_TT_EOL
;
1277 ** Here are the rules for parsing:
1278 ** {braced expression}
1279 ** - Count open and closing braces
1280 ** - Backslash escapes meaning of braces
1282 ** "quoted expression"
1283 ** - First double quote at start of word terminates the expression
1284 ** - Backslash escapes quote and bracket
1285 ** - [commands brackets] are counted/nested
1286 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1288 ** [command expression]
1289 ** - Count open and closing brackets
1290 ** - Backslash escapes quote, bracket and brace
1291 ** - [commands brackets] are counted/nested
1292 ** - "quoted expressions" are parsed according to quoting rules
1293 ** - {braced expressions} are parsed according to brace rules
1295 ** For everything, backslash escapes the next char, newline increments current line
1299 * Parses a braced expression starting at pc->p.
1301 * Positions the parser at the end of the braced expression,
1302 * sets pc->tend and possibly pc->missing.
1304 static void JimParseSubBrace(struct JimParserCtx
*pc
)
1308 /* Skip the brace */
1315 if (*++pc
->p
== '\n') {
1328 pc
->tend
= pc
->p
- 1;
1343 pc
->tend
= pc
->p
- 1;
1347 * Parses a quoted expression starting at pc->p.
1349 * Positions the parser at the end of the quoted expression,
1350 * sets pc->tend and possibly pc->missing.
1352 * Returns the type of the token of the string,
1353 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1356 static int JimParseSubQuote(struct JimParserCtx
*pc
)
1358 int tt
= JIM_TT_STR
;
1360 /* Skip the quote */
1367 if (*++pc
->p
== '\n') {
1376 pc
->tend
= pc
->p
- 1;
1398 pc
->tend
= pc
->p
- 1;
1403 * Parses a [command] expression starting at pc->p.
1405 * Positions the parser at the end of the command expression,
1406 * sets pc->tend and possibly pc->missing.
1408 static void JimParseSubCmd(struct JimParserCtx
*pc
)
1411 int startofword
= 1;
1413 /* Skip the bracket */
1420 if (*++pc
->p
== '\n') {
1433 pc
->tend
= pc
->p
- 1;
1442 JimParseSubQuote(pc
);
1448 JimParseSubBrace(pc
);
1456 startofword
= isspace(UCHAR(*pc
->p
));
1461 pc
->tend
= pc
->p
- 1;
1464 static int JimParseBrace(struct JimParserCtx
*pc
)
1466 pc
->tstart
= pc
->p
+ 1;
1467 pc
->tline
= pc
->linenr
;
1468 pc
->tt
= JIM_TT_STR
;
1469 JimParseSubBrace(pc
);
1473 static int JimParseCmd(struct JimParserCtx
*pc
)
1475 pc
->tstart
= pc
->p
+ 1;
1476 pc
->tline
= pc
->linenr
;
1477 pc
->tt
= JIM_TT_CMD
;
1482 static int JimParseQuote(struct JimParserCtx
*pc
)
1484 pc
->tstart
= pc
->p
+ 1;
1485 pc
->tline
= pc
->linenr
;
1486 pc
->tt
= JimParseSubQuote(pc
);
1490 static int JimParseVar(struct JimParserCtx
*pc
)
1492 int brace
= 0, stop
= 0;
1493 int ttype
= JIM_TT_VAR
;
1495 pc
->tstart
= ++pc
->p
;
1496 pc
->len
--; /* skip the $ */
1497 pc
->tline
= pc
->linenr
;
1498 if (*pc
->p
== '{') {
1499 pc
->tstart
= ++pc
->p
;
1505 if (*pc
->p
== '}' || pc
->len
== 0) {
1506 pc
->tend
= pc
->p
- 1;
1511 else if (*pc
->p
== '\n')
1519 /* Skip double colon, but not single colon! */
1520 if (pc
->p
[0] == ':' && pc
->len
> 1 && pc
->p
[1] == ':') {
1525 if (!((*pc
->p
>= 'a' && *pc
->p
<= 'z') ||
1526 (*pc
->p
>= 'A' && *pc
->p
<= 'Z') ||
1527 (*pc
->p
>= '0' && *pc
->p
<= '9') || *pc
->p
== '_'))
1534 /* Parse [dict get] syntax sugar. */
1535 if (*pc
->p
== '(') {
1537 const char *paren
= NULL
;
1539 while (count
&& pc
->len
) {
1542 if (*pc
->p
== '\\' && pc
->len
>= 1) {
1546 else if (*pc
->p
== '(') {
1549 else if (*pc
->p
== ')') {
1559 /* Did not find a matching paren. Back up */
1561 pc
->len
+= (pc
->p
- paren
);
1564 ttype
= (*pc
->tstart
== '(') ? JIM_TT_EXPRSUGAR
: JIM_TT_DICTSUGAR
;
1566 pc
->tend
= pc
->p
- 1;
1568 /* Check if we parsed just the '$' character.
1569 * That's not a variable so an error is returned
1570 * to tell the state machine to consider this '$' just
1572 if (pc
->tstart
== pc
->p
) {
1581 static int JimParseStr(struct JimParserCtx
*pc
)
1583 int newword
= (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1584 pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_STR
);
1585 if (newword
&& *pc
->p
== '{') {
1586 return JimParseBrace(pc
);
1588 else if (newword
&& *pc
->p
== '"') {
1589 pc
->state
= JIM_PS_QUOTE
;
1594 pc
->tline
= pc
->linenr
;
1597 if (pc
->state
== JIM_PS_QUOTE
) {
1600 pc
->tend
= pc
->p
- 1;
1601 pc
->tt
= JIM_TT_ESC
;
1606 if (pc
->state
== JIM_PS_DEF
&& *(pc
->p
+ 1) == '\n') {
1607 pc
->tend
= pc
->p
- 1;
1608 pc
->tt
= JIM_TT_ESC
;
1612 if (*(pc
->p
+ 1) == '\n') {
1620 /* If the following token is not '$' just keep going */
1621 if (pc
->len
> 1 && pc
->p
[1] != '$') {
1625 /* Only need a separate ')' token if the previous was a var */
1626 if (*pc
->p
== '(' || pc
->tt
== JIM_TT_VAR
) {
1627 if (pc
->p
== pc
->tstart
) {
1628 /* At the start of the token, so just return this char */
1632 pc
->tend
= pc
->p
- 1;
1633 pc
->tt
= JIM_TT_ESC
;
1640 pc
->tend
= pc
->p
- 1;
1641 pc
->tt
= JIM_TT_ESC
;
1648 if (pc
->state
== JIM_PS_DEF
) {
1649 pc
->tend
= pc
->p
- 1;
1650 pc
->tt
= JIM_TT_ESC
;
1653 else if (*pc
->p
== '\n') {
1658 if (pc
->state
== JIM_PS_QUOTE
) {
1659 pc
->tend
= pc
->p
- 1;
1660 pc
->tt
= JIM_TT_ESC
;
1663 pc
->state
= JIM_PS_DEF
;
1671 return JIM_OK
; /* unreached */
1674 static int JimParseComment(struct JimParserCtx
*pc
)
1677 if (*pc
->p
== '\n') {
1679 if (*(pc
->p
- 1) != '\\') {
1691 /* xdigitval and odigitval are helper functions for JimEscape() */
1692 static int xdigitval(int c
)
1694 if (c
>= '0' && c
<= '9')
1696 if (c
>= 'a' && c
<= 'f')
1697 return c
- 'a' + 10;
1698 if (c
>= 'A' && c
<= 'F')
1699 return c
- 'A' + 10;
1703 static int odigitval(int c
)
1705 if (c
>= '0' && c
<= '7')
1710 /* Perform Tcl escape substitution of 's', storing the result
1711 * string into 'dest'. The escaped string is guaranteed to
1712 * be the same length or shorted than the source string.
1713 * Slen is the length of the string at 's', if it's -1 the string
1714 * length will be calculated by the function.
1716 * The function returns the length of the resulting string. */
1717 static int JimEscape(char *dest
, const char *s
, int slen
)
1725 for (i
= 0; i
< slen
; i
++) {
1755 /* A unicode or hex sequence.
1756 * \u Expect 1-4 hex chars and convert to utf-8.
1757 * \x Expect 1-2 hex chars and convert to hex.
1758 * An invalid sequence means simply the escaped char.
1766 for (k
= 0; k
< (s
[i
] == 'u' ? 4 : 2); k
++) {
1767 int c
= xdigitval(s
[i
+ k
+ 1]);
1771 val
= (val
<< 4) | c
;
1774 /* Got a valid sequence, so convert */
1776 p
+= utf8_fromunicode(p
, val
);
1784 /* Not a valid codepoint, just an escaped char */
1797 /* Replace all spaces and tabs after backslash newline with a single space*/
1801 } while (s
[i
+ 1] == ' ' || s
[i
+ 1] == '\t');
1814 int c
= odigitval(s
[i
+ 1]);
1817 c
= odigitval(s
[i
+ 2]);
1823 val
= (val
* 8) + c
;
1824 c
= odigitval(s
[i
+ 3]);
1830 val
= (val
* 8) + c
;
1851 /* Returns a dynamically allocated copy of the current token in the
1852 * parser context. The function performs conversion of escapes if
1853 * the token is of type JIM_TT_ESC.
1855 * Note that after the conversion, tokens that are grouped with
1856 * braces in the source code, are always recognizable from the
1857 * identical string obtained in a different way from the type.
1859 * For example the string:
1863 * will return as first token "*", of type JIM_TT_STR
1869 * will return as first token "*", of type JIM_TT_ESC
1871 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
)
1873 const char *start
, *end
;
1881 token
= Jim_Alloc(1);
1885 len
= (end
- start
) + 1;
1886 token
= Jim_Alloc(len
+ 1);
1887 if (pc
->tt
!= JIM_TT_ESC
) {
1888 /* No escape conversion needed? Just copy it. */
1889 memcpy(token
, start
, len
);
1893 /* Else convert the escape chars. */
1894 len
= JimEscape(token
, start
, len
);
1898 return Jim_NewStringObjNoAlloc(interp
, token
, len
);
1901 /* Parses the given string to determine if it represents a complete script.
1903 * This is useful for interactive shells implementation, for [info complete]
1904 * and is used by source/Jim_EvalFile().
1906 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1907 * '{' on scripts incomplete missing one or more '}' to be balanced.
1908 * '"' on scripts incomplete missing a '"' char.
1910 * If the script is complete, 1 is returned, otherwise 0.
1912 int Jim_ScriptIsComplete(const char *s
, int len
, char *stateCharPtr
)
1914 struct JimParserCtx parser
;
1916 JimParserInit(&parser
, s
, len
, 1);
1917 while (!parser
.eof
) {
1918 JimParseScript(&parser
);
1921 *stateCharPtr
= parser
.missing
;
1923 return parser
.missing
== ' ';
1926 /* -----------------------------------------------------------------------------
1928 * ---------------------------------------------------------------------------*/
1929 static int JimParseListSep(struct JimParserCtx
*pc
);
1930 static int JimParseListStr(struct JimParserCtx
*pc
);
1931 static int JimParseListQuote(struct JimParserCtx
*pc
);
1933 static int JimParseList(struct JimParserCtx
*pc
)
1940 return JimParseListSep(pc
);
1943 return JimParseListQuote(pc
);
1946 return JimParseBrace(pc
);
1950 return JimParseListStr(pc
);
1955 pc
->tstart
= pc
->tend
= pc
->p
;
1956 pc
->tline
= pc
->linenr
;
1957 pc
->tt
= JIM_TT_EOL
;
1962 static int JimParseListSep(struct JimParserCtx
*pc
)
1965 pc
->tline
= pc
->linenr
;
1966 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== '\n') {
1967 if (*pc
->p
== '\n') {
1973 pc
->tend
= pc
->p
- 1;
1974 pc
->tt
= JIM_TT_SEP
;
1978 static int JimParseListQuote(struct JimParserCtx
*pc
)
1984 pc
->tline
= pc
->linenr
;
1985 pc
->tt
= JIM_TT_STR
;
1990 pc
->tt
= JIM_TT_ESC
;
1991 if (--pc
->len
== 0) {
1992 /* Trailing backslash */
2002 pc
->tend
= pc
->p
- 1;
2011 pc
->tend
= pc
->p
- 1;
2015 static int JimParseListStr(struct JimParserCtx
*pc
)
2018 pc
->tline
= pc
->linenr
;
2019 pc
->tt
= JIM_TT_STR
;
2024 if (--pc
->len
== 0) {
2025 /* Trailing backslash */
2029 pc
->tt
= JIM_TT_ESC
;
2036 pc
->tend
= pc
->p
- 1;
2042 pc
->tend
= pc
->p
- 1;
2046 /* -----------------------------------------------------------------------------
2047 * Jim_Obj related functions
2048 * ---------------------------------------------------------------------------*/
2050 /* Return a new initialized object. */
2051 Jim_Obj
*Jim_NewObj(Jim_Interp
*interp
)
2055 /* -- Check if there are objects in the free list -- */
2056 if (interp
->freeList
!= NULL
) {
2057 /* -- Unlink the object from the free list -- */
2058 objPtr
= interp
->freeList
;
2059 interp
->freeList
= objPtr
->nextObjPtr
;
2062 /* -- No ready to use objects: allocate a new one -- */
2063 objPtr
= Jim_Alloc(sizeof(*objPtr
));
2066 /* Object is returned with refCount of 0. Every
2067 * kind of GC implemented should take care to don't try
2068 * to scan objects with refCount == 0. */
2069 objPtr
->refCount
= 0;
2070 /* All the other fields are left not initialized to save time.
2071 * The caller will probably want to set them to the right
2074 /* -- Put the object into the live list -- */
2075 objPtr
->prevObjPtr
= NULL
;
2076 objPtr
->nextObjPtr
= interp
->liveList
;
2077 if (interp
->liveList
)
2078 interp
->liveList
->prevObjPtr
= objPtr
;
2079 interp
->liveList
= objPtr
;
2084 /* Free an object. Actually objects are never freed, but
2085 * just moved to the free objects list, where they will be
2086 * reused by Jim_NewObj(). */
2087 void Jim_FreeObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2089 /* Check if the object was already freed, panic. */
2090 JimPanic((objPtr
->refCount
!= 0, interp
, "!!!Object %p freed with bad refcount %d, type=%s", objPtr
,
2091 objPtr
->refCount
, objPtr
->typePtr
? objPtr
->typePtr
->name
: "<none>"));
2093 /* Free the internal representation */
2094 Jim_FreeIntRep(interp
, objPtr
);
2095 /* Free the string representation */
2096 if (objPtr
->bytes
!= NULL
) {
2097 if (objPtr
->bytes
!= JimEmptyStringRep
)
2098 Jim_Free(objPtr
->bytes
);
2100 /* Unlink the object from the live objects list */
2101 if (objPtr
->prevObjPtr
)
2102 objPtr
->prevObjPtr
->nextObjPtr
= objPtr
->nextObjPtr
;
2103 if (objPtr
->nextObjPtr
)
2104 objPtr
->nextObjPtr
->prevObjPtr
= objPtr
->prevObjPtr
;
2105 if (interp
->liveList
== objPtr
)
2106 interp
->liveList
= objPtr
->nextObjPtr
;
2107 /* Link the object into the free objects list */
2108 objPtr
->prevObjPtr
= NULL
;
2109 objPtr
->nextObjPtr
= interp
->freeList
;
2110 if (interp
->freeList
)
2111 interp
->freeList
->prevObjPtr
= objPtr
;
2112 interp
->freeList
= objPtr
;
2113 objPtr
->refCount
= -1;
2116 /* Invalidate the string representation of an object. */
2117 void Jim_InvalidateStringRep(Jim_Obj
*objPtr
)
2119 if (objPtr
->bytes
!= NULL
) {
2120 if (objPtr
->bytes
!= JimEmptyStringRep
)
2121 Jim_Free(objPtr
->bytes
);
2123 objPtr
->bytes
= NULL
;
2126 #define Jim_SetStringRep(o, b, l) \
2127 do { (o)->bytes = b; (o)->length = l; } while (0)
2129 /* Set the initial string representation for an object.
2130 * Does not try to free an old one. */
2131 void Jim_InitStringRep(Jim_Obj
*objPtr
, const char *bytes
, int length
)
2134 objPtr
->bytes
= JimEmptyStringRep
;
2138 objPtr
->bytes
= Jim_Alloc(length
+ 1);
2139 objPtr
->length
= length
;
2140 memcpy(objPtr
->bytes
, bytes
, length
);
2141 objPtr
->bytes
[length
] = '\0';
2145 /* Duplicate an object. The returned object has refcount = 0. */
2146 Jim_Obj
*Jim_DuplicateObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2150 dupPtr
= Jim_NewObj(interp
);
2151 if (objPtr
->bytes
== NULL
) {
2152 /* Object does not have a valid string representation. */
2153 dupPtr
->bytes
= NULL
;
2156 Jim_InitStringRep(dupPtr
, objPtr
->bytes
, objPtr
->length
);
2159 /* By default, the new object has the same type as the old object */
2160 dupPtr
->typePtr
= objPtr
->typePtr
;
2161 if (objPtr
->typePtr
!= NULL
) {
2162 if (objPtr
->typePtr
->dupIntRepProc
== NULL
) {
2163 dupPtr
->internalRep
= objPtr
->internalRep
;
2166 /* The dup proc may set a different type, e.g. NULL */
2167 objPtr
->typePtr
->dupIntRepProc(interp
, objPtr
, dupPtr
);
2173 /* Return the string representation for objPtr. If the object
2174 * string representation is invalid, calls the method to create
2175 * a new one starting from the internal representation of the object. */
2176 const char *Jim_GetString(Jim_Obj
*objPtr
, int *lenPtr
)
2178 if (objPtr
->bytes
== NULL
) {
2179 /* Invalid string repr. Generate it. */
2180 JimPanic((objPtr
->typePtr
->updateStringProc
== NULL
, NULL
, "UpdateStringProc called against '%s' type.", objPtr
->typePtr
->name
));
2181 objPtr
->typePtr
->updateStringProc(objPtr
);
2184 *lenPtr
= objPtr
->length
;
2185 return objPtr
->bytes
;
2188 /* Just returns the length of the object's string rep */
2189 int Jim_Length(Jim_Obj
*objPtr
)
2193 Jim_GetString(objPtr
, &len
);
2197 static void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2198 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2200 static const Jim_ObjType dictSubstObjType
= {
2201 "dict-substitution",
2202 FreeDictSubstInternalRep
,
2203 DupDictSubstInternalRep
,
2208 static void FreeInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2210 Jim_DecrRefCount(interp
, (Jim_Obj
*)objPtr
->internalRep
.twoPtrValue
.ptr2
);
2213 static const Jim_ObjType interpolatedObjType
= {
2215 FreeInterpolatedInternalRep
,
2221 /* -----------------------------------------------------------------------------
2223 * ---------------------------------------------------------------------------*/
2224 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2225 static int SetStringFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2227 static const Jim_ObjType stringObjType
= {
2230 DupStringInternalRep
,
2232 JIM_TYPE_REFERENCES
,
2235 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2237 JIM_NOTUSED(interp
);
2239 /* This is a bit subtle: the only caller of this function
2240 * should be Jim_DuplicateObj(), that will copy the
2241 * string representaion. After the copy, the duplicated
2242 * object will not have more room in teh buffer than
2243 * srcPtr->length bytes. So we just set it to length. */
2244 dupPtr
->internalRep
.strValue
.maxLength
= srcPtr
->length
;
2246 dupPtr
->internalRep
.strValue
.charLength
= srcPtr
->internalRep
.strValue
.charLength
;
2249 static int SetStringFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2251 /* Get a fresh string representation. */
2252 (void)Jim_String(objPtr
);
2253 /* Free any other internal representation. */
2254 Jim_FreeIntRep(interp
, objPtr
);
2255 /* Set it as string, i.e. just set the maxLength field. */
2256 objPtr
->typePtr
= &stringObjType
;
2257 objPtr
->internalRep
.strValue
.maxLength
= objPtr
->length
;
2258 /* Don't know the utf-8 length yet */
2259 objPtr
->internalRep
.strValue
.charLength
= -1;
2264 * Returns the length of the object string in chars, not bytes.
2266 * These may be different for a utf-8 string.
2268 int Jim_Utf8Length(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2271 if (objPtr
->typePtr
!= &stringObjType
)
2272 SetStringFromAny(interp
, objPtr
);
2274 if (objPtr
->internalRep
.strValue
.charLength
< 0) {
2275 objPtr
->internalRep
.strValue
.charLength
= utf8_strlen(objPtr
->bytes
, objPtr
->length
);
2277 return objPtr
->internalRep
.strValue
.charLength
;
2279 return Jim_Length(objPtr
);
2283 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2284 Jim_Obj
*Jim_NewStringObj(Jim_Interp
*interp
, const char *s
, int len
)
2286 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2288 /* Need to find out how many bytes the string requires */
2291 /* Alloc/Set the string rep. */
2293 objPtr
->bytes
= JimEmptyStringRep
;
2297 objPtr
->bytes
= Jim_Alloc(len
+ 1);
2298 objPtr
->length
= len
;
2299 memcpy(objPtr
->bytes
, s
, len
);
2300 objPtr
->bytes
[len
] = '\0';
2303 /* No typePtr field for the vanilla string object. */
2304 objPtr
->typePtr
= NULL
;
2308 /* charlen is in characters -- see also Jim_NewStringObj() */
2309 Jim_Obj
*Jim_NewStringObjUtf8(Jim_Interp
*interp
, const char *s
, int charlen
)
2312 /* Need to find out how many bytes the string requires */
2313 int bytelen
= utf8_index(s
, charlen
);
2315 Jim_Obj
*objPtr
= Jim_NewStringObj(interp
, s
, bytelen
);
2317 /* Remember the utf8 length, so set the type */
2318 objPtr
->typePtr
= &stringObjType
;
2319 objPtr
->internalRep
.strValue
.maxLength
= bytelen
;
2320 objPtr
->internalRep
.strValue
.charLength
= charlen
;
2324 return Jim_NewStringObj(interp
, s
, charlen
);
2328 /* This version does not try to duplicate the 's' pointer, but
2329 * use it directly. */
2330 Jim_Obj
*Jim_NewStringObjNoAlloc(Jim_Interp
*interp
, char *s
, int len
)
2332 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2336 Jim_SetStringRep(objPtr
, s
, len
);
2337 objPtr
->typePtr
= NULL
;
2341 /* Low-level string append. Use it only against objects
2342 * of type "string". */
2343 static void StringAppendString(Jim_Obj
*objPtr
, const char *str
, int len
)
2349 needlen
= objPtr
->length
+ len
;
2350 if (objPtr
->internalRep
.strValue
.maxLength
< needlen
||
2351 objPtr
->internalRep
.strValue
.maxLength
== 0) {
2353 /* Inefficient to malloc() for less than 8 bytes */
2357 if (objPtr
->bytes
== JimEmptyStringRep
) {
2358 objPtr
->bytes
= Jim_Alloc(needlen
+ 1);
2361 objPtr
->bytes
= Jim_Realloc(objPtr
->bytes
, needlen
+ 1);
2363 objPtr
->internalRep
.strValue
.maxLength
= needlen
;
2365 memcpy(objPtr
->bytes
+ objPtr
->length
, str
, len
);
2366 objPtr
->bytes
[objPtr
->length
+ len
] = '\0';
2367 if (objPtr
->internalRep
.strValue
.charLength
>= 0) {
2368 /* Update the utf-8 char length */
2369 objPtr
->internalRep
.strValue
.charLength
+= utf8_strlen(objPtr
->bytes
+ objPtr
->length
, len
);
2371 objPtr
->length
+= len
;
2374 /* Higher level API to append strings to objects. */
2375 void Jim_AppendString(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
, int len
)
2377 JimPanic((Jim_IsShared(objPtr
), interp
, "Jim_AppendString called with shared object"));
2378 if (objPtr
->typePtr
!= &stringObjType
)
2379 SetStringFromAny(interp
, objPtr
);
2380 StringAppendString(objPtr
, str
, len
);
2383 void Jim_AppendObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*appendObjPtr
)
2388 str
= Jim_GetString(appendObjPtr
, &len
);
2389 Jim_AppendString(interp
, objPtr
, str
, len
);
2392 void Jim_AppendStrings(Jim_Interp
*interp
, Jim_Obj
*objPtr
, ...)
2396 if (objPtr
->typePtr
!= &stringObjType
)
2397 SetStringFromAny(interp
, objPtr
);
2398 va_start(ap
, objPtr
);
2400 char *s
= va_arg(ap
, char *);
2404 Jim_AppendString(interp
, objPtr
, s
, -1);
2409 int Jim_StringEqObj(Jim_Obj
*aObjPtr
, Jim_Obj
*bObjPtr
)
2411 const char *aStr
, *bStr
;
2414 if (aObjPtr
== bObjPtr
)
2416 aStr
= Jim_GetString(aObjPtr
, &aLen
);
2417 bStr
= Jim_GetString(bObjPtr
, &bLen
);
2420 return JimStringCompare(aStr
, aLen
, bStr
, bLen
) == 0;
2423 int Jim_StringMatchObj(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, Jim_Obj
*objPtr
, int nocase
)
2425 return JimStringMatch(interp
, patternObjPtr
, Jim_String(objPtr
), nocase
);
2428 int Jim_StringCompareObj(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*secondObjPtr
, int nocase
)
2430 const char *s1
, *s2
;
2433 s1
= Jim_GetString(firstObjPtr
, &l1
);
2434 s2
= Jim_GetString(secondObjPtr
, &l2
);
2437 return JimStringCompareNoCase(s1
, s2
, -1);
2439 return JimStringCompare(s1
, l1
, s2
, l2
);
2442 /* Convert a range, as returned by Jim_GetRange(), into
2443 * an absolute index into an object of the specified length.
2444 * This function may return negative values, or values
2445 * bigger or equal to the length of the list if the index
2446 * is out of range. */
2447 static int JimRelToAbsIndex(int len
, int idx
)
2454 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2455 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2456 * for implementation of commands like [string range] and [lrange].
2458 * The resulting range is guaranteed to address valid elements of
2460 static void JimRelToAbsRange(int len
, int first
, int last
,
2461 int *firstPtr
, int *lastPtr
, int *rangeLenPtr
)
2469 rangeLen
= last
- first
+ 1;
2476 rangeLen
-= (last
- (len
- 1));
2486 *rangeLenPtr
= rangeLen
;
2489 Jim_Obj
*Jim_StringByteRangeObj(Jim_Interp
*interp
,
2490 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2497 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2498 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2500 str
= Jim_GetString(strObjPtr
, &bytelen
);
2501 first
= JimRelToAbsIndex(bytelen
, first
);
2502 last
= JimRelToAbsIndex(bytelen
, last
);
2503 JimRelToAbsRange(bytelen
, first
, last
, &first
, &last
, &rangeLen
);
2504 if (first
== 0 && rangeLen
== bytelen
) {
2507 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2510 Jim_Obj
*Jim_StringRangeObj(Jim_Interp
*interp
,
2511 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2519 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2520 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2522 str
= Jim_GetString(strObjPtr
, &bytelen
);
2523 len
= Jim_Utf8Length(interp
, strObjPtr
);
2524 first
= JimRelToAbsIndex(len
, first
);
2525 last
= JimRelToAbsIndex(len
, last
);
2526 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
2527 if (first
== 0 && rangeLen
== len
) {
2530 if (len
== bytelen
) {
2531 /* ASCII optimisation */
2532 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2534 return Jim_NewStringObjUtf8(interp
, str
+ utf8_index(str
, first
), rangeLen
);
2536 return Jim_StringByteRangeObj(interp
, strObjPtr
, firstObjPtr
, lastObjPtr
);
2540 static Jim_Obj
*JimStringToLower(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2546 if (strObjPtr
->typePtr
!= &stringObjType
) {
2547 SetStringFromAny(interp
, strObjPtr
);
2550 str
= Jim_GetString(strObjPtr
, &len
);
2552 buf
= p
= Jim_Alloc(len
+ 1);
2555 str
+= utf8_tounicode(str
, &c
);
2556 p
+= utf8_fromunicode(p
, utf8_lower(c
));
2559 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2562 static Jim_Obj
*JimStringToUpper(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2568 if (strObjPtr
->typePtr
!= &stringObjType
) {
2569 SetStringFromAny(interp
, strObjPtr
);
2572 str
= Jim_GetString(strObjPtr
, &len
);
2574 buf
= p
= Jim_Alloc(len
+ 1);
2577 str
+= utf8_tounicode(str
, &c
);
2578 p
+= utf8_fromunicode(p
, utf8_upper(c
));
2581 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2584 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2585 * for unicode character 'c'.
2586 * Returns the position if found or NULL if not
2588 static const char *utf8_memchr(const char *str
, int len
, int c
)
2593 int n
= utf8_tounicode(str
, &sc
);
2602 return memchr(str
, c
, len
);
2607 * Searches for the first non-trim char in string (str, len)
2609 * If none is found, returns just past the last char.
2611 * Lengths are in bytes.
2613 static const char *JimFindTrimLeft(const char *str
, int len
, const char *trimchars
, int trimlen
)
2617 int n
= utf8_tounicode(str
, &c
);
2619 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2620 /* Not a trim char, so stop */
2630 * Searches backwards for a non-trim char in string (str, len).
2632 * Returns a pointer to just after the non-trim char, or NULL if not found.
2634 * Lengths are in bytes.
2636 static const char *JimFindTrimRight(const char *str
, int len
, const char *trimchars
, int trimlen
)
2642 int n
= utf8_prev_len(str
, len
);
2647 n
= utf8_tounicode(str
, &c
);
2649 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2657 static const char default_trim_chars
[] = " \t\n\r";
2658 /* sizeof() here includes the null byte */
2659 static int default_trim_chars_len
= sizeof(default_trim_chars
);
2661 static Jim_Obj
*JimStringTrimLeft(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2664 const char *str
= Jim_GetString(strObjPtr
, &len
);
2665 const char *trimchars
= default_trim_chars
;
2666 int trimcharslen
= default_trim_chars_len
;
2669 if (trimcharsObjPtr
) {
2670 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2673 newstr
= JimFindTrimLeft(str
, len
, trimchars
, trimcharslen
);
2674 if (newstr
== str
) {
2678 return Jim_NewStringObj(interp
, newstr
, len
- (newstr
- str
));
2681 static Jim_Obj
*JimStringTrimRight(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2684 const char *trimchars
= default_trim_chars
;
2685 int trimcharslen
= default_trim_chars_len
;
2686 const char *nontrim
;
2688 if (trimcharsObjPtr
) {
2689 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2692 if (strObjPtr
->typePtr
!= &stringObjType
) {
2693 SetStringFromAny(interp
, strObjPtr
);
2695 Jim_GetString(strObjPtr
, &len
);
2696 nontrim
= JimFindTrimRight(strObjPtr
->bytes
, len
, trimchars
, trimcharslen
);
2698 if (nontrim
== NULL
) {
2699 /* All trim, so return a zero-length string */
2700 return Jim_NewEmptyStringObj(interp
);
2702 if (nontrim
== strObjPtr
->bytes
+ len
) {
2706 if (Jim_IsShared(strObjPtr
)) {
2707 strObjPtr
= Jim_NewStringObj(interp
, strObjPtr
->bytes
, (nontrim
- strObjPtr
->bytes
));
2710 /* Can modify this string in place */
2711 strObjPtr
->bytes
[nontrim
- strObjPtr
->bytes
] = 0;
2712 strObjPtr
->length
= (nontrim
- strObjPtr
->bytes
);
2718 static Jim_Obj
*JimStringTrim(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2720 /* First trim left. */
2721 Jim_Obj
*objPtr
= JimStringTrimLeft(interp
, strObjPtr
, trimcharsObjPtr
);
2723 /* Now trim right */
2724 strObjPtr
= JimStringTrimRight(interp
, objPtr
, trimcharsObjPtr
);
2726 if (objPtr
!= strObjPtr
) {
2727 /* Note that we don't want this object to be leaked */
2728 Jim_IncrRefCount(objPtr
);
2729 Jim_DecrRefCount(interp
, objPtr
);
2736 static int JimStringIs(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*strClass
, int strict
)
2738 static const char * const strclassnames
[] = {
2739 "integer", "alpha", "alnum", "ascii", "digit",
2740 "double", "lower", "upper", "space", "xdigit",
2741 "control", "print", "graph", "punct",
2745 STR_IS_INTEGER
, STR_IS_ALPHA
, STR_IS_ALNUM
, STR_IS_ASCII
, STR_IS_DIGIT
,
2746 STR_IS_DOUBLE
, STR_IS_LOWER
, STR_IS_UPPER
, STR_IS_SPACE
, STR_IS_XDIGIT
,
2747 STR_IS_CONTROL
, STR_IS_PRINT
, STR_IS_GRAPH
, STR_IS_PUNCT
2753 int (*isclassfunc
)(int c
) = NULL
;
2755 if (Jim_GetEnum(interp
, strClass
, strclassnames
, &strclass
, "class", JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
2759 str
= Jim_GetString(strObjPtr
, &len
);
2761 Jim_SetResultInt(interp
, !strict
);
2766 case STR_IS_INTEGER
:
2769 Jim_SetResultInt(interp
, JimGetWideNoErr(interp
, strObjPtr
, &w
) == JIM_OK
);
2776 Jim_SetResultInt(interp
, Jim_GetDouble(interp
, strObjPtr
, &d
) == JIM_OK
&& errno
!= ERANGE
);
2780 case STR_IS_ALPHA
: isclassfunc
= isalpha
; break;
2781 case STR_IS_ALNUM
: isclassfunc
= isalnum
; break;
2782 case STR_IS_ASCII
: isclassfunc
= isascii
; break;
2783 case STR_IS_DIGIT
: isclassfunc
= isdigit
; break;
2784 case STR_IS_LOWER
: isclassfunc
= islower
; break;
2785 case STR_IS_UPPER
: isclassfunc
= isupper
; break;
2786 case STR_IS_SPACE
: isclassfunc
= isspace
; break;
2787 case STR_IS_XDIGIT
: isclassfunc
= isxdigit
; break;
2788 case STR_IS_CONTROL
: isclassfunc
= iscntrl
; break;
2789 case STR_IS_PRINT
: isclassfunc
= isprint
; break;
2790 case STR_IS_GRAPH
: isclassfunc
= isgraph
; break;
2791 case STR_IS_PUNCT
: isclassfunc
= ispunct
; break;
2796 for (i
= 0; i
< len
; i
++) {
2797 if (!isclassfunc(str
[i
])) {
2798 Jim_SetResultInt(interp
, 0);
2802 Jim_SetResultInt(interp
, 1);
2806 /* -----------------------------------------------------------------------------
2807 * Compared String Object
2808 * ---------------------------------------------------------------------------*/
2810 /* This is strange object that allows to compare a C literal string
2811 * with a Jim object in very short time if the same comparison is done
2812 * multiple times. For example every time the [if] command is executed,
2813 * Jim has to check if a given argument is "else". This comparions if
2814 * the code has no errors are true most of the times, so we can cache
2815 * inside the object the pointer of the string of the last matching
2816 * comparison. Because most C compilers perform literal sharing,
2817 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2818 * this works pretty well even if comparisons are at different places
2819 * inside the C code. */
2821 static const Jim_ObjType comparedStringObjType
= {
2826 JIM_TYPE_REFERENCES
,
2829 /* The only way this object is exposed to the API is via the following
2830 * function. Returns true if the string and the object string repr.
2831 * are the same, otherwise zero is returned.
2833 * Note: this isn't binary safe, but it hardly needs to be.*/
2834 int Jim_CompareStringImmediate(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
)
2836 if (objPtr
->typePtr
== &comparedStringObjType
&& objPtr
->internalRep
.ptr
== str
)
2839 const char *objStr
= Jim_String(objPtr
);
2841 if (strcmp(str
, objStr
) != 0)
2843 if (objPtr
->typePtr
!= &comparedStringObjType
) {
2844 Jim_FreeIntRep(interp
, objPtr
);
2845 objPtr
->typePtr
= &comparedStringObjType
;
2847 objPtr
->internalRep
.ptr
= (char *)str
; /*ATTENTION: const cast */
2852 static int qsortCompareStringPointers(const void *a
, const void *b
)
2854 char *const *sa
= (char *const *)a
;
2855 char *const *sb
= (char *const *)b
;
2857 return strcmp(*sa
, *sb
);
2861 /* -----------------------------------------------------------------------------
2864 * This object is just a string from the language point of view, but
2865 * in the internal representation it contains the filename and line number
2866 * where this given token was read. This information is used by
2867 * Jim_EvalObj() if the object passed happens to be of type "source".
2869 * This allows to propagate the information about line numbers and file
2870 * names and give error messages with absolute line numbers.
2872 * Note that this object uses shared strings for filenames, and the
2873 * pointer to the filename together with the line number is taken into
2874 * the space for the "inline" internal representation of the Jim_Object,
2875 * so there is almost memory zero-overhead.
2877 * Also the object will be converted to something else if the given
2878 * token it represents in the source file is not something to be
2879 * evaluated (not a script), and will be specialized in some other way,
2880 * so the time overhead is also null.
2881 * ---------------------------------------------------------------------------*/
2883 static void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2884 static void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2886 static const Jim_ObjType sourceObjType
= {
2888 FreeSourceInternalRep
,
2889 DupSourceInternalRep
,
2891 JIM_TYPE_REFERENCES
,
2894 void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2896 Jim_ReleaseSharedString(interp
, objPtr
->internalRep
.sourceValue
.fileName
);
2899 void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2901 dupPtr
->internalRep
.sourceValue
.fileName
=
2902 Jim_GetSharedString(interp
, srcPtr
->internalRep
.sourceValue
.fileName
);
2903 dupPtr
->internalRep
.sourceValue
.lineNumber
= dupPtr
->internalRep
.sourceValue
.lineNumber
;
2904 dupPtr
->typePtr
= &sourceObjType
;
2907 static void JimSetSourceInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2908 const char *fileName
, int lineNumber
)
2911 JimPanic((Jim_IsShared(objPtr
), interp
, "JimSetSourceInfo called with shared object"));
2912 JimPanic((objPtr
->typePtr
!= NULL
, interp
, "JimSetSourceInfo called with typePtr != NULL"));
2913 objPtr
->internalRep
.sourceValue
.fileName
= Jim_GetSharedString(interp
, fileName
);
2914 objPtr
->internalRep
.sourceValue
.lineNumber
= lineNumber
;
2915 objPtr
->typePtr
= &sourceObjType
;
2919 /* -----------------------------------------------------------------------------
2921 * ---------------------------------------------------------------------------*/
2923 static const Jim_ObjType scriptLineObjType
= {
2931 static Jim_Obj
*JimNewScriptLineObj(Jim_Interp
*interp
, int argc
, int line
)
2935 #ifdef DEBUG_SHOW_SCRIPT
2937 snprintf(buf
, sizeof(buf
), "line=%d, argc=%d", line
, argc
);
2938 objPtr
= Jim_NewStringObj(interp
, buf
, -1);
2940 objPtr
= Jim_NewEmptyStringObj(interp
);
2942 objPtr
->typePtr
= &scriptLineObjType
;
2943 objPtr
->internalRep
.scriptLineValue
.argc
= argc
;
2944 objPtr
->internalRep
.scriptLineValue
.line
= line
;
2949 #define JIM_CMDSTRUCT_EXPAND -1
2951 static void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2952 static void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2953 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2955 static const Jim_ObjType scriptObjType
= {
2957 FreeScriptInternalRep
,
2958 DupScriptInternalRep
,
2960 JIM_TYPE_REFERENCES
,
2963 /* The ScriptToken structure represents every token into a scriptObj.
2964 * Every token contains an associated Jim_Obj that can be specialized
2965 * by commands operating on it. */
2966 typedef struct ScriptToken
2972 /* This is the script object internal representation. An array of
2973 * ScriptToken structures, including a pre-computed representation of the
2974 * command length and arguments.
2976 * For example the script:
2979 * set $i $x$y [foo]BAR
2981 * will produce a ScriptObj with the following Tokens:
2996 * "puts hello" has two args (LIN 2), composed of single tokens.
2997 * (Note that the WRD token is omitted for the common case of a single token.)
2999 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
3000 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
3002 * The precomputation of the command structure makes Jim_Eval() faster,
3003 * and simpler because there aren't dynamic lengths / allocations.
3005 * -- {expand}/{*} handling --
3007 * Expand is handled in a special way.
3009 * If a "word" begins with {*}, the word token count is -ve.
3011 * For example the command:
3015 * Will produce the following cmdstruct array:
3022 * Note that the 'LIN' token also contains the source information for the
3023 * first word of the line for error reporting purposes
3025 * -- the substFlags field of the structure --
3027 * The scriptObj structure is used to represent both "script" objects
3028 * and "subst" objects. In the second case, the there are no LIN and WRD
3029 * tokens. Instead SEP and EOL tokens are added as-is.
3030 * In addition, the field 'substFlags' is used to represent the flags used to turn
3031 * the string into the internal representation used to perform the
3032 * substitution. If this flags are not what the application requires
3033 * the scriptObj is created again. For example the script:
3035 * subst -nocommands $string
3036 * subst -novariables $string
3038 * Will recreate the internal representation of the $string object
3041 typedef struct ScriptObj
3043 int len
; /* Length as number of tokens. */
3044 ScriptToken
*token
; /* Tokens array. */
3045 int substFlags
; /* flags used for the compilation of "subst" objects */
3046 int inUse
; /* Used to share a ScriptObj. Currently
3047 only used by Jim_EvalObj() as protection against
3048 shimmering of the currently evaluated object. */
3049 const char *fileName
;
3050 int line
; /* Line number of the first line */
3053 void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3056 struct ScriptObj
*script
= (void *)objPtr
->internalRep
.ptr
;
3059 if (script
->inUse
!= 0)
3061 for (i
= 0; i
< script
->len
; i
++) {
3062 Jim_DecrRefCount(interp
, script
->token
[i
].objPtr
);
3064 Jim_Free(script
->token
);
3065 if (script
->fileName
) {
3066 Jim_ReleaseSharedString(interp
, script
->fileName
);
3071 void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
3073 JIM_NOTUSED(interp
);
3074 JIM_NOTUSED(srcPtr
);
3076 /* Just returns an simple string. */
3077 dupPtr
->typePtr
= NULL
;
3080 /* A simple parser token.
3081 * All the simple tokens for the script point into the same script string rep.
3085 const char *token
; /* Pointer to the start of the token */
3086 int len
; /* Length of this token */
3087 int type
; /* Token type */
3088 int line
; /* Line number */
3091 /* A list of parsed tokens representing a script.
3092 * Tokens are added to this list as the script is parsed.
3093 * It grows as needed.
3097 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3098 ParseToken
*list
; /* Array of tokens */
3099 int size
; /* Current size of the list */
3100 int count
; /* Number of entries used */
3101 ParseToken static_list
[20]; /* Small initial token space to avoid allocation */
3104 static void ScriptTokenListInit(ParseTokenList
*tokenlist
)
3106 tokenlist
->list
= tokenlist
->static_list
;
3107 tokenlist
->size
= sizeof(tokenlist
->static_list
) / sizeof(ParseToken
);
3108 tokenlist
->count
= 0;
3111 static void ScriptTokenListFree(ParseTokenList
*tokenlist
)
3113 if (tokenlist
->list
!= tokenlist
->static_list
) {
3114 Jim_Free(tokenlist
->list
);
3119 * Adds the new token to the tokenlist.
3120 * The token has the given length, type and line number.
3121 * The token list is resized as necessary.
3123 static void ScriptAddToken(ParseTokenList
*tokenlist
, const char *token
, int len
, int type
,
3128 if (tokenlist
->count
== tokenlist
->size
) {
3129 /* Resize the list */
3130 tokenlist
->size
*= 2;
3131 if (tokenlist
->list
!= tokenlist
->static_list
) {
3133 Jim_Realloc(tokenlist
->list
, tokenlist
->size
* sizeof(*tokenlist
->list
));
3136 /* The list needs to become allocated */
3137 tokenlist
->list
= Jim_Alloc(tokenlist
->size
* sizeof(*tokenlist
->list
));
3138 memcpy(tokenlist
->list
, tokenlist
->static_list
,
3139 tokenlist
->count
* sizeof(*tokenlist
->list
));
3142 t
= &tokenlist
->list
[tokenlist
->count
++];
3149 /* Counts the number of adjoining non-separator.
3151 * Returns -ve if the first token is the expansion
3152 * operator (in which case the count doesn't include
3155 static int JimCountWordTokens(ParseToken
*t
)
3160 /* Is the first word {*} or {expand}? */
3161 if (t
->type
== JIM_TT_STR
&& !TOKEN_IS_SEP(t
[1].type
)) {
3162 if ((t
->len
== 1 && *t
->token
== '*') || (t
->len
== 6 && strncmp(t
->token
, "expand", 6) == 0)) {
3163 /* Create an expand token */
3169 /* Now count non-separator words */
3170 while (!TOKEN_IS_SEP(t
->type
)) {
3175 return count
* expand
;
3179 * Create a script/subst object from the given token.
3181 static Jim_Obj
*JimMakeScriptObj(Jim_Interp
*interp
, const ParseToken
*t
)
3185 if (t
->type
== JIM_TT_ESC
&& memchr(t
->token
, '\\', t
->len
) != NULL
) {
3186 /* Convert the backlash escapes . */
3188 char *str
= Jim_Alloc(len
+ 1);
3189 len
= JimEscape(str
, t
->token
, len
);
3190 objPtr
= Jim_NewStringObjNoAlloc(interp
, str
, len
);
3193 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3194 * with a single space. This is currently not done.
3196 objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
3202 * Takes a tokenlist and creates the allocated list of script tokens
3203 * in script->token, of length script->len.
3205 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3208 * Also sets script->line to the line number of the first token
3210 static void ScriptObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3211 ParseTokenList
*tokenlist
)
3214 struct ScriptToken
*token
;
3215 /* Number of tokens so far for the current command */
3217 /* This is the first token for the current command */
3218 ScriptToken
*linefirst
;
3222 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3223 printf("==== Tokens ====\n");
3224 for (i
= 0; i
< tokenlist
->count
; i
++) {
3225 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
->list
[i
].line
, jim_tt_name(tokenlist
->list
[i
].type
),
3226 tokenlist
->list
[i
].len
, tokenlist
->list
[i
].token
);
3230 /* May need up to one extra script token for each EOL in the worst case */
3231 count
= tokenlist
->count
;
3232 for (i
= 0; i
< tokenlist
->count
; i
++) {
3233 if (tokenlist
->list
[i
].type
== JIM_TT_EOL
) {
3237 linenr
= script
->line
= tokenlist
->list
[0].line
;
3239 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
3241 /* This is the first token for the current command */
3242 linefirst
= token
++;
3244 for (i
= 0; i
< tokenlist
->count
; ) {
3245 /* Look ahead to find out how many tokens make up the next word */
3248 /* Skip any leading separators */
3249 while (tokenlist
->list
[i
].type
== JIM_TT_SEP
) {
3253 wordtokens
= JimCountWordTokens(tokenlist
->list
+ i
);
3255 if (wordtokens
== 0) {
3256 /* None, so at end of line */
3258 linefirst
->type
= JIM_TT_LINE
;
3259 linefirst
->objPtr
= JimNewScriptLineObj(interp
, lineargs
, linenr
);
3260 Jim_IncrRefCount(linefirst
->objPtr
);
3262 /* Reset for new line */
3264 linefirst
= token
++;
3269 else if (wordtokens
!= 1) {
3270 /* More than 1, or {expand}, so insert a WORD token */
3271 token
->type
= JIM_TT_WORD
;
3272 token
->objPtr
= Jim_NewIntObj(interp
, wordtokens
);
3273 Jim_IncrRefCount(token
->objPtr
);
3275 if (wordtokens
< 0) {
3276 /* Skip the expand token */
3278 wordtokens
= -wordtokens
- 1;
3283 if (lineargs
== 0) {
3284 /* First real token on the line, so record the line number */
3285 linenr
= tokenlist
->list
[i
].line
;
3289 /* Add each non-separator word token to the line */
3290 while (wordtokens
--) {
3291 const ParseToken
*t
= &tokenlist
->list
[i
++];
3293 token
->type
= t
->type
;
3294 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3295 Jim_IncrRefCount(token
->objPtr
);
3297 /* Every object is initially a string, but the
3298 * internal type may be specialized during execution of the
3300 JimSetSourceInfo(interp
, token
->objPtr
, script
->fileName
, t
->line
);
3305 if (lineargs
== 0) {
3309 script
->len
= token
- script
->token
;
3311 assert(script
->len
< count
);
3313 #ifdef DEBUG_SHOW_SCRIPT
3314 printf("==== Script (%s) ====\n", script
->fileName
);
3315 for (i
= 0; i
< script
->len
; i
++) {
3316 const ScriptToken
*t
= &script
->token
[i
];
3317 printf("[%2d] %s %s\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
3324 * Similar to ScriptObjAddTokens(), but for subst objects.
3326 static void SubstObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3327 ParseTokenList
*tokenlist
)
3330 struct ScriptToken
*token
;
3332 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * tokenlist
->count
);
3334 for (i
= 0; i
< tokenlist
->count
; i
++) {
3335 const ParseToken
*t
= &tokenlist
->list
[i
];
3337 /* Create a token for 't' */
3338 token
->type
= t
->type
;
3339 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3340 Jim_IncrRefCount(token
->objPtr
);
3347 /* This method takes the string representation of an object
3348 * as a Tcl script, and generates the pre-parsed internal representation
3350 int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3353 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
3354 struct JimParserCtx parser
;
3355 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
3356 ParseTokenList tokenlist
;
3358 /* Try to get information about filename / line number */
3359 if (objPtr
->typePtr
== &sourceObjType
) {
3360 script
->fileName
= Jim_GetSharedString(interp
, objPtr
->internalRep
.sourceValue
.fileName
);
3361 script
->line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
3364 script
->fileName
= NULL
;
3368 /* Initially parse the script into tokens (in tokenlist) */
3369 ScriptTokenListInit(&tokenlist
);
3371 JimParserInit(&parser
, scriptText
, scriptTextLen
, script
->line
);
3372 while (!parser
.eof
) {
3373 JimParseScript(&parser
);
3374 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
3377 /* Add a final EOF token */
3378 ScriptAddToken(&tokenlist
, scriptText
+ scriptTextLen
, 0, JIM_TT_EOF
, 0);
3380 /* Create the "real" script tokens from the initial token list */
3381 script
->substFlags
= 0;
3383 ScriptObjAddTokens(interp
, script
, &tokenlist
);
3385 /* No longer need the token list */
3386 ScriptTokenListFree(&tokenlist
);
3388 if (!script
->fileName
) {
3389 script
->fileName
= Jim_GetSharedString(interp
, "");
3392 /* Free the old internal rep and set the new one. */
3393 Jim_FreeIntRep(interp
, objPtr
);
3394 Jim_SetIntRepPtr(objPtr
, script
);
3395 objPtr
->typePtr
= &scriptObjType
;
3400 ScriptObj
*Jim_GetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3402 struct ScriptObj
*script
= Jim_GetIntRepPtr(objPtr
);
3404 if (objPtr
->typePtr
!= &scriptObjType
|| script
->substFlags
) {
3405 SetScriptFromAny(interp
, objPtr
);
3407 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
3410 /* -----------------------------------------------------------------------------
3412 * ---------------------------------------------------------------------------*/
3413 static void JimIncrCmdRefCount(Jim_Cmd
*cmdPtr
)
3418 static void JimDecrCmdRefCount(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
)
3420 if (--cmdPtr
->inUse
== 0) {
3421 if (cmdPtr
->isproc
) {
3422 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.argListObjPtr
);
3423 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.bodyObjPtr
);
3424 if (cmdPtr
->u
.proc
.staticVars
) {
3425 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3426 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3428 if (cmdPtr
->u
.proc
.prevCmd
) {
3429 /* Delete any pushed command too */
3430 JimDecrCmdRefCount(interp
, cmdPtr
->u
.proc
.prevCmd
);
3435 if (cmdPtr
->u
.native
.delProc
) {
3436 cmdPtr
->u
.native
.delProc(interp
, cmdPtr
->u
.native
.privData
);
3443 /* Commands HashTable Type.
3445 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3446 static void JimCommandsHT_ValDestructor(void *interp
, void *val
)
3448 JimDecrCmdRefCount(interp
, val
);
3451 static const Jim_HashTableType JimCommandsHashTableType
= {
3452 JimStringCopyHTHashFunction
, /* hash function */
3453 JimStringCopyHTKeyDup
, /* key dup */
3455 JimStringCopyHTKeyCompare
, /* key compare */
3456 JimStringCopyHTKeyDestructor
, /* key destructor */
3457 JimCommandsHT_ValDestructor
/* val destructor */
3460 /* ------------------------- Commands related functions --------------------- */
3462 int Jim_CreateCommand(Jim_Interp
*interp
, const char *cmdName
,
3463 Jim_CmdProc cmdProc
, void *privData
, Jim_DelCmdProc delProc
)
3467 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) != JIM_ERR
) {
3468 /* Command existed so incr proc epoch */
3469 Jim_InterpIncrProcEpoch(interp
);
3472 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3474 /* Store the new details for this proc */
3475 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3477 cmdPtr
->u
.native
.delProc
= delProc
;
3478 cmdPtr
->u
.native
.cmdProc
= cmdProc
;
3479 cmdPtr
->u
.native
.privData
= privData
;
3481 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3483 /* There is no need to increment the 'proc epoch' because
3484 * creation of a new procedure can never affect existing
3485 * cached commands. We don't do negative caching. */
3489 static int JimCreateProcedure(Jim_Interp
*interp
, const char *cmdName
,
3490 Jim_Obj
*argListObjPtr
, Jim_Obj
*staticsListObjPtr
, Jim_Obj
*bodyObjPtr
,
3491 int leftArity
, int optionalArgs
, int args
, int rightArity
)
3496 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3497 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3500 cmdPtr
->u
.proc
.argListObjPtr
= argListObjPtr
;
3501 cmdPtr
->u
.proc
.bodyObjPtr
= bodyObjPtr
;
3502 Jim_IncrRefCount(argListObjPtr
);
3503 Jim_IncrRefCount(bodyObjPtr
);
3504 cmdPtr
->u
.proc
.leftArity
= leftArity
;
3505 cmdPtr
->u
.proc
.optionalArgs
= optionalArgs
;
3506 cmdPtr
->u
.proc
.args
= args
;
3507 cmdPtr
->u
.proc
.rightArity
= rightArity
;
3508 cmdPtr
->u
.proc
.staticVars
= NULL
;
3509 cmdPtr
->u
.proc
.prevCmd
= NULL
;
3512 /* Create the statics hash table. */
3513 if (staticsListObjPtr
) {
3516 len
= Jim_ListLength(interp
, staticsListObjPtr
);
3518 cmdPtr
->u
.proc
.staticVars
= Jim_Alloc(sizeof(Jim_HashTable
));
3519 Jim_InitHashTable(cmdPtr
->u
.proc
.staticVars
, &JimVariablesHashTableType
, interp
);
3520 for (i
= 0; i
< len
; i
++) {
3521 Jim_Obj
*objPtr
= 0, *initObjPtr
= 0, *nameObjPtr
= 0;
3525 Jim_ListIndex(interp
, staticsListObjPtr
, i
, &objPtr
, JIM_NONE
);
3526 /* Check if it's composed of two elements. */
3527 subLen
= Jim_ListLength(interp
, objPtr
);
3528 if (subLen
== 1 || subLen
== 2) {
3529 /* Try to get the variable value from the current
3531 Jim_ListIndex(interp
, objPtr
, 0, &nameObjPtr
, JIM_NONE
);
3533 initObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, JIM_NONE
);
3534 if (initObjPtr
== NULL
) {
3535 Jim_SetResultFormatted(interp
,
3536 "variable for initialization of static \"%#s\" not found in the local context",
3542 Jim_ListIndex(interp
, objPtr
, 1, &initObjPtr
, JIM_NONE
);
3544 if (JimValidName(interp
, "static variable", nameObjPtr
) != JIM_OK
) {
3548 varPtr
= Jim_Alloc(sizeof(*varPtr
));
3549 varPtr
->objPtr
= initObjPtr
;
3550 Jim_IncrRefCount(initObjPtr
);
3551 varPtr
->linkFramePtr
= NULL
;
3552 if (Jim_AddHashEntry(cmdPtr
->u
.proc
.staticVars
,
3553 Jim_String(nameObjPtr
), varPtr
) != JIM_OK
) {
3554 Jim_SetResultFormatted(interp
,
3555 "static variable name \"%#s\" duplicated in statics list", nameObjPtr
);
3556 Jim_DecrRefCount(interp
, initObjPtr
);
3562 Jim_SetResultFormatted(interp
, "too many fields in static specifier \"%#s\"",
3570 /* Add the new command */
3572 /* It may already exist, so we try to delete the old one.
3573 * Note that reference count means that it won't be deleted yet if
3574 * it exists in the call stack.
3576 * BUT, if 'local' is in force, instead of deleting the existing
3577 * proc, we stash a reference to the old proc here.
3579 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3581 /* There was an old procedure with the same name, this requires
3582 * a 'proc epoch' update. */
3584 /* If a procedure with the same name didn't existed there is no need
3585 * to increment the 'proc epoch' because creation of a new procedure
3586 * can never affect existing cached commands. We don't do
3587 * negative caching. */
3588 Jim_InterpIncrProcEpoch(interp
);
3591 if (he
&& interp
->local
) {
3592 /* Just push this proc over the top of the previous one */
3593 cmdPtr
->u
.proc
.prevCmd
= he
->u
.val
;
3598 /* Replace the existing proc */
3599 Jim_DeleteHashEntry(&interp
->commands
, cmdName
);
3602 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3605 /* Unlike Tcl, set the name of the proc as the result */
3606 Jim_SetResultString(interp
, cmdName
, -1);
3610 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3611 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3612 Jim_DecrRefCount(interp
, argListObjPtr
);
3613 Jim_DecrRefCount(interp
, bodyObjPtr
);
3618 int Jim_DeleteCommand(Jim_Interp
*interp
, const char *cmdName
)
3620 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) == JIM_ERR
)
3622 Jim_InterpIncrProcEpoch(interp
);
3626 int Jim_RenameCommand(Jim_Interp
*interp
, const char *oldName
, const char *newName
)
3630 /* Does it exist? */
3631 he
= Jim_FindHashEntry(&interp
->commands
, oldName
);
3633 Jim_SetResultFormatted(interp
, "can't %s \"%s\": command doesn't exist",
3634 newName
[0] ? "rename" : "delete", oldName
);
3638 if (newName
[0] == '\0') /* Delete! */
3639 return Jim_DeleteCommand(interp
, oldName
);
3642 if (Jim_FindHashEntry(&interp
->commands
, newName
)) {
3643 Jim_SetResultFormatted(interp
, "can't rename to \"%s\": command already exists", newName
);
3647 /* Add the new name first */
3648 JimIncrCmdRefCount(he
->u
.val
);
3649 Jim_AddHashEntry(&interp
->commands
, newName
, he
->u
.val
);
3651 /* Now remove the old name */
3652 Jim_DeleteHashEntry(&interp
->commands
, oldName
);
3654 /* Increment the epoch */
3655 Jim_InterpIncrProcEpoch(interp
);
3659 /* -----------------------------------------------------------------------------
3661 * ---------------------------------------------------------------------------*/
3663 static int SetCommandFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3665 static const Jim_ObjType commandObjType
= {
3670 JIM_TYPE_REFERENCES
,
3673 int SetCommandFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3676 const char *cmdName
;
3678 /* Get the string representation */
3679 cmdName
= Jim_String(objPtr
);
3680 /* Lookup this name into the commands hash table */
3681 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3685 /* Free the old internal repr and set the new one. */
3686 Jim_FreeIntRep(interp
, objPtr
);
3687 objPtr
->typePtr
= &commandObjType
;
3688 objPtr
->internalRep
.cmdValue
.procEpoch
= interp
->procEpoch
;
3689 objPtr
->internalRep
.cmdValue
.cmdPtr
= (void *)he
->u
.val
;
3693 /* This function returns the command structure for the command name
3694 * stored in objPtr. It tries to specialize the objPtr to contain
3695 * a cached info instead to perform the lookup into the hash table
3696 * every time. The information cached may not be uptodate, in such
3697 * a case the lookup is performed and the cache updated.
3699 * Respects the 'upcall' setting
3701 Jim_Cmd
*Jim_GetCommand(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
3705 if ((objPtr
->typePtr
!= &commandObjType
||
3706 objPtr
->internalRep
.cmdValue
.procEpoch
!= interp
->procEpoch
) &&
3707 SetCommandFromAny(interp
, objPtr
) == JIM_ERR
) {
3708 if (flags
& JIM_ERRMSG
) {
3709 Jim_SetResultFormatted(interp
, "invalid command name \"%#s\"", objPtr
);
3713 cmd
= objPtr
->internalRep
.cmdValue
.cmdPtr
;
3714 while (cmd
->isproc
&& cmd
->u
.proc
.upcall
) {
3715 cmd
= cmd
->u
.proc
.prevCmd
;
3720 /* -----------------------------------------------------------------------------
3722 * ---------------------------------------------------------------------------*/
3724 /* Variables HashTable Type.
3726 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3727 static void JimVariablesHTValDestructor(void *interp
, void *val
)
3729 Jim_Var
*varPtr
= (void *)val
;
3731 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
3735 static const Jim_HashTableType JimVariablesHashTableType
= {
3736 JimStringCopyHTHashFunction
, /* hash function */
3737 JimStringCopyHTKeyDup
, /* key dup */
3739 JimStringCopyHTKeyCompare
, /* key compare */
3740 JimStringCopyHTKeyDestructor
, /* key destructor */
3741 JimVariablesHTValDestructor
/* val destructor */
3744 /* -----------------------------------------------------------------------------
3746 * ---------------------------------------------------------------------------*/
3748 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3750 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3752 static const Jim_ObjType variableObjType
= {
3757 JIM_TYPE_REFERENCES
,
3760 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3761 * is in the form "varname(key)". */
3762 static int JimNameIsDictSugar(const char *str
, int len
)
3764 if (len
&& str
[len
- 1] == ')' && strchr(str
, '(') != NULL
)
3770 * Check that the name does not contain embedded nulls.
3772 * Variable and procedure names are maniplated as null terminated strings, so
3773 * don't allow names with embedded nulls.
3775 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
)
3777 /* Variable names and proc names can't contain embedded nulls */
3778 if (nameObjPtr
->typePtr
!= &variableObjType
) {
3780 const char *str
= Jim_GetString(nameObjPtr
, &len
);
3781 if (memchr(str
, '\0', len
)) {
3782 Jim_SetResultFormatted(interp
, "%s name contains embedded null", type
);
3789 /* This method should be called only by the variable API.
3790 * It returns JIM_OK on success (variable already exists),
3791 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3792 * a variable name, but syntax glue for [dict] i.e. the last
3793 * character is ')' */
3794 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3797 const char *varName
;
3799 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3801 /* Check if the object is already an uptodate variable */
3802 if (objPtr
->typePtr
== &variableObjType
&&
3803 objPtr
->internalRep
.varValue
.callFrameId
== framePtr
->id
) {
3804 return JIM_OK
; /* nothing to do */
3807 if (objPtr
->typePtr
== &dictSubstObjType
) {
3808 return JIM_DICT_SUGAR
;
3811 if (JimValidName(interp
, "variable", objPtr
) != JIM_OK
) {
3815 /* Get the string representation */
3816 varName
= Jim_GetString(objPtr
, &len
);
3818 /* Make sure it's not syntax glue to get/set dict. */
3819 if (JimNameIsDictSugar(varName
, len
)) {
3820 return JIM_DICT_SUGAR
;
3823 if (varName
[0] == ':' && varName
[1] == ':') {
3824 framePtr
= interp
->topFramePtr
;
3825 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
+ 2);
3831 /* Lookup this name into the variables hash table */
3832 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
);
3834 /* Try with static vars. */
3835 if (framePtr
->staticVars
== NULL
)
3837 if (!(he
= Jim_FindHashEntry(framePtr
->staticVars
, varName
)))
3841 /* Free the old internal repr and set the new one. */
3842 Jim_FreeIntRep(interp
, objPtr
);
3843 objPtr
->typePtr
= &variableObjType
;
3844 objPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3845 objPtr
->internalRep
.varValue
.varPtr
= (void *)he
->u
.val
;
3849 /* -------------------- Variables related functions ------------------------- */
3850 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, Jim_Obj
*valObjPtr
);
3851 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, int flags
);
3853 /* For now that's dummy. Variables lookup should be optimized
3854 * in many ways, with caching of lookups, and possibly with
3855 * a table of pre-allocated vars in every CallFrame for local vars.
3856 * All the caching should also have an 'epoch' mechanism similar
3857 * to the one used by Tcl for procedures lookup caching. */
3859 int Jim_SetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
3865 if ((err
= SetVariableFromAny(interp
, nameObjPtr
)) != JIM_OK
) {
3866 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3868 /* Check for [dict] syntax sugar. */
3869 if (err
== JIM_DICT_SUGAR
)
3870 return JimDictSugarSet(interp
, nameObjPtr
, valObjPtr
);
3872 if (JimValidName(interp
, "variable", nameObjPtr
) != JIM_OK
) {
3876 /* New variable to create */
3877 name
= Jim_String(nameObjPtr
);
3879 var
= Jim_Alloc(sizeof(*var
));
3880 var
->objPtr
= valObjPtr
;
3881 Jim_IncrRefCount(valObjPtr
);
3882 var
->linkFramePtr
= NULL
;
3883 /* Insert the new variable */
3884 if (name
[0] == ':' && name
[1] == ':') {
3885 /* Into the top level frame */
3886 framePtr
= interp
->topFramePtr
;
3887 Jim_AddHashEntry(&framePtr
->vars
, name
+ 2, var
);
3890 Jim_AddHashEntry(&framePtr
->vars
, name
, var
);
3892 /* Make the object int rep a variable */
3893 Jim_FreeIntRep(interp
, nameObjPtr
);
3894 nameObjPtr
->typePtr
= &variableObjType
;
3895 nameObjPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3896 nameObjPtr
->internalRep
.varValue
.varPtr
= var
;
3899 var
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3900 if (var
->linkFramePtr
== NULL
) {
3901 Jim_IncrRefCount(valObjPtr
);
3902 Jim_DecrRefCount(interp
, var
->objPtr
);
3903 var
->objPtr
= valObjPtr
;
3905 else { /* Else handle the link */
3906 Jim_CallFrame
*savedCallFrame
;
3908 savedCallFrame
= interp
->framePtr
;
3909 interp
->framePtr
= var
->linkFramePtr
;
3910 err
= Jim_SetVariable(interp
, var
->objPtr
, valObjPtr
);
3911 interp
->framePtr
= savedCallFrame
;
3919 int Jim_SetVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
3921 Jim_Obj
*nameObjPtr
;
3924 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
3925 Jim_IncrRefCount(nameObjPtr
);
3926 result
= Jim_SetVariable(interp
, nameObjPtr
, objPtr
);
3927 Jim_DecrRefCount(interp
, nameObjPtr
);
3931 int Jim_SetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
3933 Jim_CallFrame
*savedFramePtr
;
3936 savedFramePtr
= interp
->framePtr
;
3937 interp
->framePtr
= interp
->topFramePtr
;
3938 result
= Jim_SetVariableStr(interp
, name
, objPtr
);
3939 interp
->framePtr
= savedFramePtr
;
3943 int Jim_SetVariableStrWithStr(Jim_Interp
*interp
, const char *name
, const char *val
)
3945 Jim_Obj
*nameObjPtr
, *valObjPtr
;
3948 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
3949 valObjPtr
= Jim_NewStringObj(interp
, val
, -1);
3950 Jim_IncrRefCount(nameObjPtr
);
3951 Jim_IncrRefCount(valObjPtr
);
3952 result
= Jim_SetVariable(interp
, nameObjPtr
, valObjPtr
);
3953 Jim_DecrRefCount(interp
, nameObjPtr
);
3954 Jim_DecrRefCount(interp
, valObjPtr
);
3958 int Jim_SetVariableLink(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
3959 Jim_Obj
*targetNameObjPtr
, Jim_CallFrame
*targetCallFrame
)
3961 const char *varName
;
3964 varName
= Jim_GetString(nameObjPtr
, &len
);
3966 if (varName
[0] == ':' && varName
[1] == ':') {
3967 /* Linking a global var does nothing */
3971 if (JimNameIsDictSugar(varName
, len
)) {
3972 Jim_SetResultString(interp
, "Dict key syntax invalid as link source", -1);
3976 /* Check for an existing variable or link */
3977 if (SetVariableFromAny(interp
, nameObjPtr
) == JIM_OK
) {
3978 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3980 if (varPtr
->linkFramePtr
== NULL
) {
3981 Jim_SetResultFormatted(interp
, "variable \"%#s\" already exists", nameObjPtr
);
3985 /* It exists, but is a link, so delete the link */
3986 varPtr
->linkFramePtr
= NULL
;
3989 /* Check for cycles. */
3990 if (interp
->framePtr
== targetCallFrame
) {
3991 Jim_Obj
*objPtr
= targetNameObjPtr
;
3994 /* Cycles are only possible with 'uplevel 0' */
3996 if (Jim_StringEqObj(objPtr
, nameObjPtr
)) {
3997 Jim_SetResultString(interp
, "can't upvar from variable to itself", -1);
4000 if (SetVariableFromAny(interp
, objPtr
) != JIM_OK
)
4002 varPtr
= objPtr
->internalRep
.varValue
.varPtr
;
4003 if (varPtr
->linkFramePtr
!= targetCallFrame
)
4005 objPtr
= varPtr
->objPtr
;
4009 /* Perform the binding */
4010 Jim_SetVariable(interp
, nameObjPtr
, targetNameObjPtr
);
4011 /* We are now sure 'nameObjPtr' type is variableObjType */
4012 nameObjPtr
->internalRep
.varValue
.varPtr
->linkFramePtr
= targetCallFrame
;
4016 /* Return the Jim_Obj pointer associated with a variable name,
4017 * or NULL if the variable was not found in the current context.
4018 * The same optimization discussed in the comment to the
4019 * 'SetVariable' function should apply here.
4021 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4022 * in a dictionary which is shared, the array variable value is duplicated first.
4023 * This allows the array element to be updated (e.g. append, lappend) without
4024 * affecting other references to the dictionary.
4026 Jim_Obj
*Jim_GetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4028 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4030 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4032 if (varPtr
->linkFramePtr
== NULL
) {
4033 return varPtr
->objPtr
;
4038 /* The variable is a link? Resolve it. */
4039 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
4041 interp
->framePtr
= varPtr
->linkFramePtr
;
4042 objPtr
= Jim_GetVariable(interp
, varPtr
->objPtr
, flags
);
4043 interp
->framePtr
= savedCallFrame
;
4047 /* Error, so fall through to the error message */
4052 case JIM_DICT_SUGAR
:
4053 /* [dict] syntax sugar. */
4054 return JimDictSugarGet(interp
, nameObjPtr
, flags
);
4056 if (flags
& JIM_ERRMSG
) {
4057 Jim_SetResultFormatted(interp
, "can't read \"%#s\": no such variable", nameObjPtr
);
4062 Jim_Obj
*Jim_GetGlobalVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4064 Jim_CallFrame
*savedFramePtr
;
4067 savedFramePtr
= interp
->framePtr
;
4068 interp
->framePtr
= interp
->topFramePtr
;
4069 objPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4070 interp
->framePtr
= savedFramePtr
;
4075 Jim_Obj
*Jim_GetVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4077 Jim_Obj
*nameObjPtr
, *varObjPtr
;
4079 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4080 Jim_IncrRefCount(nameObjPtr
);
4081 varObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4082 Jim_DecrRefCount(interp
, nameObjPtr
);
4086 Jim_Obj
*Jim_GetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4088 Jim_CallFrame
*savedFramePtr
;
4091 savedFramePtr
= interp
->framePtr
;
4092 interp
->framePtr
= interp
->topFramePtr
;
4093 objPtr
= Jim_GetVariableStr(interp
, name
, flags
);
4094 interp
->framePtr
= savedFramePtr
;
4099 /* Unset a variable.
4100 * Note: On success unset invalidates all the variable objects created
4101 * in the current call frame incrementing. */
4102 int Jim_UnsetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4108 retval
= SetVariableFromAny(interp
, nameObjPtr
);
4109 if (retval
== JIM_DICT_SUGAR
) {
4110 /* [dict] syntax sugar. */
4111 return JimDictSugarSet(interp
, nameObjPtr
, NULL
);
4113 else if (retval
== JIM_OK
) {
4114 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4116 /* If it's a link call UnsetVariable recursively */
4117 if (varPtr
->linkFramePtr
) {
4118 Jim_CallFrame
*savedCallFrame
;
4120 savedCallFrame
= interp
->framePtr
;
4121 interp
->framePtr
= varPtr
->linkFramePtr
;
4122 retval
= Jim_UnsetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
4123 interp
->framePtr
= savedCallFrame
;
4126 Jim_CallFrame
*framePtr
= interp
->framePtr
;
4128 name
= Jim_String(nameObjPtr
);
4129 if (name
[0] == ':' && name
[1] == ':') {
4130 framePtr
= interp
->topFramePtr
;
4133 retval
= Jim_DeleteHashEntry(&framePtr
->vars
, name
);
4134 if (retval
== JIM_OK
) {
4135 /* Change the callframe id, invalidating var lookup caching */
4136 JimChangeCallFrameId(interp
, framePtr
);
4140 if (retval
!= JIM_OK
&& (flags
& JIM_ERRMSG
)) {
4141 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such variable", nameObjPtr
);
4146 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4148 /* Given a variable name for [dict] operation syntax sugar,
4149 * this function returns two objects, the first with the name
4150 * of the variable to set, and the second with the rispective key.
4151 * For example "foo(bar)" will return objects with string repr. of
4154 * The returned objects have refcount = 1. The function can't fail. */
4155 static void JimDictSugarParseVarKey(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
4156 Jim_Obj
**varPtrPtr
, Jim_Obj
**keyPtrPtr
)
4158 const char *str
, *p
;
4160 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4162 str
= Jim_GetString(objPtr
, &len
);
4164 p
= strchr(str
, '(');
4165 JimPanic((p
== NULL
, interp
, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str
));
4167 varObjPtr
= Jim_NewStringObj(interp
, str
, p
- str
);
4170 keyLen
= (str
+ len
) - p
;
4171 if (str
[len
- 1] == ')') {
4175 /* Create the objects with the variable name and key. */
4176 keyObjPtr
= Jim_NewStringObj(interp
, p
, keyLen
);
4178 Jim_IncrRefCount(varObjPtr
);
4179 Jim_IncrRefCount(keyObjPtr
);
4180 *varPtrPtr
= varObjPtr
;
4181 *keyPtrPtr
= keyObjPtr
;
4184 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4185 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4186 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*valObjPtr
)
4190 SetDictSubstFromAny(interp
, objPtr
);
4192 err
= Jim_SetDictKeysVector(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4193 &objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, 1, valObjPtr
);
4195 if (err
== JIM_OK
) {
4196 /* Don't keep an extra ref to the result */
4197 Jim_SetEmptyResult(interp
);
4201 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4202 if (Jim_GetVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
, JIM_NONE
)) {
4203 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such element in array",
4208 /* Make the error more informative and Tcl-compatible */
4209 Jim_SetResultFormatted(interp
, "can't %s \"%#s\": variable isn't array",
4210 (valObjPtr
? "set" : "unset"), objPtr
);
4216 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4218 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4219 * and stored back to the variable before expansion.
4221 static Jim_Obj
*JimDictExpandArrayVariable(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
,
4222 Jim_Obj
*keyObjPtr
, int flags
)
4224 Jim_Obj
*dictObjPtr
;
4225 Jim_Obj
*resObjPtr
= NULL
;
4228 dictObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
4233 ret
= Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4234 if (ret
!= JIM_OK
) {
4237 Jim_SetResultFormatted(interp
,
4238 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr
, keyObjPtr
);
4241 Jim_SetResultFormatted(interp
,
4242 "can't read \"%#s(%#s)\": no such element in array", varObjPtr
, keyObjPtr
);
4245 else if ((flags
& JIM_UNSHARED
) && Jim_IsShared(dictObjPtr
)) {
4246 dictObjPtr
= Jim_DuplicateObj(interp
, dictObjPtr
);
4247 if (Jim_SetVariable(interp
, varObjPtr
, dictObjPtr
) != JIM_OK
) {
4248 /* This can probably never happen */
4249 JimPanic((1, interp
, "SetVariable failed for JIM_UNSHARED"));
4251 /* We know that the key exists. Get the result in the now-unshared dictionary */
4252 Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4258 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4259 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4261 SetDictSubstFromAny(interp
, objPtr
);
4263 return JimDictExpandArrayVariable(interp
,
4264 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4265 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, flags
);
4268 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4270 void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4272 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
4273 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
4276 void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4278 JIM_NOTUSED(interp
);
4280 dupPtr
->internalRep
.dictSubstValue
.varNameObjPtr
=
4281 srcPtr
->internalRep
.dictSubstValue
.varNameObjPtr
;
4282 dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
= srcPtr
->internalRep
.dictSubstValue
.indexObjPtr
;
4283 dupPtr
->typePtr
= &dictSubstObjType
;
4286 /* Note: The object *must* be in dict-sugar format */
4287 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4289 if (objPtr
->typePtr
!= &dictSubstObjType
) {
4290 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4292 if (objPtr
->typePtr
== &interpolatedObjType
) {
4293 /* An interpolated object in dict-sugar form */
4295 const ScriptToken
*token
= objPtr
->internalRep
.twoPtrValue
.ptr1
;
4297 varObjPtr
= token
[0].objPtr
;
4298 keyObjPtr
= objPtr
->internalRep
.twoPtrValue
.ptr2
;
4300 Jim_IncrRefCount(varObjPtr
);
4301 Jim_IncrRefCount(keyObjPtr
);
4304 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
4307 Jim_FreeIntRep(interp
, objPtr
);
4308 objPtr
->typePtr
= &dictSubstObjType
;
4309 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= varObjPtr
;
4310 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= keyObjPtr
;
4314 /* This function is used to expand [dict get] sugar in the form
4315 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4316 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4317 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4318 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4319 * the [dict]ionary contained in variable VARNAME. */
4320 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4322 Jim_Obj
*resObjPtr
= NULL
;
4323 Jim_Obj
*substKeyObjPtr
= NULL
;
4325 SetDictSubstFromAny(interp
, objPtr
);
4327 if (Jim_SubstObj(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
,
4328 &substKeyObjPtr
, JIM_NONE
)
4332 Jim_IncrRefCount(substKeyObjPtr
);
4334 JimDictExpandArrayVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4336 Jim_DecrRefCount(interp
, substKeyObjPtr
);
4341 static Jim_Obj
*JimExpandExprSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4343 Jim_Obj
*resultObjPtr
;
4345 if (Jim_EvalExpression(interp
, objPtr
, &resultObjPtr
) == JIM_OK
) {
4346 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4347 resultObjPtr
->refCount
--;
4348 return resultObjPtr
;
4353 /* -----------------------------------------------------------------------------
4355 * ---------------------------------------------------------------------------*/
4357 static Jim_CallFrame
*JimCreateCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*parent
)
4361 if (interp
->freeFramesList
) {
4362 cf
= interp
->freeFramesList
;
4363 interp
->freeFramesList
= cf
->nextFramePtr
;
4366 cf
= Jim_Alloc(sizeof(*cf
));
4367 cf
->vars
.table
= NULL
;
4370 cf
->id
= interp
->callFrameEpoch
++;
4371 cf
->parentCallFrame
= parent
;
4372 cf
->level
= parent
? parent
->level
+ 1 : 0;
4375 cf
->procArgsObjPtr
= NULL
;
4376 cf
->procBodyObjPtr
= NULL
;
4377 cf
->nextFramePtr
= NULL
;
4378 cf
->staticVars
= NULL
;
4379 if (cf
->vars
.table
== NULL
)
4380 Jim_InitHashTable(&cf
->vars
, &JimVariablesHashTableType
, interp
);
4384 /* Used to invalidate every caching related to callframe stability. */
4385 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
)
4387 cf
->id
= interp
->callFrameEpoch
++;
4390 #define JIM_FCF_NONE 0 /* no flags */
4391 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4392 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
)
4394 if (cf
->procArgsObjPtr
)
4395 Jim_DecrRefCount(interp
, cf
->procArgsObjPtr
);
4396 if (cf
->procBodyObjPtr
)
4397 Jim_DecrRefCount(interp
, cf
->procBodyObjPtr
);
4398 if (!(flags
& JIM_FCF_NOHT
))
4399 Jim_FreeHashTable(&cf
->vars
);
4402 Jim_HashEntry
**table
= cf
->vars
.table
, *he
;
4404 for (i
= 0; i
< JIM_HT_INITIAL_SIZE
; i
++) {
4406 while (he
!= NULL
) {
4407 Jim_HashEntry
*nextEntry
= he
->next
;
4408 Jim_Var
*varPtr
= (void *)he
->u
.val
;
4410 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
4411 Jim_Free(he
->u
.val
);
4412 Jim_Free((void *)he
->key
); /* ATTENTION: const cast */
4420 cf
->nextFramePtr
= interp
->freeFramesList
;
4421 interp
->freeFramesList
= cf
;
4424 /* -----------------------------------------------------------------------------
4426 * ---------------------------------------------------------------------------*/
4427 #ifdef JIM_REFERENCES
4429 /* References HashTable Type.
4431 * Keys are jim_wide integers, dynamically allocated for now but in the
4432 * future it's worth to cache this 8 bytes objects. Values are poitners
4433 * to Jim_References. */
4434 static void JimReferencesHTValDestructor(void *interp
, void *val
)
4436 Jim_Reference
*refPtr
= (void *)val
;
4438 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
4439 if (refPtr
->finalizerCmdNamePtr
!= NULL
) {
4440 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4445 static unsigned int JimReferencesHTHashFunction(const void *key
)
4447 /* Only the least significant bits are used. */
4448 const jim_wide
*widePtr
= key
;
4449 unsigned int intValue
= (unsigned int)*widePtr
;
4451 return Jim_IntHashFunction(intValue
);
4454 static const void *JimReferencesHTKeyDup(void *privdata
, const void *key
)
4456 void *copy
= Jim_Alloc(sizeof(jim_wide
));
4458 JIM_NOTUSED(privdata
);
4460 memcpy(copy
, key
, sizeof(jim_wide
));
4464 static int JimReferencesHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
4466 JIM_NOTUSED(privdata
);
4468 return memcmp(key1
, key2
, sizeof(jim_wide
)) == 0;
4471 static void JimReferencesHTKeyDestructor(void *privdata
, const void *key
)
4473 JIM_NOTUSED(privdata
);
4475 Jim_Free((void *)key
);
4478 static const Jim_HashTableType JimReferencesHashTableType
= {
4479 JimReferencesHTHashFunction
, /* hash function */
4480 JimReferencesHTKeyDup
, /* key dup */
4482 JimReferencesHTKeyCompare
, /* key compare */
4483 JimReferencesHTKeyDestructor
, /* key destructor */
4484 JimReferencesHTValDestructor
/* val destructor */
4487 /* -----------------------------------------------------------------------------
4488 * Reference object type and References API
4489 * ---------------------------------------------------------------------------*/
4491 /* The string representation of references has two features in order
4492 * to make the GC faster. The first is that every reference starts
4493 * with a non common character '<', in order to make the string matching
4494 * faster. The second is that the reference string rep is 42 characters
4495 * in length, this allows to avoid to check every object with a string
4496 * repr < 42, and usually there aren't many of these objects. */
4498 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4500 static int JimFormatReference(char *buf
, Jim_Reference
*refPtr
, jim_wide id
)
4502 const char *fmt
= "<reference.<%s>.%020" JIM_WIDE_MODIFIER
">";
4504 sprintf(buf
, fmt
, refPtr
->tag
, id
);
4505 return JIM_REFERENCE_SPACE
;
4508 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
);
4510 static const Jim_ObjType referenceObjType
= {
4514 UpdateStringOfReference
,
4515 JIM_TYPE_REFERENCES
,
4518 void UpdateStringOfReference(struct Jim_Obj
*objPtr
)
4521 char buf
[JIM_REFERENCE_SPACE
+ 1];
4522 Jim_Reference
*refPtr
;
4524 refPtr
= objPtr
->internalRep
.refValue
.refPtr
;
4525 len
= JimFormatReference(buf
, refPtr
, objPtr
->internalRep
.refValue
.id
);
4526 objPtr
->bytes
= Jim_Alloc(len
+ 1);
4527 memcpy(objPtr
->bytes
, buf
, len
+ 1);
4528 objPtr
->length
= len
;
4531 /* returns true if 'c' is a valid reference tag character.
4532 * i.e. inside the range [_a-zA-Z0-9] */
4533 static int isrefchar(int c
)
4535 return (c
== '_' || isalnum(c
));
4538 static int SetReferenceFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4542 const char *str
, *start
, *end
;
4544 Jim_Reference
*refPtr
;
4547 /* Get the string representation */
4548 str
= Jim_GetString(objPtr
, &len
);
4549 /* Check if it looks like a reference */
4550 if (len
< JIM_REFERENCE_SPACE
)
4554 end
= str
+ len
- 1;
4555 while (*start
== ' ')
4557 while (*end
== ' ' && end
> start
)
4559 if (end
- start
+ 1 != JIM_REFERENCE_SPACE
)
4561 /* <reference.<1234567>.%020> */
4562 if (memcmp(start
, "<reference.<", 12) != 0)
4564 if (start
[12 + JIM_REFERENCE_TAGLEN
] != '>' || end
[0] != '>')
4566 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4567 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4568 if (!isrefchar(start
[12 + i
]))
4571 /* Extract info from the reference. */
4572 memcpy(refId
, start
+ 14 + JIM_REFERENCE_TAGLEN
, 20);
4574 /* Try to convert the ID into a jim_wide */
4575 if (Jim_StringToWide(refId
, &wideValue
, 10) != JIM_OK
)
4577 /* Check if the reference really exists! */
4578 he
= Jim_FindHashEntry(&interp
->references
, &wideValue
);
4580 Jim_SetResultFormatted(interp
, "invalid reference id \"%#s\"", objPtr
);
4584 /* Free the old internal repr and set the new one. */
4585 Jim_FreeIntRep(interp
, objPtr
);
4586 objPtr
->typePtr
= &referenceObjType
;
4587 objPtr
->internalRep
.refValue
.id
= wideValue
;
4588 objPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4592 Jim_SetResultFormatted(interp
, "expected reference but got \"%#s\"", objPtr
);
4596 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4597 * as finalizer command (or NULL if there is no finalizer).
4598 * The returned reference object has refcount = 0. */
4599 Jim_Obj
*Jim_NewReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*tagPtr
, Jim_Obj
*cmdNamePtr
)
4601 struct Jim_Reference
*refPtr
;
4602 jim_wide wideValue
= interp
->referenceNextId
;
4607 /* Perform the Garbage Collection if needed. */
4608 Jim_CollectIfNeeded(interp
);
4610 refPtr
= Jim_Alloc(sizeof(*refPtr
));
4611 refPtr
->objPtr
= objPtr
;
4612 Jim_IncrRefCount(objPtr
);
4613 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4615 Jim_IncrRefCount(cmdNamePtr
);
4616 Jim_AddHashEntry(&interp
->references
, &wideValue
, refPtr
);
4617 refObjPtr
= Jim_NewObj(interp
);
4618 refObjPtr
->typePtr
= &referenceObjType
;
4619 refObjPtr
->bytes
= NULL
;
4620 refObjPtr
->internalRep
.refValue
.id
= interp
->referenceNextId
;
4621 refObjPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4622 interp
->referenceNextId
++;
4623 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4624 * that does not pass the 'isrefchar' test is replaced with '_' */
4625 tag
= Jim_GetString(tagPtr
, &tagLen
);
4626 if (tagLen
> JIM_REFERENCE_TAGLEN
)
4627 tagLen
= JIM_REFERENCE_TAGLEN
;
4628 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4629 if (i
< tagLen
&& isrefchar(tag
[i
]))
4630 refPtr
->tag
[i
] = tag
[i
];
4632 refPtr
->tag
[i
] = '_';
4634 refPtr
->tag
[JIM_REFERENCE_TAGLEN
] = '\0';
4638 Jim_Reference
*Jim_GetReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4640 if (objPtr
->typePtr
!= &referenceObjType
&& SetReferenceFromAny(interp
, objPtr
) == JIM_ERR
)
4642 return objPtr
->internalRep
.refValue
.refPtr
;
4645 int Jim_SetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*cmdNamePtr
)
4647 Jim_Reference
*refPtr
;
4649 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4651 Jim_IncrRefCount(cmdNamePtr
);
4652 if (refPtr
->finalizerCmdNamePtr
)
4653 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4654 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4658 int Jim_GetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
**cmdNamePtrPtr
)
4660 Jim_Reference
*refPtr
;
4662 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4664 *cmdNamePtrPtr
= refPtr
->finalizerCmdNamePtr
;
4668 /* -----------------------------------------------------------------------------
4669 * References Garbage Collection
4670 * ---------------------------------------------------------------------------*/
4672 /* This the hash table type for the "MARK" phase of the GC */
4673 static const Jim_HashTableType JimRefMarkHashTableType
= {
4674 JimReferencesHTHashFunction
, /* hash function */
4675 JimReferencesHTKeyDup
, /* key dup */
4677 JimReferencesHTKeyCompare
, /* key compare */
4678 JimReferencesHTKeyDestructor
, /* key destructor */
4679 NULL
/* val destructor */
4682 /* Performs the garbage collection. */
4683 int Jim_Collect(Jim_Interp
*interp
)
4685 Jim_HashTable marks
;
4686 Jim_HashTableIterator
*htiter
;
4691 /* Avoid recursive calls */
4692 if (interp
->lastCollectId
== -1) {
4693 /* Jim_Collect() already running. Return just now. */
4696 interp
->lastCollectId
= -1;
4698 /* Mark all the references found into the 'mark' hash table.
4699 * The references are searched in every live object that
4700 * is of a type that can contain references. */
4701 Jim_InitHashTable(&marks
, &JimRefMarkHashTableType
, NULL
);
4702 objPtr
= interp
->liveList
;
4704 if (objPtr
->typePtr
== NULL
|| objPtr
->typePtr
->flags
& JIM_TYPE_REFERENCES
) {
4705 const char *str
, *p
;
4708 /* If the object is of type reference, to get the
4709 * Id is simple... */
4710 if (objPtr
->typePtr
== &referenceObjType
) {
4711 Jim_AddHashEntry(&marks
, &objPtr
->internalRep
.refValue
.id
, NULL
);
4713 printf("MARK (reference): %d refcount: %d" JIM_NL
,
4714 (int)objPtr
->internalRep
.refValue
.id
, objPtr
->refCount
);
4716 objPtr
= objPtr
->nextObjPtr
;
4719 /* Get the string repr of the object we want
4720 * to scan for references. */
4721 p
= str
= Jim_GetString(objPtr
, &len
);
4722 /* Skip objects too little to contain references. */
4723 if (len
< JIM_REFERENCE_SPACE
) {
4724 objPtr
= objPtr
->nextObjPtr
;
4727 /* Extract references from the object string repr. */
4733 if ((p
= strstr(p
, "<reference.<")) == NULL
)
4735 /* Check if it's a valid reference. */
4736 if (len
- (p
- str
) < JIM_REFERENCE_SPACE
)
4738 if (p
[41] != '>' || p
[19] != '>' || p
[20] != '.')
4740 for (i
= 21; i
<= 40; i
++)
4741 if (!isdigit(UCHAR(p
[i
])))
4744 memcpy(buf
, p
+ 21, 20);
4746 Jim_StringToWide(buf
, &id
, 10);
4748 /* Ok, a reference for the given ID
4749 * was found. Mark it. */
4750 Jim_AddHashEntry(&marks
, &id
, NULL
);
4752 printf("MARK: %d" JIM_NL
, (int)id
);
4754 p
+= JIM_REFERENCE_SPACE
;
4757 objPtr
= objPtr
->nextObjPtr
;
4760 /* Run the references hash table to destroy every reference that
4761 * is not referenced outside (not present in the mark HT). */
4762 htiter
= Jim_GetHashTableIterator(&interp
->references
);
4763 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
4764 const jim_wide
*refId
;
4765 Jim_Reference
*refPtr
;
4768 /* Check if in the mark phase we encountered
4769 * this reference. */
4770 if (Jim_FindHashEntry(&marks
, refId
) == NULL
) {
4772 printf("COLLECTING %d" JIM_NL
, (int)*refId
);
4775 /* Drop the reference, but call the
4776 * finalizer first if registered. */
4778 if (refPtr
->finalizerCmdNamePtr
) {
4779 char *refstr
= Jim_Alloc(JIM_REFERENCE_SPACE
+ 1);
4780 Jim_Obj
*objv
[3], *oldResult
;
4782 JimFormatReference(refstr
, refPtr
, *refId
);
4784 objv
[0] = refPtr
->finalizerCmdNamePtr
;
4785 objv
[1] = Jim_NewStringObjNoAlloc(interp
, refstr
, 32);
4786 objv
[2] = refPtr
->objPtr
;
4787 Jim_IncrRefCount(objv
[0]);
4788 Jim_IncrRefCount(objv
[1]);
4789 Jim_IncrRefCount(objv
[2]);
4791 /* Drop the reference itself */
4792 Jim_DeleteHashEntry(&interp
->references
, refId
);
4794 /* Call the finalizer. Errors ignored. */
4795 oldResult
= interp
->result
;
4796 Jim_IncrRefCount(oldResult
);
4797 Jim_EvalObjVector(interp
, 3, objv
);
4798 Jim_SetResult(interp
, oldResult
);
4799 Jim_DecrRefCount(interp
, oldResult
);
4801 Jim_DecrRefCount(interp
, objv
[0]);
4802 Jim_DecrRefCount(interp
, objv
[1]);
4803 Jim_DecrRefCount(interp
, objv
[2]);
4806 Jim_DeleteHashEntry(&interp
->references
, refId
);
4810 Jim_FreeHashTableIterator(htiter
);
4811 Jim_FreeHashTable(&marks
);
4812 interp
->lastCollectId
= interp
->referenceNextId
;
4813 interp
->lastCollectTime
= time(NULL
);
4817 #define JIM_COLLECT_ID_PERIOD 5000
4818 #define JIM_COLLECT_TIME_PERIOD 300
4820 void Jim_CollectIfNeeded(Jim_Interp
*interp
)
4825 elapsedId
= interp
->referenceNextId
- interp
->lastCollectId
;
4826 elapsedTime
= time(NULL
) - interp
->lastCollectTime
;
4829 if (elapsedId
> JIM_COLLECT_ID_PERIOD
|| elapsedTime
> JIM_COLLECT_TIME_PERIOD
) {
4830 Jim_Collect(interp
);
4835 static int JimIsBigEndian(void)
4842 return uval
.c
[0] == 1;
4845 /* -----------------------------------------------------------------------------
4846 * Interpreter related functions
4847 * ---------------------------------------------------------------------------*/
4849 Jim_Interp
*Jim_CreateInterp(void)
4851 Jim_Interp
*i
= Jim_Alloc(sizeof(*i
));
4854 i
->errorFileName
= Jim_StrDup("");
4855 i
->addStackTrace
= 0;
4856 i
->maxNestingDepth
= JIM_MAX_NESTING_DEPTH
;
4857 i
->returnCode
= JIM_OK
;
4861 i
->callFrameEpoch
= 0;
4862 i
->liveList
= i
->freeList
= NULL
;
4863 i
->referenceNextId
= 0;
4864 i
->lastCollectId
= 0;
4865 i
->lastCollectTime
= time(NULL
);
4866 i
->freeFramesList
= NULL
;
4867 i
->prngState
= NULL
;
4870 i
->signal_level
= 0;
4871 i
->signal_set_result
= NULL
;
4872 i
->localProcs
= NULL
;
4873 i
->loadHandles
= NULL
;
4875 /* Note that we can create objects only after the
4876 * interpreter liveList and freeList pointers are
4877 * initialized to NULL. */
4878 Jim_InitHashTable(&i
->commands
, &JimCommandsHashTableType
, i
);
4880 #ifdef JIM_REFERENCES
4881 Jim_InitHashTable(&i
->references
, &JimReferencesHashTableType
, i
);
4883 Jim_InitHashTable(&i
->sharedStrings
, &JimSharedStringsHashTableType
, NULL
);
4884 Jim_InitHashTable(&i
->assocData
, &JimAssocDataHashTableType
, i
);
4885 Jim_InitHashTable(&i
->packages
, &JimStringKeyValCopyHashTableType
, NULL
);
4886 i
->framePtr
= i
->topFramePtr
= JimCreateCallFrame(i
, NULL
);
4887 i
->emptyObj
= Jim_NewEmptyStringObj(i
);
4888 i
->trueObj
= Jim_NewIntObj(i
, 1);
4889 i
->falseObj
= Jim_NewIntObj(i
, 0);
4890 i
->result
= i
->emptyObj
;
4891 i
->stackTrace
= Jim_NewListObj(i
, NULL
, 0);
4892 i
->unknown
= Jim_NewStringObj(i
, "unknown", -1);
4893 i
->unknown_called
= 0;
4894 i
->errorProc
= i
->emptyObj
;
4895 i
->currentScriptObj
= Jim_NewEmptyStringObj(i
);
4896 Jim_IncrRefCount(i
->emptyObj
);
4897 Jim_IncrRefCount(i
->result
);
4898 Jim_IncrRefCount(i
->stackTrace
);
4899 Jim_IncrRefCount(i
->unknown
);
4900 Jim_IncrRefCount(i
->currentScriptObj
);
4901 Jim_IncrRefCount(i
->errorProc
);
4902 Jim_IncrRefCount(i
->trueObj
);
4903 Jim_IncrRefCount(i
->falseObj
);
4905 /* Initialize key variables every interpreter should contain */
4906 Jim_SetVariableStrWithStr(i
, JIM_LIBPATH
, TCL_LIBRARY
);
4907 Jim_SetVariableStrWithStr(i
, JIM_INTERACTIVE
, "0");
4909 Jim_SetVariableStrWithStr(i
, "tcl_platform(os)", TCL_PLATFORM_OS
);
4910 Jim_SetVariableStrWithStr(i
, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM
);
4911 Jim_SetVariableStrWithStr(i
, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4912 Jim_SetVariableStrWithStr(i
, "tcl_platform(threaded)", "0");
4913 Jim_SetVariableStr(i
, "tcl_platform(pointerSize)", Jim_NewIntObj(i
, sizeof(void *)));
4914 Jim_SetVariableStr(i
, "tcl_platform(wordSize)", Jim_NewIntObj(i
, sizeof(jim_wide
)));
4919 void Jim_FreeInterp(Jim_Interp
*i
)
4921 Jim_CallFrame
*cf
= i
->framePtr
, *prevcf
, *nextcf
;
4922 Jim_Obj
*objPtr
, *nextObjPtr
;
4924 Jim_DecrRefCount(i
, i
->emptyObj
);
4925 Jim_DecrRefCount(i
, i
->trueObj
);
4926 Jim_DecrRefCount(i
, i
->falseObj
);
4927 Jim_DecrRefCount(i
, i
->result
);
4928 Jim_DecrRefCount(i
, i
->stackTrace
);
4929 Jim_DecrRefCount(i
, i
->errorProc
);
4930 Jim_DecrRefCount(i
, i
->unknown
);
4931 Jim_Free((void *)i
->errorFileName
);
4932 Jim_DecrRefCount(i
, i
->currentScriptObj
);
4933 Jim_FreeHashTable(&i
->commands
);
4934 #ifdef JIM_REFERENCES
4935 Jim_FreeHashTable(&i
->references
);
4937 Jim_FreeHashTable(&i
->packages
);
4938 Jim_Free(i
->prngState
);
4939 Jim_FreeHashTable(&i
->assocData
);
4940 JimDeleteLocalProcs(i
);
4942 /* Free the call frames list */
4944 prevcf
= cf
->parentCallFrame
;
4945 JimFreeCallFrame(i
, cf
, JIM_FCF_NONE
);
4948 /* Check that the live object list is empty, otherwise
4949 * there is a memory leak. */
4950 if (i
->liveList
!= NULL
) {
4951 objPtr
= i
->liveList
;
4953 printf(JIM_NL
"-------------------------------------" JIM_NL
);
4954 printf("Objects still in the free list:" JIM_NL
);
4956 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "string";
4958 printf("%p (%d) %-10s: '%.20s'" JIM_NL
,
4959 (void *)objPtr
, objPtr
->refCount
, type
, objPtr
->bytes
? objPtr
->bytes
: "(null)");
4960 if (objPtr
->typePtr
== &sourceObjType
) {
4961 printf("FILE %s LINE %d" JIM_NL
,
4962 objPtr
->internalRep
.sourceValue
.fileName
,
4963 objPtr
->internalRep
.sourceValue
.lineNumber
);
4965 objPtr
= objPtr
->nextObjPtr
;
4967 printf("-------------------------------------" JIM_NL JIM_NL
);
4968 JimPanic((1, i
, "Live list non empty freeing the interpreter! Leak?"));
4970 /* Free all the freed objects. */
4971 objPtr
= i
->freeList
;
4973 nextObjPtr
= objPtr
->nextObjPtr
;
4975 objPtr
= nextObjPtr
;
4977 /* Free cached CallFrame structures */
4978 cf
= i
->freeFramesList
;
4980 nextcf
= cf
->nextFramePtr
;
4981 if (cf
->vars
.table
!= NULL
)
4982 Jim_Free(cf
->vars
.table
);
4987 Jim_FreeLoadHandles(i
);
4990 /* Free the sharedString hash table. Make sure to free it
4991 * after every other Jim_Object was freed. */
4992 Jim_FreeHashTable(&i
->sharedStrings
);
4993 /* Free the interpreter structure. */
4997 /* Returns the call frame relative to the level represented by
4998 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5000 * This function accepts the 'level' argument in the form
5001 * of the commands [uplevel] and [upvar].
5003 * For a function accepting a relative integer as level suitable
5004 * for implementation of [info level ?level?] check the
5005 * JimGetCallFrameByInteger() function.
5007 * Returns NULL on error.
5009 Jim_CallFrame
*Jim_GetCallFrameByLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5013 Jim_CallFrame
*framePtr
;
5016 str
= Jim_String(levelObjPtr
);
5017 if (str
[0] == '#') {
5020 level
= strtol(str
+ 1, &endptr
, 0);
5021 if (str
[1] == '\0' || endptr
[0] != '\0') {
5026 if (Jim_GetLong(interp
, levelObjPtr
, &level
) != JIM_OK
|| level
< 0) {
5030 /* Convert from a relative to an absolute level */
5031 level
= interp
->framePtr
->level
- level
;
5036 str
= "1"; /* Needed to format the error message. */
5037 level
= interp
->framePtr
->level
- 1;
5041 return interp
->topFramePtr
;
5045 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5046 if (framePtr
->level
== level
) {
5052 Jim_SetResultFormatted(interp
, "bad level \"%s\"", str
);
5056 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5057 * as a relative integer like in the [info level ?level?] command.
5059 static Jim_CallFrame
*JimGetCallFrameByInteger(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5062 Jim_CallFrame
*framePtr
;
5064 if (Jim_GetLong(interp
, levelObjPtr
, &level
) == JIM_OK
) {
5066 /* Convert from a relative to an absolute level */
5067 level
= interp
->framePtr
->level
+ level
;
5071 return interp
->topFramePtr
;
5075 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5076 if (framePtr
->level
== level
) {
5082 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
5086 static void JimSetErrorFileName(Jim_Interp
*interp
, const char *filename
)
5088 Jim_Free((void *)interp
->errorFileName
);
5089 interp
->errorFileName
= Jim_StrDup(filename
);
5092 static void JimSetErrorLineNumber(Jim_Interp
*interp
, int linenr
)
5094 interp
->errorLine
= linenr
;
5097 static void JimResetStackTrace(Jim_Interp
*interp
)
5099 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5100 interp
->stackTrace
= Jim_NewListObj(interp
, NULL
, 0);
5101 Jim_IncrRefCount(interp
->stackTrace
);
5104 static void JimSetStackTrace(Jim_Interp
*interp
, Jim_Obj
*stackTraceObj
)
5108 /* Increment reference first in case these are the same object */
5109 Jim_IncrRefCount(stackTraceObj
);
5110 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5111 interp
->stackTrace
= stackTraceObj
;
5112 interp
->errorFlag
= 1;
5114 /* This is a bit ugly.
5115 * If the filename of the last entry of the stack trace is empty,
5116 * the next stack level should be added.
5118 len
= Jim_ListLength(interp
, interp
->stackTrace
);
5120 Jim_Obj
*filenameObj
;
5122 Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &filenameObj
, JIM_NONE
);
5124 Jim_GetString(filenameObj
, &len
);
5127 interp
->addStackTrace
= 1;
5132 /* Returns 1 if the stack trace information was used or 0 if not */
5133 static void JimAppendStackTrace(Jim_Interp
*interp
, const char *procname
,
5134 const char *filename
, int linenr
)
5136 if (strcmp(procname
, "unknown") == 0) {
5139 if (!*procname
&& !*filename
) {
5140 /* No useful info here */
5144 if (Jim_IsShared(interp
->stackTrace
)) {
5145 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5146 interp
->stackTrace
= Jim_DuplicateObj(interp
, interp
->stackTrace
);
5147 Jim_IncrRefCount(interp
->stackTrace
);
5150 /* If we have no procname but the previous element did, merge with that frame */
5151 if (!*procname
&& *filename
) {
5152 /* Just a filename. Check the previous entry */
5153 int len
= Jim_ListLength(interp
, interp
->stackTrace
);
5156 Jim_Obj
*procnameObj
;
5157 Jim_Obj
*filenameObj
;
5159 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 3, &procnameObj
, JIM_NONE
) == JIM_OK
5160 && Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &filenameObj
,
5161 JIM_NONE
) == JIM_OK
) {
5163 const char *prev_procname
= Jim_String(procnameObj
);
5164 const char *prev_filename
= Jim_String(filenameObj
);
5166 if (*prev_procname
&& !*prev_filename
) {
5167 ListSetIndex(interp
, interp
->stackTrace
, len
- 2, Jim_NewStringObj(interp
,
5169 ListSetIndex(interp
, interp
->stackTrace
, len
- 1, Jim_NewIntObj(interp
, linenr
),
5177 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewStringObj(interp
, procname
, -1));
5178 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewStringObj(interp
, filename
, -1));
5179 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewIntObj(interp
, linenr
));
5182 int Jim_SetAssocData(Jim_Interp
*interp
, const char *key
, Jim_InterpDeleteProc
* delProc
,
5185 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) Jim_Alloc(sizeof(AssocDataValue
));
5187 assocEntryPtr
->delProc
= delProc
;
5188 assocEntryPtr
->data
= data
;
5189 return Jim_AddHashEntry(&interp
->assocData
, key
, assocEntryPtr
);
5192 void *Jim_GetAssocData(Jim_Interp
*interp
, const char *key
)
5194 Jim_HashEntry
*entryPtr
= Jim_FindHashEntry(&interp
->assocData
, key
);
5196 if (entryPtr
!= NULL
) {
5197 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) entryPtr
->u
.val
;
5199 return assocEntryPtr
->data
;
5204 int Jim_DeleteAssocData(Jim_Interp
*interp
, const char *key
)
5206 return Jim_DeleteHashEntry(&interp
->assocData
, key
);
5209 int Jim_GetExitCode(Jim_Interp
*interp
)
5211 return interp
->exitCode
;
5214 /* -----------------------------------------------------------------------------
5216 * Every interpreter has an hash table where to put shared dynamically
5217 * allocate strings that are likely to be used a lot of times.
5218 * For example, in the 'source' object type, there is a pointer to
5219 * the filename associated with that object. Every script has a lot
5220 * of this objects with the identical file name, so it is wise to share
5223 * The API is trivial: Jim_GetSharedString(interp, "foobar")
5224 * returns the pointer to the shared string. Every time a reference
5225 * to the string is no longer used, the user should call
5226 * Jim_ReleaseSharedString(interp, stringPointer). Once no one is using
5227 * a given string, it is removed from the hash table.
5228 * ---------------------------------------------------------------------------*/
5229 const char *Jim_GetSharedString(Jim_Interp
*interp
, const char *str
)
5231 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->sharedStrings
, str
);
5234 char *strCopy
= Jim_StrDup(str
);
5236 Jim_AddHashEntry(&interp
->sharedStrings
, strCopy
, NULL
);
5237 he
= Jim_FindHashEntry(&interp
->sharedStrings
, strCopy
);
5247 void Jim_ReleaseSharedString(Jim_Interp
*interp
, const char *str
)
5249 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->sharedStrings
, str
);
5251 JimPanic((he
== NULL
, interp
, "Jim_ReleaseSharedString called with " "unknown shared string '%s'", str
));
5253 if (--he
->u
.intval
== 0) {
5254 Jim_DeleteHashEntry(&interp
->sharedStrings
, str
);
5258 /* -----------------------------------------------------------------------------
5260 * ---------------------------------------------------------------------------*/
5261 #define JIM_INTEGER_SPACE 24
5263 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
);
5264 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
5266 static const Jim_ObjType intObjType
= {
5274 /* A coerced double is closer to an int than a double.
5275 * It is an int value temporarily masquerading as a double value.
5276 * i.e. it has the same string value as an int and Jim_GetWide()
5277 * succeeds, but also Jim_GetDouble() returns the value directly.
5279 static const Jim_ObjType coercedDoubleObjType
= {
5288 void UpdateStringOfInt(struct Jim_Obj
*objPtr
)
5291 char buf
[JIM_INTEGER_SPACE
+ 1];
5293 len
= Jim_WideToString(buf
, JimWideValue(objPtr
));
5294 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5295 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5296 objPtr
->length
= len
;
5299 int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
5304 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5305 /* Simple switcheroo */
5306 objPtr
->typePtr
= &intObjType
;
5310 /* Get the string representation */
5311 str
= Jim_String(objPtr
);
5312 /* Try to convert into a jim_wide */
5313 if (Jim_StringToWide(str
, &wideValue
, 0) != JIM_OK
) {
5314 if (flags
& JIM_ERRMSG
) {
5315 Jim_SetResultFormatted(interp
, "expected integer but got \"%#s\"", objPtr
);
5319 if ((wideValue
== JIM_WIDE_MIN
|| wideValue
== JIM_WIDE_MAX
) && errno
== ERANGE
) {
5320 Jim_SetResultString(interp
, "Integer value too big to be represented", -1);
5323 /* Free the old internal repr and set the new one. */
5324 Jim_FreeIntRep(interp
, objPtr
);
5325 objPtr
->typePtr
= &intObjType
;
5326 objPtr
->internalRep
.wideValue
= wideValue
;
5330 #ifdef JIM_OPTIMIZATION
5331 static int JimIsWide(Jim_Obj
*objPtr
)
5333 return objPtr
->typePtr
== &intObjType
;
5337 int Jim_GetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5339 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
5341 *widePtr
= JimWideValue(objPtr
);
5345 /* Get a wide but does not set an error if the format is bad. */
5346 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5348 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_NONE
) == JIM_ERR
)
5350 *widePtr
= JimWideValue(objPtr
);
5354 int Jim_GetLong(Jim_Interp
*interp
, Jim_Obj
*objPtr
, long *longPtr
)
5359 retval
= Jim_GetWide(interp
, objPtr
, &wideValue
);
5360 if (retval
== JIM_OK
) {
5361 *longPtr
= (long)wideValue
;
5367 Jim_Obj
*Jim_NewIntObj(Jim_Interp
*interp
, jim_wide wideValue
)
5371 objPtr
= Jim_NewObj(interp
);
5372 objPtr
->typePtr
= &intObjType
;
5373 objPtr
->bytes
= NULL
;
5374 objPtr
->internalRep
.wideValue
= wideValue
;
5378 /* -----------------------------------------------------------------------------
5380 * ---------------------------------------------------------------------------*/
5381 #define JIM_DOUBLE_SPACE 30
5383 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
);
5384 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5386 static const Jim_ObjType doubleObjType
= {
5390 UpdateStringOfDouble
,
5394 void UpdateStringOfDouble(struct Jim_Obj
*objPtr
)
5397 char buf
[JIM_DOUBLE_SPACE
+ 1];
5399 len
= Jim_DoubleToString(buf
, objPtr
->internalRep
.doubleValue
);
5400 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5401 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5402 objPtr
->length
= len
;
5405 int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5411 /* Preserve the string representation.
5412 * Needed so we can convert back to int without loss
5414 str
= Jim_String(objPtr
);
5416 #ifdef HAVE_LONG_LONG
5417 /* Assume a 53 bit mantissa */
5418 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5419 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5421 if (objPtr
->typePtr
== &intObjType
5422 && JimWideValue(objPtr
) >= MIN_INT_IN_DOUBLE
5423 && JimWideValue(objPtr
) <= MAX_INT_IN_DOUBLE
) {
5425 /* Direct conversion to coerced double */
5426 objPtr
->typePtr
= &coercedDoubleObjType
;
5431 if (Jim_StringToWide(str
, &wideValue
, 10) == JIM_OK
) {
5432 /* Managed to convert to an int, so we can use this as a cooerced double */
5433 Jim_FreeIntRep(interp
, objPtr
);
5434 objPtr
->typePtr
= &coercedDoubleObjType
;
5435 objPtr
->internalRep
.wideValue
= wideValue
;
5439 /* Try to convert into a double */
5440 if (Jim_StringToDouble(str
, &doubleValue
) != JIM_OK
) {
5441 Jim_SetResultFormatted(interp
, "expected number but got \"%#s\"", objPtr
);
5444 /* Free the old internal repr and set the new one. */
5445 Jim_FreeIntRep(interp
, objPtr
);
5447 objPtr
->typePtr
= &doubleObjType
;
5448 objPtr
->internalRep
.doubleValue
= doubleValue
;
5452 int Jim_GetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double *doublePtr
)
5454 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5455 *doublePtr
= JimWideValue(objPtr
);
5458 if (objPtr
->typePtr
!= &doubleObjType
&& SetDoubleFromAny(interp
, objPtr
) == JIM_ERR
)
5461 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5462 *doublePtr
= JimWideValue(objPtr
);
5465 *doublePtr
= objPtr
->internalRep
.doubleValue
;
5470 Jim_Obj
*Jim_NewDoubleObj(Jim_Interp
*interp
, double doubleValue
)
5474 objPtr
= Jim_NewObj(interp
);
5475 objPtr
->typePtr
= &doubleObjType
;
5476 objPtr
->bytes
= NULL
;
5477 objPtr
->internalRep
.doubleValue
= doubleValue
;
5481 /* -----------------------------------------------------------------------------
5483 * ---------------------------------------------------------------------------*/
5484 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
);
5485 static void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5486 static void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
5487 static void UpdateStringOfList(struct Jim_Obj
*objPtr
);
5488 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
5490 /* Note that while the elements of the list may contain references,
5491 * the list object itself can't. This basically means that the
5492 * list object string representation as a whole can't contain references
5493 * that are not presents in the single elements. */
5494 static const Jim_ObjType listObjType
= {
5496 FreeListInternalRep
,
5502 void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5506 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5507 Jim_DecrRefCount(interp
, objPtr
->internalRep
.listValue
.ele
[i
]);
5509 Jim_Free(objPtr
->internalRep
.listValue
.ele
);
5512 void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
5516 JIM_NOTUSED(interp
);
5518 dupPtr
->internalRep
.listValue
.len
= srcPtr
->internalRep
.listValue
.len
;
5519 dupPtr
->internalRep
.listValue
.maxLen
= srcPtr
->internalRep
.listValue
.maxLen
;
5520 dupPtr
->internalRep
.listValue
.ele
=
5521 Jim_Alloc(sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.maxLen
);
5522 memcpy(dupPtr
->internalRep
.listValue
.ele
, srcPtr
->internalRep
.listValue
.ele
,
5523 sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.len
);
5524 for (i
= 0; i
< dupPtr
->internalRep
.listValue
.len
; i
++) {
5525 Jim_IncrRefCount(dupPtr
->internalRep
.listValue
.ele
[i
]);
5527 dupPtr
->typePtr
= &listObjType
;
5530 /* The following function checks if a given string can be encoded
5531 * into a list element without any kind of quoting, surrounded by braces,
5532 * or using escapes to quote. */
5533 #define JIM_ELESTR_SIMPLE 0
5534 #define JIM_ELESTR_BRACE 1
5535 #define JIM_ELESTR_QUOTE 2
5536 static int ListElementQuotingType(const char *s
, int len
)
5538 int i
, level
, trySimple
= 1;
5540 /* Try with the SIMPLE case */
5542 return JIM_ELESTR_BRACE
;
5544 return JIM_ELESTR_BRACE
;
5545 if (s
[0] == '"' || s
[0] == '{') {
5549 for (i
= 0; i
< len
; i
++) {
5569 return JIM_ELESTR_SIMPLE
;
5572 /* Test if it's possible to do with braces */
5573 if (s
[len
- 1] == '\\' || s
[len
- 1] == ']')
5574 return JIM_ELESTR_QUOTE
;
5576 for (i
= 0; i
< len
; i
++) {
5584 return JIM_ELESTR_QUOTE
;
5587 if (s
[i
+ 1] == '\n')
5588 return JIM_ELESTR_QUOTE
;
5589 else if (s
[i
+ 1] != '\0')
5596 return JIM_ELESTR_BRACE
;
5597 for (i
= 0; i
< len
; i
++) {
5611 return JIM_ELESTR_BRACE
;
5615 return JIM_ELESTR_SIMPLE
;
5617 return JIM_ELESTR_QUOTE
;
5620 /* Returns the malloc-ed representation of a string
5621 * using backslash to quote special chars. */
5622 static char *BackslashQuoteString(const char *s
, int len
, int *qlenPtr
)
5624 char *q
= Jim_Alloc(len
* 2 + 1), *p
;
5676 void UpdateStringOfList(struct Jim_Obj
*objPtr
)
5678 int i
, bufLen
, realLength
;
5682 Jim_Obj
**ele
= objPtr
->internalRep
.listValue
.ele
;
5684 /* (Over) Estimate the space needed. */
5685 quotingType
= Jim_Alloc(sizeof(int) * objPtr
->internalRep
.listValue
.len
+ 1);
5687 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5690 strRep
= Jim_GetString(ele
[i
], &len
);
5691 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
5692 switch (quotingType
[i
]) {
5693 case JIM_ELESTR_SIMPLE
:
5696 case JIM_ELESTR_BRACE
:
5699 case JIM_ELESTR_QUOTE
:
5703 bufLen
++; /* elements separator. */
5707 /* Generate the string rep. */
5708 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
5710 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5714 strRep
= Jim_GetString(ele
[i
], &len
);
5716 switch (quotingType
[i
]) {
5717 case JIM_ELESTR_SIMPLE
:
5718 memcpy(p
, strRep
, len
);
5722 case JIM_ELESTR_BRACE
:
5724 memcpy(p
, strRep
, len
);
5727 realLength
+= len
+ 2;
5729 case JIM_ELESTR_QUOTE
:
5730 q
= BackslashQuoteString(strRep
, len
, &qlen
);
5737 /* Add a separating space */
5738 if (i
+ 1 != objPtr
->internalRep
.listValue
.len
) {
5743 *p
= '\0'; /* nul term. */
5744 objPtr
->length
= realLength
;
5745 Jim_Free(quotingType
);
5748 int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
5750 struct JimParserCtx parser
;
5753 const char *filename
= NULL
;
5756 /* Try to preserve information about filename / line number */
5757 if (objPtr
->typePtr
== &sourceObjType
) {
5758 filename
= Jim_GetSharedString(interp
, objPtr
->internalRep
.sourceValue
.fileName
);
5759 linenr
= objPtr
->internalRep
.sourceValue
.lineNumber
;
5762 /* Get the string representation */
5763 str
= Jim_GetString(objPtr
, &strLen
);
5765 /* Free the old internal repr just now and initialize the
5766 * new one just now. The string->list conversion can't fail. */
5767 Jim_FreeIntRep(interp
, objPtr
);
5768 objPtr
->typePtr
= &listObjType
;
5769 objPtr
->internalRep
.listValue
.len
= 0;
5770 objPtr
->internalRep
.listValue
.maxLen
= 0;
5771 objPtr
->internalRep
.listValue
.ele
= NULL
;
5773 /* Convert into a list */
5774 JimParserInit(&parser
, str
, strLen
, linenr
);
5775 while (!parser
.eof
) {
5776 Jim_Obj
*elementPtr
;
5778 JimParseList(&parser
);
5779 if (parser
.tt
!= JIM_TT_STR
&& parser
.tt
!= JIM_TT_ESC
)
5781 elementPtr
= JimParserGetTokenObj(interp
, &parser
);
5782 JimSetSourceInfo(interp
, elementPtr
, filename
, parser
.tline
);
5783 ListAppendElement(objPtr
, elementPtr
);
5786 Jim_ReleaseSharedString(interp
, filename
);
5791 Jim_Obj
*Jim_NewListObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
5796 objPtr
= Jim_NewObj(interp
);
5797 objPtr
->typePtr
= &listObjType
;
5798 objPtr
->bytes
= NULL
;
5799 objPtr
->internalRep
.listValue
.ele
= NULL
;
5800 objPtr
->internalRep
.listValue
.len
= 0;
5801 objPtr
->internalRep
.listValue
.maxLen
= 0;
5802 for (i
= 0; i
< len
; i
++) {
5803 ListAppendElement(objPtr
, elements
[i
]);
5808 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5809 * length of the vector. Note that the user of this function should make
5810 * sure that the list object can't shimmer while the vector returned
5811 * is in use, this vector is the one stored inside the internal representation
5812 * of the list object. This function is not exported, extensions should
5813 * always access to the List object elements using Jim_ListIndex(). */
5814 static void JimListGetElements(Jim_Interp
*interp
, Jim_Obj
*listObj
, int *listLen
,
5817 *listLen
= Jim_ListLength(interp
, listObj
);
5818 *listVec
= listObj
->internalRep
.listValue
.ele
;
5821 /* Sorting uses ints, but commands may return wide */
5822 static int JimSign(jim_wide w
)
5833 /* ListSortElements type values */
5847 int (*subfn
)(Jim_Obj
**, Jim_Obj
**);
5850 static struct lsort_info
*sort_info
;
5852 static int ListSortIndexHelper(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5854 Jim_Obj
*lObj
, *rObj
;
5856 if (Jim_ListIndex(sort_info
->interp
, *lhsObj
, sort_info
->index
, &lObj
, JIM_ERRMSG
) != JIM_OK
||
5857 Jim_ListIndex(sort_info
->interp
, *rhsObj
, sort_info
->index
, &rObj
, JIM_ERRMSG
) != JIM_OK
) {
5858 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5860 return sort_info
->subfn(&lObj
, &rObj
);
5863 /* Sort the internal rep of a list. */
5864 static int ListSortString(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5866 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 0) * sort_info
->order
;
5869 static int ListSortStringNoCase(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5871 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 1) * sort_info
->order
;
5874 static int ListSortInteger(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5876 jim_wide lhs
= 0, rhs
= 0;
5878 if (Jim_GetWide(sort_info
->interp
, *lhsObj
, &lhs
) != JIM_OK
||
5879 Jim_GetWide(sort_info
->interp
, *rhsObj
, &rhs
) != JIM_OK
) {
5880 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5883 return JimSign(lhs
- rhs
) * sort_info
->order
;
5886 static int ListSortCommand(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5888 Jim_Obj
*compare_script
;
5893 /* This must be a valid list */
5894 compare_script
= Jim_DuplicateObj(sort_info
->interp
, sort_info
->command
);
5895 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *lhsObj
);
5896 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *rhsObj
);
5898 rc
= Jim_EvalObj(sort_info
->interp
, compare_script
);
5900 if (rc
!= JIM_OK
|| Jim_GetWide(sort_info
->interp
, Jim_GetResult(sort_info
->interp
), &ret
) != JIM_OK
) {
5901 longjmp(sort_info
->jmpbuf
, rc
);
5904 return JimSign(ret
) * sort_info
->order
;
5907 /* Sort a list *in place*. MUST be called with non-shared objects. */
5908 static int ListSortElements(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, struct lsort_info
*info
)
5910 struct lsort_info
*prev_info
;
5912 typedef int (qsort_comparator
) (const void *, const void *);
5913 int (*fn
) (Jim_Obj
**, Jim_Obj
**);
5918 JimPanic((Jim_IsShared(listObjPtr
), interp
, "Jim_ListSortElements called with shared object"));
5919 if (!Jim_IsList(listObjPtr
))
5920 SetListFromAny(interp
, listObjPtr
);
5922 /* Allow lsort to be called reentrantly */
5923 prev_info
= sort_info
;
5926 vector
= listObjPtr
->internalRep
.listValue
.ele
;
5927 len
= listObjPtr
->internalRep
.listValue
.len
;
5928 switch (info
->type
) {
5929 case JIM_LSORT_ASCII
:
5930 fn
= ListSortString
;
5932 case JIM_LSORT_NOCASE
:
5933 fn
= ListSortStringNoCase
;
5935 case JIM_LSORT_INTEGER
:
5936 fn
= ListSortInteger
;
5938 case JIM_LSORT_COMMAND
:
5939 fn
= ListSortCommand
;
5942 fn
= NULL
; /* avoid warning */
5943 JimPanic((1, interp
, "ListSort called with invalid sort type"));
5946 if (info
->indexed
) {
5947 /* Need to interpose a "list index" function */
5949 fn
= ListSortIndexHelper
;
5952 if ((rc
= setjmp(info
->jmpbuf
)) == 0) {
5953 qsort(vector
, len
, sizeof(Jim_Obj
*), (qsort_comparator
*) fn
);
5955 Jim_InvalidateStringRep(listObjPtr
);
5956 sort_info
= prev_info
;
5961 /* This is the low-level function to insert elements into a list.
5962 * The higher-level Jim_ListInsertElements() performs shared object
5963 * check and invalidate the string repr. This version is used
5964 * in the internals of the List Object and is not exported.
5966 * NOTE: this function can be called only against objects
5967 * with internal type of List. */
5968 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
)
5970 int currentLen
= listPtr
->internalRep
.listValue
.len
;
5971 int requiredLen
= currentLen
+ elemc
;
5975 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
5976 int maxLen
= requiredLen
* 2;
5978 listPtr
->internalRep
.listValue
.ele
=
5979 Jim_Realloc(listPtr
->internalRep
.listValue
.ele
, sizeof(Jim_Obj
*) * maxLen
);
5980 listPtr
->internalRep
.listValue
.maxLen
= maxLen
;
5982 point
= listPtr
->internalRep
.listValue
.ele
+ idx
;
5983 memmove(point
+ elemc
, point
, (currentLen
- idx
) * sizeof(Jim_Obj
*));
5984 for (i
= 0; i
< elemc
; ++i
) {
5985 point
[i
] = elemVec
[i
];
5986 Jim_IncrRefCount(point
[i
]);
5988 listPtr
->internalRep
.listValue
.len
+= elemc
;
5991 /* Convenience call to ListInsertElements() to append a single element.
5993 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
5995 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
, 1, &objPtr
);
5999 /* Appends every element of appendListPtr into listPtr.
6000 * Both have to be of the list type.
6001 * Convenience call to ListInsertElements()
6003 static void ListAppendList(Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6005 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
,
6006 appendListPtr
->internalRep
.listValue
.len
, appendListPtr
->internalRep
.listValue
.ele
);
6009 void Jim_ListAppendElement(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6011 JimPanic((Jim_IsShared(listPtr
), interp
, "Jim_ListAppendElement called with shared object"));
6012 if (!Jim_IsList(listPtr
))
6013 SetListFromAny(interp
, listPtr
);
6014 Jim_InvalidateStringRep(listPtr
);
6015 ListAppendElement(listPtr
, objPtr
);
6018 void Jim_ListAppendList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6020 JimPanic((Jim_IsShared(listPtr
), interp
, "Jim_ListAppendList called with shared object"));
6021 if (!Jim_IsList(listPtr
))
6022 SetListFromAny(interp
, listPtr
);
6023 Jim_InvalidateStringRep(listPtr
);
6024 ListAppendList(listPtr
, appendListPtr
);
6027 int Jim_ListLength(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6029 if (!Jim_IsList(objPtr
))
6030 SetListFromAny(interp
, objPtr
);
6031 return objPtr
->internalRep
.listValue
.len
;
6034 void Jim_ListInsertElements(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6035 int objc
, Jim_Obj
*const *objVec
)
6037 JimPanic((Jim_IsShared(listPtr
), interp
, "Jim_ListInsertElement called with shared object"));
6038 if (!Jim_IsList(listPtr
))
6039 SetListFromAny(interp
, listPtr
);
6040 if (idx
>= 0 && idx
> listPtr
->internalRep
.listValue
.len
)
6041 idx
= listPtr
->internalRep
.listValue
.len
;
6044 Jim_InvalidateStringRep(listPtr
);
6045 ListInsertElements(listPtr
, idx
, objc
, objVec
);
6048 int Jim_ListIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
, Jim_Obj
**objPtrPtr
, int flags
)
6050 if (!Jim_IsList(listPtr
))
6051 SetListFromAny(interp
, listPtr
);
6052 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6053 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6054 if (flags
& JIM_ERRMSG
) {
6055 Jim_SetResultString(interp
, "list index out of range", -1);
6061 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6062 *objPtrPtr
= listPtr
->internalRep
.listValue
.ele
[idx
];
6066 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6067 Jim_Obj
*newObjPtr
, int flags
)
6069 if (!Jim_IsList(listPtr
))
6070 SetListFromAny(interp
, listPtr
);
6071 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6072 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6073 if (flags
& JIM_ERRMSG
) {
6074 Jim_SetResultString(interp
, "list index out of range", -1);
6079 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6080 Jim_DecrRefCount(interp
, listPtr
->internalRep
.listValue
.ele
[idx
]);
6081 listPtr
->internalRep
.listValue
.ele
[idx
] = newObjPtr
;
6082 Jim_IncrRefCount(newObjPtr
);
6086 /* Modify the list stored into the variable named 'varNamePtr'
6087 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6088 * with the new element 'newObjptr'. */
6089 int Jim_SetListIndex(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6090 Jim_Obj
*const *indexv
, int indexc
, Jim_Obj
*newObjPtr
)
6092 Jim_Obj
*varObjPtr
, *objPtr
, *listObjPtr
;
6095 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
| JIM_UNSHARED
);
6098 if ((shared
= Jim_IsShared(objPtr
)))
6099 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6100 for (i
= 0; i
< indexc
- 1; i
++) {
6101 listObjPtr
= objPtr
;
6102 if (Jim_GetIndex(interp
, indexv
[i
], &idx
) != JIM_OK
)
6104 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_ERRMSG
) != JIM_OK
) {
6107 if (Jim_IsShared(objPtr
)) {
6108 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6109 ListSetIndex(interp
, listObjPtr
, idx
, objPtr
, JIM_NONE
);
6111 Jim_InvalidateStringRep(listObjPtr
);
6113 if (Jim_GetIndex(interp
, indexv
[indexc
- 1], &idx
) != JIM_OK
)
6115 if (ListSetIndex(interp
, objPtr
, idx
, newObjPtr
, JIM_ERRMSG
) == JIM_ERR
)
6117 Jim_InvalidateStringRep(objPtr
);
6118 Jim_InvalidateStringRep(varObjPtr
);
6119 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
6121 Jim_SetResult(interp
, varObjPtr
);
6125 Jim_FreeNewObj(interp
, varObjPtr
);
6130 Jim_Obj
*Jim_ConcatObj(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
6134 /* If all the objects in objv are lists,
6135 * it's possible to return a list as result, that's the
6136 * concatenation of all the lists. */
6137 for (i
= 0; i
< objc
; i
++) {
6138 if (!Jim_IsList(objv
[i
]))
6142 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
6144 for (i
= 0; i
< objc
; i
++)
6145 Jim_ListAppendList(interp
, objPtr
, objv
[i
]);
6149 /* Else... we have to glue strings together */
6150 int len
= 0, objLen
;
6153 /* Compute the length */
6154 for (i
= 0; i
< objc
; i
++) {
6155 Jim_GetString(objv
[i
], &objLen
);
6160 /* Create the string rep, and a string object holding it. */
6161 p
= bytes
= Jim_Alloc(len
+ 1);
6162 for (i
= 0; i
< objc
; i
++) {
6163 const char *s
= Jim_GetString(objv
[i
], &objLen
);
6165 /* Remove leading space */
6166 while (objLen
&& (*s
== ' ' || *s
== '\t' || *s
== '\n')) {
6171 /* And trailing space */
6172 while (objLen
&& (s
[objLen
- 1] == ' ' ||
6173 s
[objLen
- 1] == '\n' || s
[objLen
- 1] == '\t')) {
6174 /* Handle trailing backslash-space case */
6175 if (objLen
> 1 && s
[objLen
- 2] == '\\') {
6181 memcpy(p
, s
, objLen
);
6183 if (objLen
&& i
+ 1 != objc
) {
6186 else if (i
+ 1 != objc
) {
6187 /* Drop the space calcuated for this
6188 * element that is instead null. */
6193 return Jim_NewStringObjNoAlloc(interp
, bytes
, len
);
6197 /* Returns a list composed of the elements in the specified range.
6198 * first and start are directly accepted as Jim_Objects and
6199 * processed for the end?-index? case. */
6200 Jim_Obj
*Jim_ListRange(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*firstObjPtr
,
6201 Jim_Obj
*lastObjPtr
)
6206 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
6207 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
6209 len
= Jim_ListLength(interp
, listObjPtr
); /* will convert into list */
6210 first
= JimRelToAbsIndex(len
, first
);
6211 last
= JimRelToAbsIndex(len
, last
);
6212 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
6213 return Jim_NewListObj(interp
, listObjPtr
->internalRep
.listValue
.ele
+ first
, rangeLen
);
6216 /* -----------------------------------------------------------------------------
6218 * ---------------------------------------------------------------------------*/
6219 static void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6220 static void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
6221 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
);
6222 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6224 /* Dict HashTable Type.
6226 * Keys and Values are Jim objects. */
6228 static unsigned int JimObjectHTHashFunction(const void *key
)
6231 Jim_Obj
*objPtr
= (Jim_Obj
*)key
;
6234 str
= Jim_GetString(objPtr
, &len
);
6235 h
= Jim_GenHashFunction((unsigned char *)str
, len
);
6239 static int JimObjectHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
6241 JIM_NOTUSED(privdata
);
6243 return Jim_StringEqObj((Jim_Obj
*)key1
, (Jim_Obj
*)key2
);
6246 static void JimObjectHTKeyValDestructor(void *interp
, void *val
)
6248 Jim_Obj
*objPtr
= val
;
6250 Jim_DecrRefCount(interp
, objPtr
);
6253 static const Jim_HashTableType JimDictHashTableType
= {
6254 JimObjectHTHashFunction
, /* hash function */
6257 JimObjectHTKeyCompare
, /* key compare */
6258 (void (*)(void *, const void *)) /* ATTENTION: const cast */
6259 JimObjectHTKeyValDestructor
, /* key destructor */
6260 JimObjectHTKeyValDestructor
/* val destructor */
6263 /* Note that while the elements of the dict may contain references,
6264 * the list object itself can't. This basically means that the
6265 * dict object string representation as a whole can't contain references
6266 * that are not presents in the single elements. */
6267 static const Jim_ObjType dictObjType
= {
6269 FreeDictInternalRep
,
6275 void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6277 JIM_NOTUSED(interp
);
6279 Jim_FreeHashTable(objPtr
->internalRep
.ptr
);
6280 Jim_Free(objPtr
->internalRep
.ptr
);
6283 void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
6285 Jim_HashTable
*ht
, *dupHt
;
6286 Jim_HashTableIterator
*htiter
;
6289 /* Create a new hash table */
6290 ht
= srcPtr
->internalRep
.ptr
;
6291 dupHt
= Jim_Alloc(sizeof(*dupHt
));
6292 Jim_InitHashTable(dupHt
, &JimDictHashTableType
, interp
);
6294 Jim_ExpandHashTable(dupHt
, ht
->size
);
6295 /* Copy every element from the source to the dup hash table */
6296 htiter
= Jim_GetHashTableIterator(ht
);
6297 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6298 const Jim_Obj
*keyObjPtr
= he
->key
;
6299 Jim_Obj
*valObjPtr
= he
->u
.val
;
6301 Jim_IncrRefCount((Jim_Obj
*)keyObjPtr
); /* ATTENTION: const cast */
6302 Jim_IncrRefCount(valObjPtr
);
6303 Jim_AddHashEntry(dupHt
, keyObjPtr
, valObjPtr
);
6305 Jim_FreeHashTableIterator(htiter
);
6307 dupPtr
->internalRep
.ptr
= dupHt
;
6308 dupPtr
->typePtr
= &dictObjType
;
6311 void UpdateStringOfDict(struct Jim_Obj
*objPtr
)
6313 int i
, bufLen
, realLength
;
6316 int *quotingType
, objc
;
6318 Jim_HashTableIterator
*htiter
;
6322 /* Trun the hash table into a flat vector of Jim_Objects. */
6323 ht
= objPtr
->internalRep
.ptr
;
6324 objc
= ht
->used
* 2;
6325 objv
= Jim_Alloc(objc
* sizeof(Jim_Obj
*));
6326 htiter
= Jim_GetHashTableIterator(ht
);
6328 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6329 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6330 objv
[i
++] = he
->u
.val
;
6332 Jim_FreeHashTableIterator(htiter
);
6333 /* (Over) Estimate the space needed. */
6334 quotingType
= Jim_Alloc(sizeof(int) * objc
);
6336 for (i
= 0; i
< objc
; i
++) {
6339 strRep
= Jim_GetString(objv
[i
], &len
);
6340 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
6341 switch (quotingType
[i
]) {
6342 case JIM_ELESTR_SIMPLE
:
6345 case JIM_ELESTR_BRACE
:
6348 case JIM_ELESTR_QUOTE
:
6352 bufLen
++; /* elements separator. */
6356 /* Generate the string rep. */
6357 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
6359 for (i
= 0; i
< objc
; i
++) {
6363 strRep
= Jim_GetString(objv
[i
], &len
);
6365 switch (quotingType
[i
]) {
6366 case JIM_ELESTR_SIMPLE
:
6367 memcpy(p
, strRep
, len
);
6371 case JIM_ELESTR_BRACE
:
6373 memcpy(p
, strRep
, len
);
6376 realLength
+= len
+ 2;
6378 case JIM_ELESTR_QUOTE
:
6379 q
= BackslashQuoteString(strRep
, len
, &qlen
);
6386 /* Add a separating space */
6387 if (i
+ 1 != objc
) {
6392 *p
= '\0'; /* nul term. */
6393 objPtr
->length
= realLength
;
6394 Jim_Free(quotingType
);
6398 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
6402 /* Get the string representation. Do this first so we don't
6403 * change order in case of fast conversion to dict.
6407 /* For simplicity, convert a non-list object to a list and then to a dict */
6408 listlen
= Jim_ListLength(interp
, objPtr
);
6410 Jim_SetResultString(interp
,
6411 "invalid dictionary value: must be a list with an even number of elements", -1);
6415 /* Now it is easy to convert to a dict from a list, and it can't fail */
6419 ht
= Jim_Alloc(sizeof(*ht
));
6420 Jim_InitHashTable(ht
, &JimDictHashTableType
, interp
);
6422 for (i
= 0; i
< listlen
; i
+= 2) {
6426 Jim_ListIndex(interp
, objPtr
, i
, &keyObjPtr
, JIM_NONE
);
6427 Jim_ListIndex(interp
, objPtr
, i
+ 1, &valObjPtr
, JIM_NONE
);
6429 Jim_IncrRefCount(keyObjPtr
);
6430 Jim_IncrRefCount(valObjPtr
);
6432 if (Jim_AddHashEntry(ht
, keyObjPtr
, valObjPtr
) != JIM_OK
) {
6435 he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6436 Jim_DecrRefCount(interp
, keyObjPtr
);
6437 /* ATTENTION: const cast */
6438 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6439 he
->u
.val
= valObjPtr
;
6443 Jim_FreeIntRep(interp
, objPtr
);
6444 objPtr
->typePtr
= &dictObjType
;
6445 objPtr
->internalRep
.ptr
= ht
;
6451 /* Dict object API */
6453 /* Add an element to a dict. objPtr must be of the "dict" type.
6454 * The higer-level exported function is Jim_DictAddElement().
6455 * If an element with the specified key already exists, the value
6456 * associated is replaced with the new one.
6458 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6459 static int DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6460 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6462 Jim_HashTable
*ht
= objPtr
->internalRep
.ptr
;
6464 if (valueObjPtr
== NULL
) { /* unset */
6465 return Jim_DeleteHashEntry(ht
, keyObjPtr
);
6467 Jim_IncrRefCount(keyObjPtr
);
6468 Jim_IncrRefCount(valueObjPtr
);
6469 if (Jim_AddHashEntry(ht
, keyObjPtr
, valueObjPtr
) != JIM_OK
) {
6470 Jim_HashEntry
*he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6472 Jim_DecrRefCount(interp
, keyObjPtr
);
6473 /* ATTENTION: const cast */
6474 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6475 he
->u
.val
= valueObjPtr
;
6480 /* Add an element, higher-level interface for DictAddElement().
6481 * If valueObjPtr == NULL, the key is removed if it exists. */
6482 int Jim_DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6483 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6487 JimPanic((Jim_IsShared(objPtr
), interp
, "Jim_DictAddElement called with shared object"));
6488 if (objPtr
->typePtr
!= &dictObjType
) {
6489 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
)
6492 retcode
= DictAddElement(interp
, objPtr
, keyObjPtr
, valueObjPtr
);
6493 Jim_InvalidateStringRep(objPtr
);
6497 Jim_Obj
*Jim_NewDictObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
6502 JimPanic((len
% 2, interp
, "Jim_NewDictObj() 'len' argument must be even"));
6504 objPtr
= Jim_NewObj(interp
);
6505 objPtr
->typePtr
= &dictObjType
;
6506 objPtr
->bytes
= NULL
;
6507 objPtr
->internalRep
.ptr
= Jim_Alloc(sizeof(Jim_HashTable
));
6508 Jim_InitHashTable(objPtr
->internalRep
.ptr
, &JimDictHashTableType
, interp
);
6509 for (i
= 0; i
< len
; i
+= 2)
6510 DictAddElement(interp
, objPtr
, elements
[i
], elements
[i
+ 1]);
6514 /* Return the value associated to the specified dict key
6515 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6517 int Jim_DictKey(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
*keyPtr
,
6518 Jim_Obj
**objPtrPtr
, int flags
)
6523 if (dictPtr
->typePtr
!= &dictObjType
) {
6524 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6527 ht
= dictPtr
->internalRep
.ptr
;
6528 if ((he
= Jim_FindHashEntry(ht
, keyPtr
)) == NULL
) {
6529 if (flags
& JIM_ERRMSG
) {
6530 Jim_SetResultFormatted(interp
, "key \"%#s\" not found in dictionary", keyPtr
);
6534 *objPtrPtr
= he
->u
.val
;
6538 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6539 int Jim_DictPairs(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
***objPtrPtr
, int *len
)
6542 Jim_HashTableIterator
*htiter
;
6547 if (dictPtr
->typePtr
!= &dictObjType
) {
6548 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6551 ht
= dictPtr
->internalRep
.ptr
;
6553 /* Turn the hash table into a flat vector of Jim_Objects. */
6554 objv
= Jim_Alloc((ht
->used
* 2) * sizeof(Jim_Obj
*));
6555 htiter
= Jim_GetHashTableIterator(ht
);
6557 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6558 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6559 objv
[i
++] = he
->u
.val
;
6562 Jim_FreeHashTableIterator(htiter
);
6568 /* Return the value associated to the specified dict keys */
6569 int Jim_DictKeysVector(Jim_Interp
*interp
, Jim_Obj
*dictPtr
,
6570 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
**objPtrPtr
, int flags
)
6575 *objPtrPtr
= dictPtr
;
6579 for (i
= 0; i
< keyc
; i
++) {
6582 if (Jim_DictKey(interp
, dictPtr
, keyv
[i
], &objPtr
, flags
)
6587 *objPtrPtr
= dictPtr
;
6591 /* Modify the dict stored into the variable named 'varNamePtr'
6592 * setting the element specified by the 'keyc' keys objects in 'keyv',
6593 * with the new value of the element 'newObjPtr'.
6595 * If newObjPtr == NULL the operation is to remove the given key
6596 * from the dictionary. */
6597 int Jim_SetDictKeysVector(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6598 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*newObjPtr
)
6600 Jim_Obj
*varObjPtr
, *objPtr
, *dictObjPtr
;
6603 varObjPtr
= objPtr
=
6604 Jim_GetVariable(interp
, varNamePtr
, newObjPtr
== NULL
? JIM_ERRMSG
: JIM_NONE
);
6605 if (objPtr
== NULL
) {
6606 if (newObjPtr
== NULL
) /* Cannot remove a key from non existing var */
6608 varObjPtr
= objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6609 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
6610 Jim_FreeNewObj(interp
, varObjPtr
);
6614 if ((shared
= Jim_IsShared(objPtr
)))
6615 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6616 for (i
= 0; i
< keyc
- 1; i
++) {
6617 dictObjPtr
= objPtr
;
6619 /* Check if it's a valid dictionary */
6620 if (dictObjPtr
->typePtr
!= &dictObjType
) {
6621 if (SetDictFromAny(interp
, dictObjPtr
) != JIM_OK
)
6624 /* Check if the given key exists. */
6625 Jim_InvalidateStringRep(dictObjPtr
);
6626 if (Jim_DictKey(interp
, dictObjPtr
, keyv
[i
], &objPtr
,
6627 newObjPtr
? JIM_NONE
: JIM_ERRMSG
) == JIM_OK
) {
6628 /* This key exists at the current level.
6629 * Make sure it's not shared!. */
6630 if (Jim_IsShared(objPtr
)) {
6631 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6632 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6636 /* Key not found. If it's an [unset] operation
6637 * this is an error. Only the last key may not
6639 if (newObjPtr
== NULL
)
6641 /* Otherwise set an empty dictionary
6642 * as key's value. */
6643 objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6644 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6647 if (Jim_DictAddElement(interp
, objPtr
, keyv
[keyc
- 1], newObjPtr
) != JIM_OK
) {
6650 Jim_InvalidateStringRep(objPtr
);
6651 Jim_InvalidateStringRep(varObjPtr
);
6652 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
6654 Jim_SetResult(interp
, varObjPtr
);
6658 Jim_FreeNewObj(interp
, varObjPtr
);
6663 /* -----------------------------------------------------------------------------
6665 * ---------------------------------------------------------------------------*/
6666 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
);
6667 static int SetIndexFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6669 static const Jim_ObjType indexObjType
= {
6673 UpdateStringOfIndex
,
6677 void UpdateStringOfIndex(struct Jim_Obj
*objPtr
)
6680 char buf
[JIM_INTEGER_SPACE
+ 1];
6682 if (objPtr
->internalRep
.indexValue
>= 0)
6683 len
= sprintf(buf
, "%d", objPtr
->internalRep
.indexValue
);
6684 else if (objPtr
->internalRep
.indexValue
== -1)
6685 len
= sprintf(buf
, "end");
6687 len
= sprintf(buf
, "end%d", objPtr
->internalRep
.indexValue
+ 1);
6689 objPtr
->bytes
= Jim_Alloc(len
+ 1);
6690 memcpy(objPtr
->bytes
, buf
, len
+ 1);
6691 objPtr
->length
= len
;
6694 int SetIndexFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6700 /* Get the string representation */
6701 str
= Jim_String(objPtr
);
6703 /* Try to convert into an index */
6704 if (strncmp(str
, "end", 3) == 0) {
6710 idx
= strtol(str
, &endptr
, 10);
6712 if (endptr
== str
) {
6718 /* Now str may include or +<num> or -<num> */
6719 if (*str
== '+' || *str
== '-') {
6720 int sign
= (*str
== '+' ? 1 : -1);
6722 idx
+= sign
* strtol(++str
, &endptr
, 10);
6723 if (str
== endptr
|| *endptr
) {
6728 /* The only thing left should be spaces */
6729 while (isspace(UCHAR(*str
))) {
6740 /* end-1 is repesented as -2 */
6748 /* Free the old internal repr and set the new one. */
6749 Jim_FreeIntRep(interp
, objPtr
);
6750 objPtr
->typePtr
= &indexObjType
;
6751 objPtr
->internalRep
.indexValue
= idx
;
6755 Jim_SetResultFormatted(interp
,
6756 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr
);
6760 int Jim_GetIndex(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *indexPtr
)
6762 /* Avoid shimmering if the object is an integer. */
6763 if (objPtr
->typePtr
== &intObjType
) {
6764 jim_wide val
= JimWideValue(objPtr
);
6766 if (!(val
< LONG_MIN
) && !(val
> LONG_MAX
)) {
6767 *indexPtr
= (val
< 0) ? -INT_MAX
: (long)val
;;
6771 if (objPtr
->typePtr
!= &indexObjType
&& SetIndexFromAny(interp
, objPtr
) == JIM_ERR
)
6773 *indexPtr
= objPtr
->internalRep
.indexValue
;
6777 /* -----------------------------------------------------------------------------
6778 * Return Code Object.
6779 * ---------------------------------------------------------------------------*/
6781 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6782 static const char * const jimReturnCodes
[] = {
6784 [JIM_ERR
] = "error",
6785 [JIM_RETURN
] = "return",
6786 [JIM_BREAK
] = "break",
6787 [JIM_CONTINUE
] = "continue",
6788 [JIM_SIGNAL
] = "signal",
6789 [JIM_EXIT
] = "exit",
6790 [JIM_EVAL
] = "eval",
6794 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6796 static int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6798 static const Jim_ObjType returnCodeObjType
= {
6806 /* Converts a (standard) return code to a string. Returns "?" for
6807 * non-standard return codes.
6809 const char *Jim_ReturnCode(int code
)
6811 if (code
< 0 || code
>= (int)jimReturnCodesSize
) {
6815 return jimReturnCodes
[code
];
6819 int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6824 /* Try to convert into an integer */
6825 if (JimGetWideNoErr(interp
, objPtr
, &wideValue
) != JIM_ERR
)
6826 returnCode
= (int)wideValue
;
6827 else if (Jim_GetEnum(interp
, objPtr
, jimReturnCodes
, &returnCode
, NULL
, JIM_NONE
) != JIM_OK
) {
6828 Jim_SetResultFormatted(interp
, "expected return code but got \"%#s\"", objPtr
);
6831 /* Free the old internal repr and set the new one. */
6832 Jim_FreeIntRep(interp
, objPtr
);
6833 objPtr
->typePtr
= &returnCodeObjType
;
6834 objPtr
->internalRep
.returnCode
= returnCode
;
6838 int Jim_GetReturnCode(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *intPtr
)
6840 if (objPtr
->typePtr
!= &returnCodeObjType
&& SetReturnCodeFromAny(interp
, objPtr
) == JIM_ERR
)
6842 *intPtr
= objPtr
->internalRep
.returnCode
;
6846 /* -----------------------------------------------------------------------------
6847 * Expression Parsing
6848 * ---------------------------------------------------------------------------*/
6849 static int JimParseExprOperator(struct JimParserCtx
*pc
);
6850 static int JimParseExprNumber(struct JimParserCtx
*pc
);
6851 static int JimParseExprIrrational(struct JimParserCtx
*pc
);
6853 /* Exrp's Stack machine operators opcodes. */
6855 /* Binary operators (numbers) */
6858 /* Continues on from the JIM_TT_ space */
6860 JIM_EXPROP_MUL
= JIM_TT_EXPR_OP
, /* 15 */
6875 JIM_EXPROP_BITAND
, /* 30 */
6879 /* Note must keep these together */
6880 JIM_EXPROP_LOGICAND
, /* 33 */
6881 JIM_EXPROP_LOGICAND_LEFT
,
6882 JIM_EXPROP_LOGICAND_RIGHT
,
6885 JIM_EXPROP_LOGICOR
, /* 36 */
6886 JIM_EXPROP_LOGICOR_LEFT
,
6887 JIM_EXPROP_LOGICOR_RIGHT
,
6890 /* Ternary operators */
6891 JIM_EXPROP_TERNARY
, /* 39 */
6892 JIM_EXPROP_TERNARY_LEFT
,
6893 JIM_EXPROP_TERNARY_RIGHT
,
6896 JIM_EXPROP_COLON
, /* 42 */
6897 JIM_EXPROP_COLON_LEFT
,
6898 JIM_EXPROP_COLON_RIGHT
,
6900 JIM_EXPROP_POW
, /* 45 */
6902 /* Binary operators (strings) */
6908 /* Unary operators (numbers) */
6911 JIM_EXPROP_UNARYMINUS
,
6912 JIM_EXPROP_UNARYPLUS
,
6915 JIM_EXPROP_FUNC_FIRST
,
6916 JIM_EXPROP_FUNC_INT
= JIM_EXPROP_FUNC_FIRST
,
6917 JIM_EXPROP_FUNC_ABS
,
6918 JIM_EXPROP_FUNC_DOUBLE
,
6919 JIM_EXPROP_FUNC_ROUND
,
6921 #ifdef JIM_MATH_FUNCTIONS
6922 /* math functions from libm */
6923 JIM_EXPROP_FUNC_SIN
,
6924 JIM_EXPROP_FUNC_COS
,
6925 JIM_EXPROP_FUNC_TAN
,
6926 JIM_EXPROP_FUNC_ASIN
,
6927 JIM_EXPROP_FUNC_ACOS
,
6928 JIM_EXPROP_FUNC_ATAN
,
6929 JIM_EXPROP_FUNC_SINH
,
6930 JIM_EXPROP_FUNC_COSH
,
6931 JIM_EXPROP_FUNC_TANH
,
6932 JIM_EXPROP_FUNC_CEIL
,
6933 JIM_EXPROP_FUNC_FLOOR
,
6934 JIM_EXPROP_FUNC_EXP
,
6935 JIM_EXPROP_FUNC_LOG
,
6936 JIM_EXPROP_FUNC_LOG10
,
6937 JIM_EXPROP_FUNC_SQRT
,
6949 /* Operators table */
6950 typedef struct Jim_ExprOperator
6955 int (*funcop
) (Jim_Interp
*interp
, struct JimExprState
* e
);
6959 static void ExprPush(struct JimExprState
*e
, Jim_Obj
*obj
)
6961 Jim_IncrRefCount(obj
);
6962 e
->stack
[e
->stacklen
++] = obj
;
6965 static Jim_Obj
*ExprPop(struct JimExprState
*e
)
6967 return e
->stack
[--e
->stacklen
];
6970 static int JimExprOpNumUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
6974 Jim_Obj
*A
= ExprPop(e
);
6976 jim_wide wA
, wC
= 0;
6978 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) && JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
) {
6981 switch (e
->opcode
) {
6982 case JIM_EXPROP_FUNC_INT
:
6985 case JIM_EXPROP_FUNC_ROUND
:
6988 case JIM_EXPROP_FUNC_DOUBLE
:
6992 case JIM_EXPROP_FUNC_ABS
:
6993 wC
= wA
>= 0 ? wA
: -wA
;
6995 case JIM_EXPROP_UNARYMINUS
:
6998 case JIM_EXPROP_UNARYPLUS
:
7001 case JIM_EXPROP_NOT
:
7008 else if ((rc
= Jim_GetDouble(interp
, A
, &dA
)) == JIM_OK
) {
7009 switch (e
->opcode
) {
7010 case JIM_EXPROP_FUNC_INT
:
7014 case JIM_EXPROP_FUNC_ROUND
:
7015 wC
= dA
< 0 ? (dA
- 0.5) : (dA
+ 0.5);
7018 case JIM_EXPROP_FUNC_DOUBLE
:
7021 case JIM_EXPROP_FUNC_ABS
:
7022 dC
= dA
>= 0 ? dA
: -dA
;
7024 case JIM_EXPROP_UNARYMINUS
:
7027 case JIM_EXPROP_UNARYPLUS
:
7030 case JIM_EXPROP_NOT
:
7041 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7044 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7048 Jim_DecrRefCount(interp
, A
);
7053 static int JimExprOpIntUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7055 Jim_Obj
*A
= ExprPop(e
);
7060 if (Jim_GetWide(interp
, A
, &wA
) == JIM_OK
) {
7063 switch (e
->opcode
) {
7064 case JIM_EXPROP_BITNOT
:
7070 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7074 Jim_DecrRefCount(interp
, A
);
7079 #ifdef JIM_MATH_FUNCTIONS
7080 static int JimExprOpDoubleUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7083 Jim_Obj
*A
= ExprPop(e
);
7086 rc
= Jim_GetDouble(interp
, A
, &dA
);
7088 switch (e
->opcode
) {
7089 case JIM_EXPROP_FUNC_SIN
:
7092 case JIM_EXPROP_FUNC_COS
:
7095 case JIM_EXPROP_FUNC_TAN
:
7098 case JIM_EXPROP_FUNC_ASIN
:
7101 case JIM_EXPROP_FUNC_ACOS
:
7104 case JIM_EXPROP_FUNC_ATAN
:
7107 case JIM_EXPROP_FUNC_SINH
:
7110 case JIM_EXPROP_FUNC_COSH
:
7113 case JIM_EXPROP_FUNC_TANH
:
7116 case JIM_EXPROP_FUNC_CEIL
:
7119 case JIM_EXPROP_FUNC_FLOOR
:
7122 case JIM_EXPROP_FUNC_EXP
:
7125 case JIM_EXPROP_FUNC_LOG
:
7128 case JIM_EXPROP_FUNC_LOG10
:
7131 case JIM_EXPROP_FUNC_SQRT
:
7137 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7140 Jim_DecrRefCount(interp
, A
);
7146 /* A binary operation on two ints */
7147 static int JimExprOpIntBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7149 Jim_Obj
*B
= ExprPop(e
);
7150 Jim_Obj
*A
= ExprPop(e
);
7154 if (Jim_GetWide(interp
, A
, &wA
) == JIM_OK
&& Jim_GetWide(interp
, B
, &wB
) == JIM_OK
) {
7159 switch (e
->opcode
) {
7160 case JIM_EXPROP_LSHIFT
:
7163 case JIM_EXPROP_RSHIFT
:
7166 case JIM_EXPROP_BITAND
:
7169 case JIM_EXPROP_BITXOR
:
7172 case JIM_EXPROP_BITOR
:
7175 case JIM_EXPROP_MOD
:
7178 Jim_SetResultString(interp
, "Division by zero", -1);
7185 * This code is tricky: C doesn't guarantee much
7186 * about the quotient or remainder, but Tcl does.
7187 * The remainder always has the same sign as the
7188 * divisor and a smaller absolute value.
7206 case JIM_EXPROP_ROTL
:
7207 case JIM_EXPROP_ROTR
:{
7208 /* uint32_t would be better. But not everyone has inttypes.h? */
7209 unsigned long uA
= (unsigned long)wA
;
7210 unsigned long uB
= (unsigned long)wB
;
7211 const unsigned int S
= sizeof(unsigned long) * 8;
7213 /* Shift left by the word size or more is undefined. */
7216 if (e
->opcode
== JIM_EXPROP_ROTR
) {
7219 wC
= (unsigned long)(uA
<< uB
) | (uA
>> (S
- uB
));
7225 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7229 Jim_DecrRefCount(interp
, A
);
7230 Jim_DecrRefCount(interp
, B
);
7236 /* A binary operation on two ints or two doubles (or two strings for some ops) */
7237 static int JimExprOpBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7241 double dA
, dB
, dC
= 0;
7242 jim_wide wA
, wB
, wC
= 0;
7244 Jim_Obj
*B
= ExprPop(e
);
7245 Jim_Obj
*A
= ExprPop(e
);
7247 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) &&
7248 (B
->typePtr
!= &doubleObjType
|| B
->bytes
) &&
7249 JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
&& JimGetWideNoErr(interp
, B
, &wB
) == JIM_OK
) {
7255 switch (e
->opcode
) {
7256 case JIM_EXPROP_POW
:
7257 wC
= JimPowWide(wA
, wB
);
7259 case JIM_EXPROP_ADD
:
7262 case JIM_EXPROP_SUB
:
7265 case JIM_EXPROP_MUL
:
7268 case JIM_EXPROP_DIV
:
7270 Jim_SetResultString(interp
, "Division by zero", -1);
7277 * This code is tricky: C doesn't guarantee much
7278 * about the quotient or remainder, but Tcl does.
7279 * The remainder always has the same sign as the
7280 * divisor and a smaller absolute value.
7298 case JIM_EXPROP_LTE
:
7301 case JIM_EXPROP_GTE
:
7304 case JIM_EXPROP_NUMEQ
:
7307 case JIM_EXPROP_NUMNE
:
7314 else if (Jim_GetDouble(interp
, A
, &dA
) == JIM_OK
&& Jim_GetDouble(interp
, B
, &dB
) == JIM_OK
) {
7315 switch (e
->opcode
) {
7316 case JIM_EXPROP_POW
:
7317 #ifdef JIM_MATH_FUNCTIONS
7320 Jim_SetResultString(interp
, "unsupported", -1);
7324 case JIM_EXPROP_ADD
:
7327 case JIM_EXPROP_SUB
:
7330 case JIM_EXPROP_MUL
:
7333 case JIM_EXPROP_DIV
:
7336 dC
= dA
< 0 ? -INFINITY
: INFINITY
;
7338 dC
= (dA
< 0 ? -1.0 : 1.0) * strtod("Inf", NULL
);
7353 case JIM_EXPROP_LTE
:
7357 case JIM_EXPROP_GTE
:
7361 case JIM_EXPROP_NUMEQ
:
7365 case JIM_EXPROP_NUMNE
:
7374 /* Handle the string case */
7376 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7377 int i
= Jim_StringCompareObj(interp
, A
, B
, 0);
7381 switch (e
->opcode
) {
7388 case JIM_EXPROP_LTE
:
7391 case JIM_EXPROP_GTE
:
7394 case JIM_EXPROP_NUMEQ
:
7397 case JIM_EXPROP_NUMNE
:
7408 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7411 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7415 Jim_DecrRefCount(interp
, A
);
7416 Jim_DecrRefCount(interp
, B
);
7421 static int JimSearchList(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*valObj
)
7426 listlen
= Jim_ListLength(interp
, listObjPtr
);
7427 for (i
= 0; i
< listlen
; i
++) {
7430 Jim_ListIndex(interp
, listObjPtr
, i
, &objPtr
, JIM_NONE
);
7432 if (Jim_StringEqObj(objPtr
, valObj
)) {
7439 static int JimExprOpStrBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7441 Jim_Obj
*B
= ExprPop(e
);
7442 Jim_Obj
*A
= ExprPop(e
);
7446 switch (e
->opcode
) {
7447 case JIM_EXPROP_STREQ
:
7448 case JIM_EXPROP_STRNE
: {
7450 const char *sA
= Jim_GetString(A
, &Alen
);
7451 const char *sB
= Jim_GetString(B
, &Blen
);
7453 if (e
->opcode
== JIM_EXPROP_STREQ
) {
7454 wC
= (Alen
== Blen
&& memcmp(sA
, sB
, Alen
) == 0);
7457 wC
= (Alen
!= Blen
|| memcmp(sA
, sB
, Alen
) != 0);
7461 case JIM_EXPROP_STRIN
:
7462 wC
= JimSearchList(interp
, B
, A
);
7464 case JIM_EXPROP_STRNI
:
7465 wC
= !JimSearchList(interp
, B
, A
);
7470 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7472 Jim_DecrRefCount(interp
, A
);
7473 Jim_DecrRefCount(interp
, B
);
7478 static int ExprBool(Jim_Interp
*interp
, Jim_Obj
*obj
)
7483 if (Jim_GetLong(interp
, obj
, &l
) == JIM_OK
) {
7486 if (Jim_GetDouble(interp
, obj
, &d
) == JIM_OK
) {
7492 static int JimExprOpAndLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7494 Jim_Obj
*skip
= ExprPop(e
);
7495 Jim_Obj
*A
= ExprPop(e
);
7498 switch (ExprBool(interp
, A
)) {
7500 /* false, so skip RHS opcodes with a 0 result */
7501 e
->skip
= JimWideValue(skip
);
7502 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7506 /* true so continue */
7513 Jim_DecrRefCount(interp
, A
);
7514 Jim_DecrRefCount(interp
, skip
);
7519 static int JimExprOpOrLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7521 Jim_Obj
*skip
= ExprPop(e
);
7522 Jim_Obj
*A
= ExprPop(e
);
7525 switch (ExprBool(interp
, A
)) {
7527 /* false, so do nothing */
7531 /* true so skip RHS opcodes with a 1 result */
7532 e
->skip
= JimWideValue(skip
);
7533 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7541 Jim_DecrRefCount(interp
, A
);
7542 Jim_DecrRefCount(interp
, skip
);
7547 static int JimExprOpAndOrRight(Jim_Interp
*interp
, struct JimExprState
*e
)
7549 Jim_Obj
*A
= ExprPop(e
);
7552 switch (ExprBool(interp
, A
)) {
7554 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7558 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7566 Jim_DecrRefCount(interp
, A
);
7571 static int JimExprOpTernaryLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7573 Jim_Obj
*skip
= ExprPop(e
);
7574 Jim_Obj
*A
= ExprPop(e
);
7580 switch (ExprBool(interp
, A
)) {
7582 /* false, skip RHS opcodes */
7583 e
->skip
= JimWideValue(skip
);
7584 /* Push a dummy value */
7585 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7589 /* true so do nothing */
7597 Jim_DecrRefCount(interp
, A
);
7598 Jim_DecrRefCount(interp
, skip
);
7603 static int JimExprOpColonLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7605 Jim_Obj
*skip
= ExprPop(e
);
7606 Jim_Obj
*B
= ExprPop(e
);
7607 Jim_Obj
*A
= ExprPop(e
);
7609 /* No need to check for A as non-boolean */
7610 if (ExprBool(interp
, A
)) {
7611 /* true, so skip RHS opcodes */
7612 e
->skip
= JimWideValue(skip
);
7613 /* Repush B as the answer */
7617 Jim_DecrRefCount(interp
, skip
);
7618 Jim_DecrRefCount(interp
, A
);
7619 Jim_DecrRefCount(interp
, B
);
7623 static int JimExprOpNull(Jim_Interp
*interp
, struct JimExprState
*e
)
7636 /* name - precedence - arity - opcode */
7637 static const struct Jim_ExprOperator Jim_ExprOperators
[] = {
7638 [JIM_EXPROP_FUNC_INT
] = {"int", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7639 [JIM_EXPROP_FUNC_DOUBLE
] = {"double", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7640 [JIM_EXPROP_FUNC_ABS
] = {"abs", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7641 [JIM_EXPROP_FUNC_ROUND
] = {"round", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7643 #ifdef JIM_MATH_FUNCTIONS
7644 [JIM_EXPROP_FUNC_SIN
] = {"sin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7645 [JIM_EXPROP_FUNC_COS
] = {"cos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7646 [JIM_EXPROP_FUNC_TAN
] = {"tan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7647 [JIM_EXPROP_FUNC_ASIN
] = {"asin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7648 [JIM_EXPROP_FUNC_ACOS
] = {"acos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7649 [JIM_EXPROP_FUNC_ATAN
] = {"atan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7650 [JIM_EXPROP_FUNC_SINH
] = {"sinh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7651 [JIM_EXPROP_FUNC_COSH
] = {"cosh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7652 [JIM_EXPROP_FUNC_TANH
] = {"tanh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7653 [JIM_EXPROP_FUNC_CEIL
] = {"ceil", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7654 [JIM_EXPROP_FUNC_FLOOR
] = {"floor", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7655 [JIM_EXPROP_FUNC_EXP
] = {"exp", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7656 [JIM_EXPROP_FUNC_LOG
] = {"log", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7657 [JIM_EXPROP_FUNC_LOG10
] = {"log10", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7658 [JIM_EXPROP_FUNC_SQRT
] = {"sqrt", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7661 [JIM_EXPROP_NOT
] = {"!", 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7662 [JIM_EXPROP_BITNOT
] = {"~", 300, 1, JimExprOpIntUnary
, LAZY_NONE
},
7663 [JIM_EXPROP_UNARYMINUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7664 [JIM_EXPROP_UNARYPLUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7666 [JIM_EXPROP_POW
] = {"**", 250, 2, JimExprOpBin
, LAZY_NONE
},
7668 [JIM_EXPROP_MUL
] = {"*", 200, 2, JimExprOpBin
, LAZY_NONE
},
7669 [JIM_EXPROP_DIV
] = {"/", 200, 2, JimExprOpBin
, LAZY_NONE
},
7670 [JIM_EXPROP_MOD
] = {"%", 200, 2, JimExprOpIntBin
, LAZY_NONE
},
7672 [JIM_EXPROP_SUB
] = {"-", 100, 2, JimExprOpBin
, LAZY_NONE
},
7673 [JIM_EXPROP_ADD
] = {"+", 100, 2, JimExprOpBin
, LAZY_NONE
},
7675 [JIM_EXPROP_ROTL
] = {"<<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7676 [JIM_EXPROP_ROTR
] = {">>>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7677 [JIM_EXPROP_LSHIFT
] = {"<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7678 [JIM_EXPROP_RSHIFT
] = {">>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7680 [JIM_EXPROP_LT
] = {"<", 80, 2, JimExprOpBin
, LAZY_NONE
},
7681 [JIM_EXPROP_GT
] = {">", 80, 2, JimExprOpBin
, LAZY_NONE
},
7682 [JIM_EXPROP_LTE
] = {"<=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7683 [JIM_EXPROP_GTE
] = {">=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7685 [JIM_EXPROP_NUMEQ
] = {"==", 70, 2, JimExprOpBin
, LAZY_NONE
},
7686 [JIM_EXPROP_NUMNE
] = {"!=", 70, 2, JimExprOpBin
, LAZY_NONE
},
7688 [JIM_EXPROP_STREQ
] = {"eq", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7689 [JIM_EXPROP_STRNE
] = {"ne", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7691 [JIM_EXPROP_STRIN
] = {"in", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7692 [JIM_EXPROP_STRNI
] = {"ni", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7694 [JIM_EXPROP_BITAND
] = {"&", 50, 2, JimExprOpIntBin
, LAZY_NONE
},
7695 [JIM_EXPROP_BITXOR
] = {"^", 49, 2, JimExprOpIntBin
, LAZY_NONE
},
7696 [JIM_EXPROP_BITOR
] = {"|", 48, 2, JimExprOpIntBin
, LAZY_NONE
},
7698 [JIM_EXPROP_LOGICAND
] = {"&&", 10, 2, NULL
, LAZY_OP
},
7699 [JIM_EXPROP_LOGICOR
] = {"||", 9, 2, NULL
, LAZY_OP
},
7701 [JIM_EXPROP_TERNARY
] = {"?", 5, 2, JimExprOpNull
, LAZY_OP
},
7702 [JIM_EXPROP_COLON
] = {":", 5, 2, JimExprOpNull
, LAZY_OP
},
7704 /* private operators */
7705 [JIM_EXPROP_TERNARY_LEFT
] = {NULL
, 5, 2, JimExprOpTernaryLeft
, LAZY_LEFT
},
7706 [JIM_EXPROP_TERNARY_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7707 [JIM_EXPROP_COLON_LEFT
] = {NULL
, 5, 2, JimExprOpColonLeft
, LAZY_LEFT
},
7708 [JIM_EXPROP_COLON_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7709 [JIM_EXPROP_LOGICAND_LEFT
] = {NULL
, 10, 2, JimExprOpAndLeft
, LAZY_LEFT
},
7710 [JIM_EXPROP_LOGICAND_RIGHT
] = {NULL
, 10, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7711 [JIM_EXPROP_LOGICOR_LEFT
] = {NULL
, 9, 2, JimExprOpOrLeft
, LAZY_LEFT
},
7712 [JIM_EXPROP_LOGICOR_RIGHT
] = {NULL
, 9, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7715 #define JIM_EXPR_OPERATORS_NUM \
7716 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7718 static int JimParseExpression(struct JimParserCtx
*pc
)
7720 /* Discard spaces and quoted newline */
7721 while (isspace(UCHAR(*pc
->p
)) || (*(pc
->p
) == '\\' && *(pc
->p
+ 1) == '\n')) {
7727 pc
->tstart
= pc
->tend
= pc
->p
;
7728 pc
->tline
= pc
->linenr
;
7729 pc
->tt
= JIM_TT_EOL
;
7735 pc
->tstart
= pc
->tend
= pc
->p
;
7736 pc
->tline
= pc
->linenr
;
7737 pc
->tt
= JIM_TT_SUBEXPR_START
;
7742 pc
->tstart
= pc
->tend
= pc
->p
;
7743 pc
->tline
= pc
->linenr
;
7744 pc
->tt
= JIM_TT_SUBEXPR_END
;
7749 return JimParseCmd(pc
);
7751 if (JimParseVar(pc
) == JIM_ERR
)
7752 return JimParseExprOperator(pc
);
7754 /* Don't allow expr sugar in expressions */
7755 if (pc
->tt
== JIM_TT_EXPRSUGAR
) {
7772 return JimParseExprNumber(pc
);
7774 return JimParseQuote(pc
);
7776 return JimParseBrace(pc
);
7782 if (JimParseExprIrrational(pc
) == JIM_ERR
)
7783 return JimParseExprOperator(pc
);
7786 return JimParseExprOperator(pc
);
7792 static int JimParseExprNumber(struct JimParserCtx
*pc
)
7797 /* Assume an integer for now */
7798 pc
->tt
= JIM_TT_EXPR_INT
;
7800 pc
->tline
= pc
->linenr
;
7801 while (isdigit(UCHAR(*pc
->p
))
7802 || (allowhex
&& isxdigit(UCHAR(*pc
->p
)))
7803 || (allowdot
&& *pc
->p
== '.')
7804 || (pc
->p
- pc
->tstart
== 1 && *pc
->tstart
== '0' && (*pc
->p
== 'x' || *pc
->p
== 'X'))
7806 if ((*pc
->p
== 'x') || (*pc
->p
== 'X')) {
7810 if (*pc
->p
== '.') {
7812 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7816 if (!allowhex
&& (*pc
->p
== 'e' || *pc
->p
== 'E') && (pc
->p
[1] == '-' || pc
->p
[1] == '+'
7817 || isdigit(UCHAR(pc
->p
[1])))) {
7820 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7823 pc
->tend
= pc
->p
- 1;
7827 static int JimParseExprIrrational(struct JimParserCtx
*pc
)
7829 const char *Tokens
[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL
};
7832 for (token
= Tokens
; *token
!= NULL
; token
++) {
7833 int len
= strlen(*token
);
7835 if (strncmp(*token
, pc
->p
, len
) == 0) {
7837 pc
->tend
= pc
->p
+ len
- 1;
7840 pc
->tline
= pc
->linenr
;
7841 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7848 static int JimParseExprOperator(struct JimParserCtx
*pc
)
7851 int bestIdx
= -1, bestLen
= 0;
7853 /* Try to get the longest match. */
7854 for (i
= JIM_TT_EXPR_OP
; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++) {
7858 opname
= Jim_ExprOperators
[i
].name
;
7859 if (opname
== NULL
) {
7862 oplen
= strlen(opname
);
7864 if (strncmp(opname
, pc
->p
, oplen
) == 0 && oplen
> bestLen
) {
7869 if (bestIdx
== -1) {
7873 /* Validate paretheses around function arguments */
7874 if (bestIdx
>= JIM_EXPROP_FUNC_FIRST
) {
7875 const char *p
= pc
->p
+ bestLen
;
7876 int len
= pc
->len
- bestLen
;
7878 while (len
&& isspace(UCHAR(*p
))) {
7887 pc
->tend
= pc
->p
+ bestLen
- 1;
7890 pc
->tline
= pc
->linenr
;
7896 static const struct Jim_ExprOperator
*JimExprOperatorInfoByOpcode(int opcode
)
7898 return &Jim_ExprOperators
[opcode
];
7901 const char *jim_tt_name(int type
)
7903 static const char * const tt_names
[JIM_TT_EXPR_OP
] =
7904 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", "INT",
7906 if (type
< JIM_TT_EXPR_OP
) {
7907 return tt_names
[type
];
7910 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(type
);
7911 static char buf
[20];
7913 if (op
&& op
->name
) {
7916 sprintf(buf
, "(%d)", type
);
7921 /* -----------------------------------------------------------------------------
7923 * ---------------------------------------------------------------------------*/
7924 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
7925 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
7926 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
7928 static const Jim_ObjType exprObjType
= {
7930 FreeExprInternalRep
,
7933 JIM_TYPE_REFERENCES
,
7936 /* Expr bytecode structure */
7937 typedef struct ExprByteCode
7939 int len
; /* Length as number of tokens. */
7940 ScriptToken
*token
; /* Tokens array. */
7941 int inUse
; /* Used for sharing. */
7944 static void ExprFreeByteCode(Jim_Interp
*interp
, ExprByteCode
* expr
)
7948 for (i
= 0; i
< expr
->len
; i
++) {
7949 Jim_DecrRefCount(interp
, expr
->token
[i
].objPtr
);
7951 Jim_Free(expr
->token
);
7955 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
7957 ExprByteCode
*expr
= (void *)objPtr
->internalRep
.ptr
;
7960 if (--expr
->inUse
!= 0) {
7964 ExprFreeByteCode(interp
, expr
);
7968 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
7970 JIM_NOTUSED(interp
);
7971 JIM_NOTUSED(srcPtr
);
7973 /* Just returns an simple string. */
7974 dupPtr
->typePtr
= NULL
;
7977 /* Check if an expr program looks correct. */
7978 static int ExprCheckCorrectness(ExprByteCode
* expr
)
7984 /* Try to check if there are stack underflows,
7985 * and make sure at the end of the program there is
7986 * a single result on the stack. */
7987 for (i
= 0; i
< expr
->len
; i
++) {
7988 ScriptToken
*t
= &expr
->token
[i
];
7989 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
7992 stacklen
-= op
->arity
;
7996 if (t
->type
== JIM_EXPROP_TERNARY
|| t
->type
== JIM_EXPROP_TERNARY_LEFT
) {
7999 else if (t
->type
== JIM_EXPROP_COLON
|| t
->type
== JIM_EXPROP_COLON_LEFT
) {
8004 /* All operations and operands add one to the stack */
8007 if (stacklen
!= 1 || ternary
!= 0) {
8013 /* This procedure converts every occurrence of || and && opereators
8014 * in lazy unary versions.
8016 * a b || is converted into:
8018 * a <offset> |L b |R
8020 * a b && is converted into:
8022 * a <offset> &L b &R
8024 * "|L" checks if 'a' is true:
8025 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8026 * the opcode just after |R.
8027 * 2) if it is false does nothing.
8028 * "|R" checks if 'b' is true:
8029 * 1) if it is true pushes 1, otherwise pushes 0.
8031 * "&L" checks if 'a' is true:
8032 * 1) if it is true does nothing.
8033 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8034 * the opcode just after &R
8035 * "&R" checks if 'a' is true:
8036 * if it is true pushes 1, otherwise pushes 0.
8038 static int ExprAddLazyOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8042 int leftindex
, arity
, offset
;
8044 /* Search for the end of the first operator */
8045 leftindex
= expr
->len
- 1;
8049 ScriptToken
*tt
= &expr
->token
[leftindex
];
8051 if (tt
->type
>= JIM_TT_EXPR_OP
) {
8052 arity
+= JimExprOperatorInfoByOpcode(tt
->type
)->arity
;
8055 if (--leftindex
< 0) {
8062 memmove(&expr
->token
[leftindex
+ 2], &expr
->token
[leftindex
],
8063 sizeof(*expr
->token
) * (expr
->len
- leftindex
));
8065 offset
= (expr
->len
- leftindex
) - 1;
8067 /* Now we rely on the fact the the left and right version have opcodes
8068 * 1 and 2 after the main opcode respectively
8070 expr
->token
[leftindex
+ 1].type
= t
->type
+ 1;
8071 expr
->token
[leftindex
+ 1].objPtr
= interp
->emptyObj
;
8073 expr
->token
[leftindex
].type
= JIM_TT_EXPR_INT
;
8074 expr
->token
[leftindex
].objPtr
= Jim_NewIntObj(interp
, offset
);
8076 /* Now add the 'R' operator */
8077 expr
->token
[expr
->len
].objPtr
= interp
->emptyObj
;
8078 expr
->token
[expr
->len
].type
= t
->type
+ 2;
8081 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8082 for (i
= leftindex
- 1; i
> 0; i
--) {
8083 if (JimExprOperatorInfoByOpcode(expr
->token
[i
].type
)->lazy
== LAZY_LEFT
) {
8084 if (JimWideValue(expr
->token
[i
- 1].objPtr
) + i
- 1 >= leftindex
) {
8085 JimWideValue(expr
->token
[i
- 1].objPtr
) += 2;
8092 static int ExprAddOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8094 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8096 if (JimExprOperatorInfoByOpcode(t
->type
)->lazy
== LAZY_OP
) {
8097 return ExprAddLazyOperator(interp
, expr
, t
);
8100 token
->objPtr
= interp
->emptyObj
;
8101 token
->type
= t
->type
;
8108 * Returns the index of the COLON_LEFT to the left of 'right_index'
8109 * taking into account nesting.
8111 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8113 static int ExprTernaryGetColonLeftIndex(ExprByteCode
*expr
, int right_index
)
8115 int ternary_count
= 1;
8119 while (right_index
> 1) {
8120 if (expr
->token
[right_index
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8123 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_RIGHT
) {
8126 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_LEFT
&& ternary_count
== 1) {
8137 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8139 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8140 * Otherwise returns 0.
8142 static int ExprTernaryGetMoveIndices(ExprByteCode
*expr
, int right_index
, int *prev_right_index
, int *prev_left_index
)
8144 int i
= right_index
- 1;
8145 int ternary_count
= 1;
8148 if (expr
->token
[i
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8149 if (--ternary_count
== 0 && expr
->token
[i
- 2].type
== JIM_EXPROP_COLON_RIGHT
) {
8150 *prev_right_index
= i
- 2;
8151 *prev_left_index
= ExprTernaryGetColonLeftIndex(expr
, *prev_right_index
);
8155 else if (expr
->token
[i
].type
== JIM_EXPROP_COLON_RIGHT
) {
8156 if (ternary_count
== 0) {
8167 * ExprTernaryReorderExpression description
8168 * ========================================
8170 * ?: is right-to-left associative which doesn't work with the stack-based
8171 * expression engine. The fix is to reorder the bytecode.
8177 * Has initial bytecode:
8179 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8180 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8182 * The fix involves simulating this expression instead:
8186 * With the following bytecode:
8188 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8189 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8191 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8192 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8193 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8194 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8196 * ExprTernaryReorderExpression works thus as follows :
8197 * - start from the end of the stack
8198 * - while walking towards the beginning of the stack
8199 * if token=JIM_EXPROP_COLON_RIGHT then
8200 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8201 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8202 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8204 * perform the rotation
8205 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8209 * Note: care has to be taken for nested ternary constructs!!!
8211 static void ExprTernaryReorderExpression(Jim_Interp
*interp
, ExprByteCode
*expr
)
8215 for (i
= expr
->len
- 1; i
> 1; i
--) {
8216 int prev_right_index
;
8217 int prev_left_index
;
8221 if (expr
->token
[i
].type
!= JIM_EXPROP_COLON_RIGHT
) {
8225 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8226 if (ExprTernaryGetMoveIndices(expr
, i
, &prev_right_index
, &prev_left_index
) == 0) {
8231 ** rotate tokens down
8233 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8242 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8244 tmp
= expr
->token
[prev_right_index
];
8245 for (j
= prev_right_index
; j
< i
; j
++) {
8246 expr
->token
[j
] = expr
->token
[j
+ 1];
8248 expr
->token
[i
] = tmp
;
8250 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8252 * This is 'colon left increment' = i - prev_right_index
8254 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8255 * [prev_left_index-1] : skip_count
8258 JimWideValue(expr
->token
[prev_left_index
-1].objPtr
) += (i
- prev_right_index
);
8260 /* Adjust for i-- in the loop */
8265 static ExprByteCode
*ExprCreateByteCode(Jim_Interp
*interp
, const ParseTokenList
*tokenlist
)
8271 int prevtt
= JIM_TT_NONE
;
8272 int have_ternary
= 0;
8275 int count
= tokenlist
->count
- 1;
8277 expr
= Jim_Alloc(sizeof(*expr
));
8281 Jim_InitStack(&stack
);
8283 /* Need extra bytecodes for lazy operators.
8284 * Also check for the ternary operator
8286 for (i
= 0; i
< tokenlist
->count
; i
++) {
8287 ParseToken
*t
= &tokenlist
->list
[i
];
8289 if (JimExprOperatorInfoByOpcode(t
->type
)->lazy
== LAZY_OP
) {
8291 /* Ternary is a lazy op but also needs reordering */
8292 if (t
->type
== JIM_EXPROP_TERNARY
) {
8298 expr
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
8300 for (i
= 0; i
< tokenlist
->count
&& ok
; i
++) {
8301 ParseToken
*t
= &tokenlist
->list
[i
];
8303 /* Next token will be stored here */
8304 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8306 if (t
->type
== JIM_TT_EOL
) {
8314 case JIM_TT_DICTSUGAR
:
8315 case JIM_TT_EXPRSUGAR
:
8317 token
->objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
8318 token
->type
= t
->type
;
8322 case JIM_TT_EXPR_INT
:
8323 token
->objPtr
= Jim_NewIntObj(interp
, strtoull(t
->token
, NULL
, 0));
8324 token
->type
= t
->type
;
8328 case JIM_TT_EXPR_DOUBLE
:
8329 token
->objPtr
= Jim_NewDoubleObj(interp
, strtod(t
->token
, NULL
));
8330 token
->type
= t
->type
;
8334 case JIM_TT_SUBEXPR_START
:
8335 Jim_StackPush(&stack
, t
);
8336 prevtt
= JIM_TT_NONE
;
8339 case JIM_TT_SUBEXPR_END
:
8341 while (Jim_StackLen(&stack
)) {
8342 ParseToken
*tt
= Jim_StackPop(&stack
);
8344 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8349 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8354 Jim_SetResultString(interp
, "Unexpected close parenthesis", -1);
8361 /* Must be an operator */
8362 const struct Jim_ExprOperator
*op
;
8365 /* Convert -/+ to unary minus or unary plus if necessary */
8366 if (prevtt
== JIM_TT_NONE
|| prevtt
>= JIM_TT_EXPR_OP
) {
8367 if (t
->type
== JIM_EXPROP_SUB
) {
8368 t
->type
= JIM_EXPROP_UNARYMINUS
;
8370 else if (t
->type
== JIM_EXPROP_ADD
) {
8371 t
->type
= JIM_EXPROP_UNARYPLUS
;
8375 op
= JimExprOperatorInfoByOpcode(t
->type
);
8377 /* Now handle precedence */
8378 while ((tt
= Jim_StackPeek(&stack
)) != NULL
) {
8379 const struct Jim_ExprOperator
*tt_op
=
8380 JimExprOperatorInfoByOpcode(tt
->type
);
8382 /* Note that right-to-left associativity of ?: operator is handled later */
8384 if (op
->arity
!= 1 && tt_op
->precedence
>= op
->precedence
) {
8385 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8389 Jim_StackPop(&stack
);
8395 Jim_StackPush(&stack
, t
);
8402 /* Reduce any remaining subexpr */
8403 while (Jim_StackLen(&stack
)) {
8404 ParseToken
*tt
= Jim_StackPop(&stack
);
8406 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8408 Jim_SetResultString(interp
, "Missing close parenthesis", -1);
8411 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8418 ExprTernaryReorderExpression(interp
, expr
);
8422 /* Free the stack used for the compilation. */
8423 Jim_FreeStack(&stack
);
8425 for (i
= 0; i
< expr
->len
; i
++) {
8426 Jim_IncrRefCount(expr
->token
[i
].objPtr
);
8430 ExprFreeByteCode(interp
, expr
);
8438 /* This method takes the string representation of an expression
8439 * and generates a program for the Expr's stack-based VM. */
8440 int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
8443 const char *exprText
;
8444 struct JimParserCtx parser
;
8445 struct ExprByteCode
*expr
;
8446 ParseTokenList tokenlist
;
8449 exprText
= Jim_GetString(objPtr
, &exprTextLen
);
8451 /* Initially tokenise the expression into tokenlist */
8452 ScriptTokenListInit(&tokenlist
);
8454 JimParserInit(&parser
, exprText
, exprTextLen
, 0);
8455 while (!parser
.eof
) {
8456 if (JimParseExpression(&parser
) != JIM_OK
) {
8457 ScriptTokenListFree(&tokenlist
);
8459 Jim_SetResultFormatted(interp
, "syntax error in expression: \"%#s\"", objPtr
);
8464 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
8468 #ifdef DEBUG_SHOW_EXPR_TOKENS
8471 printf("==== Expr Tokens ====\n");
8472 for (i
= 0; i
< tokenlist
.count
; i
++) {
8473 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
.list
[i
].line
, jim_tt_name(tokenlist
.list
[i
].type
),
8474 tokenlist
.list
[i
].len
, tokenlist
.list
[i
].token
);
8479 /* Now create the expression bytecode from the tokenlist */
8480 expr
= ExprCreateByteCode(interp
, &tokenlist
);
8482 /* No longer need the token list */
8483 ScriptTokenListFree(&tokenlist
);
8489 #ifdef DEBUG_SHOW_EXPR
8493 printf("==== Expr ====\n");
8494 for (i
= 0; i
< expr
->len
; i
++) {
8495 ScriptToken
*t
= &expr
->token
[i
];
8497 printf("[%2d] %s '%s'\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
8502 /* Check program correctness. */
8503 if (ExprCheckCorrectness(expr
) != JIM_OK
) {
8504 ExprFreeByteCode(interp
, expr
);
8511 /* Free the old internal rep and set the new one. */
8512 Jim_FreeIntRep(interp
, objPtr
);
8513 Jim_SetIntRepPtr(objPtr
, expr
);
8514 objPtr
->typePtr
= &exprObjType
;
8518 static ExprByteCode
*JimGetExpression(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8520 if (objPtr
->typePtr
!= &exprObjType
) {
8521 if (SetExprFromAny(interp
, objPtr
) != JIM_OK
) {
8525 return (ExprByteCode
*) Jim_GetIntRepPtr(objPtr
);
8528 /* -----------------------------------------------------------------------------
8529 * Expressions evaluation.
8530 * Jim uses a specialized stack-based virtual machine for expressions,
8531 * that takes advantage of the fact that expr's operators
8532 * can't be redefined.
8534 * Jim_EvalExpression() uses the bytecode compiled by
8535 * SetExprFromAny() method of the "expression" object.
8537 * On success a Tcl Object containing the result of the evaluation
8538 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8540 * On error the function returns a retcode != to JIM_OK and set a suitable
8541 * error on the interp.
8542 * ---------------------------------------------------------------------------*/
8543 #define JIM_EE_STATICSTACK_LEN 10
8545 int Jim_EvalExpression(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, Jim_Obj
**exprResultPtrPtr
)
8548 Jim_Obj
*staticStack
[JIM_EE_STATICSTACK_LEN
];
8550 int retcode
= JIM_OK
;
8551 struct JimExprState e
;
8553 expr
= JimGetExpression(interp
, exprObjPtr
);
8555 return JIM_ERR
; /* error in expression. */
8558 #ifdef JIM_OPTIMIZATION
8559 /* Check for one of the following common expressions used by while/for
8564 * $a < CONST, $a < $b
8565 * $a <= CONST, $a <= $b
8566 * $a > CONST, $a > $b
8567 * $a >= CONST, $a >= $b
8568 * $a != CONST, $a != $b
8569 * $a == CONST, $a == $b
8574 /* STEP 1 -- Check if there are the conditions to run the specialized
8575 * version of while */
8577 switch (expr
->len
) {
8579 if (expr
->token
[0].type
== JIM_TT_EXPR_INT
) {
8580 *exprResultPtrPtr
= expr
->token
[0].objPtr
;
8581 Jim_IncrRefCount(*exprResultPtrPtr
);
8584 if (expr
->token
[0].type
== JIM_TT_VAR
) {
8585 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_ERRMSG
);
8587 *exprResultPtrPtr
= objPtr
;
8588 Jim_IncrRefCount(*exprResultPtrPtr
);
8595 if (expr
->token
[1].type
== JIM_EXPROP_NOT
&& expr
->token
[0].type
== JIM_TT_VAR
) {
8598 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8599 if (objPtr
&& JimIsWide(objPtr
)
8600 && Jim_GetWide(interp
, objPtr
, &wideValue
) == JIM_OK
) {
8601 *exprResultPtrPtr
= wideValue
? interp
->falseObj
: interp
->trueObj
;
8602 Jim_IncrRefCount(*exprResultPtrPtr
);
8609 if (expr
->token
[0].type
== JIM_TT_VAR
&& (expr
->token
[1].type
== JIM_TT_EXPR_INT
8610 || expr
->token
[1].type
== JIM_TT_VAR
)) {
8611 switch (expr
->token
[2].type
) {
8613 case JIM_EXPROP_LTE
:
8615 case JIM_EXPROP_GTE
:
8616 case JIM_EXPROP_NUMEQ
:
8617 case JIM_EXPROP_NUMNE
:{
8619 jim_wide wideValueA
;
8620 jim_wide wideValueB
;
8622 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8623 if (objPtr
&& JimIsWide(objPtr
)
8624 && Jim_GetWide(interp
, objPtr
, &wideValueA
) == JIM_OK
) {
8625 if (expr
->token
[1].type
== JIM_TT_VAR
) {
8627 Jim_GetVariable(interp
, expr
->token
[1].objPtr
,
8631 objPtr
= expr
->token
[1].objPtr
;
8633 if (objPtr
&& JimIsWide(objPtr
)
8634 && Jim_GetWide(interp
, objPtr
, &wideValueB
) == JIM_OK
) {
8637 switch (expr
->token
[2].type
) {
8639 cmpRes
= wideValueA
< wideValueB
;
8641 case JIM_EXPROP_LTE
:
8642 cmpRes
= wideValueA
<= wideValueB
;
8645 cmpRes
= wideValueA
> wideValueB
;
8647 case JIM_EXPROP_GTE
:
8648 cmpRes
= wideValueA
>= wideValueB
;
8650 case JIM_EXPROP_NUMEQ
:
8651 cmpRes
= wideValueA
== wideValueB
;
8653 case JIM_EXPROP_NUMNE
:
8654 cmpRes
= wideValueA
!= wideValueB
;
8656 default: /*notreached */
8660 cmpRes
? interp
->trueObj
: interp
->falseObj
;
8661 Jim_IncrRefCount(*exprResultPtrPtr
);
8673 /* In order to avoid that the internal repr gets freed due to
8674 * shimmering of the exprObjPtr's object, we make the internal rep
8678 /* The stack-based expr VM itself */
8680 /* Stack allocation. Expr programs have the feature that
8681 * a program of length N can't require a stack longer than
8683 if (expr
->len
> JIM_EE_STATICSTACK_LEN
)
8684 e
.stack
= Jim_Alloc(sizeof(Jim_Obj
*) * expr
->len
);
8686 e
.stack
= staticStack
;
8690 /* Execute every instruction */
8691 for (i
= 0; i
< expr
->len
&& retcode
== JIM_OK
; i
++) {
8694 switch (expr
->token
[i
].type
) {
8695 case JIM_TT_EXPR_INT
:
8696 case JIM_TT_EXPR_DOUBLE
:
8698 ExprPush(&e
, expr
->token
[i
].objPtr
);
8702 objPtr
= Jim_GetVariable(interp
, expr
->token
[i
].objPtr
, JIM_ERRMSG
);
8704 ExprPush(&e
, objPtr
);
8711 case JIM_TT_DICTSUGAR
:
8712 objPtr
= JimExpandDictSugar(interp
, expr
->token
[i
].objPtr
);
8714 ExprPush(&e
, objPtr
);
8722 retcode
= Jim_SubstObj(interp
, expr
->token
[i
].objPtr
, &objPtr
, JIM_NONE
);
8723 if (retcode
== JIM_OK
) {
8724 ExprPush(&e
, objPtr
);
8729 retcode
= Jim_EvalObj(interp
, expr
->token
[i
].objPtr
);
8730 if (retcode
== JIM_OK
) {
8731 ExprPush(&e
, Jim_GetResult(interp
));
8736 /* Find and execute the operation */
8738 e
.opcode
= expr
->token
[i
].type
;
8740 retcode
= JimExprOperatorInfoByOpcode(e
.opcode
)->funcop(interp
, &e
);
8741 /* Skip some opcodes if necessary */
8750 if (retcode
== JIM_OK
) {
8751 *exprResultPtrPtr
= ExprPop(&e
);
8754 for (i
= 0; i
< e
.stacklen
; i
++) {
8755 Jim_DecrRefCount(interp
, e
.stack
[i
]);
8758 if (e
.stack
!= staticStack
) {
8764 int Jim_GetBoolFromExpr(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, int *boolPtr
)
8769 Jim_Obj
*exprResultPtr
;
8771 retcode
= Jim_EvalExpression(interp
, exprObjPtr
, &exprResultPtr
);
8772 if (retcode
!= JIM_OK
)
8775 if (JimGetWideNoErr(interp
, exprResultPtr
, &wideValue
) != JIM_OK
) {
8776 if (Jim_GetDouble(interp
, exprResultPtr
, &doubleValue
) != JIM_OK
) {
8777 Jim_DecrRefCount(interp
, exprResultPtr
);
8781 Jim_DecrRefCount(interp
, exprResultPtr
);
8782 *boolPtr
= doubleValue
!= 0;
8786 *boolPtr
= wideValue
!= 0;
8788 Jim_DecrRefCount(interp
, exprResultPtr
);
8792 /* -----------------------------------------------------------------------------
8793 * ScanFormat String Object
8794 * ---------------------------------------------------------------------------*/
8796 /* This Jim_Obj will held a parsed representation of a format string passed to
8797 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8798 * to be parsed in its entirely first and then, if correct, can be used for
8799 * scanning. To avoid endless re-parsing, the parsed representation will be
8800 * stored in an internal representation and re-used for performance reason. */
8802 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8803 * scanformat string. This part will later be used to extract information
8804 * out from the string to be parsed by Jim_ScanString */
8806 typedef struct ScanFmtPartDescr
8808 char type
; /* Type of conversion (e.g. c, d, f) */
8809 char modifier
; /* Modify type (e.g. l - long, h - short */
8810 size_t width
; /* Maximal width of input to be converted */
8811 int pos
; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8812 char *arg
; /* Specification of a CHARSET conversion */
8813 char *prefix
; /* Prefix to be scanned literally before conversion */
8816 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8817 * string parsed and separated in part descriptions. Furthermore it contains
8818 * the original string representation of the scanformat string to allow for
8819 * fast update of the Jim_Obj's string representation part.
8821 * As an add-on the internal object representation adds some scratch pad area
8822 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8823 * memory for purpose of string scanning.
8825 * The error member points to a static allocated string in case of a mal-
8826 * formed scanformat string or it contains '0' (NULL) in case of a valid
8827 * parse representation.
8829 * The whole memory of the internal representation is allocated as a single
8830 * area of memory that will be internally separated. So freeing and duplicating
8831 * of such an object is cheap */
8833 typedef struct ScanFmtStringObj
8835 jim_wide size
; /* Size of internal repr in bytes */
8836 char *stringRep
; /* Original string representation */
8837 size_t count
; /* Number of ScanFmtPartDescr contained */
8838 size_t convCount
; /* Number of conversions that will assign */
8839 size_t maxPos
; /* Max position index if XPG3 is used */
8840 const char *error
; /* Ptr to error text (NULL if no error */
8841 char *scratch
; /* Some scratch pad used by Jim_ScanString */
8842 ScanFmtPartDescr descr
[1]; /* The vector of partial descriptions */
8846 static void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
8847 static void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
8848 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
);
8850 static const Jim_ObjType scanFmtStringObjType
= {
8852 FreeScanFmtInternalRep
,
8853 DupScanFmtInternalRep
,
8854 UpdateStringOfScanFmt
,
8858 void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8860 JIM_NOTUSED(interp
);
8861 Jim_Free((char *)objPtr
->internalRep
.ptr
);
8862 objPtr
->internalRep
.ptr
= 0;
8865 void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8867 size_t size
= (size_t) ((ScanFmtStringObj
*) srcPtr
->internalRep
.ptr
)->size
;
8868 ScanFmtStringObj
*newVec
= (ScanFmtStringObj
*) Jim_Alloc(size
);
8870 JIM_NOTUSED(interp
);
8871 memcpy(newVec
, srcPtr
->internalRep
.ptr
, size
);
8872 dupPtr
->internalRep
.ptr
= newVec
;
8873 dupPtr
->typePtr
= &scanFmtStringObjType
;
8876 void UpdateStringOfScanFmt(Jim_Obj
*objPtr
)
8878 char *bytes
= ((ScanFmtStringObj
*) objPtr
->internalRep
.ptr
)->stringRep
;
8880 objPtr
->bytes
= Jim_StrDup(bytes
);
8881 objPtr
->length
= strlen(bytes
);
8884 /* SetScanFmtFromAny will parse a given string and create the internal
8885 * representation of the format specification. In case of an error
8886 * the error data member of the internal representation will be set
8887 * to an descriptive error text and the function will be left with
8888 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
8891 static int SetScanFmtFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8893 ScanFmtStringObj
*fmtObj
;
8895 int maxCount
, i
, approxSize
, lastPos
= -1;
8896 const char *fmt
= objPtr
->bytes
;
8897 int maxFmtLen
= objPtr
->length
;
8898 const char *fmtEnd
= fmt
+ maxFmtLen
;
8901 Jim_FreeIntRep(interp
, objPtr
);
8902 /* Count how many conversions could take place maximally */
8903 for (i
= 0, maxCount
= 0; i
< maxFmtLen
; ++i
)
8906 /* Calculate an approximation of the memory necessary */
8907 approxSize
= sizeof(ScanFmtStringObj
) /* Size of the container */
8908 +(maxCount
+ 1) * sizeof(ScanFmtPartDescr
) /* Size of all partials */
8909 +maxFmtLen
* sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
8910 + maxFmtLen
* sizeof(char) + 1 /* Original stringrep */
8911 + maxFmtLen
* sizeof(char) /* Arg for CHARSETs */
8912 +(maxCount
+ 1) * sizeof(char) /* '\0' for every partial */
8913 +1; /* safety byte */
8914 fmtObj
= (ScanFmtStringObj
*) Jim_Alloc(approxSize
);
8915 memset(fmtObj
, 0, approxSize
);
8916 fmtObj
->size
= approxSize
;
8918 fmtObj
->scratch
= (char *)&fmtObj
->descr
[maxCount
+ 1];
8919 fmtObj
->stringRep
= fmtObj
->scratch
+ maxFmtLen
+ 3 + 1;
8920 memcpy(fmtObj
->stringRep
, fmt
, maxFmtLen
);
8921 buffer
= fmtObj
->stringRep
+ maxFmtLen
+ 1;
8922 objPtr
->internalRep
.ptr
= fmtObj
;
8923 objPtr
->typePtr
= &scanFmtStringObjType
;
8924 for (i
= 0, curr
= 0; fmt
< fmtEnd
; ++fmt
) {
8925 int width
= 0, skip
;
8926 ScanFmtPartDescr
*descr
= &fmtObj
->descr
[curr
];
8929 descr
->width
= 0; /* Assume width unspecified */
8930 /* Overread and store any "literal" prefix */
8931 if (*fmt
!= '%' || fmt
[1] == '%') {
8933 descr
->prefix
= &buffer
[i
];
8934 for (; fmt
< fmtEnd
; ++fmt
) {
8944 /* Skip the conversion introducing '%' sign */
8946 /* End reached due to non-conversion literal only? */
8949 descr
->pos
= 0; /* Assume "natural" positioning */
8951 descr
->pos
= -1; /* Okay, conversion will not be assigned */
8955 fmtObj
->convCount
++; /* Otherwise count as assign-conversion */
8956 /* Check if next token is a number (could be width or pos */
8957 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
8959 /* Was the number a XPG3 position specifier? */
8960 if (descr
->pos
!= -1 && *fmt
== '$') {
8966 /* Look if "natural" postioning and XPG3 one was mixed */
8967 if ((lastPos
== 0 && descr
->pos
> 0)
8968 || (lastPos
> 0 && descr
->pos
== 0)) {
8969 fmtObj
->error
= "cannot mix \"%\" and \"%n$\" conversion specifiers";
8972 /* Look if this position was already used */
8973 for (prev
= 0; prev
< curr
; ++prev
) {
8974 if (fmtObj
->descr
[prev
].pos
== -1)
8976 if (fmtObj
->descr
[prev
].pos
== descr
->pos
) {
8978 "variable is assigned by multiple \"%n$\" conversion specifiers";
8982 /* Try to find a width after the XPG3 specifier */
8983 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
8984 descr
->width
= width
;
8987 if (descr
->pos
> 0 && (size_t) descr
->pos
> fmtObj
->maxPos
)
8988 fmtObj
->maxPos
= descr
->pos
;
8991 /* Number was not a XPG3, so it has to be a width */
8992 descr
->width
= width
;
8995 /* If positioning mode was undetermined yet, fix this */
8997 lastPos
= descr
->pos
;
8998 /* Handle CHARSET conversion type ... */
9000 int swapped
= 1, beg
= i
, end
, j
;
9003 descr
->arg
= &buffer
[i
];
9006 buffer
[i
++] = *fmt
++;
9008 buffer
[i
++] = *fmt
++;
9009 while (*fmt
&& *fmt
!= ']')
9010 buffer
[i
++] = *fmt
++;
9012 fmtObj
->error
= "unmatched [ in format string";
9017 /* In case a range fence was given "backwards", swap it */
9020 for (j
= beg
+ 1; j
< end
- 1; ++j
) {
9021 if (buffer
[j
] == '-' && buffer
[j
- 1] > buffer
[j
+ 1]) {
9022 char tmp
= buffer
[j
- 1];
9024 buffer
[j
- 1] = buffer
[j
+ 1];
9025 buffer
[j
+ 1] = tmp
;
9032 /* Remember any valid modifier if given */
9033 if (strchr("hlL", *fmt
) != 0)
9034 descr
->modifier
= tolower((int)*fmt
++);
9037 if (strchr("efgcsndoxui", *fmt
) == 0) {
9038 fmtObj
->error
= "bad scan conversion character";
9041 else if (*fmt
== 'c' && descr
->width
!= 0) {
9042 fmtObj
->error
= "field width may not be specified in %c " "conversion";
9045 else if (*fmt
== 'u' && descr
->modifier
== 'l') {
9046 fmtObj
->error
= "unsigned wide not supported";
9056 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9058 #define FormatGetCnvCount(_fo_) \
9059 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9060 #define FormatGetMaxPos(_fo_) \
9061 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9062 #define FormatGetError(_fo_) \
9063 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9065 /* JimScanAString is used to scan an unspecified string that ends with
9066 * next WS, or a string that is specified via a charset.
9069 static Jim_Obj
*JimScanAString(Jim_Interp
*interp
, const char *sdescr
, const char *str
)
9071 char *buffer
= Jim_StrDup(str
);
9078 if (!sdescr
&& isspace(UCHAR(*str
)))
9079 break; /* EOS via WS if unspecified */
9081 n
= utf8_tounicode(str
, &c
);
9082 if (sdescr
&& !JimCharsetMatch(sdescr
, c
, JIM_CHARSET_SCAN
))
9088 return Jim_NewStringObjNoAlloc(interp
, buffer
, p
- buffer
);
9091 /* ScanOneEntry will scan one entry out of the string passed as argument.
9092 * It use the sscanf() function for this task. After extracting and
9093 * converting of the value, the count of scanned characters will be
9094 * returned of -1 in case of no conversion tool place and string was
9095 * already scanned thru */
9097 static int ScanOneEntry(Jim_Interp
*interp
, const char *str
, int pos
, int strLen
,
9098 ScanFmtStringObj
* fmtObj
, long idx
, Jim_Obj
**valObjPtr
)
9101 const ScanFmtPartDescr
*descr
= &fmtObj
->descr
[idx
];
9103 size_t anchor
= pos
;
9105 Jim_Obj
*tmpObj
= NULL
;
9107 /* First pessimistically assume, we will not scan anything :-) */
9109 if (descr
->prefix
) {
9110 /* There was a prefix given before the conversion, skip it and adjust
9111 * the string-to-be-parsed accordingly */
9112 /* XXX: Should be checking strLen, not str[pos] */
9113 for (i
= 0; pos
< strLen
&& descr
->prefix
[i
]; ++i
) {
9114 /* If prefix require, skip WS */
9115 if (isspace(UCHAR(descr
->prefix
[i
])))
9116 while (pos
< strLen
&& isspace(UCHAR(str
[pos
])))
9118 else if (descr
->prefix
[i
] != str
[pos
])
9119 break; /* Prefix do not match here, leave the loop */
9121 ++pos
; /* Prefix matched so far, next round */
9123 if (pos
>= strLen
) {
9124 return -1; /* All of str consumed: EOF condition */
9126 else if (descr
->prefix
[i
] != 0)
9127 return 0; /* Not whole prefix consumed, no conversion possible */
9129 /* For all but following conversion, skip leading WS */
9130 if (descr
->type
!= 'c' && descr
->type
!= '[' && descr
->type
!= 'n')
9131 while (isspace(UCHAR(str
[pos
])))
9133 /* Determine how much skipped/scanned so far */
9134 scanned
= pos
- anchor
;
9136 /* %c is a special, simple case. no width */
9137 if (descr
->type
== 'n') {
9138 /* Return pseudo conversion means: how much scanned so far? */
9139 *valObjPtr
= Jim_NewIntObj(interp
, anchor
+ scanned
);
9141 else if (pos
>= strLen
) {
9142 /* Cannot scan anything, as str is totally consumed */
9145 else if (descr
->type
== 'c') {
9147 scanned
+= utf8_tounicode(&str
[pos
], &c
);
9148 *valObjPtr
= Jim_NewIntObj(interp
, c
);
9152 /* Processing of conversions follows ... */
9153 if (descr
->width
> 0) {
9154 /* Do not try to scan as fas as possible but only the given width.
9155 * To ensure this, we copy the part that should be scanned. */
9156 size_t sLen
= utf8_strlen(&str
[pos
], strLen
- pos
);
9157 size_t tLen
= descr
->width
> sLen
? sLen
: descr
->width
;
9159 tmpObj
= Jim_NewStringObjUtf8(interp
, str
+ pos
, tLen
);
9160 tok
= tmpObj
->bytes
;
9163 /* As no width was given, simply refer to the original string */
9166 switch (descr
->type
) {
9172 char *endp
; /* Position where the number finished */
9175 int base
= descr
->type
== 'o' ? 8
9176 : descr
->type
== 'x' ? 16 : descr
->type
== 'i' ? 0 : 10;
9178 /* Try to scan a number with the given base */
9179 w
= strtoull(tok
, &endp
, base
);
9180 if (endp
== tok
&& base
== 0) {
9181 /* If scanning failed, and base was undetermined, simply
9182 * put it to 10 and try once more. This should catch the
9183 * case where %i begin to parse a number prefix (e.g.
9184 * '0x' but no further digits follows. This will be
9185 * handled as a ZERO followed by a char 'x' by Tcl */
9186 w
= strtoull(tok
, &endp
, 10);
9190 /* There was some number sucessfully scanned! */
9191 *valObjPtr
= Jim_NewIntObj(interp
, w
);
9193 /* Adjust the number-of-chars scanned so far */
9194 scanned
+= endp
- tok
;
9197 /* Nothing was scanned. We have to determine if this
9198 * happened due to e.g. prefix mismatch or input str
9200 scanned
= *tok
? 0 : -1;
9206 *valObjPtr
= JimScanAString(interp
, descr
->arg
, tok
);
9207 scanned
+= Jim_Length(*valObjPtr
);
9214 double value
= strtod(tok
, &endp
);
9217 /* There was some number sucessfully scanned! */
9218 *valObjPtr
= Jim_NewDoubleObj(interp
, value
);
9219 /* Adjust the number-of-chars scanned so far */
9220 scanned
+= endp
- tok
;
9223 /* Nothing was scanned. We have to determine if this
9224 * happened due to e.g. prefix mismatch or input str
9226 scanned
= *tok
? 0 : -1;
9231 /* If a substring was allocated (due to pre-defined width) do not
9232 * forget to free it */
9234 Jim_FreeNewObj(interp
, tmpObj
);
9240 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9241 * string and returns all converted (and not ignored) values in a list back
9242 * to the caller. If an error occured, a NULL pointer will be returned */
9244 Jim_Obj
*Jim_ScanString(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*fmtObjPtr
, int flags
)
9248 const char *str
= Jim_String(strObjPtr
);
9249 int strLen
= Jim_Utf8Length(interp
, strObjPtr
);
9250 Jim_Obj
*resultList
= 0;
9251 Jim_Obj
**resultVec
= 0;
9253 Jim_Obj
*emptyStr
= 0;
9254 ScanFmtStringObj
*fmtObj
;
9256 /* This should never happen. The format object should already be of the correct type */
9257 JimPanic((fmtObjPtr
->typePtr
!= &scanFmtStringObjType
, interp
, "Jim_ScanString() for non-scan format"));
9259 fmtObj
= (ScanFmtStringObj
*) fmtObjPtr
->internalRep
.ptr
;
9260 /* Check if format specification was valid */
9261 if (fmtObj
->error
!= 0) {
9262 if (flags
& JIM_ERRMSG
)
9263 Jim_SetResultString(interp
, fmtObj
->error
, -1);
9266 /* Allocate a new "shared" empty string for all unassigned conversions */
9267 emptyStr
= Jim_NewEmptyStringObj(interp
);
9268 Jim_IncrRefCount(emptyStr
);
9269 /* Create a list and fill it with empty strings up to max specified XPG3 */
9270 resultList
= Jim_NewListObj(interp
, 0, 0);
9271 if (fmtObj
->maxPos
> 0) {
9272 for (i
= 0; i
< fmtObj
->maxPos
; ++i
)
9273 Jim_ListAppendElement(interp
, resultList
, emptyStr
);
9274 JimListGetElements(interp
, resultList
, &resultc
, &resultVec
);
9276 /* Now handle every partial format description */
9277 for (i
= 0, pos
= 0; i
< fmtObj
->count
; ++i
) {
9278 ScanFmtPartDescr
*descr
= &(fmtObj
->descr
[i
]);
9281 /* Only last type may be "literal" w/o conversion - skip it! */
9282 if (descr
->type
== 0)
9284 /* As long as any conversion could be done, we will proceed */
9286 scanned
= ScanOneEntry(interp
, str
, pos
, strLen
, fmtObj
, i
, &value
);
9287 /* In case our first try results in EOF, we will leave */
9288 if (scanned
== -1 && i
== 0)
9290 /* Advance next pos-to-be-scanned for the amount scanned already */
9293 /* value == 0 means no conversion took place so take empty string */
9295 value
= Jim_NewEmptyStringObj(interp
);
9296 /* If value is a non-assignable one, skip it */
9297 if (descr
->pos
== -1) {
9298 Jim_FreeNewObj(interp
, value
);
9300 else if (descr
->pos
== 0)
9301 /* Otherwise append it to the result list if no XPG3 was given */
9302 Jim_ListAppendElement(interp
, resultList
, value
);
9303 else if (resultVec
[descr
->pos
- 1] == emptyStr
) {
9304 /* But due to given XPG3, put the value into the corr. slot */
9305 Jim_DecrRefCount(interp
, resultVec
[descr
->pos
- 1]);
9306 Jim_IncrRefCount(value
);
9307 resultVec
[descr
->pos
- 1] = value
;
9310 /* Otherwise, the slot was already used - free obj and ERROR */
9311 Jim_FreeNewObj(interp
, value
);
9315 Jim_DecrRefCount(interp
, emptyStr
);
9318 Jim_DecrRefCount(interp
, emptyStr
);
9319 Jim_FreeNewObj(interp
, resultList
);
9320 return (Jim_Obj
*)EOF
;
9322 Jim_DecrRefCount(interp
, emptyStr
);
9323 Jim_FreeNewObj(interp
, resultList
);
9327 /* -----------------------------------------------------------------------------
9328 * Pseudo Random Number Generation
9329 * ---------------------------------------------------------------------------*/
9330 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
);
9332 /* Initialize the sbox with the numbers from 0 to 255 */
9333 static void JimPrngInit(Jim_Interp
*interp
)
9335 #define PRNG_SEED_SIZE 256
9338 time_t t
= time(NULL
);
9340 interp
->prngState
= Jim_Alloc(sizeof(Jim_PrngState
));
9342 seed
= Jim_Alloc(PRNG_SEED_SIZE
* sizeof(*seed
));
9343 for (i
= 0; i
< PRNG_SEED_SIZE
; i
++) {
9344 seed
[i
] = (rand() ^ t
^ clock());
9346 JimPrngSeed(interp
, (unsigned char *)seed
, PRNG_SEED_SIZE
* sizeof(*seed
));
9350 /* Generates N bytes of random data */
9351 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
)
9353 Jim_PrngState
*prng
;
9354 unsigned char *destByte
= (unsigned char *)dest
;
9355 unsigned int si
, sj
, x
;
9357 /* initialization, only needed the first time */
9358 if (interp
->prngState
== NULL
)
9359 JimPrngInit(interp
);
9360 prng
= interp
->prngState
;
9361 /* generates 'len' bytes of pseudo-random numbers */
9362 for (x
= 0; x
< len
; x
++) {
9363 prng
->i
= (prng
->i
+ 1) & 0xff;
9364 si
= prng
->sbox
[prng
->i
];
9365 prng
->j
= (prng
->j
+ si
) & 0xff;
9366 sj
= prng
->sbox
[prng
->j
];
9367 prng
->sbox
[prng
->i
] = sj
;
9368 prng
->sbox
[prng
->j
] = si
;
9369 *destByte
++ = prng
->sbox
[(si
+ sj
) & 0xff];
9373 /* Re-seed the generator with user-provided bytes */
9374 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
)
9377 Jim_PrngState
*prng
;
9379 /* initialization, only needed the first time */
9380 if (interp
->prngState
== NULL
)
9381 JimPrngInit(interp
);
9382 prng
= interp
->prngState
;
9384 /* Set the sbox[i] with i */
9385 for (i
= 0; i
< 256; i
++)
9387 /* Now use the seed to perform a random permutation of the sbox */
9388 for (i
= 0; i
< seedLen
; i
++) {
9391 t
= prng
->sbox
[i
& 0xFF];
9392 prng
->sbox
[i
& 0xFF] = prng
->sbox
[seed
[i
]];
9393 prng
->sbox
[seed
[i
]] = t
;
9395 prng
->i
= prng
->j
= 0;
9397 /* discard at least the first 256 bytes of stream.
9398 * borrow the seed buffer for this
9400 for (i
= 0; i
< 256; i
+= seedLen
) {
9401 JimRandomBytes(interp
, seed
, seedLen
);
9406 static int Jim_IncrCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
9408 jim_wide wideValue
, increment
= 1;
9411 if (argc
!= 2 && argc
!= 3) {
9412 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?increment?");
9416 if (Jim_GetWide(interp
, argv
[2], &increment
) != JIM_OK
)
9419 intObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
9421 /* Set missing variable to 0 */
9424 else if (Jim_GetWide(interp
, intObjPtr
, &wideValue
) != JIM_OK
) {
9427 if (!intObjPtr
|| Jim_IsShared(intObjPtr
)) {
9428 intObjPtr
= Jim_NewIntObj(interp
, wideValue
+ increment
);
9429 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
9430 Jim_FreeNewObj(interp
, intObjPtr
);
9435 /* Can do it the quick way */
9436 Jim_InvalidateStringRep(intObjPtr
);
9437 JimWideValue(intObjPtr
) = wideValue
+ increment
;
9439 /* The following step is required in order to invalidate the
9440 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9441 if (argv
[1]->typePtr
!= &variableObjType
) {
9442 /* Note that this can't fail since GetVariable already succeeded */
9443 Jim_SetVariable(interp
, argv
[1], intObjPtr
);
9446 Jim_SetResult(interp
, intObjPtr
);
9451 /* -----------------------------------------------------------------------------
9453 * ---------------------------------------------------------------------------*/
9454 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9455 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9457 /* Handle calls to the [unknown] command */
9458 static int JimUnknown(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, const char *filename
,
9461 Jim_Obj
**v
, *sv
[JIM_EVAL_SARGV_LEN
];
9464 /* If JimUnknown() is recursively called too many times...
9467 if (interp
->unknown_called
> 50) {
9471 /* If the [unknown] command does not exists returns
9473 if (Jim_GetCommand(interp
, interp
->unknown
, JIM_NONE
) == NULL
)
9476 /* The object interp->unknown just contains
9477 * the "unknown" string, it is used in order to
9478 * avoid to lookup the unknown command every time
9479 * but instread to cache the result. */
9480 if (argc
+ 1 <= JIM_EVAL_SARGV_LEN
)
9483 v
= Jim_Alloc(sizeof(Jim_Obj
*) * (argc
+ 1));
9484 /* Make a copy of the arguments vector, but shifted on
9485 * the right of one position. The command name of the
9486 * command will be instead the first argument of the
9487 * [unknown] call. */
9488 memcpy(v
+ 1, argv
, sizeof(Jim_Obj
*) * argc
);
9489 v
[0] = interp
->unknown
;
9491 interp
->unknown_called
++;
9492 retCode
= JimEvalObjVector(interp
, argc
+ 1, v
, filename
, linenr
);
9493 interp
->unknown_called
--;
9501 /* Eval the object vector 'objv' composed of 'objc' elements.
9502 * Every element is used as single argument.
9503 * Jim_EvalObj() will call this function every time its object
9504 * argument is of "list" type, with no string representation.
9506 * This is possible because the string representation of a
9507 * list object generated by the UpdateStringOfList is made
9508 * in a way that ensures that every list element is a different
9509 * command argument. */
9510 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
9511 const char *filename
, int linenr
)
9516 /* Incr refcount of arguments. */
9517 for (i
= 0; i
< objc
; i
++)
9518 Jim_IncrRefCount(objv
[i
]);
9519 /* Command lookup */
9520 cmdPtr
= Jim_GetCommand(interp
, objv
[0], JIM_ERRMSG
);
9521 if (cmdPtr
== NULL
) {
9522 retcode
= JimUnknown(interp
, objc
, objv
, filename
, linenr
);
9525 /* Call it -- Make sure result is an empty object. */
9526 JimIncrCmdRefCount(cmdPtr
);
9527 Jim_SetEmptyResult(interp
);
9528 if (cmdPtr
->isproc
) {
9529 retcode
= JimCallProcedure(interp
, cmdPtr
, filename
, linenr
, objc
, objv
);
9532 interp
->cmdPrivData
= cmdPtr
->u
.native
.privData
;
9533 retcode
= cmdPtr
->u
.native
.cmdProc(interp
, objc
, objv
);
9535 JimDecrCmdRefCount(interp
, cmdPtr
);
9537 /* Decr refcount of arguments and return the retcode */
9538 for (i
= 0; i
< objc
; i
++)
9539 Jim_DecrRefCount(interp
, objv
[i
]);
9544 int Jim_EvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
9546 return JimEvalObjVector(interp
, objc
, objv
, NULL
, 0);
9550 * Invokes 'prefix' as a command with the objv array as arguments.
9552 int Jim_EvalObjPrefix(Jim_Interp
*interp
, const char *prefix
, int objc
, Jim_Obj
*const *objv
)
9556 Jim_Obj
**nargv
= Jim_Alloc((objc
+ 1) * sizeof(*nargv
));
9558 nargv
[0] = Jim_NewStringObj(interp
, prefix
, -1);
9559 for (i
= 0; i
< objc
; i
++) {
9560 nargv
[i
+ 1] = objv
[i
];
9562 ret
= Jim_EvalObjVector(interp
, objc
+ 1, nargv
);
9567 static void JimAddErrorToStack(Jim_Interp
*interp
, int retcode
, const char *filename
, int line
)
9571 if (rc
== JIM_ERR
&& !interp
->errorFlag
) {
9572 /* This is the first error, so save the file/line information and reset the stack */
9573 interp
->errorFlag
= 1;
9574 JimSetErrorFileName(interp
, filename
);
9575 JimSetErrorLineNumber(interp
, line
);
9577 JimResetStackTrace(interp
);
9578 /* Always add a level where the error first occurs */
9579 interp
->addStackTrace
++;
9582 /* Now if this is an "interesting" level, add it to the stack trace */
9583 if (rc
== JIM_ERR
&& interp
->addStackTrace
> 0) {
9584 /* Add the stack info for the current level */
9586 JimAppendStackTrace(interp
, Jim_String(interp
->errorProc
), filename
, line
);
9588 /* Note: if we didn't have a filename for this level,
9589 * don't clear the addStackTrace flag
9590 * so we can pick it up at the next level
9593 interp
->addStackTrace
= 0;
9596 Jim_DecrRefCount(interp
, interp
->errorProc
);
9597 interp
->errorProc
= interp
->emptyObj
;
9598 Jim_IncrRefCount(interp
->errorProc
);
9600 else if (rc
== JIM_RETURN
&& interp
->returnCode
== JIM_ERR
) {
9601 /* Propagate the addStackTrace value through 'return -code error' */
9604 interp
->addStackTrace
= 0;
9608 /* And delete any local procs */
9609 static void JimDeleteLocalProcs(Jim_Interp
*interp
)
9611 if (interp
->localProcs
) {
9614 while ((procname
= Jim_StackPop(interp
->localProcs
)) != NULL
) {
9615 /* If there is a pushed command, find it */
9616 Jim_Cmd
*prevCmd
= NULL
;
9617 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->commands
, procname
);
9619 Jim_Cmd
*cmd
= (Jim_Cmd
*)he
->u
.val
;
9620 if (cmd
->isproc
&& cmd
->u
.proc
.prevCmd
) {
9621 prevCmd
= cmd
->u
.proc
.prevCmd
;
9622 cmd
->u
.proc
.prevCmd
= NULL
;
9626 /* Delete the local proc */
9627 Jim_DeleteCommand(interp
, procname
);
9630 /* And restore the pushed command */
9631 Jim_AddHashEntry(&interp
->commands
, procname
, prevCmd
);
9635 Jim_FreeStack(interp
->localProcs
);
9636 Jim_Free(interp
->localProcs
);
9637 interp
->localProcs
= NULL
;
9641 static int JimSubstOneToken(Jim_Interp
*interp
, const ScriptToken
*token
, Jim_Obj
**objPtrPtr
)
9645 switch (token
->type
) {
9648 objPtr
= token
->objPtr
;
9651 objPtr
= Jim_GetVariable(interp
, token
->objPtr
, JIM_ERRMSG
);
9653 case JIM_TT_DICTSUGAR
:
9654 objPtr
= JimExpandDictSugar(interp
, token
->objPtr
);
9656 case JIM_TT_EXPRSUGAR
:
9657 objPtr
= JimExpandExprSugar(interp
, token
->objPtr
);
9660 switch (Jim_EvalObj(interp
, token
->objPtr
)) {
9663 objPtr
= interp
->result
;
9666 /* Stop substituting */
9669 /* just skip this one */
9670 return JIM_CONTINUE
;
9676 JimPanic((1, interp
,
9677 "default token type (%d) reached " "in Jim_SubstObj().", token
->type
));
9682 *objPtrPtr
= objPtr
;
9688 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9689 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9690 * The returned object has refcount = 0.
9692 static Jim_Obj
*JimInterpolateTokens(Jim_Interp
*interp
, const ScriptToken
* token
, int tokens
, int flags
)
9696 Jim_Obj
*sintv
[JIM_EVAL_SINTV_LEN
];
9700 if (tokens
<= JIM_EVAL_SINTV_LEN
)
9703 intv
= Jim_Alloc(sizeof(Jim_Obj
*) * tokens
);
9705 /* Compute every token forming the argument
9706 * in the intv objects vector. */
9707 for (i
= 0; i
< tokens
; i
++) {
9708 switch (JimSubstOneToken(interp
, &token
[i
], &intv
[i
])) {
9713 if (flags
& JIM_SUBST_FLAG
) {
9718 /* XXX: Should probably set an error about break outside loop */
9719 /* fall through to error */
9721 if (flags
& JIM_SUBST_FLAG
) {
9725 /* XXX: Ditto continue outside loop */
9726 /* fall through to error */
9729 Jim_DecrRefCount(interp
, intv
[i
]);
9731 if (intv
!= sintv
) {
9736 Jim_IncrRefCount(intv
[i
]);
9737 Jim_String(intv
[i
]);
9738 totlen
+= intv
[i
]->length
;
9741 /* Fast path return for a single token */
9742 if (tokens
== 1 && intv
[0] && intv
== sintv
) {
9743 Jim_DecrRefCount(interp
, intv
[0]);
9747 /* Concatenate every token in an unique
9749 objPtr
= Jim_NewStringObjNoAlloc(interp
, NULL
, 0);
9751 if (tokens
== 4 && token
[0].type
== JIM_TT_ESC
&& token
[1].type
== JIM_TT_ESC
9752 && token
[2].type
== JIM_TT_VAR
) {
9753 /* May be able to do fast interpolated object -> dictSubst */
9754 objPtr
->typePtr
= &interpolatedObjType
;
9755 objPtr
->internalRep
.twoPtrValue
.ptr1
= (void *)token
;
9756 objPtr
->internalRep
.twoPtrValue
.ptr2
= intv
[2];
9757 Jim_IncrRefCount(intv
[2]);
9760 s
= objPtr
->bytes
= Jim_Alloc(totlen
+ 1);
9761 objPtr
->length
= totlen
;
9762 for (i
= 0; i
< tokens
; i
++) {
9764 memcpy(s
, intv
[i
]->bytes
, intv
[i
]->length
);
9765 s
+= intv
[i
]->length
;
9766 Jim_DecrRefCount(interp
, intv
[i
]);
9769 objPtr
->bytes
[totlen
] = '\0';
9770 /* Free the intv vector if not static. */
9771 if (intv
!= sintv
) {
9779 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9780 * Otherwise eval with Jim_EvalObj()
9782 int Jim_EvalObjList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, const char *filename
, int linenr
)
9784 if (!Jim_IsList(listPtr
)) {
9785 return Jim_EvalObj(interp
, listPtr
);
9788 int retcode
= JIM_OK
;
9790 if (listPtr
->internalRep
.listValue
.len
) {
9791 Jim_IncrRefCount(listPtr
);
9792 retcode
= JimEvalObjVector(interp
,
9793 listPtr
->internalRep
.listValue
.len
,
9794 listPtr
->internalRep
.listValue
.ele
, filename
, linenr
);
9795 Jim_DecrRefCount(interp
, listPtr
);
9801 int Jim_EvalObj(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
9806 int retcode
= JIM_OK
;
9807 Jim_Obj
*sargv
[JIM_EVAL_SARGV_LEN
], **argv
= NULL
;
9810 interp
->errorFlag
= 0;
9812 /* If the object is of type "list", we can call
9813 * a specialized version of Jim_EvalObj() */
9814 if (Jim_IsList(scriptObjPtr
)) {
9815 return Jim_EvalObjList(interp
, scriptObjPtr
, NULL
, 0);
9818 Jim_IncrRefCount(scriptObjPtr
); /* Make sure it's shared. */
9819 script
= Jim_GetScript(interp
, scriptObjPtr
);
9821 /* Reset the interpreter result. This is useful to
9822 * return the empty result in the case of empty program. */
9823 Jim_SetEmptyResult(interp
);
9825 #ifdef JIM_OPTIMIZATION
9826 /* Check for one of the following common scripts used by for, while
9831 if (script
->len
== 0) {
9832 Jim_DecrRefCount(interp
, scriptObjPtr
);
9835 if (script
->len
== 3
9836 && script
->token
[1].objPtr
->typePtr
== &commandObjType
9837 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->isproc
== 0
9838 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->u
.native
.cmdProc
== Jim_IncrCoreCommand
9839 && script
->token
[2].objPtr
->typePtr
== &variableObjType
) {
9841 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, script
->token
[2].objPtr
, JIM_NONE
);
9843 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
9844 JimWideValue(objPtr
)++;
9845 Jim_InvalidateStringRep(objPtr
);
9846 Jim_DecrRefCount(interp
, scriptObjPtr
);
9847 Jim_SetResult(interp
, objPtr
);
9853 /* Now we have to make sure the internal repr will not be
9854 * freed on shimmering.
9856 * Think for example to this:
9858 * set x {llength $x; ... some more code ...}; eval $x
9860 * In order to preserve the internal rep, we increment the
9861 * inUse field of the script internal rep structure. */
9864 token
= script
->token
;
9867 /* Execute every command sequentially until the end of the script
9868 * or an error occurs.
9870 for (i
= 0; i
< script
->len
&& retcode
== JIM_OK
; ) {
9875 /* First token of the line is always JIM_TT_LINE */
9876 argc
= token
[i
].objPtr
->internalRep
.scriptLineValue
.argc
;
9877 linenr
= token
[i
].objPtr
->internalRep
.scriptLineValue
.line
;
9879 /* Allocate the arguments vector if required */
9880 if (argc
> JIM_EVAL_SARGV_LEN
)
9881 argv
= Jim_Alloc(sizeof(Jim_Obj
*) * argc
);
9883 /* Skip the JIM_TT_LINE token */
9886 /* Populate the arguments objects.
9887 * If an error occurs, retcode will be set and
9888 * 'j' will be set to the number of args expanded
9890 for (j
= 0; j
< argc
; j
++) {
9891 long wordtokens
= 1;
9893 Jim_Obj
*wordObjPtr
= NULL
;
9895 if (token
[i
].type
== JIM_TT_WORD
) {
9896 wordtokens
= JimWideValue(token
[i
++].objPtr
);
9897 if (wordtokens
< 0) {
9899 wordtokens
= -wordtokens
;
9903 if (wordtokens
== 1) {
9904 /* Fast path if the token does not
9905 * need interpolation */
9907 switch (token
[i
].type
) {
9910 wordObjPtr
= token
[i
].objPtr
;
9913 wordObjPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
9915 case JIM_TT_EXPRSUGAR
:
9916 wordObjPtr
= JimExpandExprSugar(interp
, token
[i
].objPtr
);
9918 case JIM_TT_DICTSUGAR
:
9919 wordObjPtr
= JimExpandDictSugar(interp
, token
[i
].objPtr
);
9922 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
9923 if (retcode
== JIM_OK
) {
9924 wordObjPtr
= Jim_GetResult(interp
);
9928 JimPanic((1, interp
, "default token type reached " "in Jim_EvalObj()."));
9932 /* For interpolation we call a helper
9933 * function to do the work for us. */
9934 wordObjPtr
= JimInterpolateTokens(interp
, token
+ i
, wordtokens
, JIM_NONE
);
9938 if (retcode
== JIM_OK
) {
9944 Jim_IncrRefCount(wordObjPtr
);
9948 argv
[j
] = wordObjPtr
;
9951 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
9952 int len
= Jim_ListLength(interp
, wordObjPtr
);
9953 int newargc
= argc
+ len
- 1;
9957 if (argv
== sargv
) {
9958 if (newargc
> JIM_EVAL_SARGV_LEN
) {
9959 argv
= Jim_Alloc(sizeof(*argv
) * newargc
);
9960 memcpy(argv
, sargv
, sizeof(*argv
) * j
);
9964 /* Need to realloc to make room for (len - 1) more entries */
9965 argv
= Jim_Realloc(argv
, sizeof(*argv
) * newargc
);
9969 /* Now copy in the expanded version */
9970 for (k
= 0; k
< len
; k
++) {
9971 argv
[j
++] = wordObjPtr
->internalRep
.listValue
.ele
[k
];
9972 Jim_IncrRefCount(wordObjPtr
->internalRep
.listValue
.ele
[k
]);
9975 /* The original object reference is no longer needed,
9976 * after the expansion it is no longer present on
9977 * the argument vector, but the single elements are
9979 Jim_DecrRefCount(interp
, wordObjPtr
);
9981 /* And update the indexes */
9987 if (retcode
== JIM_OK
&& argc
) {
9988 /* Lookup the command to call */
9989 cmd
= Jim_GetCommand(interp
, argv
[0], JIM_ERRMSG
);
9991 /* Call it -- Make sure result is an empty object. */
9992 JimIncrCmdRefCount(cmd
);
9993 Jim_SetEmptyResult(interp
);
9996 JimCallProcedure(interp
, cmd
, script
->fileName
, linenr
, argc
, argv
);
9998 interp
->cmdPrivData
= cmd
->u
.native
.privData
;
9999 retcode
= cmd
->u
.native
.cmdProc(interp
, argc
, argv
);
10001 JimDecrCmdRefCount(interp
, cmd
);
10004 /* Call [unknown] */
10005 retcode
= JimUnknown(interp
, argc
, argv
, script
->fileName
, linenr
);
10007 if (interp
->signal_level
&& interp
->sigmask
) {
10008 /* Check for a signal after each command */
10009 retcode
= JIM_SIGNAL
;
10013 /* Finished with the command, so decrement ref counts of each argument */
10015 Jim_DecrRefCount(interp
, argv
[j
]);
10018 if (argv
!= sargv
) {
10024 /* Possibly add to the error stack trace */
10025 JimAddErrorToStack(interp
, retcode
, script
->fileName
, linenr
);
10027 /* Note that we don't have to decrement inUse, because the
10028 * following code transfers our use of the reference again to
10029 * the script object. */
10030 Jim_FreeIntRep(interp
, scriptObjPtr
);
10031 scriptObjPtr
->typePtr
= &scriptObjType
;
10032 Jim_SetIntRepPtr(scriptObjPtr
, script
);
10033 Jim_DecrRefCount(interp
, scriptObjPtr
);
10038 static int JimSetProcArg(Jim_Interp
*interp
, Jim_Obj
*argNameObj
, Jim_Obj
*argValObj
)
10041 /* If argObjPtr begins with '&', do an automatic upvar */
10042 const char *varname
= Jim_String(argNameObj
);
10043 if (*varname
== '&') {
10044 /* First check that the target variable exists */
10046 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
10048 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10049 objPtr
= Jim_GetVariable(interp
, argValObj
, JIM_ERRMSG
);
10050 interp
->framePtr
= savedCallFrame
;
10055 /* It exists, so perform the binding. */
10056 objPtr
= Jim_NewStringObj(interp
, varname
+ 1, -1);
10057 Jim_IncrRefCount(objPtr
);
10058 retcode
= Jim_SetVariableLink(interp
, objPtr
, argValObj
, interp
->framePtr
->parentCallFrame
);
10059 Jim_DecrRefCount(interp
, objPtr
);
10062 retcode
= Jim_SetVariable(interp
, argNameObj
, argValObj
);
10067 /* Call a procedure implemented in Tcl.
10068 * It's possible to speed-up a lot this function, currently
10069 * the callframes are not cached, but allocated and
10070 * destroied every time. What is expecially costly is
10071 * to create/destroy the local vars hash table every time.
10073 * This can be fixed just implementing callframes caching
10074 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10075 int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, const char *filename
, int linenr
, int argc
,
10076 Jim_Obj
*const *argv
)
10079 Jim_CallFrame
*callFramePtr
;
10080 Jim_Obj
*argObjPtr
;
10081 Jim_Obj
*procname
= argv
[0];
10082 Jim_Stack
*prevLocalProcs
;
10085 if (argc
- 1 < cmd
->u
.proc
.leftArity
+ cmd
->u
.proc
.rightArity
||
10086 (!cmd
->u
.proc
.args
&& argc
- 1 > cmd
->u
.proc
.leftArity
+ cmd
->u
.proc
.rightArity
+ cmd
->u
.proc
.optionalArgs
)) {
10087 /* Create a nice error message, consistent with Tcl 8.5 */
10088 Jim_Obj
*argmsg
= Jim_NewStringObj(interp
, "", 0);
10089 int arglen
= Jim_ListLength(interp
, cmd
->u
.proc
.argListObjPtr
);
10091 for (i
= 0; i
< arglen
; i
++) {
10093 Jim_ListIndex(interp
, cmd
->u
.proc
.argListObjPtr
, i
, &argObjPtr
, JIM_NONE
);
10095 Jim_AppendString(interp
, argmsg
, " ", 1);
10097 if (i
< cmd
->u
.proc
.leftArity
|| i
>= arglen
- cmd
->u
.proc
.rightArity
) {
10098 Jim_AppendObj(interp
, argmsg
, argObjPtr
);
10100 else if (i
== arglen
- cmd
->u
.proc
.rightArity
- cmd
->u
.proc
.args
) {
10101 if (Jim_ListLength(interp
, argObjPtr
) == 1) {
10102 /* We have plain args */
10103 Jim_AppendString(interp
, argmsg
, "?argument ...?", -1);
10106 Jim_AppendString(interp
, argmsg
, "?", 1);
10107 Jim_ListIndex(interp
, argObjPtr
, 1, &objPtr
, JIM_NONE
);
10108 Jim_AppendObj(interp
, argmsg
, objPtr
);
10109 Jim_AppendString(interp
, argmsg
, " ...?", -1);
10113 Jim_AppendString(interp
, argmsg
, "?", 1);
10114 Jim_ListIndex(interp
, argObjPtr
, 0, &objPtr
, JIM_NONE
);
10115 Jim_AppendObj(interp
, argmsg
, objPtr
);
10116 Jim_AppendString(interp
, argmsg
, "?", 1);
10119 Jim_SetResultFormatted(interp
, "wrong # args: should be \"%#s%#s\"", procname
, argmsg
);
10120 Jim_FreeNewObj(interp
, argmsg
);
10124 /* Check if there are too nested calls */
10125 if (interp
->framePtr
->level
== interp
->maxNestingDepth
) {
10126 Jim_SetResultString(interp
, "Too many nested calls. Infinite recursion?", -1);
10130 /* Create a new callframe */
10131 callFramePtr
= JimCreateCallFrame(interp
, interp
->framePtr
);
10132 callFramePtr
->argv
= argv
;
10133 callFramePtr
->argc
= argc
;
10134 callFramePtr
->procArgsObjPtr
= cmd
->u
.proc
.argListObjPtr
;
10135 callFramePtr
->procBodyObjPtr
= cmd
->u
.proc
.bodyObjPtr
;
10136 callFramePtr
->staticVars
= cmd
->u
.proc
.staticVars
;
10137 callFramePtr
->filename
= filename
;
10138 callFramePtr
->line
= linenr
;
10139 Jim_IncrRefCount(cmd
->u
.proc
.argListObjPtr
);
10140 Jim_IncrRefCount(cmd
->u
.proc
.bodyObjPtr
);
10141 interp
->framePtr
= callFramePtr
;
10143 /* Simplify arg counting */
10147 /* Set arguments */
10149 /* Assign in this order:
10150 * leftArity required args.
10151 * rightArity required args (but actually do it last for simplicity)
10152 * optionalArgs optional args
10153 * remaining args into 'args' if 'args'
10156 /* Note that 'd' steps along the arg list, whilst argc/argv follow the supplied args */
10158 /* leftArity required args */
10159 for (d
= 0; d
< cmd
->u
.proc
.leftArity
; d
++) {
10160 Jim_ListIndex(interp
, cmd
->u
.proc
.argListObjPtr
, d
, &argObjPtr
, JIM_NONE
);
10161 retcode
= JimSetProcArg(interp
, argObjPtr
, *argv
++);
10162 if (retcode
!= JIM_OK
) {
10168 /* Shorten our idea of the number of supplied args */
10169 argc
-= cmd
->u
.proc
.rightArity
;
10171 /* optionalArgs optional args */
10172 for (i
= 0; i
< cmd
->u
.proc
.optionalArgs
; i
++) {
10173 Jim_Obj
*nameObjPtr
;
10174 Jim_Obj
*valueObjPtr
;
10176 Jim_ListIndex(interp
, cmd
->u
.proc
.argListObjPtr
, d
++, &argObjPtr
, JIM_NONE
);
10178 /* The name is the first element of the list */
10179 Jim_ListIndex(interp
, argObjPtr
, 0, &nameObjPtr
, JIM_NONE
);
10181 valueObjPtr
= *argv
++;
10185 /* No more values, so use default */
10186 /* The value is the second element of the list */
10187 Jim_ListIndex(interp
, argObjPtr
, 1, &valueObjPtr
, JIM_NONE
);
10189 Jim_SetVariable(interp
, nameObjPtr
, valueObjPtr
);
10192 /* Any remaining args go to 'args' */
10193 if (cmd
->u
.proc
.args
) {
10194 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, argv
, argc
);
10196 /* Get the 'args' name from the procedure args */
10197 Jim_ListIndex(interp
, cmd
->u
.proc
.argListObjPtr
, d
, &argObjPtr
, JIM_NONE
);
10199 /* It is possible to rename args. */
10200 i
= Jim_ListLength(interp
, argObjPtr
);
10202 Jim_ListIndex(interp
, argObjPtr
, 1, &argObjPtr
, JIM_NONE
);
10205 Jim_SetVariable(interp
, argObjPtr
, listObjPtr
);
10210 /* rightArity required args */
10211 for (i
= 0; i
< cmd
->u
.proc
.rightArity
; i
++) {
10212 Jim_ListIndex(interp
, cmd
->u
.proc
.argListObjPtr
, d
++, &argObjPtr
, JIM_NONE
);
10213 retcode
= JimSetProcArg(interp
, argObjPtr
, *argv
++);
10214 if (retcode
!= JIM_OK
) {
10219 /* Install a new stack for local procs */
10220 prevLocalProcs
= interp
->localProcs
;
10221 interp
->localProcs
= NULL
;
10223 /* Eval the body */
10224 retcode
= Jim_EvalObj(interp
, cmd
->u
.proc
.bodyObjPtr
);
10226 /* Delete any local procs */
10227 JimDeleteLocalProcs(interp
);
10228 interp
->localProcs
= prevLocalProcs
;
10231 /* Destroy the callframe */
10232 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10233 if (callFramePtr
->vars
.size
!= JIM_HT_INITIAL_SIZE
) {
10234 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NONE
);
10237 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NOHT
);
10239 /* Handle the JIM_EVAL return code */
10240 while (retcode
== JIM_EVAL
) {
10241 Jim_Obj
*resultScriptObjPtr
= Jim_GetResult(interp
);
10243 Jim_IncrRefCount(resultScriptObjPtr
);
10244 /* Should be a list! */
10245 retcode
= Jim_EvalObjList(interp
, resultScriptObjPtr
, filename
, linenr
);
10246 Jim_DecrRefCount(interp
, resultScriptObjPtr
);
10248 /* Handle the JIM_RETURN return code */
10249 if (retcode
== JIM_RETURN
) {
10250 if (--interp
->returnLevel
<= 0) {
10251 retcode
= interp
->returnCode
;
10252 interp
->returnCode
= JIM_OK
;
10253 interp
->returnLevel
= 0;
10256 else if (retcode
== JIM_ERR
) {
10257 interp
->addStackTrace
++;
10258 Jim_DecrRefCount(interp
, interp
->errorProc
);
10259 interp
->errorProc
= procname
;
10260 Jim_IncrRefCount(interp
->errorProc
);
10265 int Jim_Eval_Named(Jim_Interp
*interp
, const char *script
, const char *filename
, int lineno
)
10268 Jim_Obj
*scriptObjPtr
;
10270 scriptObjPtr
= Jim_NewStringObj(interp
, script
, -1);
10271 Jim_IncrRefCount(scriptObjPtr
);
10275 Jim_Obj
*prevScriptObj
;
10277 JimSetSourceInfo(interp
, scriptObjPtr
, filename
, lineno
);
10279 prevScriptObj
= interp
->currentScriptObj
;
10280 interp
->currentScriptObj
= scriptObjPtr
;
10282 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10284 interp
->currentScriptObj
= prevScriptObj
;
10287 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10289 Jim_DecrRefCount(interp
, scriptObjPtr
);
10293 int Jim_Eval(Jim_Interp
*interp
, const char *script
)
10295 return Jim_Eval_Named(interp
, script
, NULL
, 0);
10298 /* Execute script in the scope of the global level */
10299 int Jim_EvalGlobal(Jim_Interp
*interp
, const char *script
)
10302 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10304 interp
->framePtr
= interp
->topFramePtr
;
10305 retval
= Jim_Eval(interp
, script
);
10306 interp
->framePtr
= savedFramePtr
;
10311 int Jim_EvalFileGlobal(Jim_Interp
*interp
, const char *filename
)
10314 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10316 interp
->framePtr
= interp
->topFramePtr
;
10317 retval
= Jim_EvalFile(interp
, filename
);
10318 interp
->framePtr
= savedFramePtr
;
10323 #include <sys/stat.h>
10325 int Jim_EvalFile(Jim_Interp
*interp
, const char *filename
)
10329 Jim_Obj
*scriptObjPtr
;
10330 Jim_Obj
*prevScriptObj
;
10331 Jim_Stack
*prevLocalProcs
;
10337 if (stat(filename
, &sb
) != 0 || (fp
= fopen(filename
, "rt")) == NULL
) {
10338 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", filename
, strerror(errno
));
10341 if (sb
.st_size
== 0) {
10346 buf
= Jim_Alloc(sb
.st_size
+ 1);
10347 readlen
= fread(buf
, 1, sb
.st_size
, fp
);
10351 Jim_SetResultFormatted(interp
, "failed to load file \"%s\": %s", filename
, strerror(errno
));
10357 if (!Jim_ScriptIsComplete(buf
, sb
.st_size
, &missing
)) {
10358 Jim_SetResultFormatted(interp
, "missing %s in \"%s\"",
10359 missing
== '{' ? "close-brace" : "\"", filename
);
10364 scriptObjPtr
= Jim_NewStringObjNoAlloc(interp
, buf
, readlen
);
10365 JimSetSourceInfo(interp
, scriptObjPtr
, filename
, 1);
10366 Jim_IncrRefCount(scriptObjPtr
);
10368 prevScriptObj
= interp
->currentScriptObj
;
10369 interp
->currentScriptObj
= scriptObjPtr
;
10371 /* Install a new stack for local procs */
10372 prevLocalProcs
= interp
->localProcs
;
10373 interp
->localProcs
= NULL
;
10375 retcode
= Jim_EvalObj(interp
, scriptObjPtr
);
10377 /* Delete any local procs */
10378 JimDeleteLocalProcs(interp
);
10379 interp
->localProcs
= prevLocalProcs
;
10381 /* Handle the JIM_RETURN return code */
10382 if (retcode
== JIM_RETURN
) {
10383 if (--interp
->returnLevel
<= 0) {
10384 retcode
= interp
->returnCode
;
10385 interp
->returnCode
= JIM_OK
;
10386 interp
->returnLevel
= 0;
10389 if (retcode
== JIM_ERR
) {
10390 /* EvalFile changes context, so add a stack frame here */
10391 interp
->addStackTrace
++;
10394 interp
->currentScriptObj
= prevScriptObj
;
10396 Jim_DecrRefCount(interp
, scriptObjPtr
);
10401 /* -----------------------------------------------------------------------------
10403 * ---------------------------------------------------------------------------*/
10404 static int JimParseSubstStr(struct JimParserCtx
*pc
)
10406 pc
->tstart
= pc
->p
;
10407 pc
->tline
= pc
->linenr
;
10408 while (pc
->len
&& *pc
->p
!= '$' && *pc
->p
!= '[') {
10409 if (*pc
->p
== '\\' && pc
->len
> 1) {
10416 pc
->tend
= pc
->p
- 1;
10417 pc
->tt
= JIM_TT_ESC
;
10421 static int JimParseSubst(struct JimParserCtx
*pc
, int flags
)
10425 if (pc
->len
== 0) {
10426 pc
->tstart
= pc
->tend
= pc
->p
;
10427 pc
->tline
= pc
->linenr
;
10428 pc
->tt
= JIM_TT_EOL
;
10434 retval
= JimParseCmd(pc
);
10435 if (flags
& JIM_SUBST_NOCMD
) {
10438 pc
->tt
= (flags
& JIM_SUBST_NOESC
) ? JIM_TT_STR
: JIM_TT_ESC
;
10443 if (JimParseVar(pc
) == JIM_ERR
) {
10444 pc
->tstart
= pc
->tend
= pc
->p
++;
10446 pc
->tline
= pc
->linenr
;
10447 pc
->tt
= JIM_TT_STR
;
10450 if (flags
& JIM_SUBST_NOVAR
) {
10452 if (flags
& JIM_SUBST_NOESC
)
10453 pc
->tt
= JIM_TT_STR
;
10455 pc
->tt
= JIM_TT_ESC
;
10456 if (*pc
->tstart
== '{') {
10458 if (*(pc
->tend
+ 1))
10465 retval
= JimParseSubstStr(pc
);
10466 if (flags
& JIM_SUBST_NOESC
)
10467 pc
->tt
= JIM_TT_STR
;
10474 /* The subst object type reuses most of the data structures and functions
10475 * of the script object. Script's data structures are a bit more complex
10476 * for what is needed for [subst]itution tasks, but the reuse helps to
10477 * deal with a single data structure at the cost of some more memory
10478 * usage for substitutions. */
10480 /* This method takes the string representation of an object
10481 * as a Tcl string where to perform [subst]itution, and generates
10482 * the pre-parsed internal representation. */
10483 static int SetSubstFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, int flags
)
10486 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
10487 struct JimParserCtx parser
;
10488 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
10489 ParseTokenList tokenlist
;
10491 /* Initially parse the subst into tokens (in tokenlist) */
10492 ScriptTokenListInit(&tokenlist
);
10494 JimParserInit(&parser
, scriptText
, scriptTextLen
, 1);
10496 JimParseSubst(&parser
, flags
);
10498 /* Note that subst doesn't need the EOL token */
10501 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
10505 /* Create the "real" subst/script tokens from the initial token list */
10507 script
->substFlags
= flags
;
10508 script
->fileName
= NULL
;
10509 SubstObjAddTokens(interp
, script
, &tokenlist
);
10511 /* No longer need the token list */
10512 ScriptTokenListFree(&tokenlist
);
10514 #ifdef DEBUG_SHOW_SUBST
10518 printf("==== Subst ====\n");
10519 for (i
= 0; i
< script
->len
; i
++) {
10520 printf("[%2d] %s '%s'\n", i
, jim_tt_name(script
->token
[i
].type
),
10521 Jim_String(script
->token
[i
].objPtr
));
10526 /* Free the old internal rep and set the new one. */
10527 Jim_FreeIntRep(interp
, objPtr
);
10528 Jim_SetIntRepPtr(objPtr
, script
);
10529 objPtr
->typePtr
= &scriptObjType
;
10533 static ScriptObj
*Jim_GetSubst(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
10535 if (objPtr
->typePtr
!= &scriptObjType
|| ((ScriptObj
*)Jim_GetIntRepPtr(objPtr
))->substFlags
!= flags
)
10536 SetSubstFromAny(interp
, objPtr
, flags
);
10537 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
10540 /* Performs commands,variables,blackslashes substitution,
10541 * storing the result object (with refcount 0) into
10543 int Jim_SubstObj(Jim_Interp
*interp
, Jim_Obj
*substObjPtr
, Jim_Obj
**resObjPtrPtr
, int flags
)
10545 ScriptObj
*script
= Jim_GetSubst(interp
, substObjPtr
, flags
);
10547 Jim_IncrRefCount(substObjPtr
); /* Make sure it's shared. */
10548 /* In order to preserve the internal rep, we increment the
10549 * inUse field of the script internal rep structure. */
10552 *resObjPtrPtr
= JimInterpolateTokens(interp
, script
->token
, script
->len
, flags
);
10555 Jim_DecrRefCount(interp
, substObjPtr
);
10556 if (*resObjPtrPtr
== NULL
) {
10562 /* -----------------------------------------------------------------------------
10563 * Core commands utility functions
10564 * ---------------------------------------------------------------------------*/
10565 void Jim_WrongNumArgs(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, const char *msg
)
10568 Jim_Obj
*objPtr
= Jim_NewEmptyStringObj(interp
);
10570 Jim_AppendString(interp
, objPtr
, "wrong # args: should be \"", -1);
10571 for (i
= 0; i
< argc
; i
++) {
10572 Jim_AppendObj(interp
, objPtr
, argv
[i
]);
10573 if (!(i
+ 1 == argc
&& msg
[0] == '\0'))
10574 Jim_AppendString(interp
, objPtr
, " ", 1);
10576 Jim_AppendString(interp
, objPtr
, msg
, -1);
10577 Jim_AppendString(interp
, objPtr
, "\"", 1);
10578 Jim_SetResult(interp
, objPtr
);
10581 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10583 /* type is: 0=commands, 1=procs, 2=channels */
10584 static Jim_Obj
*JimCommandsList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int type
)
10586 Jim_HashTableIterator
*htiter
;
10588 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10590 /* Check for the non-pattern case. We can do this much more efficiently. */
10591 if (patternObjPtr
&& JimTrivialMatch(Jim_String(patternObjPtr
))) {
10592 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, patternObjPtr
, JIM_NONE
);
10594 if (type
== 1 && !cmdPtr
->isproc
) {
10597 else if (type
== 2 && !Jim_AioFilehandle(interp
, patternObjPtr
)) {
10598 /* not a channel */
10601 Jim_ListAppendElement(interp
, listObjPtr
, patternObjPtr
);
10607 htiter
= Jim_GetHashTableIterator(&interp
->commands
);
10608 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10609 Jim_Cmd
*cmdPtr
= he
->u
.val
;
10610 Jim_Obj
*cmdNameObj
;
10612 if (type
== 1 && !cmdPtr
->isproc
) {
10616 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10619 cmdNameObj
= Jim_NewStringObj(interp
, he
->key
, -1);
10621 /* Is it a channel? */
10622 if (type
== 2 && !Jim_AioFilehandle(interp
, cmdNameObj
)) {
10623 Jim_FreeNewObj(interp
, cmdNameObj
);
10627 Jim_ListAppendElement(interp
, listObjPtr
, cmdNameObj
);
10629 Jim_FreeHashTableIterator(htiter
);
10633 /* Keep this in order */
10634 #define JIM_VARLIST_GLOBALS 0
10635 #define JIM_VARLIST_LOCALS 1
10636 #define JIM_VARLIST_VARS 2
10638 static Jim_Obj
*JimVariablesList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int mode
)
10640 Jim_HashTableIterator
*htiter
;
10642 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10644 if (mode
== JIM_VARLIST_GLOBALS
) {
10645 htiter
= Jim_GetHashTableIterator(&interp
->topFramePtr
->vars
);
10648 /* For [info locals], if we are at top level an emtpy list
10649 * is returned. I don't agree, but we aim at compatibility (SS) */
10650 if (mode
== JIM_VARLIST_LOCALS
&& interp
->framePtr
== interp
->topFramePtr
)
10652 htiter
= Jim_GetHashTableIterator(&interp
->framePtr
->vars
);
10654 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10655 Jim_Var
*varPtr
= (Jim_Var
*)he
->u
.val
;
10657 if (mode
== JIM_VARLIST_LOCALS
) {
10658 if (varPtr
->linkFramePtr
!= NULL
)
10661 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10663 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, he
->key
, -1));
10665 Jim_FreeHashTableIterator(htiter
);
10669 static int JimInfoLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
10670 Jim_Obj
**objPtrPtr
, int info_level_cmd
)
10672 Jim_CallFrame
*targetCallFrame
;
10674 targetCallFrame
= JimGetCallFrameByInteger(interp
, levelObjPtr
);
10675 if (targetCallFrame
== NULL
) {
10678 /* No proc call at toplevel callframe */
10679 if (targetCallFrame
== interp
->topFramePtr
) {
10680 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
10683 if (info_level_cmd
) {
10684 *objPtrPtr
= Jim_NewListObj(interp
, targetCallFrame
->argv
, targetCallFrame
->argc
);
10687 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
10689 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->argv
[0]);
10690 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
,
10691 targetCallFrame
->filename
? targetCallFrame
->filename
: "", -1));
10692 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, targetCallFrame
->line
));
10693 *objPtrPtr
= listObj
;
10698 /* -----------------------------------------------------------------------------
10700 * ---------------------------------------------------------------------------*/
10702 /* fake [puts] -- not the real puts, just for debugging. */
10703 static int Jim_PutsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10705 if (argc
!= 2 && argc
!= 3) {
10706 Jim_WrongNumArgs(interp
, 1, argv
, "?-nonewline? string");
10710 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-nonewline")) {
10711 Jim_SetResultString(interp
, "The second argument must " "be -nonewline", -1);
10715 fputs(Jim_String(argv
[2]), stdout
);
10719 puts(Jim_String(argv
[1]));
10724 /* Helper for [+] and [*] */
10725 static int JimAddMulHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10727 jim_wide wideValue
, res
;
10728 double doubleValue
, doubleRes
;
10731 res
= (op
== JIM_EXPROP_ADD
) ? 0 : 1;
10733 for (i
= 1; i
< argc
; i
++) {
10734 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
)
10736 if (op
== JIM_EXPROP_ADD
)
10741 Jim_SetResultInt(interp
, res
);
10744 doubleRes
= (double)res
;
10745 for (; i
< argc
; i
++) {
10746 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10748 if (op
== JIM_EXPROP_ADD
)
10749 doubleRes
+= doubleValue
;
10751 doubleRes
*= doubleValue
;
10753 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10757 /* Helper for [-] and [/] */
10758 static int JimSubDivHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10760 jim_wide wideValue
, res
= 0;
10761 double doubleValue
, doubleRes
= 0;
10765 Jim_WrongNumArgs(interp
, 1, argv
, "number ?number ... number?");
10768 else if (argc
== 2) {
10769 /* The arity = 2 case is different. For [- x] returns -x,
10770 * while [/ x] returns 1/x. */
10771 if (Jim_GetWide(interp
, argv
[1], &wideValue
) != JIM_OK
) {
10772 if (Jim_GetDouble(interp
, argv
[1], &doubleValue
) != JIM_OK
) {
10776 if (op
== JIM_EXPROP_SUB
)
10777 doubleRes
= -doubleValue
;
10779 doubleRes
= 1.0 / doubleValue
;
10780 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10784 if (op
== JIM_EXPROP_SUB
) {
10786 Jim_SetResultInt(interp
, res
);
10789 doubleRes
= 1.0 / wideValue
;
10790 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10795 if (Jim_GetWide(interp
, argv
[1], &res
) != JIM_OK
) {
10796 if (Jim_GetDouble(interp
, argv
[1], &doubleRes
)
10805 for (i
= 2; i
< argc
; i
++) {
10806 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
) {
10807 doubleRes
= (double)res
;
10810 if (op
== JIM_EXPROP_SUB
)
10815 Jim_SetResultInt(interp
, res
);
10818 for (; i
< argc
; i
++) {
10819 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10821 if (op
== JIM_EXPROP_SUB
)
10822 doubleRes
-= doubleValue
;
10824 doubleRes
/= doubleValue
;
10826 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10832 static int Jim_AddCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10834 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_ADD
);
10838 static int Jim_MulCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10840 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_MUL
);
10844 static int Jim_SubCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10846 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_SUB
);
10850 static int Jim_DivCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10852 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_DIV
);
10856 static int Jim_SetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10858 if (argc
!= 2 && argc
!= 3) {
10859 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?newValue?");
10865 objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
10868 Jim_SetResult(interp
, objPtr
);
10871 /* argc == 3 case. */
10872 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
10874 Jim_SetResult(interp
, argv
[2]);
10880 * unset ?-nocomplain? ?--? ?varName ...?
10882 static int Jim_UnsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10888 if (Jim_CompareStringImmediate(interp
, argv
[i
], "--")) {
10892 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-nocomplain")) {
10901 if (Jim_UnsetVariable(interp
, argv
[i
], complain
? JIM_ERRMSG
: JIM_NONE
) != JIM_OK
10911 static int Jim_WhileCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10914 Jim_WrongNumArgs(interp
, 1, argv
, "condition body");
10918 /* The general purpose implementation of while starts here */
10920 int boolean
, retval
;
10922 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[1], &boolean
)) != JIM_OK
)
10927 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
10941 Jim_SetEmptyResult(interp
);
10946 static int Jim_ForCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10950 Jim_Obj
*varNamePtr
= NULL
;
10951 Jim_Obj
*stopVarNamePtr
= NULL
;
10954 Jim_WrongNumArgs(interp
, 1, argv
, "start test next body");
10958 /* Do the initialisation */
10959 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
) {
10963 /* And do the first test now. Better for optimisation
10964 * if we can do next/test at the bottom of the loop
10966 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
10968 /* Ready to do the body as follows:
10970 * body // check retcode
10971 * next // check retcode
10972 * test // check retcode/test bool
10976 #ifdef JIM_OPTIMIZATION
10977 /* Check if the for is on the form:
10978 * for ... {$i < CONST} {incr i}
10979 * for ... {$i < $j} {incr i}
10981 if (retval
== JIM_OK
&& boolean
) {
10982 ScriptObj
*incrScript
;
10983 ExprByteCode
*expr
;
10984 jim_wide stop
, currentVal
;
10985 unsigned jim_wide procEpoch
;
10989 /* Do it only if there aren't shared arguments */
10990 expr
= JimGetExpression(interp
, argv
[2]);
10991 incrScript
= Jim_GetScript(interp
, argv
[3]);
10993 /* Ensure proper lengths to start */
10994 if (incrScript
->len
!= 3 || !expr
|| expr
->len
!= 3) {
10997 /* Ensure proper token types. */
10998 if (incrScript
->token
[1].type
!= JIM_TT_ESC
||
10999 expr
->token
[0].type
!= JIM_TT_VAR
||
11000 (expr
->token
[1].type
!= JIM_TT_EXPR_INT
&& expr
->token
[1].type
!= JIM_TT_VAR
)) {
11004 if (expr
->token
[2].type
== JIM_EXPROP_LT
) {
11007 else if (expr
->token
[2].type
== JIM_EXPROP_LTE
) {
11014 /* Update command must be incr */
11015 if (!Jim_CompareStringImmediate(interp
, incrScript
->token
[1].objPtr
, "incr")) {
11019 /* incr, expression must be about the same variable */
11020 if (!Jim_StringEqObj(incrScript
->token
[2].objPtr
, expr
->token
[0].objPtr
)) {
11024 /* Get the stop condition (must be a variable or integer) */
11025 if (expr
->token
[1].type
== JIM_TT_EXPR_INT
) {
11026 if (Jim_GetWide(interp
, expr
->token
[1].objPtr
, &stop
) == JIM_ERR
) {
11031 stopVarNamePtr
= expr
->token
[1].objPtr
;
11032 Jim_IncrRefCount(stopVarNamePtr
);
11033 /* Keep the compiler happy */
11037 /* Initialization */
11038 procEpoch
= interp
->procEpoch
;
11039 varNamePtr
= expr
->token
[0].objPtr
;
11040 Jim_IncrRefCount(varNamePtr
);
11042 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_NONE
);
11043 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
) {
11047 /* --- OPTIMIZED FOR --- */
11048 while (retval
== JIM_OK
) {
11049 /* === Check condition === */
11050 /* Note that currentVal is already set here */
11052 /* Immediate or Variable? get the 'stop' value if the latter. */
11053 if (stopVarNamePtr
) {
11054 objPtr
= Jim_GetVariable(interp
, stopVarNamePtr
, JIM_NONE
);
11055 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, &stop
) != JIM_OK
) {
11060 if (currentVal
>= stop
+ cmpOffset
) {
11065 retval
= Jim_EvalObj(interp
, argv
[4]);
11066 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11068 /* If there was a change in procedures/command continue
11069 * with the usual [for] command implementation */
11070 if (procEpoch
!= interp
->procEpoch
) {
11074 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
11077 if (objPtr
== NULL
) {
11081 if (!Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11082 currentVal
= ++JimWideValue(objPtr
);
11083 Jim_InvalidateStringRep(objPtr
);
11086 if (Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
||
11087 Jim_SetVariable(interp
, varNamePtr
, Jim_NewIntObj(interp
,
11088 ++currentVal
)) != JIM_OK
) {
11099 while (boolean
&& (retval
== JIM_OK
|| retval
== JIM_CONTINUE
)) {
11101 retval
= Jim_EvalObj(interp
, argv
[4]);
11103 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11106 retval
= Jim_EvalObj(interp
, argv
[3]);
11107 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11110 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11115 if (stopVarNamePtr
) {
11116 Jim_DecrRefCount(interp
, stopVarNamePtr
);
11119 Jim_DecrRefCount(interp
, varNamePtr
);
11122 if (retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
|| retval
== JIM_OK
) {
11123 Jim_SetEmptyResult(interp
);
11131 static int Jim_LoopCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11137 Jim_Obj
*bodyObjPtr
;
11139 if (argc
!= 5 && argc
!= 6) {
11140 Jim_WrongNumArgs(interp
, 1, argv
, "var first limit ?incr? body");
11144 if (Jim_GetWide(interp
, argv
[2], &i
) != JIM_OK
||
11145 Jim_GetWide(interp
, argv
[3], &limit
) != JIM_OK
||
11146 (argc
== 6 && Jim_GetWide(interp
, argv
[4], &incr
) != JIM_OK
)) {
11149 bodyObjPtr
= (argc
== 5) ? argv
[4] : argv
[5];
11151 retval
= Jim_SetVariable(interp
, argv
[1], argv
[2]);
11153 while (((i
< limit
&& incr
> 0) || (i
> limit
&& incr
< 0)) && retval
== JIM_OK
) {
11154 retval
= Jim_EvalObj(interp
, bodyObjPtr
);
11155 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11156 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11163 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11164 if (argv
[1]->typePtr
!= &variableObjType
) {
11165 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11169 JimWideValue(objPtr
) = i
;
11170 Jim_InvalidateStringRep(objPtr
);
11172 /* The following step is required in order to invalidate the
11173 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11174 if (argv
[1]->typePtr
!= &variableObjType
) {
11175 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11182 objPtr
= Jim_NewIntObj(interp
, i
);
11183 retval
= Jim_SetVariable(interp
, argv
[1], objPtr
);
11184 if (retval
!= JIM_OK
) {
11185 Jim_FreeNewObj(interp
, objPtr
);
11191 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
) {
11192 Jim_SetEmptyResult(interp
);
11198 /* foreach + lmap implementation. */
11199 static int JimForeachMapHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int doMap
)
11201 int result
= JIM_ERR
, i
, nbrOfLists
, *listsIdx
, *listsEnd
;
11202 int nbrOfLoops
= 0;
11203 Jim_Obj
*emptyStr
, *script
, *mapRes
= NULL
;
11205 if (argc
< 4 || argc
% 2 != 0) {
11206 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varList list ...? script");
11210 mapRes
= Jim_NewListObj(interp
, NULL
, 0);
11211 Jim_IncrRefCount(mapRes
);
11213 emptyStr
= Jim_NewEmptyStringObj(interp
);
11214 Jim_IncrRefCount(emptyStr
);
11215 script
= argv
[argc
- 1]; /* Last argument is a script */
11216 nbrOfLists
= (argc
- 1 - 1) / 2; /* argc - 'foreach' - script */
11217 listsIdx
= (int *)Jim_Alloc(nbrOfLists
* sizeof(int));
11218 listsEnd
= (int *)Jim_Alloc(nbrOfLists
* 2 * sizeof(int));
11219 /* Initialize iterators and remember max nbr elements each list */
11220 memset(listsIdx
, 0, nbrOfLists
* sizeof(int));
11221 /* Remember lengths of all lists and calculate how much rounds to loop */
11222 for (i
= 0; i
< nbrOfLists
* 2; i
+= 2) {
11226 listsEnd
[i
] = Jim_ListLength(interp
, argv
[i
+ 1]);
11227 listsEnd
[i
+ 1] = Jim_ListLength(interp
, argv
[i
+ 2]);
11228 if (listsEnd
[i
] == 0) {
11229 Jim_SetResultString(interp
, "foreach varlist is empty", -1);
11232 cnt
= div(listsEnd
[i
+ 1], listsEnd
[i
]);
11233 count
= cnt
.quot
+ (cnt
.rem
? 1 : 0);
11234 if (count
> nbrOfLoops
)
11235 nbrOfLoops
= count
;
11237 for (; nbrOfLoops
-- > 0;) {
11238 for (i
= 0; i
< nbrOfLists
; ++i
) {
11239 int varIdx
= 0, var
= i
* 2;
11241 while (varIdx
< listsEnd
[var
]) {
11242 Jim_Obj
*varName
, *ele
;
11243 int lst
= i
* 2 + 1;
11245 /* List index operations below can't fail */
11246 Jim_ListIndex(interp
, argv
[var
+ 1], varIdx
, &varName
, JIM_NONE
);
11247 if (listsIdx
[i
] < listsEnd
[lst
]) {
11248 Jim_ListIndex(interp
, argv
[lst
+ 1], listsIdx
[i
], &ele
, JIM_NONE
);
11249 /* Avoid shimmering */
11250 Jim_IncrRefCount(ele
);
11251 result
= Jim_SetVariable(interp
, varName
, ele
);
11252 Jim_DecrRefCount(interp
, ele
);
11253 if (result
== JIM_OK
) {
11254 ++listsIdx
[i
]; /* Remember next iterator of current list */
11255 ++varIdx
; /* Next variable */
11259 else if (Jim_SetVariable(interp
, varName
, emptyStr
) == JIM_OK
) {
11260 ++varIdx
; /* Next variable */
11266 switch (result
= Jim_EvalObj(interp
, script
)) {
11269 Jim_ListAppendElement(interp
, mapRes
, interp
->result
);
11283 Jim_SetResult(interp
, mapRes
);
11285 Jim_SetEmptyResult(interp
);
11288 Jim_DecrRefCount(interp
, mapRes
);
11289 Jim_DecrRefCount(interp
, emptyStr
);
11290 Jim_Free(listsIdx
);
11291 Jim_Free(listsEnd
);
11296 static int Jim_ForeachCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11298 return JimForeachMapHelper(interp
, argc
, argv
, 0);
11302 static int Jim_LmapCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11304 return JimForeachMapHelper(interp
, argc
, argv
, 1);
11308 static int Jim_IfCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11310 int boolean
, retval
, current
= 1, falsebody
= 0;
11314 /* Far not enough arguments given! */
11315 if (current
>= argc
)
11317 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[current
++], &boolean
))
11320 /* There lacks something, isn't it? */
11321 if (current
>= argc
)
11323 if (Jim_CompareStringImmediate(interp
, argv
[current
], "then"))
11325 /* Tsk tsk, no then-clause? */
11326 if (current
>= argc
)
11329 return Jim_EvalObj(interp
, argv
[current
]);
11330 /* Ok: no else-clause follows */
11331 if (++current
>= argc
) {
11332 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11335 falsebody
= current
++;
11336 if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "else")) {
11337 /* IIICKS - else-clause isn't last cmd? */
11338 if (current
!= argc
- 1)
11340 return Jim_EvalObj(interp
, argv
[current
]);
11342 else if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "elseif"))
11343 /* Ok: elseif follows meaning all the stuff
11344 * again (how boring...) */
11346 /* OOPS - else-clause is not last cmd? */
11347 else if (falsebody
!= argc
- 1)
11349 return Jim_EvalObj(interp
, argv
[falsebody
]);
11354 Jim_WrongNumArgs(interp
, 1, argv
, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11359 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11360 int Jim_CommandMatchObj(Jim_Interp
*interp
, Jim_Obj
*commandObj
, Jim_Obj
*patternObj
,
11361 Jim_Obj
*stringObj
, int nocase
)
11368 parms
[argc
++] = commandObj
;
11370 parms
[argc
++] = Jim_NewStringObj(interp
, "-nocase", -1);
11372 parms
[argc
++] = patternObj
;
11373 parms
[argc
++] = stringObj
;
11375 rc
= Jim_EvalObjVector(interp
, argc
, parms
);
11377 if (rc
!= JIM_OK
|| Jim_GetLong(interp
, Jim_GetResult(interp
), &eq
) != JIM_OK
) {
11385 { SWITCH_EXACT
, SWITCH_GLOB
, SWITCH_RE
, SWITCH_CMD
};
11388 static int Jim_SwitchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11390 int matchOpt
= SWITCH_EXACT
, opt
= 1, patCount
, i
;
11391 Jim_Obj
*command
= 0, *const *caseList
= 0, *strObj
;
11392 Jim_Obj
*script
= 0;
11396 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string "
11397 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11400 for (opt
= 1; opt
< argc
; ++opt
) {
11401 const char *option
= Jim_GetString(argv
[opt
], 0);
11403 if (*option
!= '-')
11405 else if (strncmp(option
, "--", 2) == 0) {
11409 else if (strncmp(option
, "-exact", 2) == 0)
11410 matchOpt
= SWITCH_EXACT
;
11411 else if (strncmp(option
, "-glob", 2) == 0)
11412 matchOpt
= SWITCH_GLOB
;
11413 else if (strncmp(option
, "-regexp", 2) == 0)
11414 matchOpt
= SWITCH_RE
;
11415 else if (strncmp(option
, "-command", 2) == 0) {
11416 matchOpt
= SWITCH_CMD
;
11417 if ((argc
- opt
) < 2)
11419 command
= argv
[++opt
];
11422 Jim_SetResultFormatted(interp
,
11423 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11427 if ((argc
- opt
) < 2)
11430 strObj
= argv
[opt
++];
11431 patCount
= argc
- opt
;
11432 if (patCount
== 1) {
11435 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11439 caseList
= &argv
[opt
];
11440 if (patCount
== 0 || patCount
% 2 != 0)
11442 for (i
= 0; script
== 0 && i
< patCount
; i
+= 2) {
11443 Jim_Obj
*patObj
= caseList
[i
];
11445 if (!Jim_CompareStringImmediate(interp
, patObj
, "default")
11446 || i
< (patCount
- 2)) {
11447 switch (matchOpt
) {
11449 if (Jim_StringEqObj(strObj
, patObj
))
11450 script
= caseList
[i
+ 1];
11453 if (Jim_StringMatchObj(interp
, patObj
, strObj
, 0))
11454 script
= caseList
[i
+ 1];
11457 command
= Jim_NewStringObj(interp
, "regexp", -1);
11458 /* Fall thru intentionally */
11460 int rc
= Jim_CommandMatchObj(interp
, command
, patObj
, strObj
, 0);
11462 /* After the execution of a command we need to
11463 * make sure to reconvert the object into a list
11464 * again. Only for the single-list style [switch]. */
11465 if (argc
- opt
== 1) {
11468 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11471 /* command is here already decref'd */
11476 script
= caseList
[i
+ 1];
11482 script
= caseList
[i
+ 1];
11485 for (; i
< patCount
&& Jim_CompareStringImmediate(interp
, script
, "-"); i
+= 2)
11486 script
= caseList
[i
+ 1];
11487 if (script
&& Jim_CompareStringImmediate(interp
, script
, "-")) {
11488 Jim_SetResultFormatted(interp
, "no body specified for pattern \"%#s\"", caseList
[i
- 2]);
11491 Jim_SetEmptyResult(interp
);
11493 return Jim_EvalObj(interp
, script
);
11499 static int Jim_ListCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11501 Jim_Obj
*listObjPtr
;
11503 listObjPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
11504 Jim_SetResult(interp
, listObjPtr
);
11509 static int Jim_LindexCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11511 Jim_Obj
*objPtr
, *listObjPtr
;
11516 Jim_WrongNumArgs(interp
, 1, argv
, "list index ?...?");
11520 Jim_IncrRefCount(objPtr
);
11521 for (i
= 2; i
< argc
; i
++) {
11522 listObjPtr
= objPtr
;
11523 if (Jim_GetIndex(interp
, argv
[i
], &idx
) != JIM_OK
) {
11524 Jim_DecrRefCount(interp
, listObjPtr
);
11527 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_NONE
) != JIM_OK
) {
11528 /* Returns an empty object if the index
11529 * is out of range. */
11530 Jim_DecrRefCount(interp
, listObjPtr
);
11531 Jim_SetEmptyResult(interp
);
11534 Jim_IncrRefCount(objPtr
);
11535 Jim_DecrRefCount(interp
, listObjPtr
);
11537 Jim_SetResult(interp
, objPtr
);
11538 Jim_DecrRefCount(interp
, objPtr
);
11543 static int Jim_LlengthCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11546 Jim_WrongNumArgs(interp
, 1, argv
, "list");
11549 Jim_SetResultInt(interp
, Jim_ListLength(interp
, argv
[1]));
11554 static int Jim_LsearchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11556 static const char * const options
[] = {
11557 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11561 { OPT_BOOL
, OPT_NOT
, OPT_NOCASE
, OPT_EXACT
, OPT_GLOB
, OPT_REGEXP
, OPT_ALL
, OPT_INLINE
,
11566 int opt_nocase
= 0;
11568 int opt_inline
= 0;
11569 int opt_match
= OPT_EXACT
;
11572 Jim_Obj
*listObjPtr
= NULL
;
11573 Jim_Obj
*commandObj
= NULL
;
11577 Jim_WrongNumArgs(interp
, 1, argv
,
11578 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11582 for (i
= 1; i
< argc
- 2; i
++) {
11585 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
11607 if (i
>= argc
- 2) {
11610 commandObj
= argv
[++i
];
11615 opt_match
= option
;
11623 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11625 if (opt_match
== OPT_REGEXP
) {
11626 commandObj
= Jim_NewStringObj(interp
, "regexp", -1);
11629 Jim_IncrRefCount(commandObj
);
11632 listlen
= Jim_ListLength(interp
, argv
[0]);
11633 for (i
= 0; i
< listlen
; i
++) {
11637 Jim_ListIndex(interp
, argv
[0], i
, &objPtr
, JIM_NONE
);
11638 switch (opt_match
) {
11640 eq
= Jim_StringCompareObj(interp
, objPtr
, argv
[1], opt_nocase
) == 0;
11644 eq
= Jim_StringMatchObj(interp
, argv
[1], objPtr
, opt_nocase
);
11649 eq
= Jim_CommandMatchObj(interp
, commandObj
, argv
[1], objPtr
, opt_nocase
);
11652 Jim_FreeNewObj(interp
, listObjPtr
);
11660 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11661 if (!eq
&& opt_bool
&& opt_not
&& !opt_all
) {
11665 if ((!opt_bool
&& eq
== !opt_not
) || (opt_bool
&& (eq
|| opt_all
))) {
11666 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11667 Jim_Obj
*resultObj
;
11670 resultObj
= Jim_NewIntObj(interp
, eq
^ opt_not
);
11672 else if (!opt_inline
) {
11673 resultObj
= Jim_NewIntObj(interp
, i
);
11676 resultObj
= objPtr
;
11680 Jim_ListAppendElement(interp
, listObjPtr
, resultObj
);
11683 Jim_SetResult(interp
, resultObj
);
11690 Jim_SetResult(interp
, listObjPtr
);
11695 Jim_SetResultBool(interp
, opt_not
);
11697 else if (!opt_inline
) {
11698 Jim_SetResultInt(interp
, -1);
11704 Jim_DecrRefCount(interp
, commandObj
);
11710 static int Jim_LappendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11712 Jim_Obj
*listObjPtr
;
11716 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
11719 listObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
11721 /* Create the list if it does not exists */
11722 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11723 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11724 Jim_FreeNewObj(interp
, listObjPtr
);
11728 shared
= Jim_IsShared(listObjPtr
);
11730 listObjPtr
= Jim_DuplicateObj(interp
, listObjPtr
);
11731 for (i
= 2; i
< argc
; i
++)
11732 Jim_ListAppendElement(interp
, listObjPtr
, argv
[i
]);
11733 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11735 Jim_FreeNewObj(interp
, listObjPtr
);
11738 Jim_SetResult(interp
, listObjPtr
);
11743 static int Jim_LinsertCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11749 Jim_WrongNumArgs(interp
, 1, argv
, "list index element " "?element ...?");
11753 if (Jim_IsShared(listPtr
))
11754 listPtr
= Jim_DuplicateObj(interp
, listPtr
);
11755 if (Jim_GetIndex(interp
, argv
[2], &idx
) != JIM_OK
)
11757 len
= Jim_ListLength(interp
, listPtr
);
11761 idx
= len
+ idx
+ 1;
11762 Jim_ListInsertElements(interp
, listPtr
, idx
, argc
- 3, &argv
[3]);
11763 Jim_SetResult(interp
, listPtr
);
11766 if (listPtr
!= argv
[1]) {
11767 Jim_FreeNewObj(interp
, listPtr
);
11773 static int Jim_LreplaceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11775 int first
, last
, len
, rangeLen
;
11777 Jim_Obj
*newListObj
;
11782 Jim_WrongNumArgs(interp
, 1, argv
, "list first last ?element element ...?");
11785 if (Jim_GetIndex(interp
, argv
[2], &first
) != JIM_OK
||
11786 Jim_GetIndex(interp
, argv
[3], &last
) != JIM_OK
) {
11791 len
= Jim_ListLength(interp
, listObj
);
11793 first
= JimRelToAbsIndex(len
, first
);
11794 last
= JimRelToAbsIndex(len
, last
);
11795 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
11797 /* Now construct a new list which consists of:
11798 * <elements before first> <supplied elements> <elements after last>
11801 /* Check to see if trying to replace past the end of the list */
11803 /* OK. Not past the end */
11805 else if (len
== 0) {
11806 /* Special for empty list, adjust first to 0 */
11810 Jim_SetResultString(interp
, "list doesn't contain element ", -1);
11811 Jim_AppendObj(interp
, Jim_GetResult(interp
), argv
[2]);
11815 newListObj
= Jim_NewListObj(interp
, NULL
, 0);
11817 shared
= Jim_IsShared(listObj
);
11819 listObj
= Jim_DuplicateObj(interp
, listObj
);
11822 /* Add the first set of elements */
11823 for (i
= 0; i
< first
; i
++) {
11824 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11827 /* Add supplied elements */
11828 for (i
= 4; i
< argc
; i
++) {
11829 Jim_ListAppendElement(interp
, newListObj
, argv
[i
]);
11832 /* Add the remaining elements */
11833 for (i
= first
+ rangeLen
; i
< len
; i
++) {
11834 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11836 Jim_SetResult(interp
, newListObj
);
11838 Jim_FreeNewObj(interp
, listObj
);
11844 static int Jim_LsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11847 Jim_WrongNumArgs(interp
, 1, argv
, "listVar ?index...? newVal");
11850 else if (argc
== 3) {
11851 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
11853 Jim_SetResult(interp
, argv
[2]);
11856 if (Jim_SetListIndex(interp
, argv
[1], argv
+ 2, argc
- 3, argv
[argc
- 1])
11863 static int Jim_LsortCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const argv
[])
11865 const char *options
[] = {
11866 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11869 { OPT_ASCII
, OPT_NOCASE
, OPT_INCREASING
, OPT_DECREASING
, OPT_COMMAND
, OPT_INTEGER
, OPT_INDEX
};
11874 struct lsort_info info
;
11877 Jim_WrongNumArgs(interp
, 1, argv
, "?options? list");
11881 info
.type
= JIM_LSORT_ASCII
;
11884 info
.command
= NULL
;
11885 info
.interp
= interp
;
11887 for (i
= 1; i
< (argc
- 1); i
++) {
11890 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
)
11895 info
.type
= JIM_LSORT_ASCII
;
11898 info
.type
= JIM_LSORT_NOCASE
;
11901 info
.type
= JIM_LSORT_INTEGER
;
11903 case OPT_INCREASING
:
11906 case OPT_DECREASING
:
11910 if (i
>= (argc
- 2)) {
11911 Jim_SetResultString(interp
, "\"-command\" option must be followed by comparison command", -1);
11914 info
.type
= JIM_LSORT_COMMAND
;
11915 info
.command
= argv
[i
+ 1];
11919 if (i
>= (argc
- 2)) {
11920 Jim_SetResultString(interp
, "\"-index\" option must be followed by list index", -1);
11923 if (Jim_GetIndex(interp
, argv
[i
+ 1], &info
.index
) != JIM_OK
) {
11931 resObj
= Jim_DuplicateObj(interp
, argv
[argc
- 1]);
11932 retCode
= ListSortElements(interp
, resObj
, &info
);
11933 if (retCode
== JIM_OK
) {
11934 Jim_SetResult(interp
, resObj
);
11937 Jim_FreeNewObj(interp
, resObj
);
11943 static int Jim_AppendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11945 Jim_Obj
*stringObjPtr
;
11949 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
11953 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11959 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
11960 if (!stringObjPtr
) {
11961 /* Create the string if it doesn't exist */
11962 stringObjPtr
= Jim_NewEmptyStringObj(interp
);
11965 else if (Jim_IsShared(stringObjPtr
)) {
11967 stringObjPtr
= Jim_DuplicateObj(interp
, stringObjPtr
);
11969 for (i
= 2; i
< argc
; i
++) {
11970 Jim_AppendObj(interp
, stringObjPtr
, argv
[i
]);
11972 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
) != JIM_OK
) {
11974 Jim_FreeNewObj(interp
, stringObjPtr
);
11979 Jim_SetResult(interp
, stringObjPtr
);
11984 static int Jim_DebugCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11986 #ifdef JIM_DEBUG_COMMAND
11987 const char *options
[] = {
11988 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
11994 OPT_REFCOUNT
, OPT_OBJCOUNT
, OPT_OBJECTS
, OPT_INVSTR
, OPT_SCRIPTLEN
,
11995 OPT_EXPRLEN
, OPT_EXPRBC
, OPT_SHOW
,
12000 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?...?");
12003 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
)
12005 if (option
== OPT_REFCOUNT
) {
12007 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12010 Jim_SetResultInt(interp
, argv
[2]->refCount
);
12013 else if (option
== OPT_OBJCOUNT
) {
12014 int freeobj
= 0, liveobj
= 0;
12019 Jim_WrongNumArgs(interp
, 2, argv
, "");
12022 /* Count the number of free objects. */
12023 objPtr
= interp
->freeList
;
12026 objPtr
= objPtr
->nextObjPtr
;
12028 /* Count the number of live objects. */
12029 objPtr
= interp
->liveList
;
12032 objPtr
= objPtr
->nextObjPtr
;
12034 /* Set the result string and return. */
12035 sprintf(buf
, "free %d used %d", freeobj
, liveobj
);
12036 Jim_SetResultString(interp
, buf
, -1);
12039 else if (option
== OPT_OBJECTS
) {
12040 Jim_Obj
*objPtr
, *listObjPtr
, *subListObjPtr
;
12042 /* Count the number of live objects. */
12043 objPtr
= interp
->liveList
;
12044 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12047 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "";
12049 subListObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12050 sprintf(buf
, "%p", objPtr
);
12051 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
12052 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, type
, -1));
12053 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewIntObj(interp
, objPtr
->refCount
));
12054 Jim_ListAppendElement(interp
, subListObjPtr
, objPtr
);
12055 Jim_ListAppendElement(interp
, listObjPtr
, subListObjPtr
);
12056 objPtr
= objPtr
->nextObjPtr
;
12058 Jim_SetResult(interp
, listObjPtr
);
12061 else if (option
== OPT_INVSTR
) {
12065 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12069 if (objPtr
->typePtr
!= NULL
)
12070 Jim_InvalidateStringRep(objPtr
);
12071 Jim_SetEmptyResult(interp
);
12074 else if (option
== OPT_SHOW
) {
12079 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12082 s
= Jim_GetString(argv
[2], &len
);
12083 charlen
= Jim_Utf8Length(interp
, argv
[2]);
12084 printf("chars (%d): <<%s>>\n", charlen
, s
);
12085 printf("bytes (%d):", len
);
12087 printf(" %02x", (unsigned char)*s
++);
12092 else if (option
== OPT_SCRIPTLEN
) {
12096 Jim_WrongNumArgs(interp
, 2, argv
, "script");
12099 script
= Jim_GetScript(interp
, argv
[2]);
12100 Jim_SetResultInt(interp
, script
->len
);
12103 else if (option
== OPT_EXPRLEN
) {
12104 ExprByteCode
*expr
;
12107 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12110 expr
= JimGetExpression(interp
, argv
[2]);
12113 Jim_SetResultInt(interp
, expr
->len
);
12116 else if (option
== OPT_EXPRBC
) {
12118 ExprByteCode
*expr
;
12122 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12125 expr
= JimGetExpression(interp
, argv
[2]);
12128 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
12129 for (i
= 0; i
< expr
->len
; i
++) {
12131 const Jim_ExprOperator
*op
;
12132 Jim_Obj
*obj
= expr
->token
[i
].objPtr
;
12134 switch (expr
->token
[i
].type
) {
12135 case JIM_TT_EXPR_INT
:
12138 case JIM_TT_EXPR_DOUBLE
:
12147 case JIM_TT_DICTSUGAR
:
12148 type
= "dictsugar";
12150 case JIM_TT_EXPRSUGAR
:
12151 type
= "exprsugar";
12160 op
= JimExprOperatorInfoByOpcode(expr
->token
[i
].type
);
12167 obj
= Jim_NewStringObj(interp
, op
? op
->name
: "", -1);
12170 Jim_ListAppendElement(interp
, objPtr
, Jim_NewStringObj(interp
, type
, -1));
12171 Jim_ListAppendElement(interp
, objPtr
, obj
);
12173 Jim_SetResult(interp
, objPtr
);
12177 Jim_SetResultString(interp
,
12178 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12183 Jim_SetResultString(interp
, "unsupported", -1);
12189 static int Jim_EvalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12192 Jim_Stack
*prevLocalProcs
;
12195 Jim_WrongNumArgs(interp
, 1, argv
, "script ?...?");
12199 /* Install a new stack for local procs */
12200 prevLocalProcs
= interp
->localProcs
;
12201 interp
->localProcs
= NULL
;
12204 rc
= Jim_EvalObj(interp
, argv
[1]);
12207 rc
= Jim_EvalObj(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12210 /* Delete any local procs */
12211 JimDeleteLocalProcs(interp
);
12212 interp
->localProcs
= prevLocalProcs
;
12214 if (rc
== JIM_ERR
) {
12215 /* eval is "interesting", so add a stack frame here */
12216 interp
->addStackTrace
++;
12222 static int Jim_UplevelCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12226 Jim_CallFrame
*savedCallFrame
, *targetCallFrame
;
12230 /* Save the old callframe pointer */
12231 savedCallFrame
= interp
->framePtr
;
12233 /* Lookup the target frame pointer */
12234 str
= Jim_String(argv
[1]);
12235 if ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#') {
12236 targetCallFrame
=Jim_GetCallFrameByLevel(interp
, argv
[1]);
12241 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12243 if (targetCallFrame
== NULL
) {
12248 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12251 /* Eval the code in the target callframe. */
12252 interp
->framePtr
= targetCallFrame
;
12254 retcode
= Jim_EvalObj(interp
, argv
[1]);
12257 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12258 Jim_IncrRefCount(objPtr
);
12259 retcode
= Jim_EvalObj(interp
, objPtr
);
12260 Jim_DecrRefCount(interp
, objPtr
);
12262 interp
->framePtr
= savedCallFrame
;
12266 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12272 static int Jim_ExprCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12274 Jim_Obj
*exprResultPtr
;
12278 retcode
= Jim_EvalExpression(interp
, argv
[1], &exprResultPtr
);
12280 else if (argc
> 2) {
12283 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12284 Jim_IncrRefCount(objPtr
);
12285 retcode
= Jim_EvalExpression(interp
, objPtr
, &exprResultPtr
);
12286 Jim_DecrRefCount(interp
, objPtr
);
12289 Jim_WrongNumArgs(interp
, 1, argv
, "expression ?...?");
12292 if (retcode
!= JIM_OK
)
12294 Jim_SetResult(interp
, exprResultPtr
);
12295 Jim_DecrRefCount(interp
, exprResultPtr
);
12300 static int Jim_BreakCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12303 Jim_WrongNumArgs(interp
, 1, argv
, "");
12310 static int Jim_ContinueCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12313 Jim_WrongNumArgs(interp
, 1, argv
, "");
12316 return JIM_CONTINUE
;
12320 static int Jim_ReturnCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12323 Jim_Obj
*stackTraceObj
= NULL
;
12324 Jim_Obj
*errorCodeObj
= NULL
;
12325 int returnCode
= JIM_OK
;
12328 for (i
= 1; i
< argc
- 1; i
+= 2) {
12329 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-code")) {
12330 if (Jim_GetReturnCode(interp
, argv
[i
+ 1], &returnCode
) == JIM_ERR
) {
12334 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorinfo")) {
12335 stackTraceObj
= argv
[i
+ 1];
12337 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorcode")) {
12338 errorCodeObj
= argv
[i
+ 1];
12340 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-level")) {
12341 if (Jim_GetLong(interp
, argv
[i
+ 1], &level
) != JIM_OK
|| level
< 0) {
12342 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", argv
[i
+ 1]);
12351 if (i
!= argc
- 1 && i
!= argc
) {
12352 Jim_WrongNumArgs(interp
, 1, argv
,
12353 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12356 /* If a stack trace is supplied and code is error, set the stack trace */
12357 if (stackTraceObj
&& returnCode
== JIM_ERR
) {
12358 JimSetStackTrace(interp
, stackTraceObj
);
12360 /* If an error code list is supplied, set the global $errorCode */
12361 if (errorCodeObj
&& returnCode
== JIM_ERR
) {
12362 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCodeObj
);
12364 interp
->returnCode
= returnCode
;
12365 interp
->returnLevel
= level
;
12367 if (i
== argc
- 1) {
12368 Jim_SetResult(interp
, argv
[i
]);
12374 static int Jim_TailcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12378 objPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
12379 Jim_SetResult(interp
, objPtr
);
12384 static int Jim_ProcCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12387 int leftArity
, rightArity
;
12389 int optionalArgs
= 0;
12392 if (argc
!= 4 && argc
!= 5) {
12393 Jim_WrongNumArgs(interp
, 1, argv
, "name arglist ?statics? body");
12397 if (JimValidName(interp
, "procedure", argv
[1]) != JIM_OK
) {
12401 argListLen
= Jim_ListLength(interp
, argv
[2]);
12405 /* Examine the argument list for default parameters and 'args' */
12406 for (i
= 0; i
< argListLen
; i
++) {
12410 /* Examine a parameter */
12411 Jim_ListIndex(interp
, argv
[2], i
, &argPtr
, JIM_NONE
);
12412 len
= Jim_ListLength(interp
, argPtr
);
12414 Jim_SetResultString(interp
, "procedure has argument with no name", -1);
12418 Jim_SetResultString(interp
, "procedure has argument with too many fields", -1);
12423 /* May be {args newname} */
12424 Jim_ListIndex(interp
, argPtr
, 0, &argPtr
, JIM_NONE
);
12427 if (Jim_CompareStringImmediate(interp
, argPtr
, "args")) {
12429 Jim_SetResultString(interp
, "procedure has 'args' specified more than once", -1);
12433 Jim_SetResultString(interp
, "procedure has 'args' in invalid position", -1);
12440 /* Does this parameter have a default? */
12442 /* A required arg. Is it part of leftArity or rightArity? */
12443 if (optionalArgs
|| args
) {
12451 /* Optional arg. Can't be after rightArity */
12452 if (rightArity
|| args
) {
12453 Jim_SetResultString(interp
, "procedure has optional arg in invalid position", -1);
12461 return JimCreateProcedure(interp
, Jim_String(argv
[1]),
12462 argv
[2], NULL
, argv
[3], leftArity
, optionalArgs
, args
, rightArity
);
12465 return JimCreateProcedure(interp
, Jim_String(argv
[1]),
12466 argv
[2], argv
[3], argv
[4], leftArity
, optionalArgs
, args
, rightArity
);
12471 static int Jim_LocalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12475 /* Evaluate the arguments with 'local' in force */
12477 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12481 /* If OK, and the result is a proc, add it to the list of local procs */
12482 if (retcode
== 0) {
12483 const char *procname
= Jim_String(Jim_GetResult(interp
));
12485 if (Jim_FindHashEntry(&interp
->commands
, procname
) == NULL
) {
12486 Jim_SetResultFormatted(interp
, "not a proc: \"%s\"", procname
);
12489 if (interp
->localProcs
== NULL
) {
12490 interp
->localProcs
= Jim_Alloc(sizeof(*interp
->localProcs
));
12491 Jim_InitStack(interp
->localProcs
);
12493 Jim_StackPush(interp
->localProcs
, Jim_StrDup(procname
));
12500 static int Jim_UpcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12503 Jim_WrongNumArgs(interp
, 1, argv
, "cmd ?args ...?");
12509 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, argv
[1], JIM_ERRMSG
);
12510 if (cmdPtr
== NULL
|| !cmdPtr
->isproc
|| !cmdPtr
->u
.proc
.prevCmd
) {
12511 Jim_SetResultFormatted(interp
, "no previous proc: \"%#s\"", argv
[1]);
12514 /* OK. Mark this command as being in an upcall */
12515 cmdPtr
->u
.proc
.upcall
++;
12516 JimIncrCmdRefCount(cmdPtr
);
12518 /* Invoke the command as normal */
12519 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12521 /* No longer in an upcall */
12522 cmdPtr
->u
.proc
.upcall
--;
12523 JimDecrCmdRefCount(interp
, cmdPtr
);
12530 static int Jim_ConcatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12532 Jim_SetResult(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12537 static int Jim_UpvarCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12540 Jim_CallFrame
*targetCallFrame
;
12542 /* Lookup the target frame pointer */
12543 if (argc
> 3 && (argc
% 2 == 0)) {
12544 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, argv
[1]);
12549 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12551 if (targetCallFrame
== NULL
) {
12555 /* Check for arity */
12557 Jim_WrongNumArgs(interp
, 1, argv
, "?level? otherVar localVar ?otherVar localVar ...?");
12561 /* Now... for every other/local couple: */
12562 for (i
= 1; i
< argc
; i
+= 2) {
12563 if (Jim_SetVariableLink(interp
, argv
[i
+ 1], argv
[i
], targetCallFrame
) != JIM_OK
)
12570 static int Jim_GlobalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12575 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
12578 /* Link every var to the toplevel having the same name */
12579 if (interp
->framePtr
->level
== 0)
12580 return JIM_OK
; /* global at toplevel... */
12581 for (i
= 1; i
< argc
; i
++) {
12582 if (Jim_SetVariableLink(interp
, argv
[i
], argv
[i
], interp
->topFramePtr
) != JIM_OK
)
12588 /* does the [string map] operation. On error NULL is returned,
12589 * otherwise a new string object with the result, having refcount = 0,
12591 static Jim_Obj
*JimStringMap(Jim_Interp
*interp
, Jim_Obj
*mapListObjPtr
,
12592 Jim_Obj
*objPtr
, int nocase
)
12595 const char *str
, *noMatchStart
= NULL
;
12597 Jim_Obj
*resultObjPtr
;
12599 numMaps
= Jim_ListLength(interp
, mapListObjPtr
);
12601 Jim_SetResultString(interp
, "list must contain an even number of elements", -1);
12605 str
= Jim_String(objPtr
);
12606 strLen
= Jim_Utf8Length(interp
, objPtr
);
12609 resultObjPtr
= Jim_NewStringObj(interp
, "", 0);
12611 for (i
= 0; i
< numMaps
; i
+= 2) {
12616 Jim_ListIndex(interp
, mapListObjPtr
, i
, &objPtr
, JIM_NONE
);
12617 k
= Jim_String(objPtr
);
12618 kl
= Jim_Utf8Length(interp
, objPtr
);
12620 if (strLen
>= kl
&& kl
) {
12623 rc
= JimStringCompareNoCase(str
, k
, kl
);
12626 rc
= JimStringCompare(str
, kl
, k
, kl
);
12629 if (noMatchStart
) {
12630 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12631 noMatchStart
= NULL
;
12633 Jim_ListIndex(interp
, mapListObjPtr
, i
+ 1, &objPtr
, JIM_NONE
);
12634 Jim_AppendObj(interp
, resultObjPtr
, objPtr
);
12635 str
+= utf8_index(str
, kl
);
12641 if (i
== numMaps
) { /* no match */
12643 if (noMatchStart
== NULL
)
12644 noMatchStart
= str
;
12645 str
+= utf8_tounicode(str
, &c
);
12649 if (noMatchStart
) {
12650 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12652 return resultObjPtr
;
12656 static int Jim_StringCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12661 static const char * const options
[] = {
12662 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12663 "repeat", "reverse", "index", "first", "last",
12664 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12668 OPT_BYTELENGTH
, OPT_LENGTH
, OPT_COMPARE
, OPT_MATCH
, OPT_EQUAL
, OPT_IS
, OPT_BYTERANGE
, OPT_RANGE
, OPT_MAP
,
12669 OPT_REPEAT
, OPT_REVERSE
, OPT_INDEX
, OPT_FIRST
, OPT_LAST
,
12670 OPT_TRIM
, OPT_TRIMLEFT
, OPT_TRIMRIGHT
, OPT_TOLOWER
, OPT_TOUPPER
12672 static const char * const nocase_options
[] = {
12677 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
12680 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
,
12681 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
)
12686 case OPT_BYTELENGTH
:
12688 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12691 if (option
== OPT_LENGTH
) {
12692 len
= Jim_Utf8Length(interp
, argv
[2]);
12695 len
= Jim_Length(argv
[2]);
12697 Jim_SetResultInt(interp
, len
);
12704 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12705 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12706 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? string1 string2");
12709 if (opt_case
== 0) {
12712 if (option
== OPT_COMPARE
|| !opt_case
) {
12713 Jim_SetResultInt(interp
, Jim_StringCompareObj(interp
, argv
[2], argv
[3], !opt_case
));
12716 Jim_SetResultBool(interp
, Jim_StringEqObj(argv
[2], argv
[3]));
12723 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12724 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12725 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? pattern string");
12728 if (opt_case
== 0) {
12731 Jim_SetResultBool(interp
, Jim_StringMatchObj(interp
, argv
[2], argv
[3], !opt_case
));
12739 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12740 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12741 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? mapList string");
12745 if (opt_case
== 0) {
12748 objPtr
= JimStringMap(interp
, argv
[2], argv
[3], !opt_case
);
12749 if (objPtr
== NULL
) {
12752 Jim_SetResult(interp
, objPtr
);
12757 case OPT_BYTERANGE
:{
12761 Jim_WrongNumArgs(interp
, 2, argv
, "string first last");
12764 if (option
== OPT_RANGE
) {
12765 objPtr
= Jim_StringRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12769 objPtr
= Jim_StringByteRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12772 if (objPtr
== NULL
) {
12775 Jim_SetResult(interp
, objPtr
);
12784 Jim_WrongNumArgs(interp
, 2, argv
, "string count");
12787 if (Jim_GetWide(interp
, argv
[3], &count
) != JIM_OK
) {
12790 objPtr
= Jim_NewStringObj(interp
, "", 0);
12793 Jim_AppendObj(interp
, objPtr
, argv
[2]);
12796 Jim_SetResult(interp
, objPtr
);
12807 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12811 str
= Jim_GetString(argv
[2], &len
);
12816 buf
= Jim_Alloc(len
+ 1);
12819 for (i
= 0; i
< len
; ) {
12821 int l
= utf8_tounicode(str
, &c
);
12822 memcpy(p
- l
, str
, l
);
12827 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
12836 Jim_WrongNumArgs(interp
, 2, argv
, "string index");
12839 if (Jim_GetIndex(interp
, argv
[3], &idx
) != JIM_OK
) {
12842 str
= Jim_String(argv
[2]);
12843 len
= Jim_Utf8Length(interp
, argv
[2]);
12844 if (idx
!= INT_MIN
&& idx
!= INT_MAX
) {
12845 idx
= JimRelToAbsIndex(len
, idx
);
12847 if (idx
< 0 || idx
>= len
|| str
== NULL
) {
12848 Jim_SetResultString(interp
, "", 0);
12850 else if (len
== Jim_Length(argv
[2])) {
12851 /* ASCII optimisation */
12852 Jim_SetResultString(interp
, str
+ idx
, 1);
12856 int i
= utf8_index(str
, idx
);
12857 Jim_SetResultString(interp
, str
+ i
, utf8_tounicode(str
+ i
, &c
));
12864 int idx
= 0, l1
, l2
;
12865 const char *s1
, *s2
;
12867 if (argc
!= 4 && argc
!= 5) {
12868 Jim_WrongNumArgs(interp
, 2, argv
, "subString string ?index?");
12871 s1
= Jim_String(argv
[2]);
12872 s2
= Jim_String(argv
[3]);
12873 l1
= Jim_Utf8Length(interp
, argv
[2]);
12874 l2
= Jim_Utf8Length(interp
, argv
[3]);
12876 if (Jim_GetIndex(interp
, argv
[4], &idx
) != JIM_OK
) {
12879 idx
= JimRelToAbsIndex(l2
, idx
);
12881 else if (option
== OPT_LAST
) {
12884 if (option
== OPT_FIRST
) {
12885 Jim_SetResultInt(interp
, JimStringFirst(s1
, l1
, s2
, l2
, idx
));
12889 Jim_SetResultInt(interp
, JimStringLastUtf8(s1
, l1
, s2
, idx
));
12891 Jim_SetResultInt(interp
, JimStringLast(s1
, l1
, s2
, idx
));
12899 case OPT_TRIMRIGHT
:{
12900 Jim_Obj
*trimchars
;
12902 if (argc
!= 3 && argc
!= 4) {
12903 Jim_WrongNumArgs(interp
, 2, argv
, "string ?trimchars?");
12906 trimchars
= (argc
== 4 ? argv
[3] : NULL
);
12907 if (option
== OPT_TRIM
) {
12908 Jim_SetResult(interp
, JimStringTrim(interp
, argv
[2], trimchars
));
12910 else if (option
== OPT_TRIMLEFT
) {
12911 Jim_SetResult(interp
, JimStringTrimLeft(interp
, argv
[2], trimchars
));
12913 else if (option
== OPT_TRIMRIGHT
) {
12914 Jim_SetResult(interp
, JimStringTrimRight(interp
, argv
[2], trimchars
));
12922 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12925 if (option
== OPT_TOLOWER
) {
12926 Jim_SetResult(interp
, JimStringToLower(interp
, argv
[2]));
12929 Jim_SetResult(interp
, JimStringToUpper(interp
, argv
[2]));
12934 if (argc
== 4 || (argc
== 5 && Jim_CompareStringImmediate(interp
, argv
[3], "-strict"))) {
12935 return JimStringIs(interp
, argv
[argc
- 1], argv
[2], argc
== 5);
12937 Jim_WrongNumArgs(interp
, 2, argv
, "class ?-strict? str");
12944 static int Jim_TimeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12947 jim_wide start
, elapsed
;
12949 const char *fmt
= "%" JIM_WIDE_MODIFIER
" microseconds per iteration";
12952 Jim_WrongNumArgs(interp
, 1, argv
, "script ?count?");
12956 if (Jim_GetLong(interp
, argv
[2], &count
) != JIM_OK
)
12962 start
= JimClock();
12966 retval
= Jim_EvalObj(interp
, argv
[1]);
12967 if (retval
!= JIM_OK
) {
12971 elapsed
= JimClock() - start
;
12972 sprintf(buf
, fmt
, count
== 0 ? 0 : elapsed
/ count
);
12973 Jim_SetResultString(interp
, buf
, -1);
12978 static int Jim_ExitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12983 Jim_WrongNumArgs(interp
, 1, argv
, "?exitCode?");
12987 if (Jim_GetLong(interp
, argv
[1], &exitCode
) != JIM_OK
)
12990 interp
->exitCode
= exitCode
;
12995 static int Jim_CatchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13001 /* Which return codes are caught? These are the defaults */
13003 (1 << JIM_OK
| 1 << JIM_ERR
| 1 << JIM_BREAK
| 1 << JIM_CONTINUE
| 1 << JIM_RETURN
);
13005 /* Reset the error code before catch.
13006 * Note that this is not strictly correct.
13008 Jim_SetGlobalVariableStr(interp
, "errorCode", Jim_NewStringObj(interp
, "NONE", -1));
13010 for (i
= 1; i
< argc
- 1; i
++) {
13011 const char *arg
= Jim_String(argv
[i
]);
13015 /* It's a pity we can't use Jim_GetEnum here :-( */
13016 if (strcmp(arg
, "--") == 0) {
13024 if (strncmp(arg
, "-no", 3) == 0) {
13033 if (Jim_StringToWide(arg
, &option
, 10) != JIM_OK
) {
13037 option
= Jim_FindByName(arg
, jimReturnCodes
, jimReturnCodesSize
);
13044 mask
|= (1 << option
);
13047 mask
&= ~(1 << option
);
13052 if (argc
< 1 || argc
> 3) {
13054 Jim_WrongNumArgs(interp
, 1, argv
,
13055 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13060 if (mask
& (1 << JIM_SIGNAL
)) {
13064 interp
->signal_level
+= sig
;
13065 if (interp
->signal_level
&& interp
->sigmask
) {
13066 /* If a signal is set, don't even try to execute the body */
13067 exitCode
= JIM_SIGNAL
;
13070 exitCode
= Jim_EvalObj(interp
, argv
[0]);
13072 interp
->signal_level
-= sig
;
13074 /* Catch or pass through? Only the first 64 codes can be passed through */
13075 if (exitCode
>= 0 && exitCode
< (int)sizeof(mask
) && ((1 << exitCode
) & mask
) == 0) {
13076 /* Not caught, pass it up */
13080 if (sig
&& exitCode
== JIM_SIGNAL
) {
13081 /* Catch the signal at this level */
13082 if (interp
->signal_set_result
) {
13083 interp
->signal_set_result(interp
, interp
->sigmask
);
13086 Jim_SetResultInt(interp
, interp
->sigmask
);
13088 interp
->sigmask
= 0;
13092 if (Jim_SetVariable(interp
, argv
[1], Jim_GetResult(interp
)) != JIM_OK
) {
13096 Jim_Obj
*optListObj
= Jim_NewListObj(interp
, NULL
, 0);
13098 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-code", -1));
13099 Jim_ListAppendElement(interp
, optListObj
,
13100 Jim_NewIntObj(interp
, exitCode
== JIM_RETURN
? interp
->returnCode
: exitCode
));
13101 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-level", -1));
13102 Jim_ListAppendElement(interp
, optListObj
, Jim_NewIntObj(interp
, interp
->returnLevel
));
13103 if (exitCode
== JIM_ERR
) {
13104 Jim_Obj
*errorCode
;
13105 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorinfo",
13107 Jim_ListAppendElement(interp
, optListObj
, interp
->stackTrace
);
13109 errorCode
= Jim_GetGlobalVariableStr(interp
, "errorCode", JIM_NONE
);
13111 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorcode", -1));
13112 Jim_ListAppendElement(interp
, optListObj
, errorCode
);
13115 if (Jim_SetVariable(interp
, argv
[2], optListObj
) != JIM_OK
) {
13120 Jim_SetResultInt(interp
, exitCode
);
13124 #ifdef JIM_REFERENCES
13127 static int Jim_RefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13129 if (argc
!= 3 && argc
!= 4) {
13130 Jim_WrongNumArgs(interp
, 1, argv
, "string tag ?finalizer?");
13134 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], NULL
));
13137 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], argv
[3]));
13143 static int Jim_GetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13145 Jim_Reference
*refPtr
;
13148 Jim_WrongNumArgs(interp
, 1, argv
, "reference");
13151 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13153 Jim_SetResult(interp
, refPtr
->objPtr
);
13158 static int Jim_SetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13160 Jim_Reference
*refPtr
;
13163 Jim_WrongNumArgs(interp
, 1, argv
, "reference newValue");
13166 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13168 Jim_IncrRefCount(argv
[2]);
13169 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
13170 refPtr
->objPtr
= argv
[2];
13171 Jim_SetResult(interp
, argv
[2]);
13176 static int Jim_CollectCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13179 Jim_WrongNumArgs(interp
, 1, argv
, "");
13182 Jim_SetResultInt(interp
, Jim_Collect(interp
));
13184 /* Free all the freed objects. */
13185 while (interp
->freeList
) {
13186 Jim_Obj
*nextObjPtr
= interp
->freeList
->nextObjPtr
;
13187 Jim_Free(interp
->freeList
);
13188 interp
->freeList
= nextObjPtr
;
13194 /* [finalize] reference ?newValue? */
13195 static int Jim_FinalizeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13197 if (argc
!= 2 && argc
!= 3) {
13198 Jim_WrongNumArgs(interp
, 1, argv
, "reference ?finalizerProc?");
13202 Jim_Obj
*cmdNamePtr
;
13204 if (Jim_GetFinalizer(interp
, argv
[1], &cmdNamePtr
) != JIM_OK
)
13206 if (cmdNamePtr
!= NULL
) /* otherwise the null string is returned. */
13207 Jim_SetResult(interp
, cmdNamePtr
);
13210 if (Jim_SetFinalizer(interp
, argv
[1], argv
[2]) != JIM_OK
)
13212 Jim_SetResult(interp
, argv
[2]);
13217 /* [info references] */
13218 static int JimInfoReferences(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13220 Jim_Obj
*listObjPtr
;
13221 Jim_HashTableIterator
*htiter
;
13224 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13226 htiter
= Jim_GetHashTableIterator(&interp
->references
);
13227 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
13228 char buf
[JIM_REFERENCE_SPACE
];
13229 Jim_Reference
*refPtr
= he
->u
.val
;
13230 const jim_wide
*refId
= he
->key
;
13232 JimFormatReference(buf
, refPtr
, *refId
);
13233 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
13235 Jim_FreeHashTableIterator(htiter
);
13236 Jim_SetResult(interp
, listObjPtr
);
13242 static int Jim_RenameCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13244 const char *oldName
, *newName
;
13247 Jim_WrongNumArgs(interp
, 1, argv
, "oldName newName");
13251 if (JimValidName(interp
, "new procedure", argv
[2])) {
13255 oldName
= Jim_String(argv
[1]);
13256 newName
= Jim_String(argv
[2]);
13257 return Jim_RenameCommand(interp
, oldName
, newName
);
13260 int Jim_DictKeys(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*patternObj
)
13264 Jim_Obj
*resultObj
;
13266 Jim_Obj
**dictValuesObj
;
13268 if (Jim_DictKeysVector(interp
, objPtr
, NULL
, 0, &dictObj
, JIM_ERRMSG
) != JIM_OK
) {
13272 /* XXX: Could make the exact-match case much more efficient here.
13273 * See JimCommandsList()
13275 if (Jim_DictPairs(interp
, dictObj
, &dictValuesObj
, &len
) != JIM_OK
) {
13279 /* Only return the matching values */
13280 resultObj
= Jim_NewListObj(interp
, NULL
, 0);
13282 for (i
= 0; i
< len
; i
+= 2) {
13283 if (patternObj
== NULL
|| Jim_StringMatchObj(interp
, patternObj
, dictValuesObj
[i
], 0)) {
13284 Jim_ListAppendElement(interp
, resultObj
, dictValuesObj
[i
]);
13287 Jim_Free(dictValuesObj
);
13289 Jim_SetResult(interp
, resultObj
);
13293 int Jim_DictSize(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
13295 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
13298 return ((Jim_HashTable
*)objPtr
->internalRep
.ptr
)->used
;
13302 static int Jim_DictCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13306 const char *options
[] = {
13307 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13311 OPT_CREATE
, OPT_GET
, OPT_SET
, OPT_UNSET
, OPT_EXIST
, OPT_KEYS
, OPT_MERGE
, OPT_SIZE
, OPT_WITH
,
13315 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?arguments ...?");
13319 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
) {
13326 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13329 if (Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, &objPtr
,
13330 JIM_ERRMSG
) != JIM_OK
) {
13333 Jim_SetResult(interp
, objPtr
);
13338 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...? value");
13341 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 4, argv
[argc
- 1]);
13345 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13348 Jim_SetResultBool(interp
, Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3,
13349 &objPtr
, JIM_ERRMSG
) == JIM_OK
);
13354 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...?");
13357 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, NULL
);
13360 if (argc
!= 3 && argc
!= 4) {
13361 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?pattern?");
13364 return Jim_DictKeys(interp
, argv
[2], argc
== 4 ? argv
[3] : NULL
);
13370 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar");
13374 size
= Jim_DictSize(interp
, argv
[2]);
13378 Jim_SetResultInt(interp
, size
);
13386 else if (argv
[2]->typePtr
!= &dictObjType
&& SetDictFromAny(interp
, argv
[2]) != JIM_OK
) {
13390 return Jim_EvalObjPrefix(interp
, "dict merge", argc
- 2, argv
+ 2);
13395 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?key ...? script");
13398 else if (Jim_GetVariable(interp
, argv
[2], JIM_ERRMSG
) == NULL
) {
13402 return Jim_EvalObjPrefix(interp
, "dict with", argc
- 2, argv
+ 2);
13407 Jim_WrongNumArgs(interp
, 2, argv
, "?key value ...?");
13410 objPtr
= Jim_NewDictObj(interp
, argv
+ 2, argc
- 2);
13411 Jim_SetResult(interp
, objPtr
);
13420 static int Jim_SubstCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13422 const char *options
[] = {
13423 "-nobackslashes", "-nocommands", "-novariables", NULL
13426 { OPT_NOBACKSLASHES
, OPT_NOCOMMANDS
, OPT_NOVARIABLES
};
13428 int flags
= JIM_SUBST_FLAG
;
13432 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string");
13435 for (i
= 1; i
< (argc
- 1); i
++) {
13438 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
,
13439 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13443 case OPT_NOBACKSLASHES
:
13444 flags
|= JIM_SUBST_NOESC
;
13446 case OPT_NOCOMMANDS
:
13447 flags
|= JIM_SUBST_NOCMD
;
13449 case OPT_NOVARIABLES
:
13450 flags
|= JIM_SUBST_NOVAR
;
13454 if (Jim_SubstObj(interp
, argv
[argc
- 1], &objPtr
, flags
) != JIM_OK
) {
13457 Jim_SetResult(interp
, objPtr
);
13462 static int Jim_InfoCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13468 static const char * const commands
[] = {
13469 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13470 "vars", "version", "patchlevel", "complete", "args", "hostname",
13471 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13475 { INFO_BODY
, INFO_COMMANDS
, INFO_PROCS
, INFO_CHANNELS
, INFO_EXISTS
, INFO_GLOBALS
, INFO_LEVEL
,
13476 INFO_FRAME
, INFO_LOCALS
, INFO_VARS
, INFO_VERSION
, INFO_PATCHLEVEL
, INFO_COMPLETE
, INFO_ARGS
,
13477 INFO_HOSTNAME
, INFO_SCRIPT
, INFO_SOURCE
, INFO_STACKTRACE
, INFO_NAMEOFEXECUTABLE
,
13478 INFO_RETURNCODES
, INFO_REFERENCES
,
13482 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?args ...?");
13485 if (Jim_GetEnum(interp
, argv
[1], commands
, &cmd
, "subcommand", JIM_ERRMSG
| JIM_ENUM_ABBREV
)
13490 /* Test for the the most common commands first, just in case it makes a difference */
13494 Jim_WrongNumArgs(interp
, 2, argv
, "varName");
13497 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, argv
[2], 0) != NULL
);
13501 case INFO_CHANNELS
:
13502 #ifndef jim_ext_aio
13503 Jim_SetResultString(interp
, "aio not enabled", -1);
13506 case INFO_COMMANDS
:
13508 if (argc
!= 2 && argc
!= 3) {
13509 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13512 Jim_SetResult(interp
, JimCommandsList(interp
, (argc
== 3) ? argv
[2] : NULL
,
13513 (cmd
- INFO_COMMANDS
)));
13517 mode
++; /* JIM_VARLIST_VARS */
13519 mode
++; /* JIM_VARLIST_LOCALS */
13521 /* mode 0 => JIM_VARLIST_GLOBALS */
13522 if (argc
!= 2 && argc
!= 3) {
13523 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13526 Jim_SetResult(interp
, JimVariablesList(interp
, argc
== 3 ? argv
[2] : NULL
, mode
));
13531 Jim_WrongNumArgs(interp
, 2, argv
, "");
13534 Jim_SetResultString(interp
, Jim_GetScript(interp
, interp
->currentScriptObj
)->fileName
,
13539 const char *filename
= "";
13541 Jim_Obj
*resObjPtr
;
13544 Jim_WrongNumArgs(interp
, 2, argv
, "source");
13547 if (argv
[2]->typePtr
== &sourceObjType
) {
13548 filename
= argv
[2]->internalRep
.sourceValue
.fileName
;
13549 line
= argv
[2]->internalRep
.sourceValue
.lineNumber
;
13551 else if (argv
[2]->typePtr
== &scriptObjType
) {
13552 ScriptObj
*script
= Jim_GetScript(interp
, argv
[2]);
13553 filename
= script
->fileName
;
13554 line
= script
->line
;
13556 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13557 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewStringObj(interp
, filename
, -1));
13558 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewIntObj(interp
, line
));
13559 Jim_SetResult(interp
, resObjPtr
);
13563 case INFO_STACKTRACE
:
13564 Jim_SetResult(interp
, interp
->stackTrace
);
13571 Jim_SetResultInt(interp
, interp
->framePtr
->level
);
13575 if (JimInfoLevel(interp
, argv
[2], &objPtr
, cmd
== INFO_LEVEL
) != JIM_OK
) {
13578 Jim_SetResult(interp
, objPtr
);
13582 Jim_WrongNumArgs(interp
, 2, argv
, "?levelNum?");
13592 Jim_WrongNumArgs(interp
, 2, argv
, "procname");
13595 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
) {
13598 if (!cmdPtr
->isproc
) {
13599 Jim_SetResultFormatted(interp
, "command \"%#s\" is not a procedure", argv
[2]);
13602 Jim_SetResult(interp
,
13603 cmd
== INFO_BODY
? cmdPtr
->u
.proc
.bodyObjPtr
: cmdPtr
->u
.proc
.argListObjPtr
);
13608 case INFO_PATCHLEVEL
:{
13609 char buf
[(JIM_INTEGER_SPACE
* 2) + 1];
13611 sprintf(buf
, "%d.%d", JIM_VERSION
/ 100, JIM_VERSION
% 100);
13612 Jim_SetResultString(interp
, buf
, -1);
13616 case INFO_COMPLETE
:
13617 if (argc
!= 3 && argc
!= 4) {
13618 Jim_WrongNumArgs(interp
, 2, argv
, "script ?missing?");
13623 const char *s
= Jim_GetString(argv
[2], &len
);
13624 char missing
= '\0';
13626 Jim_SetResultBool(interp
, Jim_ScriptIsComplete(s
, len
, &missing
));
13627 if (missing
&& argc
== 4) {
13628 Jim_SetVariable(interp
, argv
[3], Jim_NewStringObj(interp
, &missing
, 1));
13633 case INFO_HOSTNAME
:
13634 /* Redirect to os.gethostname if it exists */
13635 return Jim_Eval(interp
, "os.gethostname");
13637 case INFO_NAMEOFEXECUTABLE
:
13638 /* Redirect to Tcl proc */
13639 return Jim_Eval(interp
, "{info nameofexecutable}");
13641 case INFO_RETURNCODES
:
13644 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13646 for (i
= 0; jimReturnCodes
[i
]; i
++) {
13647 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewIntObj(interp
, i
));
13648 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
,
13649 jimReturnCodes
[i
], -1));
13652 Jim_SetResult(interp
, listObjPtr
);
13654 else if (argc
== 3) {
13658 if (Jim_GetLong(interp
, argv
[2], &code
) != JIM_OK
) {
13661 name
= Jim_ReturnCode(code
);
13662 if (*name
== '?') {
13663 Jim_SetResultInt(interp
, code
);
13666 Jim_SetResultString(interp
, name
, -1);
13670 Jim_WrongNumArgs(interp
, 2, argv
, "?code?");
13674 case INFO_REFERENCES
:
13675 #ifdef JIM_REFERENCES
13676 return JimInfoReferences(interp
, argc
, argv
);
13678 Jim_SetResultString(interp
, "not supported", -1);
13686 static int Jim_ExistsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13690 static const char * const options
[] = {
13691 "-command", "-proc", "-var", NULL
13695 OPT_COMMAND
, OPT_PROC
, OPT_VAR
13703 else if (argc
== 3) {
13704 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13710 Jim_WrongNumArgs(interp
, 1, argv
, "?option? name");
13714 /* Test for the the most common commands first, just in case it makes a difference */
13717 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, objPtr
, 0) != NULL
);
13722 Jim_Cmd
*cmd
= Jim_GetCommand(interp
, objPtr
, JIM_NONE
);
13723 Jim_SetResultBool(interp
, cmd
!= NULL
&& (option
== OPT_COMMAND
|| cmd
->isproc
));
13731 static int Jim_SplitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13733 const char *str
, *splitChars
, *noMatchStart
;
13734 int splitLen
, strLen
;
13735 Jim_Obj
*resObjPtr
;
13739 if (argc
!= 2 && argc
!= 3) {
13740 Jim_WrongNumArgs(interp
, 1, argv
, "string ?splitChars?");
13744 str
= Jim_GetString(argv
[1], &len
);
13748 strLen
= Jim_Utf8Length(interp
, argv
[1]);
13752 splitChars
= " \n\t\r";
13756 splitChars
= Jim_String(argv
[2]);
13757 splitLen
= Jim_Utf8Length(interp
, argv
[2]);
13760 noMatchStart
= str
;
13761 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13767 const char *sc
= splitChars
;
13768 int scLen
= splitLen
;
13769 int sl
= utf8_tounicode(str
, &c
);
13772 sc
+= utf8_tounicode(sc
, &pc
);
13774 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13775 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13776 noMatchStart
= str
+ sl
;
13782 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13783 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13786 /* This handles the special case of splitchars eq {}
13787 * Optimise by sharing common (ASCII) characters
13789 Jim_Obj
**commonObj
= NULL
;
13790 #define NUM_COMMON (128 - 32)
13792 int n
= utf8_tounicode(str
, &c
);
13793 #ifdef JIM_OPTIMIZATION
13794 if (c
>= 32 && c
< 128) {
13795 /* Common ASCII char */
13798 commonObj
= Jim_Alloc(sizeof(*commonObj
) * NUM_COMMON
);
13799 memset(commonObj
, 0, sizeof(*commonObj
) * NUM_COMMON
);
13801 if (!commonObj
[c
]) {
13802 commonObj
[c
] = Jim_NewStringObj(interp
, str
, 1);
13804 Jim_ListAppendElement(interp
, resObjPtr
, commonObj
[c
]);
13809 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewStringObjUtf8(interp
, str
, 1));
13812 Jim_Free(commonObj
);
13815 Jim_SetResult(interp
, resObjPtr
);
13820 static int Jim_JoinCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13822 const char *joinStr
;
13823 int joinStrLen
, i
, listLen
;
13824 Jim_Obj
*resObjPtr
;
13826 if (argc
!= 2 && argc
!= 3) {
13827 Jim_WrongNumArgs(interp
, 1, argv
, "list ?joinString?");
13836 joinStr
= Jim_GetString(argv
[2], &joinStrLen
);
13838 listLen
= Jim_ListLength(interp
, argv
[1]);
13839 resObjPtr
= Jim_NewStringObj(interp
, NULL
, 0);
13841 for (i
= 0; i
< listLen
; i
++) {
13842 Jim_Obj
*objPtr
= 0;
13844 Jim_ListIndex(interp
, argv
[1], i
, &objPtr
, JIM_NONE
);
13845 Jim_AppendObj(interp
, resObjPtr
, objPtr
);
13846 if (i
+ 1 != listLen
) {
13847 Jim_AppendString(interp
, resObjPtr
, joinStr
, joinStrLen
);
13850 Jim_SetResult(interp
, resObjPtr
);
13855 static int Jim_FormatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13860 Jim_WrongNumArgs(interp
, 1, argv
, "formatString ?arg arg ...?");
13863 objPtr
= Jim_FormatString(interp
, argv
[1], argc
- 2, argv
+ 2);
13864 if (objPtr
== NULL
)
13866 Jim_SetResult(interp
, objPtr
);
13871 static int Jim_ScanCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13873 Jim_Obj
*listPtr
, **outVec
;
13877 Jim_WrongNumArgs(interp
, 1, argv
, "string format ?varName varName ...?");
13880 if (argv
[2]->typePtr
!= &scanFmtStringObjType
)
13881 SetScanFmtFromAny(interp
, argv
[2]);
13882 if (FormatGetError(argv
[2]) != 0) {
13883 Jim_SetResultString(interp
, FormatGetError(argv
[2]), -1);
13887 int maxPos
= FormatGetMaxPos(argv
[2]);
13888 int count
= FormatGetCnvCount(argv
[2]);
13890 if (maxPos
> argc
- 3) {
13891 Jim_SetResultString(interp
, "\"%n$\" argument index out of range", -1);
13894 else if (count
> argc
- 3) {
13895 Jim_SetResultString(interp
, "different numbers of variable names and "
13896 "field specifiers", -1);
13899 else if (count
< argc
- 3) {
13900 Jim_SetResultString(interp
, "variable is not assigned by any "
13901 "conversion specifiers", -1);
13905 listPtr
= Jim_ScanString(interp
, argv
[1], argv
[2], JIM_ERRMSG
);
13912 if (listPtr
!= 0 && listPtr
!= (Jim_Obj
*)EOF
) {
13913 int len
= Jim_ListLength(interp
, listPtr
);
13916 JimListGetElements(interp
, listPtr
, &outc
, &outVec
);
13917 for (i
= 0; i
< outc
; ++i
) {
13918 if (Jim_Length(outVec
[i
]) > 0) {
13920 if (Jim_SetVariable(interp
, argv
[3 + i
], outVec
[i
]) != JIM_OK
) {
13926 Jim_FreeNewObj(interp
, listPtr
);
13931 if (rc
== JIM_OK
) {
13932 Jim_SetResultInt(interp
, count
);
13937 if (listPtr
== (Jim_Obj
*)EOF
) {
13938 Jim_SetResult(interp
, Jim_NewListObj(interp
, 0, 0));
13941 Jim_SetResult(interp
, listPtr
);
13947 static int Jim_ErrorCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13949 if (argc
!= 2 && argc
!= 3) {
13950 Jim_WrongNumArgs(interp
, 1, argv
, "message ?stacktrace?");
13953 Jim_SetResult(interp
, argv
[1]);
13955 JimSetStackTrace(interp
, argv
[2]);
13958 interp
->addStackTrace
++;
13963 static int Jim_LrangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13968 Jim_WrongNumArgs(interp
, 1, argv
, "list first last");
13971 if ((objPtr
= Jim_ListRange(interp
, argv
[1], argv
[2], argv
[3])) == NULL
)
13973 Jim_SetResult(interp
, objPtr
);
13978 static int Jim_LrepeatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13983 if (argc
< 2 || Jim_GetLong(interp
, argv
[1], &count
) != JIM_OK
|| count
< 0) {
13984 Jim_WrongNumArgs(interp
, 1, argv
, "count ?value ...?");
13988 if (count
== 0 || argc
== 2) {
13995 objPtr
= Jim_NewListObj(interp
, argv
, argc
);
13999 for (i
= 0; i
< argc
; i
++) {
14000 ListAppendElement(objPtr
, argv
[i
]);
14004 Jim_SetResult(interp
, objPtr
);
14008 char **Jim_GetEnviron(void)
14010 #if defined(HAVE__NSGETENVIRON)
14011 return *_NSGetEnviron();
14013 #if !defined(NO_ENVIRON_EXTERN)
14014 extern char **environ
;
14021 void Jim_SetEnviron(char **env
)
14023 #if defined(HAVE__NSGETENVIRON)
14024 *_NSGetEnviron() = env
;
14026 #if !defined(NO_ENVIRON_EXTERN)
14027 extern char **environ
;
14035 static int Jim_EnvCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14041 char **e
= Jim_GetEnviron();
14044 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14046 for (i
= 0; e
[i
]; i
++) {
14047 const char *equals
= strchr(e
[i
], '=');
14050 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, e
[i
],
14052 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, equals
+ 1, -1));
14056 Jim_SetResult(interp
, listObjPtr
);
14061 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?default?");
14064 key
= Jim_String(argv
[1]);
14068 Jim_SetResultFormatted(interp
, "environment variable \"%#s\" does not exist", argv
[1]);
14071 val
= Jim_String(argv
[2]);
14073 Jim_SetResult(interp
, Jim_NewStringObj(interp
, val
, -1));
14078 static int Jim_SourceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14083 Jim_WrongNumArgs(interp
, 1, argv
, "fileName");
14086 retval
= Jim_EvalFile(interp
, Jim_String(argv
[1]));
14087 if (retval
== JIM_RETURN
)
14093 static int Jim_LreverseCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14095 Jim_Obj
*revObjPtr
, **ele
;
14099 Jim_WrongNumArgs(interp
, 1, argv
, "list");
14102 JimListGetElements(interp
, argv
[1], &len
, &ele
);
14104 revObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14106 ListAppendElement(revObjPtr
, ele
[len
--]);
14107 Jim_SetResult(interp
, revObjPtr
);
14111 static int JimRangeLen(jim_wide start
, jim_wide end
, jim_wide step
)
14119 else if (step
> 0 && start
> end
)
14121 else if (step
< 0 && end
> start
)
14125 len
= -len
; /* abs(len) */
14127 step
= -step
; /* abs(step) */
14128 len
= 1 + ((len
- 1) / step
);
14129 /* We can truncate safely to INT_MAX, the range command
14130 * will always return an error for a such long range
14131 * because Tcl lists can't be so long. */
14134 return (int)((len
< 0) ? -1 : len
);
14138 static int Jim_RangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14140 jim_wide start
= 0, end
, step
= 1;
14144 if (argc
< 2 || argc
> 4) {
14145 Jim_WrongNumArgs(interp
, 1, argv
, "?start? end ?step?");
14149 if (Jim_GetWide(interp
, argv
[1], &end
) != JIM_OK
)
14153 if (Jim_GetWide(interp
, argv
[1], &start
) != JIM_OK
||
14154 Jim_GetWide(interp
, argv
[2], &end
) != JIM_OK
)
14156 if (argc
== 4 && Jim_GetWide(interp
, argv
[3], &step
) != JIM_OK
)
14159 if ((len
= JimRangeLen(start
, end
, step
)) == -1) {
14160 Jim_SetResultString(interp
, "Invalid (infinite?) range specified", -1);
14163 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
14164 for (i
= 0; i
< len
; i
++)
14165 ListAppendElement(objPtr
, Jim_NewIntObj(interp
, start
+ i
* step
));
14166 Jim_SetResult(interp
, objPtr
);
14171 static int Jim_RandCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14173 jim_wide min
= 0, max
= 0, len
, maxMul
;
14175 if (argc
< 1 || argc
> 3) {
14176 Jim_WrongNumArgs(interp
, 1, argv
, "?min? max");
14180 max
= JIM_WIDE_MAX
;
14181 } else if (argc
== 2) {
14182 if (Jim_GetWide(interp
, argv
[1], &max
) != JIM_OK
)
14184 } else if (argc
== 3) {
14185 if (Jim_GetWide(interp
, argv
[1], &min
) != JIM_OK
||
14186 Jim_GetWide(interp
, argv
[2], &max
) != JIM_OK
)
14191 Jim_SetResultString(interp
, "Invalid arguments (max < min)", -1);
14194 maxMul
= JIM_WIDE_MAX
- (len
? (JIM_WIDE_MAX
%len
) : 0);
14198 JimRandomBytes(interp
, &r
, sizeof(jim_wide
));
14199 if (r
< 0 || r
>= maxMul
) continue;
14200 r
= (len
== 0) ? 0 : r
%len
;
14201 Jim_SetResultInt(interp
, min
+r
);
14206 static const struct {
14208 Jim_CmdProc cmdProc
;
14209 } Jim_CoreCommandsTable
[] = {
14210 {"set", Jim_SetCoreCommand
},
14211 {"unset", Jim_UnsetCoreCommand
},
14212 {"puts", Jim_PutsCoreCommand
},
14213 {"+", Jim_AddCoreCommand
},
14214 {"*", Jim_MulCoreCommand
},
14215 {"-", Jim_SubCoreCommand
},
14216 {"/", Jim_DivCoreCommand
},
14217 {"incr", Jim_IncrCoreCommand
},
14218 {"while", Jim_WhileCoreCommand
},
14219 {"loop", Jim_LoopCoreCommand
},
14220 {"for", Jim_ForCoreCommand
},
14221 {"foreach", Jim_ForeachCoreCommand
},
14222 {"lmap", Jim_LmapCoreCommand
},
14223 {"if", Jim_IfCoreCommand
},
14224 {"switch", Jim_SwitchCoreCommand
},
14225 {"list", Jim_ListCoreCommand
},
14226 {"lindex", Jim_LindexCoreCommand
},
14227 {"lset", Jim_LsetCoreCommand
},
14228 {"lsearch", Jim_LsearchCoreCommand
},
14229 {"llength", Jim_LlengthCoreCommand
},
14230 {"lappend", Jim_LappendCoreCommand
},
14231 {"linsert", Jim_LinsertCoreCommand
},
14232 {"lreplace", Jim_LreplaceCoreCommand
},
14233 {"lsort", Jim_LsortCoreCommand
},
14234 {"append", Jim_AppendCoreCommand
},
14235 {"debug", Jim_DebugCoreCommand
},
14236 {"eval", Jim_EvalCoreCommand
},
14237 {"uplevel", Jim_UplevelCoreCommand
},
14238 {"expr", Jim_ExprCoreCommand
},
14239 {"break", Jim_BreakCoreCommand
},
14240 {"continue", Jim_ContinueCoreCommand
},
14241 {"proc", Jim_ProcCoreCommand
},
14242 {"concat", Jim_ConcatCoreCommand
},
14243 {"return", Jim_ReturnCoreCommand
},
14244 {"upvar", Jim_UpvarCoreCommand
},
14245 {"global", Jim_GlobalCoreCommand
},
14246 {"string", Jim_StringCoreCommand
},
14247 {"time", Jim_TimeCoreCommand
},
14248 {"exit", Jim_ExitCoreCommand
},
14249 {"catch", Jim_CatchCoreCommand
},
14250 #ifdef JIM_REFERENCES
14251 {"ref", Jim_RefCoreCommand
},
14252 {"getref", Jim_GetrefCoreCommand
},
14253 {"setref", Jim_SetrefCoreCommand
},
14254 {"finalize", Jim_FinalizeCoreCommand
},
14255 {"collect", Jim_CollectCoreCommand
},
14257 {"rename", Jim_RenameCoreCommand
},
14258 {"dict", Jim_DictCoreCommand
},
14259 {"subst", Jim_SubstCoreCommand
},
14260 {"info", Jim_InfoCoreCommand
},
14261 {"exists", Jim_ExistsCoreCommand
},
14262 {"split", Jim_SplitCoreCommand
},
14263 {"join", Jim_JoinCoreCommand
},
14264 {"format", Jim_FormatCoreCommand
},
14265 {"scan", Jim_ScanCoreCommand
},
14266 {"error", Jim_ErrorCoreCommand
},
14267 {"lrange", Jim_LrangeCoreCommand
},
14268 {"lrepeat", Jim_LrepeatCoreCommand
},
14269 {"env", Jim_EnvCoreCommand
},
14270 {"source", Jim_SourceCoreCommand
},
14271 {"lreverse", Jim_LreverseCoreCommand
},
14272 {"range", Jim_RangeCoreCommand
},
14273 {"rand", Jim_RandCoreCommand
},
14274 {"tailcall", Jim_TailcallCoreCommand
},
14275 {"local", Jim_LocalCoreCommand
},
14276 {"upcall", Jim_UpcallCoreCommand
},
14280 void Jim_RegisterCoreCommands(Jim_Interp
*interp
)
14284 while (Jim_CoreCommandsTable
[i
].name
!= NULL
) {
14285 Jim_CreateCommand(interp
,
14286 Jim_CoreCommandsTable
[i
].name
, Jim_CoreCommandsTable
[i
].cmdProc
, NULL
, NULL
);
14291 /* -----------------------------------------------------------------------------
14292 * Interactive prompt
14293 * ---------------------------------------------------------------------------*/
14294 void Jim_MakeErrorMessage(Jim_Interp
*interp
)
14298 argv
[0] = Jim_NewStringObj(interp
, "errorInfo", -1);
14299 argv
[1] = interp
->result
;
14301 Jim_EvalObjVector(interp
, 2, argv
);
14304 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
14305 const char *prefix
, const char *const *tablePtr
, const char *name
)
14308 char **tablePtrSorted
;
14311 for (count
= 0; tablePtr
[count
]; count
++) {
14314 if (name
== NULL
) {
14318 Jim_SetResultFormatted(interp
, "%s%s \"%s\": must be ", badtype
, name
, arg
);
14319 tablePtrSorted
= Jim_Alloc(sizeof(char *) * count
);
14320 memcpy(tablePtrSorted
, tablePtr
, sizeof(char *) * count
);
14321 qsort(tablePtrSorted
, count
, sizeof(char *), qsortCompareStringPointers
);
14322 for (i
= 0; i
< count
; i
++) {
14323 if (i
+ 1 == count
&& count
> 1) {
14324 Jim_AppendString(interp
, Jim_GetResult(interp
), "or ", -1);
14326 Jim_AppendStrings(interp
, Jim_GetResult(interp
), prefix
, tablePtrSorted
[i
], NULL
);
14327 if (i
+ 1 != count
) {
14328 Jim_AppendString(interp
, Jim_GetResult(interp
), ", ", -1);
14331 Jim_Free(tablePtrSorted
);
14334 int Jim_GetEnum(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
14335 const char *const *tablePtr
, int *indexPtr
, const char *name
, int flags
)
14337 const char *bad
= "bad ";
14338 const char *const *entryPtr
= NULL
;
14342 const char *arg
= Jim_GetString(objPtr
, &arglen
);
14346 for (entryPtr
= tablePtr
, i
= 0; *entryPtr
!= NULL
; entryPtr
++, i
++) {
14347 if (Jim_CompareStringImmediate(interp
, objPtr
, *entryPtr
)) {
14348 /* Found an exact match */
14352 if (flags
& JIM_ENUM_ABBREV
) {
14353 /* Accept an unambiguous abbreviation.
14354 * Note that '-' doesnt' consitute a valid abbreviation
14356 if (strncmp(arg
, *entryPtr
, arglen
) == 0) {
14357 if (*arg
== '-' && arglen
== 1) {
14361 bad
= "ambiguous ";
14369 /* If we had an unambiguous partial match */
14376 if (flags
& JIM_ERRMSG
) {
14377 JimSetFailedEnumResult(interp
, arg
, bad
, "", tablePtr
, name
);
14382 int Jim_FindByName(const char *name
, const char * const array
[], size_t len
)
14386 for (i
= 0; i
< (int)len
; i
++) {
14387 if (array
[i
] && strcmp(array
[i
], name
) == 0) {
14394 int Jim_IsDict(Jim_Obj
*objPtr
)
14396 return objPtr
->typePtr
== &dictObjType
;
14399 int Jim_IsList(Jim_Obj
*objPtr
)
14401 return objPtr
->typePtr
== &listObjType
;
14405 * Very simple printf-like formatting, designed for error messages.
14407 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14408 * The resulting string is created and set as the result.
14410 * Each '%s' should correspond to a regular string parameter.
14411 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14412 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14414 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14416 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14418 void Jim_SetResultFormatted(Jim_Interp
*interp
, const char *format
, ...)
14420 /* Initial space needed */
14421 int len
= strlen(format
);
14424 const char *params
[5];
14429 va_start(args
, format
);
14431 for (i
= 0; i
< len
&& n
< 5; i
++) {
14434 if (strncmp(format
+ i
, "%s", 2) == 0) {
14435 params
[n
] = va_arg(args
, char *);
14437 l
= strlen(params
[n
]);
14439 else if (strncmp(format
+ i
, "%#s", 3) == 0) {
14440 Jim_Obj
*objPtr
= va_arg(args
, Jim_Obj
*);
14442 params
[n
] = Jim_GetString(objPtr
, &l
);
14445 if (format
[i
] == '%') {
14455 buf
= Jim_Alloc(len
+ 1);
14456 len
= snprintf(buf
, len
+ 1, format
, params
[0], params
[1], params
[2], params
[3], params
[4]);
14458 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
14462 #ifndef jim_ext_package
14463 int Jim_PackageProvide(Jim_Interp
*interp
, const char *name
, const char *ver
, int flags
)
14468 #ifndef jim_ext_aio
14469 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*fhObj
)
14471 Jim_SetResultString(interp
, "aio not enabled", -1);
14478 * Local Variables: ***
14479 * c-basic-offset: 4 ***