1 /* Jim - A small embeddable Tcl interpreter
3 * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
4 * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
5 * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
6 * Copyright 2008,2009 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
7 * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
8 * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
9 * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
10 * Copyright 2008 Steve Bennett <steveb@workware.net.au>
11 * Copyright 2009 Nico Coesel <ncoesel@dealogic.nl>
12 * Copyright 2009 Zachary T Welch zw@superlucidity.net
13 * Copyright 2009 David Brownell
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above
22 * copyright notice, this list of conditions and the following
23 * disclaimer in the documentation and/or other materials
24 * provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
27 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
28 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
29 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
30 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
31 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
32 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
37 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 * The views and conclusions contained in the software and documentation
40 * are those of the authors and should not be interpreted as representing
41 * official policies, either expressed or implied, of the Jim Tcl Project.
43 #define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
45 #define _GNU_SOURCE /* Mostly just for environ */
61 #include "jimautoconf.h"
64 #ifdef HAVE_SYS_TIME_H
70 #ifdef HAVE_CRT_EXTERNS_H
71 #include <crt_externs.h>
74 /* For INFINITY, even if math functions are not enabled */
77 /* We may decide to switch to using $[...] after all, so leave it as an option */
78 /*#define EXPRSUGAR_BRACKET*/
80 /* For the no-autoconf case */
82 #define TCL_LIBRARY "."
84 #ifndef TCL_PLATFORM_OS
85 #define TCL_PLATFORM_OS "unknown"
87 #ifndef TCL_PLATFORM_PLATFORM
88 #define TCL_PLATFORM_PLATFORM "unknown"
90 #ifndef TCL_PLATFORM_PATH_SEPARATOR
91 #define TCL_PLATFORM_PATH_SEPARATOR ":"
94 /*#define DEBUG_SHOW_SCRIPT*/
95 /*#define DEBUG_SHOW_SCRIPT_TOKENS*/
96 /*#define DEBUG_SHOW_SUBST*/
97 /*#define DEBUG_SHOW_EXPR*/
98 /*#define DEBUG_SHOW_EXPR_TOKENS*/
99 /*#define JIM_DEBUG_GC*/
100 #ifdef JIM_MAINTAINER
101 #define JIM_DEBUG_COMMAND
102 #define JIM_DEBUG_PANIC
104 /* Enable this (in conjunction with valgrind) to help debug
105 * reference counting issues
107 /*#define JIM_DISABLE_OBJECT_POOL*/
109 /* Maximum size of an integer */
110 #define JIM_INTEGER_SPACE 24
112 const char *jim_tt_name(int type
);
114 #ifdef JIM_DEBUG_PANIC
115 static void JimPanicDump(int fail_condition
, const char *fmt
, ...);
116 #define JimPanic(X) JimPanicDump X
121 #ifdef JIM_OPTIMIZATION
122 #define JIM_IF_OPTIM(X) X
124 #define JIM_IF_OPTIM(X)
127 /* -----------------------------------------------------------------------------
129 * ---------------------------------------------------------------------------*/
131 /* A shared empty string for the objects string representation.
132 * Jim_InvalidateStringRep knows about it and doesn't try to free it. */
133 static char JimEmptyStringRep
[] = "";
135 /* -----------------------------------------------------------------------------
136 * Required prototypes of not exported functions
137 * ---------------------------------------------------------------------------*/
138 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int action
);
139 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int listindex
, Jim_Obj
*newObjPtr
,
141 static int JimDeleteLocalProcs(Jim_Interp
*interp
, Jim_Stack
*localCommands
);
142 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
143 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
144 static Jim_Obj
**JimDictPairs(Jim_Obj
*dictPtr
, int *len
);
145 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
146 const char *prefix
, const char *const *tablePtr
, const char *name
);
147 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, int argc
, Jim_Obj
*const *argv
);
148 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
);
149 static int JimSign(jim_wide w
);
150 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
);
151 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
);
152 static int JimSetNewVariable(Jim_HashTable
*ht
, Jim_Obj
*nameObjPtr
, Jim_Var
*var
);
153 static Jim_Var
*JimFindVariable(Jim_HashTable
*ht
, Jim_Obj
*nameObjPtr
);
156 /* Fast access to the int (wide) value of an object which is known to be of int type */
157 #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
159 #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
161 static int utf8_tounicode_case(const char *s
, int *uc
, int upper
)
163 int l
= utf8_tounicode(s
, uc
);
165 *uc
= utf8_upper(*uc
);
170 /* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
171 #define JIM_CHARSET_SCAN 2
172 #define JIM_CHARSET_GLOB 0
175 * pattern points to a string like "[^a-z\ub5]"
177 * The pattern may contain trailing chars, which are ignored.
179 * The pattern is matched against unicode char 'c'.
181 * If (flags & JIM_NOCASE), case is ignored when matching.
182 * If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
183 * of the charset, per scan, rather than glob/string match.
185 * If the unicode char 'c' matches that set, returns a pointer to the ']' character,
186 * or the null character if the ']' is missing.
188 * Returns NULL on no match.
190 static const char *JimCharsetMatch(const char *pattern
, int plen
, int c
, int flags
)
198 if (flags
& JIM_NOCASE
) {
203 if (flags
& JIM_CHARSET_SCAN
) {
204 if (*pattern
== '^') {
210 /* Special case. If the first char is ']', it is part of the set */
211 if (*pattern
== ']') {
216 while (plen
&& *pattern
!= ']') {
218 if (pattern
[0] == '\\') {
220 n
= utf8_tounicode_case(pattern
, &pchar
, nocase
);
225 /* Is this a range? a-z */
229 n
= utf8_tounicode_case(pattern
, &start
, nocase
);
232 if (pattern
[0] == '-' && plen
> 1) {
234 n
= 1 + utf8_tounicode_case(pattern
+ 1, &end
, nocase
);
238 /* Handle reversed range too */
239 if ((c
>= start
&& c
<= end
) || (c
>= end
&& c
<= start
)) {
255 return match
? pattern
: NULL
;
258 /* Glob-style pattern matching. */
260 /* Note: string *must* be valid UTF-8 sequences
262 static int JimGlobMatch(const char *pattern
, int plen
, const char *string
, int slen
, int nocase
)
269 switch (pattern
[0]) {
271 while (pattern
[1] == '*' && plen
) {
278 return 1; /* match */
281 /* Recursive call - Does the remaining pattern match anywhere? */
282 if (JimGlobMatch(pattern
, plen
, string
, slen
, nocase
))
283 return 1; /* match */
284 n
= utf8_tounicode(string
, &c
);
288 return 0; /* no match */
291 n
= utf8_tounicode(string
, &c
);
297 n
= utf8_tounicode(string
, &c
);
300 p
= JimCharsetMatch(pattern
+ 1, plen
- 1, c
, nocase
? JIM_NOCASE
: 0);
308 /* Ran out of pattern (no ']') */
320 n
= utf8_tounicode_case(string
, &c
, nocase
);
323 utf8_tounicode_case(pattern
, &pchar
, nocase
);
329 n
= utf8_tounicode_case(pattern
, &pchar
, nocase
);
333 while (*pattern
== '*' && plen
) {
340 if (!plen
&& !slen
) {
347 * utf-8 string comparison. case-insensitive if nocase is set.
351 * Note that the lengths are character lengths, not byte lengths.
353 static int JimStringCompareUtf8(const char *s1
, int l1
, const char *s2
, int l2
, int nocase
)
361 s1
+= utf8_tounicode_case(s1
, &c1
, nocase
);
362 s2
+= utf8_tounicode_case(s2
, &c2
, nocase
);
364 return JimSign(c1
- c2
);
368 /* Equal to this point, so the shorter string is less */
378 /* Search for 's1' inside 's2', starting to search from char 'index' of 's2'.
379 * The index of the first occurrence of s1 in s2 is returned.
380 * If s1 is not found inside s2, -1 is returned.
382 * Note: Lengths and return value are in bytes, not chars.
384 static int JimStringFirst(const char *s1
, int l1
, const char *s2
, int l2
, int idx
)
389 if (!l1
|| !l2
|| l1
> l2
) {
394 s2
+= utf8_index(s2
, idx
);
396 l1bytelen
= utf8_index(s1
, l1
);
398 for (i
= idx
; i
<= l2
- l1
; i
++) {
400 if (memcmp(s2
, s1
, l1bytelen
) == 0) {
403 s2
+= utf8_tounicode(s2
, &c
);
408 /* Search for the last occurrence 's1' inside 's2', starting to search from char 'index' of 's2'.
409 * The index of the last occurrence of s1 in s2 is returned.
410 * If s1 is not found inside s2, -1 is returned.
412 * Note: Lengths and return value are in bytes, not chars.
414 static int JimStringLast(const char *s1
, int l1
, const char *s2
, int l2
)
418 if (!l1
|| !l2
|| l1
> l2
)
421 /* Now search for the needle */
422 for (p
= s2
+ l2
- 1; p
!= s2
- 1; p
--) {
423 if (*p
== *s1
&& memcmp(s1
, p
, l1
) == 0) {
432 * Per JimStringLast but lengths and return value are in chars, not bytes.
434 static int JimStringLastUtf8(const char *s1
, int l1
, const char *s2
, int l2
)
436 int n
= JimStringLast(s1
, utf8_index(s1
, l1
), s2
, utf8_index(s2
, l2
));
438 n
= utf8_strlen(s2
, n
);
445 * After an strtol()/strtod()-like conversion,
446 * check whether something was converted and that
447 * the only thing left is white space.
449 * Returns JIM_OK or JIM_ERR.
451 static int JimCheckConversion(const char *str
, const char *endptr
)
453 if (str
[0] == '\0' || str
== endptr
) {
457 if (endptr
[0] != '\0') {
459 if (!isspace(UCHAR(*endptr
))) {
468 /* Parses the front of a number to determine its sign and base.
469 * Returns the index to start parsing according to the given base
471 static int JimNumberBase(const char *str
, int *base
, int *sign
)
477 while (isspace(UCHAR(str
[i
]))) {
497 /* We have 0<x>, so see if we can convert it */
498 switch (str
[i
+ 1]) {
499 case 'x': case 'X': *base
= 16; break;
500 case 'o': case 'O': *base
= 8; break;
501 case 'b': case 'B': *base
= 2; break;
505 /* Ensure that (e.g.) 0x-5 fails to parse */
506 if (str
[i
] != '-' && str
[i
] != '+' && !isspace(UCHAR(str
[i
]))) {
507 /* Parse according to this base */
510 /* Parse as base 10 */
515 /* Converts a number as per strtol(..., 0) except leading zeros do *not*
516 * imply octal. Instead, decimal is assumed unless the number begins with 0x, 0o or 0b
518 static long jim_strtol(const char *str
, char **endptr
)
522 int i
= JimNumberBase(str
, &base
, &sign
);
525 long value
= strtol(str
+ i
, endptr
, base
);
526 if (endptr
== NULL
|| *endptr
!= str
+ i
) {
531 /* Can just do a regular base-10 conversion */
532 return strtol(str
, endptr
, 10);
536 /* Converts a number as per strtoull(..., 0) except leading zeros do *not*
537 * imply octal. Instead, decimal is assumed unless the number begins with 0x, 0o or 0b
539 static jim_wide
jim_strtoull(const char *str
, char **endptr
)
541 #ifdef HAVE_LONG_LONG
544 int i
= JimNumberBase(str
, &base
, &sign
);
547 jim_wide value
= strtoull(str
+ i
, endptr
, base
);
548 if (endptr
== NULL
|| *endptr
!= str
+ i
) {
553 /* Can just do a regular base-10 conversion */
554 return strtoull(str
, endptr
, 10);
556 return (unsigned long)jim_strtol(str
, endptr
);
560 int Jim_StringToWide(const char *str
, jim_wide
* widePtr
, int base
)
565 *widePtr
= strtoull(str
, &endptr
, base
);
568 *widePtr
= jim_strtoull(str
, &endptr
);
571 return JimCheckConversion(str
, endptr
);
574 int Jim_StringToDouble(const char *str
, double *doublePtr
)
578 /* Callers can check for underflow via ERANGE */
581 *doublePtr
= strtod(str
, &endptr
);
583 return JimCheckConversion(str
, endptr
);
586 static jim_wide
JimPowWide(jim_wide b
, jim_wide e
)
599 /* Only special case is -1 ^ -n
617 /* -----------------------------------------------------------------------------
619 * ---------------------------------------------------------------------------*/
620 #ifdef JIM_DEBUG_PANIC
621 static void JimPanicDump(int condition
, const char *fmt
, ...)
631 fprintf(stderr
, "\nJIM INTERPRETER PANIC: ");
632 vfprintf(stderr
, fmt
, ap
);
633 fprintf(stderr
, "\n\n");
636 #ifdef HAVE_BACKTRACE
642 size
= backtrace(array
, 40);
643 strings
= backtrace_symbols(array
, size
);
644 for (i
= 0; i
< size
; i
++)
645 fprintf(stderr
, "[backtrace] %s\n", strings
[i
]);
646 fprintf(stderr
, "[backtrace] Include the above lines and the output\n");
647 fprintf(stderr
, "[backtrace] of 'nm <executable>' in the bug report.\n");
655 /* -----------------------------------------------------------------------------
657 * ---------------------------------------------------------------------------*/
659 void *Jim_Alloc(int size
)
661 return size
? malloc(size
) : NULL
;
664 void Jim_Free(void *ptr
)
669 void *Jim_Realloc(void *ptr
, int size
)
671 return realloc(ptr
, size
);
674 char *Jim_StrDup(const char *s
)
679 char *Jim_StrDupLen(const char *s
, int l
)
681 char *copy
= Jim_Alloc(l
+ 1);
683 memcpy(copy
, s
, l
+ 1);
684 copy
[l
] = 0; /* Just to be sure, original could be substring */
688 /* -----------------------------------------------------------------------------
689 * Time related functions
690 * ---------------------------------------------------------------------------*/
692 /* Returns current time in microseconds */
693 static jim_wide
JimClock(void)
697 gettimeofday(&tv
, NULL
);
698 return (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
;
701 /* -----------------------------------------------------------------------------
703 * ---------------------------------------------------------------------------*/
705 /* -------------------------- private prototypes ---------------------------- */
706 static void JimExpandHashTableIfNeeded(Jim_HashTable
*ht
);
707 static unsigned int JimHashTableNextPower(unsigned int size
);
708 static Jim_HashEntry
*JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
, int replace
);
710 /* -------------------------- hash functions -------------------------------- */
712 /* Thomas Wang's 32 bit Mix Function */
713 unsigned int Jim_IntHashFunction(unsigned int key
)
724 /* Generic hash function (we are using to multiply by 9 and add the byte
726 unsigned int Jim_GenHashFunction(const unsigned char *buf
, int len
)
731 h
+= (h
<< 3) + *buf
++;
735 /* ----------------------------- API implementation ------------------------- */
738 * Reset a hashtable already initialized.
739 * The table data should already have been freed.
741 * Note that type and privdata are not initialised
742 * to allow the now-empty hashtable to be reused
744 static void JimResetHashTable(Jim_HashTable
*ht
)
751 #ifdef JIM_RANDOMISE_HASH
752 /* This is initialised to a random value to avoid a hash collision attack.
753 * See: n.runs-SA-2011.004
755 ht
->uniq
= (rand() ^ time(NULL
) ^ clock());
761 static void JimInitHashTableIterator(Jim_HashTable
*ht
, Jim_HashTableIterator
*iter
)
766 iter
->nextEntry
= NULL
;
769 /* Initialize the hash table */
770 int Jim_InitHashTable(Jim_HashTable
*ht
, const Jim_HashTableType
*type
, void *privDataPtr
)
772 JimResetHashTable(ht
);
774 ht
->privdata
= privDataPtr
;
778 /* Expand or create the hashtable */
779 void Jim_ExpandHashTable(Jim_HashTable
*ht
, unsigned int size
)
781 Jim_HashTable n
; /* the new hashtable */
782 unsigned int realsize
= JimHashTableNextPower(size
), i
;
784 /* the size is invalid if it is smaller than the number of
785 * elements already inside the hashtable */
786 if (size
<= ht
->used
)
789 Jim_InitHashTable(&n
, ht
->type
, ht
->privdata
);
791 n
.sizemask
= realsize
- 1;
792 n
.table
= Jim_Alloc(realsize
* sizeof(Jim_HashEntry
*));
793 /* Keep the same 'uniq' as the original */
796 /* Initialize all the pointers to NULL */
797 memset(n
.table
, 0, realsize
* sizeof(Jim_HashEntry
*));
799 /* Copy all the elements from the old to the new table:
800 * note that if the old hash table is empty ht->used is zero,
801 * so Jim_ExpandHashTable just creates an empty hash table. */
803 for (i
= 0; ht
->used
> 0; i
++) {
804 Jim_HashEntry
*he
, *nextHe
;
806 if (ht
->table
[i
] == NULL
)
809 /* For each hash entry on this slot... */
815 /* Get the new element index */
816 h
= Jim_HashKey(ht
, he
->key
) & n
.sizemask
;
817 he
->next
= n
.table
[h
];
820 /* Pass to the next element */
824 assert(ht
->used
== 0);
827 /* Remap the new hashtable in the old */
831 /* Add an element to the target hash table */
832 int Jim_AddHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
834 Jim_HashEntry
*entry
;
836 /* Get the index of the new element, or -1 if
837 * the element already exists. */
838 entry
= JimInsertHashEntry(ht
, key
, 0);
842 /* Set the hash entry fields. */
843 Jim_SetHashKey(ht
, entry
, key
);
844 Jim_SetHashVal(ht
, entry
, val
);
848 /* Add an element, discarding the old if the key already exists */
849 int Jim_ReplaceHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
852 Jim_HashEntry
*entry
;
854 /* Get the index of the new element, or -1 if
855 * the element already exists. */
856 entry
= JimInsertHashEntry(ht
, key
, 1);
858 /* It already exists, so only replace the value.
859 * Note if both a destructor and a duplicate function exist,
860 * need to dup before destroy. perhaps they are the same
861 * reference counted object
863 if (ht
->type
->valDestructor
&& ht
->type
->valDup
) {
864 void *newval
= ht
->type
->valDup(ht
->privdata
, val
);
865 ht
->type
->valDestructor(ht
->privdata
, entry
->u
.val
);
866 entry
->u
.val
= newval
;
869 Jim_FreeEntryVal(ht
, entry
);
870 Jim_SetHashVal(ht
, entry
, val
);
875 /* Doesn't exist, so set the key */
876 Jim_SetHashKey(ht
, entry
, key
);
877 Jim_SetHashVal(ht
, entry
, val
);
884 /* Search and remove an element */
885 int Jim_DeleteHashEntry(Jim_HashTable
*ht
, const void *key
)
888 Jim_HashEntry
*he
, *prevHe
;
892 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
897 if (Jim_CompareHashKeys(ht
, key
, he
->key
)) {
898 /* Unlink the element from the list */
900 prevHe
->next
= he
->next
;
902 ht
->table
[h
] = he
->next
;
903 Jim_FreeEntryKey(ht
, he
);
904 Jim_FreeEntryVal(ht
, he
);
912 return JIM_ERR
; /* not found */
916 * Clear all hash entries from the table, but don't free
919 void Jim_ClearHashTable(Jim_HashTable
*ht
)
923 /* Free all the elements */
924 for (i
= 0; ht
->used
> 0; i
++) {
925 Jim_HashEntry
*he
, *nextHe
;
930 Jim_FreeEntryKey(ht
, he
);
931 Jim_FreeEntryVal(ht
, he
);
940 /* Remove all entries from the hash table
941 * and leave it empty for reuse
943 int Jim_FreeHashTable(Jim_HashTable
*ht
)
945 Jim_ClearHashTable(ht
);
946 /* Free the table and the allocated cache structure */
948 /* Re-initialize the table */
949 JimResetHashTable(ht
);
950 return JIM_OK
; /* never fails */
953 Jim_HashEntry
*Jim_FindHashEntry(Jim_HashTable
*ht
, const void *key
)
960 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
963 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
970 Jim_HashTableIterator
*Jim_GetHashTableIterator(Jim_HashTable
*ht
)
972 Jim_HashTableIterator
*iter
= Jim_Alloc(sizeof(*iter
));
973 JimInitHashTableIterator(ht
, iter
);
977 Jim_HashEntry
*Jim_NextHashEntry(Jim_HashTableIterator
*iter
)
980 if (iter
->entry
== NULL
) {
982 if (iter
->index
>= (signed)iter
->ht
->size
)
984 iter
->entry
= iter
->ht
->table
[iter
->index
];
987 iter
->entry
= iter
->nextEntry
;
990 /* We need to save the 'next' here, the iterator user
991 * may delete the entry we are returning. */
992 iter
->nextEntry
= iter
->entry
->next
;
999 /* ------------------------- private functions ------------------------------ */
1001 /* Expand the hash table if needed */
1002 static void JimExpandHashTableIfNeeded(Jim_HashTable
*ht
)
1004 /* If the hash table is empty expand it to the intial size,
1005 * if the table is "full" double its size. */
1007 Jim_ExpandHashTable(ht
, JIM_HT_INITIAL_SIZE
);
1008 if (ht
->size
== ht
->used
)
1009 Jim_ExpandHashTable(ht
, ht
->size
* 2);
1012 /* Our hash table capability is a power of two */
1013 static unsigned int JimHashTableNextPower(unsigned int size
)
1015 unsigned int i
= JIM_HT_INITIAL_SIZE
;
1017 if (size
>= 2147483648U)
1026 /* Returns the index of a free slot that can be populated with
1027 * a hash entry for the given 'key'.
1028 * If the key already exists, -1 is returned. */
1029 static Jim_HashEntry
*JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
, int replace
)
1034 /* Expand the hashtable if needed */
1035 JimExpandHashTableIfNeeded(ht
);
1037 /* Compute the key hash value */
1038 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
1039 /* Search if this slot does not already contain the given key */
1042 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
1043 return replace
? he
: NULL
;
1047 /* Allocates the memory and stores key */
1048 he
= Jim_Alloc(sizeof(*he
));
1049 he
->next
= ht
->table
[h
];
1057 /* ----------------------- StringCopy Hash Table Type ------------------------*/
1059 static unsigned int JimStringCopyHTHashFunction(const void *key
)
1061 return Jim_GenHashFunction(key
, strlen(key
));
1064 static void *JimStringCopyHTDup(void *privdata
, const void *key
)
1066 return Jim_StrDup(key
);
1069 static int JimStringCopyHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
1071 return strcmp(key1
, key2
) == 0;
1074 static void JimStringCopyHTKeyDestructor(void *privdata
, void *key
)
1079 static const Jim_HashTableType JimPackageHashTableType
= {
1080 JimStringCopyHTHashFunction
, /* hash function */
1081 JimStringCopyHTDup
, /* key dup */
1083 JimStringCopyHTKeyCompare
, /* key compare */
1084 JimStringCopyHTKeyDestructor
, /* key destructor */
1085 NULL
/* val destructor */
1088 typedef struct AssocDataValue
1090 Jim_InterpDeleteProc
*delProc
;
1094 static void JimAssocDataHashTableValueDestructor(void *privdata
, void *data
)
1096 AssocDataValue
*assocPtr
= (AssocDataValue
*) data
;
1098 if (assocPtr
->delProc
!= NULL
)
1099 assocPtr
->delProc((Jim_Interp
*)privdata
, assocPtr
->data
);
1103 static const Jim_HashTableType JimAssocDataHashTableType
= {
1104 JimStringCopyHTHashFunction
, /* hash function */
1105 JimStringCopyHTDup
, /* key dup */
1107 JimStringCopyHTKeyCompare
, /* key compare */
1108 JimStringCopyHTKeyDestructor
, /* key destructor */
1109 JimAssocDataHashTableValueDestructor
/* val destructor */
1112 /* -----------------------------------------------------------------------------
1113 * Stack - This is a simple generic stack implementation. It is used for
1114 * example in the 'expr' expression compiler.
1115 * ---------------------------------------------------------------------------*/
1116 void Jim_InitStack(Jim_Stack
*stack
)
1120 stack
->vector
= NULL
;
1123 void Jim_FreeStack(Jim_Stack
*stack
)
1125 Jim_Free(stack
->vector
);
1128 int Jim_StackLen(Jim_Stack
*stack
)
1133 void Jim_StackPush(Jim_Stack
*stack
, void *element
)
1135 int neededLen
= stack
->len
+ 1;
1137 if (neededLen
> stack
->maxlen
) {
1138 stack
->maxlen
= neededLen
< 20 ? 20 : neededLen
* 2;
1139 stack
->vector
= Jim_Realloc(stack
->vector
, sizeof(void *) * stack
->maxlen
);
1141 stack
->vector
[stack
->len
] = element
;
1145 void *Jim_StackPop(Jim_Stack
*stack
)
1147 if (stack
->len
== 0)
1150 return stack
->vector
[stack
->len
];
1153 void *Jim_StackPeek(Jim_Stack
*stack
)
1155 if (stack
->len
== 0)
1157 return stack
->vector
[stack
->len
- 1];
1160 void Jim_FreeStackElements(Jim_Stack
*stack
, void (*freeFunc
) (void *ptr
))
1164 for (i
= 0; i
< stack
->len
; i
++)
1165 freeFunc(stack
->vector
[i
]);
1168 /* -----------------------------------------------------------------------------
1170 * ---------------------------------------------------------------------------*/
1173 #define JIM_TT_NONE 0 /* No token returned */
1174 #define JIM_TT_STR 1 /* simple string */
1175 #define JIM_TT_ESC 2 /* string that needs escape chars conversion */
1176 #define JIM_TT_VAR 3 /* var substitution */
1177 #define JIM_TT_DICTSUGAR 4 /* Syntax sugar for [dict get], $foo(bar) */
1178 #define JIM_TT_CMD 5 /* command substitution */
1179 /* Note: Keep these three together for TOKEN_IS_SEP() */
1180 #define JIM_TT_SEP 6 /* word separator (white space) */
1181 #define JIM_TT_EOL 7 /* line separator */
1182 #define JIM_TT_EOF 8 /* end of script */
1184 #define JIM_TT_LINE 9 /* special 'start-of-line' token. arg is # of arguments to the command. -ve if {*} */
1185 #define JIM_TT_WORD 10 /* special 'start-of-word' token. arg is # of tokens to combine. -ve if {*} */
1187 /* Additional token types needed for expressions */
1188 #define JIM_TT_SUBEXPR_START 11
1189 #define JIM_TT_SUBEXPR_END 12
1190 #define JIM_TT_SUBEXPR_COMMA 13
1191 #define JIM_TT_EXPR_INT 14
1192 #define JIM_TT_EXPR_DOUBLE 15
1193 #define JIM_TT_EXPR_BOOLEAN 16
1195 #define JIM_TT_EXPRSUGAR 17 /* $(expression) */
1197 /* Operator token types start here */
1198 #define JIM_TT_EXPR_OP 20
1200 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1201 /* Can this token start an expression? */
1202 #define TOKEN_IS_EXPR_START(type) (type == JIM_TT_NONE || type == JIM_TT_SUBEXPR_START || type == JIM_TT_SUBEXPR_COMMA)
1203 /* Is this token an expression operator? */
1204 #define TOKEN_IS_EXPR_OP(type) (type >= JIM_TT_EXPR_OP)
1207 * Results of missing quotes, braces, etc. from parsing.
1209 struct JimParseMissing
{
1210 int ch
; /* At end of parse, ' ' if complete or '{', '[', '"', '\\', '}' if incomplete */
1211 int line
; /* Line number starting the missing token */
1214 /* Parser context structure. The same context is used to parse
1215 * Tcl scripts, expressions and lists. */
1218 const char *p
; /* Pointer to the point of the program we are parsing */
1219 int len
; /* Remaining length */
1220 int linenr
; /* Current line number */
1222 const char *tend
; /* Returned token is at tstart-tend in 'prg'. */
1223 int tline
; /* Line number of the returned token */
1224 int tt
; /* Token type */
1225 int eof
; /* Non zero if EOF condition is true. */
1226 int inquote
; /* Parsing a quoted string */
1227 int comment
; /* Non zero if the next chars may be a comment. */
1228 struct JimParseMissing missing
; /* Details of any missing quotes, etc. */
1231 static int JimParseScript(struct JimParserCtx
*pc
);
1232 static int JimParseSep(struct JimParserCtx
*pc
);
1233 static int JimParseEol(struct JimParserCtx
*pc
);
1234 static int JimParseCmd(struct JimParserCtx
*pc
);
1235 static int JimParseQuote(struct JimParserCtx
*pc
);
1236 static int JimParseVar(struct JimParserCtx
*pc
);
1237 static int JimParseBrace(struct JimParserCtx
*pc
);
1238 static int JimParseStr(struct JimParserCtx
*pc
);
1239 static int JimParseComment(struct JimParserCtx
*pc
);
1240 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1241 static int JimParseSubQuote(struct JimParserCtx
*pc
);
1242 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
);
1244 /* Initialize a parser context.
1245 * 'prg' is a pointer to the program text, linenr is the line
1246 * number of the first line contained in the program. */
1247 static void JimParserInit(struct JimParserCtx
*pc
, const char *prg
, int len
, int linenr
)
1254 pc
->tt
= JIM_TT_NONE
;
1257 pc
->linenr
= linenr
;
1259 pc
->missing
.ch
= ' ';
1260 pc
->missing
.line
= linenr
;
1263 static int JimParseScript(struct JimParserCtx
*pc
)
1265 while (1) { /* the while is used to reiterate with continue if needed */
1268 pc
->tend
= pc
->p
- 1;
1269 pc
->tline
= pc
->linenr
;
1270 pc
->tt
= JIM_TT_EOL
;
1276 if (*(pc
->p
+ 1) == '\n' && !pc
->inquote
) {
1277 return JimParseSep(pc
);
1280 return JimParseStr(pc
);
1286 return JimParseSep(pc
);
1288 return JimParseStr(pc
);
1293 return JimParseEol(pc
);
1294 return JimParseStr(pc
);
1297 return JimParseCmd(pc
);
1300 if (JimParseVar(pc
) == JIM_ERR
) {
1301 /* An orphan $. Create as a separate token */
1302 pc
->tstart
= pc
->tend
= pc
->p
++;
1304 pc
->tt
= JIM_TT_ESC
;
1309 JimParseComment(pc
);
1312 return JimParseStr(pc
);
1315 return JimParseStr(pc
);
1321 static int JimParseSep(struct JimParserCtx
*pc
)
1324 pc
->tline
= pc
->linenr
;
1325 while (isspace(UCHAR(*pc
->p
)) || (*pc
->p
== '\\' && *(pc
->p
+ 1) == '\n')) {
1326 if (*pc
->p
== '\n') {
1329 if (*pc
->p
== '\\') {
1337 pc
->tend
= pc
->p
- 1;
1338 pc
->tt
= JIM_TT_SEP
;
1342 static int JimParseEol(struct JimParserCtx
*pc
)
1345 pc
->tline
= pc
->linenr
;
1346 while (isspace(UCHAR(*pc
->p
)) || *pc
->p
== ';') {
1352 pc
->tend
= pc
->p
- 1;
1353 pc
->tt
= JIM_TT_EOL
;
1358 ** Here are the rules for parsing:
1359 ** {braced expression}
1360 ** - Count open and closing braces
1361 ** - Backslash escapes meaning of braces but doesn't remove the backslash
1363 ** "quoted expression"
1364 ** - Unescaped double quote terminates the expression
1365 ** - Backslash escapes next char
1366 ** - [commands brackets] are counted/nested
1367 ** - command rules apply within [brackets], not quoting rules (i.e. brackets have their own rules)
1369 ** [command expression]
1370 ** - Count open and closing brackets
1371 ** - Backslash escapes next char
1372 ** - [commands brackets] are counted/nested
1373 ** - "quoted expressions" are parsed according to quoting rules
1374 ** - {braced expressions} are parsed according to brace rules
1376 ** For everything, backslash escapes the next char, newline increments current line
1380 * Parses a braced expression starting at pc->p.
1382 * Positions the parser at the end of the braced expression,
1383 * sets pc->tend and possibly pc->missing.
1385 static void JimParseSubBrace(struct JimParserCtx
*pc
)
1389 /* Skip the brace */
1396 if (*++pc
->p
== '\n') {
1409 pc
->tend
= pc
->p
- 1;
1423 pc
->missing
.ch
= '{';
1424 pc
->missing
.line
= pc
->tline
;
1425 pc
->tend
= pc
->p
- 1;
1429 * Parses a quoted expression starting at pc->p.
1431 * Positions the parser at the end of the quoted expression,
1432 * sets pc->tend and possibly pc->missing.
1434 * Returns the type of the token of the string,
1435 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1438 static int JimParseSubQuote(struct JimParserCtx
*pc
)
1440 int tt
= JIM_TT_STR
;
1441 int line
= pc
->tline
;
1443 /* Skip the quote */
1450 if (*++pc
->p
== '\n') {
1459 pc
->tend
= pc
->p
- 1;
1480 pc
->missing
.ch
= '"';
1481 pc
->missing
.line
= line
;
1482 pc
->tend
= pc
->p
- 1;
1487 * Parses a [command] expression starting at pc->p.
1489 * Positions the parser at the end of the command expression,
1490 * sets pc->tend and possibly pc->missing.
1492 static void JimParseSubCmd(struct JimParserCtx
*pc
)
1495 int startofword
= 1;
1496 int line
= pc
->tline
;
1498 /* Skip the bracket */
1505 if (*++pc
->p
== '\n') {
1518 pc
->tend
= pc
->p
- 1;
1527 JimParseSubQuote(pc
);
1528 if (pc
->missing
.ch
== '"') {
1536 JimParseSubBrace(pc
);
1544 startofword
= isspace(UCHAR(*pc
->p
));
1548 pc
->missing
.ch
= '[';
1549 pc
->missing
.line
= line
;
1550 pc
->tend
= pc
->p
- 1;
1553 static int JimParseBrace(struct JimParserCtx
*pc
)
1555 pc
->tstart
= pc
->p
+ 1;
1556 pc
->tline
= pc
->linenr
;
1557 pc
->tt
= JIM_TT_STR
;
1558 JimParseSubBrace(pc
);
1562 static int JimParseCmd(struct JimParserCtx
*pc
)
1564 pc
->tstart
= pc
->p
+ 1;
1565 pc
->tline
= pc
->linenr
;
1566 pc
->tt
= JIM_TT_CMD
;
1571 static int JimParseQuote(struct JimParserCtx
*pc
)
1573 pc
->tstart
= pc
->p
+ 1;
1574 pc
->tline
= pc
->linenr
;
1575 pc
->tt
= JimParseSubQuote(pc
);
1579 static int JimParseVar(struct JimParserCtx
*pc
)
1585 #ifdef EXPRSUGAR_BRACKET
1586 if (*pc
->p
== '[') {
1587 /* Parse $[...] expr shorthand syntax */
1589 pc
->tt
= JIM_TT_EXPRSUGAR
;
1595 pc
->tt
= JIM_TT_VAR
;
1596 pc
->tline
= pc
->linenr
;
1598 if (*pc
->p
== '{') {
1599 pc
->tstart
= ++pc
->p
;
1602 while (pc
->len
&& *pc
->p
!= '}') {
1603 if (*pc
->p
== '\n') {
1609 pc
->tend
= pc
->p
- 1;
1617 /* Skip double colon, but not single colon! */
1618 if (pc
->p
[0] == ':' && pc
->p
[1] == ':') {
1619 while (*pc
->p
== ':') {
1625 /* Note that any char >= 0x80 must be part of a utf-8 char.
1626 * We consider all unicode points outside of ASCII as letters
1628 if (isalnum(UCHAR(*pc
->p
)) || *pc
->p
== '_' || UCHAR(*pc
->p
) >= 0x80) {
1635 /* Parse [dict get] syntax sugar. */
1636 if (*pc
->p
== '(') {
1638 const char *paren
= NULL
;
1640 pc
->tt
= JIM_TT_DICTSUGAR
;
1642 while (count
&& pc
->len
) {
1645 if (*pc
->p
== '\\' && pc
->len
>= 1) {
1649 else if (*pc
->p
== '(') {
1652 else if (*pc
->p
== ')') {
1662 /* Did not find a matching paren. Back up */
1664 pc
->len
+= (pc
->p
- paren
);
1667 #ifndef EXPRSUGAR_BRACKET
1668 if (*pc
->tstart
== '(') {
1669 pc
->tt
= JIM_TT_EXPRSUGAR
;
1673 pc
->tend
= pc
->p
- 1;
1675 /* Check if we parsed just the '$' character.
1676 * That's not a variable so an error is returned
1677 * to tell the state machine to consider this '$' just
1679 if (pc
->tstart
== pc
->p
) {
1687 static int JimParseStr(struct JimParserCtx
*pc
)
1689 if (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1690 pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_STR
) {
1691 /* Starting a new word */
1692 if (*pc
->p
== '{') {
1693 return JimParseBrace(pc
);
1695 if (*pc
->p
== '"') {
1699 /* In case the end quote is missing */
1700 pc
->missing
.line
= pc
->tline
;
1704 pc
->tline
= pc
->linenr
;
1708 pc
->missing
.ch
= '"';
1710 pc
->tend
= pc
->p
- 1;
1711 pc
->tt
= JIM_TT_ESC
;
1716 if (!pc
->inquote
&& *(pc
->p
+ 1) == '\n') {
1717 pc
->tend
= pc
->p
- 1;
1718 pc
->tt
= JIM_TT_ESC
;
1722 if (*(pc
->p
+ 1) == '\n') {
1728 else if (pc
->len
== 1) {
1729 /* End of script with trailing backslash */
1730 pc
->missing
.ch
= '\\';
1734 /* If the following token is not '$' just keep going */
1735 if (pc
->len
> 1 && pc
->p
[1] != '$') {
1740 /* Only need a separate ')' token if the previous was a var */
1741 if (*pc
->p
== '(' || pc
->tt
== JIM_TT_VAR
) {
1742 if (pc
->p
== pc
->tstart
) {
1743 /* At the start of the token, so just return this char */
1747 pc
->tend
= pc
->p
- 1;
1748 pc
->tt
= JIM_TT_ESC
;
1755 pc
->tend
= pc
->p
- 1;
1756 pc
->tt
= JIM_TT_ESC
;
1765 pc
->tend
= pc
->p
- 1;
1766 pc
->tt
= JIM_TT_ESC
;
1769 else if (*pc
->p
== '\n') {
1775 pc
->tend
= pc
->p
- 1;
1776 pc
->tt
= JIM_TT_ESC
;
1787 return JIM_OK
; /* unreached */
1790 static int JimParseComment(struct JimParserCtx
*pc
)
1793 if (*pc
->p
== '\\') {
1797 pc
->missing
.ch
= '\\';
1800 if (*pc
->p
== '\n') {
1804 else if (*pc
->p
== '\n') {
1816 /* xdigitval and odigitval are helper functions for JimEscape() */
1817 static int xdigitval(int c
)
1819 if (c
>= '0' && c
<= '9')
1821 if (c
>= 'a' && c
<= 'f')
1822 return c
- 'a' + 10;
1823 if (c
>= 'A' && c
<= 'F')
1824 return c
- 'A' + 10;
1828 static int odigitval(int c
)
1830 if (c
>= '0' && c
<= '7')
1835 /* Perform Tcl escape substitution of 's', storing the result
1836 * string into 'dest'. The escaped string is guaranteed to
1837 * be the same length or shorter than the source string.
1838 * slen is the length of the string at 's'.
1840 * The function returns the length of the resulting string. */
1841 static int JimEscape(char *dest
, const char *s
, int slen
)
1846 for (i
= 0; i
< slen
; i
++) {
1877 /* A unicode or hex sequence.
1878 * \x Expect 1-2 hex chars and convert to hex.
1879 * \u Expect 1-4 hex chars and convert to utf-8.
1880 * \U Expect 1-8 hex chars and convert to utf-8.
1881 * \u{NNN} supports 1-6 hex chars and convert to utf-8.
1882 * An invalid sequence means simply the escaped char.
1894 else if (s
[i
] == 'u') {
1895 if (s
[i
+ 1] == '{') {
1904 for (k
= 0; k
< maxchars
; k
++) {
1905 int c
= xdigitval(s
[i
+ k
+ 1]);
1909 val
= (val
<< 4) | c
;
1911 /* The \u{nnn} syntax supports up to 21 bit codepoints. */
1913 if (k
== 0 || val
> 0x1fffff || s
[i
+ k
+ 1] != '}') {
1919 /* Skip the closing brace */
1924 /* Got a valid sequence, so convert */
1929 p
+= utf8_fromunicode(p
, val
);
1934 /* Not a valid codepoint, just an escaped char */
1947 /* Replace all spaces and tabs after backslash newline with a single space*/
1951 } while (s
[i
+ 1] == ' ' || s
[i
+ 1] == '\t');
1964 int c
= odigitval(s
[i
+ 1]);
1967 c
= odigitval(s
[i
+ 2]);
1973 val
= (val
* 8) + c
;
1974 c
= odigitval(s
[i
+ 3]);
1980 val
= (val
* 8) + c
;
2001 /* Returns a dynamically allocated copy of the current token in the
2002 * parser context. The function performs conversion of escapes if
2003 * the token is of type JIM_TT_ESC.
2005 * Note that after the conversion, tokens that are grouped with
2006 * braces in the source code, are always recognizable from the
2007 * identical string obtained in a different way from the type.
2009 * For example the string:
2013 * will return as first token "*", of type JIM_TT_STR
2019 * will return as first token "*", of type JIM_TT_ESC
2021 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
)
2023 const char *start
, *end
;
2029 len
= (end
- start
) + 1;
2033 token
= Jim_Alloc(len
+ 1);
2034 if (pc
->tt
!= JIM_TT_ESC
) {
2035 /* No escape conversion needed? Just copy it. */
2036 memcpy(token
, start
, len
);
2040 /* Else convert the escape chars. */
2041 len
= JimEscape(token
, start
, len
);
2044 return Jim_NewStringObjNoAlloc(interp
, token
, len
);
2047 /* -----------------------------------------------------------------------------
2049 * ---------------------------------------------------------------------------*/
2050 static int JimParseListSep(struct JimParserCtx
*pc
);
2051 static int JimParseListStr(struct JimParserCtx
*pc
);
2052 static int JimParseListQuote(struct JimParserCtx
*pc
);
2054 static int JimParseList(struct JimParserCtx
*pc
)
2056 if (isspace(UCHAR(*pc
->p
))) {
2057 return JimParseListSep(pc
);
2061 return JimParseListQuote(pc
);
2064 return JimParseBrace(pc
);
2068 return JimParseListStr(pc
);
2073 pc
->tstart
= pc
->tend
= pc
->p
;
2074 pc
->tline
= pc
->linenr
;
2075 pc
->tt
= JIM_TT_EOL
;
2080 static int JimParseListSep(struct JimParserCtx
*pc
)
2083 pc
->tline
= pc
->linenr
;
2084 while (isspace(UCHAR(*pc
->p
))) {
2085 if (*pc
->p
== '\n') {
2091 pc
->tend
= pc
->p
- 1;
2092 pc
->tt
= JIM_TT_SEP
;
2096 static int JimParseListQuote(struct JimParserCtx
*pc
)
2102 pc
->tline
= pc
->linenr
;
2103 pc
->tt
= JIM_TT_STR
;
2108 pc
->tt
= JIM_TT_ESC
;
2109 if (--pc
->len
== 0) {
2110 /* Trailing backslash */
2120 pc
->tend
= pc
->p
- 1;
2129 pc
->tend
= pc
->p
- 1;
2133 static int JimParseListStr(struct JimParserCtx
*pc
)
2136 pc
->tline
= pc
->linenr
;
2137 pc
->tt
= JIM_TT_STR
;
2140 if (isspace(UCHAR(*pc
->p
))) {
2141 pc
->tend
= pc
->p
- 1;
2144 if (*pc
->p
== '\\') {
2145 if (--pc
->len
== 0) {
2146 /* Trailing backslash */
2150 pc
->tt
= JIM_TT_ESC
;
2156 pc
->tend
= pc
->p
- 1;
2160 /* -----------------------------------------------------------------------------
2161 * Jim_Obj related functions
2162 * ---------------------------------------------------------------------------*/
2164 /* Return a new initialized object. */
2165 Jim_Obj
*Jim_NewObj(Jim_Interp
*interp
)
2169 /* -- Check if there are objects in the free list -- */
2170 if (interp
->freeList
!= NULL
) {
2171 /* -- Unlink the object from the free list -- */
2172 objPtr
= interp
->freeList
;
2173 interp
->freeList
= objPtr
->nextObjPtr
;
2176 /* -- No ready to use objects: allocate a new one -- */
2177 objPtr
= Jim_Alloc(sizeof(*objPtr
));
2180 /* Object is returned with refCount of 0. Every
2181 * kind of GC implemented should take care to avoid
2182 * scanning objects with refCount == 0. */
2183 objPtr
->refCount
= 0;
2184 /* All the other fields are left uninitialized to save time.
2185 * The caller will probably want to set them to the right
2188 /* -- Put the object into the live list -- */
2189 objPtr
->prevObjPtr
= NULL
;
2190 objPtr
->nextObjPtr
= interp
->liveList
;
2191 if (interp
->liveList
)
2192 interp
->liveList
->prevObjPtr
= objPtr
;
2193 interp
->liveList
= objPtr
;
2198 /* Free an object. Actually objects are never freed, but
2199 * just moved to the free objects list, where they will be
2200 * reused by Jim_NewObj(). */
2201 void Jim_FreeObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2203 /* Check if the object was already freed, panic. */
2204 JimPanic((objPtr
->refCount
!= 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr
,
2205 objPtr
->refCount
, objPtr
->typePtr
? objPtr
->typePtr
->name
: "<none>"));
2207 /* Free the internal representation */
2208 Jim_FreeIntRep(interp
, objPtr
);
2209 /* Free the string representation */
2210 if (objPtr
->bytes
!= NULL
) {
2211 if (objPtr
->bytes
!= JimEmptyStringRep
)
2212 Jim_Free(objPtr
->bytes
);
2214 /* Unlink the object from the live objects list */
2215 if (objPtr
->prevObjPtr
)
2216 objPtr
->prevObjPtr
->nextObjPtr
= objPtr
->nextObjPtr
;
2217 if (objPtr
->nextObjPtr
)
2218 objPtr
->nextObjPtr
->prevObjPtr
= objPtr
->prevObjPtr
;
2219 if (interp
->liveList
== objPtr
)
2220 interp
->liveList
= objPtr
->nextObjPtr
;
2221 #ifdef JIM_DISABLE_OBJECT_POOL
2224 /* Link the object into the free objects list */
2225 objPtr
->prevObjPtr
= NULL
;
2226 objPtr
->nextObjPtr
= interp
->freeList
;
2227 if (interp
->freeList
)
2228 interp
->freeList
->prevObjPtr
= objPtr
;
2229 interp
->freeList
= objPtr
;
2230 objPtr
->refCount
= -1;
2234 /* Invalidate the string representation of an object. */
2235 void Jim_InvalidateStringRep(Jim_Obj
*objPtr
)
2237 if (objPtr
->bytes
!= NULL
) {
2238 if (objPtr
->bytes
!= JimEmptyStringRep
)
2239 Jim_Free(objPtr
->bytes
);
2241 objPtr
->bytes
= NULL
;
2244 /* Duplicate an object. The returned object has refcount = 0. */
2245 Jim_Obj
*Jim_DuplicateObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2249 dupPtr
= Jim_NewObj(interp
);
2250 if (objPtr
->bytes
== NULL
) {
2251 /* Object does not have a valid string representation. */
2252 dupPtr
->bytes
= NULL
;
2254 else if (objPtr
->length
== 0) {
2255 /* Zero length, so don't even bother with the type-specific dup,
2256 * since all zero length objects look the same
2258 dupPtr
->bytes
= JimEmptyStringRep
;
2260 dupPtr
->typePtr
= NULL
;
2264 dupPtr
->bytes
= Jim_Alloc(objPtr
->length
+ 1);
2265 dupPtr
->length
= objPtr
->length
;
2266 /* Copy the null byte too */
2267 memcpy(dupPtr
->bytes
, objPtr
->bytes
, objPtr
->length
+ 1);
2270 /* By default, the new object has the same type as the old object */
2271 dupPtr
->typePtr
= objPtr
->typePtr
;
2272 if (objPtr
->typePtr
!= NULL
) {
2273 if (objPtr
->typePtr
->dupIntRepProc
== NULL
) {
2274 dupPtr
->internalRep
= objPtr
->internalRep
;
2277 /* The dup proc may set a different type, e.g. NULL */
2278 objPtr
->typePtr
->dupIntRepProc(interp
, objPtr
, dupPtr
);
2284 /* Return the string representation for objPtr. If the object's
2285 * string representation is invalid, calls the updateStringProc method to create
2286 * a new one from the internal representation of the object.
2288 const char *Jim_GetString(Jim_Obj
*objPtr
, int *lenPtr
)
2290 if (objPtr
->bytes
== NULL
) {
2291 /* Invalid string repr. Generate it. */
2292 JimPanic((objPtr
->typePtr
->updateStringProc
== NULL
, "UpdateStringProc called against '%s' type.", objPtr
->typePtr
->name
));
2293 objPtr
->typePtr
->updateStringProc(objPtr
);
2296 *lenPtr
= objPtr
->length
;
2297 return objPtr
->bytes
;
2300 /* Just returns the length (in bytes) of the object's string rep */
2301 int Jim_Length(Jim_Obj
*objPtr
)
2303 if (objPtr
->bytes
== NULL
) {
2304 /* Invalid string repr. Generate it. */
2305 Jim_GetString(objPtr
, NULL
);
2307 return objPtr
->length
;
2310 /* Just returns object's string rep */
2311 const char *Jim_String(Jim_Obj
*objPtr
)
2313 if (objPtr
->bytes
== NULL
) {
2314 /* Invalid string repr. Generate it. */
2315 Jim_GetString(objPtr
, NULL
);
2317 return objPtr
->bytes
;
2320 static void JimSetStringBytes(Jim_Obj
*objPtr
, const char *str
)
2322 objPtr
->bytes
= Jim_StrDup(str
);
2323 objPtr
->length
= strlen(str
);
2326 static void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2327 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2329 static const Jim_ObjType dictSubstObjType
= {
2330 "dict-substitution",
2331 FreeDictSubstInternalRep
,
2332 DupDictSubstInternalRep
,
2337 static void FreeInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2338 static void DupInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2340 static const Jim_ObjType interpolatedObjType
= {
2342 FreeInterpolatedInternalRep
,
2343 DupInterpolatedInternalRep
,
2348 static void FreeInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2350 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
2353 static void DupInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2355 /* Copy the interal rep */
2356 dupPtr
->internalRep
= srcPtr
->internalRep
;
2357 /* Need to increment the key ref count */
2358 Jim_IncrRefCount(dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
2361 /* -----------------------------------------------------------------------------
2363 * ---------------------------------------------------------------------------*/
2364 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2365 static int SetStringFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2367 static const Jim_ObjType stringObjType
= {
2370 DupStringInternalRep
,
2372 JIM_TYPE_REFERENCES
,
2375 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2377 JIM_NOTUSED(interp
);
2379 /* This is a bit subtle: the only caller of this function
2380 * should be Jim_DuplicateObj(), that will copy the
2381 * string representaion. After the copy, the duplicated
2382 * object will not have more room in the buffer than
2383 * srcPtr->length bytes. So we just set it to length. */
2384 dupPtr
->internalRep
.strValue
.maxLength
= srcPtr
->length
;
2385 dupPtr
->internalRep
.strValue
.charLength
= srcPtr
->internalRep
.strValue
.charLength
;
2388 static int SetStringFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2390 if (objPtr
->typePtr
!= &stringObjType
) {
2391 /* Get a fresh string representation. */
2392 if (objPtr
->bytes
== NULL
) {
2393 /* Invalid string repr. Generate it. */
2394 JimPanic((objPtr
->typePtr
->updateStringProc
== NULL
, "UpdateStringProc called against '%s' type.", objPtr
->typePtr
->name
));
2395 objPtr
->typePtr
->updateStringProc(objPtr
);
2397 /* Free any other internal representation. */
2398 Jim_FreeIntRep(interp
, objPtr
);
2399 /* Set it as string, i.e. just set the maxLength field. */
2400 objPtr
->typePtr
= &stringObjType
;
2401 objPtr
->internalRep
.strValue
.maxLength
= objPtr
->length
;
2402 /* Don't know the utf-8 length yet */
2403 objPtr
->internalRep
.strValue
.charLength
= -1;
2409 * Returns the length of the object string in chars, not bytes.
2411 * These may be different for a utf-8 string.
2413 int Jim_Utf8Length(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2416 SetStringFromAny(interp
, objPtr
);
2418 if (objPtr
->internalRep
.strValue
.charLength
< 0) {
2419 objPtr
->internalRep
.strValue
.charLength
= utf8_strlen(objPtr
->bytes
, objPtr
->length
);
2421 return objPtr
->internalRep
.strValue
.charLength
;
2423 return Jim_Length(objPtr
);
2427 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2428 Jim_Obj
*Jim_NewStringObj(Jim_Interp
*interp
, const char *s
, int len
)
2430 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2432 /* Need to find out how many bytes the string requires */
2435 /* Alloc/Set the string rep. */
2437 objPtr
->bytes
= JimEmptyStringRep
;
2440 objPtr
->bytes
= Jim_StrDupLen(s
, len
);
2442 objPtr
->length
= len
;
2444 /* No typePtr field for the vanilla string object. */
2445 objPtr
->typePtr
= NULL
;
2449 /* charlen is in characters -- see also Jim_NewStringObj() */
2450 Jim_Obj
*Jim_NewStringObjUtf8(Jim_Interp
*interp
, const char *s
, int charlen
)
2453 /* Need to find out how many bytes the string requires */
2454 int bytelen
= utf8_index(s
, charlen
);
2456 Jim_Obj
*objPtr
= Jim_NewStringObj(interp
, s
, bytelen
);
2458 /* Remember the utf8 length, so set the type */
2459 objPtr
->typePtr
= &stringObjType
;
2460 objPtr
->internalRep
.strValue
.maxLength
= bytelen
;
2461 objPtr
->internalRep
.strValue
.charLength
= charlen
;
2465 return Jim_NewStringObj(interp
, s
, charlen
);
2469 /* This version does not try to duplicate the 's' pointer, but
2470 * use it directly. */
2471 Jim_Obj
*Jim_NewStringObjNoAlloc(Jim_Interp
*interp
, char *s
, int len
)
2473 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2476 objPtr
->length
= (len
== -1) ? strlen(s
) : len
;
2477 objPtr
->typePtr
= NULL
;
2481 /* Low-level string append. Use it only against unshared objects
2482 * of type "string". */
2483 static void StringAppendString(Jim_Obj
*objPtr
, const char *str
, int len
)
2489 needlen
= objPtr
->length
+ len
;
2490 if (objPtr
->internalRep
.strValue
.maxLength
< needlen
||
2491 objPtr
->internalRep
.strValue
.maxLength
== 0) {
2493 /* Inefficient to malloc() for less than 8 bytes */
2497 if (objPtr
->bytes
== JimEmptyStringRep
) {
2498 objPtr
->bytes
= Jim_Alloc(needlen
+ 1);
2501 objPtr
->bytes
= Jim_Realloc(objPtr
->bytes
, needlen
+ 1);
2503 objPtr
->internalRep
.strValue
.maxLength
= needlen
;
2505 memcpy(objPtr
->bytes
+ objPtr
->length
, str
, len
);
2506 objPtr
->bytes
[objPtr
->length
+ len
] = '\0';
2508 if (objPtr
->internalRep
.strValue
.charLength
>= 0) {
2509 /* Update the utf-8 char length */
2510 objPtr
->internalRep
.strValue
.charLength
+= utf8_strlen(objPtr
->bytes
+ objPtr
->length
, len
);
2512 objPtr
->length
+= len
;
2515 /* Higher level API to append strings to objects.
2516 * Object must not be unshared for each of these.
2518 void Jim_AppendString(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
, int len
)
2520 JimPanic((Jim_IsShared(objPtr
), "Jim_AppendString called with shared object"));
2521 SetStringFromAny(interp
, objPtr
);
2522 StringAppendString(objPtr
, str
, len
);
2525 void Jim_AppendObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*appendObjPtr
)
2528 const char *str
= Jim_GetString(appendObjPtr
, &len
);
2529 Jim_AppendString(interp
, objPtr
, str
, len
);
2532 void Jim_AppendStrings(Jim_Interp
*interp
, Jim_Obj
*objPtr
, ...)
2536 SetStringFromAny(interp
, objPtr
);
2537 va_start(ap
, objPtr
);
2539 const char *s
= va_arg(ap
, const char *);
2543 Jim_AppendString(interp
, objPtr
, s
, -1);
2548 int Jim_StringEqObj(Jim_Obj
*aObjPtr
, Jim_Obj
*bObjPtr
)
2550 if (aObjPtr
== bObjPtr
) {
2555 const char *sA
= Jim_GetString(aObjPtr
, &Alen
);
2556 const char *sB
= Jim_GetString(bObjPtr
, &Blen
);
2558 return Alen
== Blen
&& memcmp(sA
, sB
, Alen
) == 0;
2563 * Note. Does not support embedded nulls in either the pattern or the object.
2565 int Jim_StringMatchObj(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, Jim_Obj
*objPtr
, int nocase
)
2568 const char *pattern
= Jim_GetString(patternObjPtr
, &plen
);
2569 const char *string
= Jim_GetString(objPtr
, &slen
);
2570 return JimGlobMatch(pattern
, plen
, string
, slen
, nocase
);
2573 int Jim_StringCompareObj(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*secondObjPtr
, int nocase
)
2575 const char *s1
= Jim_String(firstObjPtr
);
2576 int l1
= Jim_Utf8Length(interp
, firstObjPtr
);
2577 const char *s2
= Jim_String(secondObjPtr
);
2578 int l2
= Jim_Utf8Length(interp
, secondObjPtr
);
2579 return JimStringCompareUtf8(s1
, l1
, s2
, l2
, nocase
);
2582 /* Convert a range, as returned by Jim_GetRange(), into
2583 * an absolute index into an object of the specified length.
2584 * This function may return negative values, or values
2585 * greater than or equal to the length of the list if the index
2586 * is out of range. */
2587 static int JimRelToAbsIndex(int len
, int idx
)
2594 /* Convert a pair of indexes (*firstPtr, *lastPtr) as normalized by JimRelToAbsIndex(),
2595 * into a form suitable for implementation of commands like [string range] and [lrange].
2597 * The resulting range is guaranteed to address valid elements of
2600 static void JimRelToAbsRange(int len
, int *firstPtr
, int *lastPtr
, int *rangeLenPtr
)
2604 if (*firstPtr
> *lastPtr
) {
2608 rangeLen
= *lastPtr
- *firstPtr
+ 1;
2610 if (*firstPtr
< 0) {
2611 rangeLen
+= *firstPtr
;
2614 if (*lastPtr
>= len
) {
2615 rangeLen
-= (*lastPtr
- (len
- 1));
2623 *rangeLenPtr
= rangeLen
;
2626 static int JimStringGetRange(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
,
2627 int len
, int *first
, int *last
, int *range
)
2629 if (Jim_GetIndex(interp
, firstObjPtr
, first
) != JIM_OK
) {
2632 if (Jim_GetIndex(interp
, lastObjPtr
, last
) != JIM_OK
) {
2635 *first
= JimRelToAbsIndex(len
, *first
);
2636 *last
= JimRelToAbsIndex(len
, *last
);
2637 JimRelToAbsRange(len
, first
, last
, range
);
2641 Jim_Obj
*Jim_StringByteRangeObj(Jim_Interp
*interp
,
2642 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2649 str
= Jim_GetString(strObjPtr
, &bytelen
);
2651 if (JimStringGetRange(interp
, firstObjPtr
, lastObjPtr
, bytelen
, &first
, &last
, &rangeLen
) != JIM_OK
) {
2655 if (first
== 0 && rangeLen
== bytelen
) {
2658 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2661 Jim_Obj
*Jim_StringRangeObj(Jim_Interp
*interp
,
2662 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2670 str
= Jim_GetString(strObjPtr
, &bytelen
);
2671 len
= Jim_Utf8Length(interp
, strObjPtr
);
2673 if (JimStringGetRange(interp
, firstObjPtr
, lastObjPtr
, len
, &first
, &last
, &rangeLen
) != JIM_OK
) {
2677 if (first
== 0 && rangeLen
== len
) {
2680 if (len
== bytelen
) {
2681 /* ASCII optimisation */
2682 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2684 return Jim_NewStringObjUtf8(interp
, str
+ utf8_index(str
, first
), rangeLen
);
2686 return Jim_StringByteRangeObj(interp
, strObjPtr
, firstObjPtr
, lastObjPtr
);
2690 Jim_Obj
*JimStringReplaceObj(Jim_Interp
*interp
,
2691 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
, Jim_Obj
*newStrObj
)
2698 len
= Jim_Utf8Length(interp
, strObjPtr
);
2700 if (JimStringGetRange(interp
, firstObjPtr
, lastObjPtr
, len
, &first
, &last
, &rangeLen
) != JIM_OK
) {
2708 str
= Jim_String(strObjPtr
);
2711 objPtr
= Jim_NewStringObjUtf8(interp
, str
, first
);
2715 Jim_AppendObj(interp
, objPtr
, newStrObj
);
2719 Jim_AppendString(interp
, objPtr
, str
+ utf8_index(str
, last
+ 1), len
- last
- 1);
2725 * Note: does not support embedded nulls.
2727 static void JimStrCopyUpperLower(char *dest
, const char *str
, int uc
)
2731 str
+= utf8_tounicode(str
, &c
);
2732 dest
+= utf8_getchars(dest
, uc
? utf8_upper(c
) : utf8_lower(c
));
2738 * Note: does not support embedded nulls.
2740 static Jim_Obj
*JimStringToLower(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2746 str
= Jim_GetString(strObjPtr
, &len
);
2749 /* Case mapping can change the utf-8 length of the string.
2750 * But at worst it will be by one extra byte per char
2754 buf
= Jim_Alloc(len
+ 1);
2755 JimStrCopyUpperLower(buf
, str
, 0);
2756 return Jim_NewStringObjNoAlloc(interp
, buf
, -1);
2760 * Note: does not support embedded nulls.
2762 static Jim_Obj
*JimStringToUpper(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2768 str
= Jim_GetString(strObjPtr
, &len
);
2771 /* Case mapping can change the utf-8 length of the string.
2772 * But at worst it will be by one extra byte per char
2776 buf
= Jim_Alloc(len
+ 1);
2777 JimStrCopyUpperLower(buf
, str
, 1);
2778 return Jim_NewStringObjNoAlloc(interp
, buf
, -1);
2782 * Note: does not support embedded nulls.
2784 static Jim_Obj
*JimStringToTitle(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2791 str
= Jim_GetString(strObjPtr
, &len
);
2794 /* Case mapping can change the utf-8 length of the string.
2795 * But at worst it will be by one extra byte per char
2799 buf
= p
= Jim_Alloc(len
+ 1);
2801 str
+= utf8_tounicode(str
, &c
);
2802 p
+= utf8_getchars(p
, utf8_title(c
));
2804 JimStrCopyUpperLower(p
, str
, 0);
2806 return Jim_NewStringObjNoAlloc(interp
, buf
, -1);
2809 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2810 * for unicode character 'c'.
2811 * Returns the position if found or NULL if not
2813 static const char *utf8_memchr(const char *str
, int len
, int c
)
2818 int n
= utf8_tounicode(str
, &sc
);
2827 return memchr(str
, c
, len
);
2832 * Searches for the first non-trim char in string (str, len)
2834 * If none is found, returns just past the last char.
2836 * Lengths are in bytes.
2838 static const char *JimFindTrimLeft(const char *str
, int len
, const char *trimchars
, int trimlen
)
2842 int n
= utf8_tounicode(str
, &c
);
2844 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2845 /* Not a trim char, so stop */
2855 * Searches backwards for a non-trim char in string (str, len).
2857 * Returns a pointer to just after the non-trim char, or NULL if not found.
2859 * Lengths are in bytes.
2861 static const char *JimFindTrimRight(const char *str
, int len
, const char *trimchars
, int trimlen
)
2867 int n
= utf8_prev_len(str
, len
);
2872 n
= utf8_tounicode(str
, &c
);
2874 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2882 static const char default_trim_chars
[] = " \t\n\r";
2883 /* sizeof() here includes the null byte */
2884 static int default_trim_chars_len
= sizeof(default_trim_chars
);
2886 static Jim_Obj
*JimStringTrimLeft(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2889 const char *str
= Jim_GetString(strObjPtr
, &len
);
2890 const char *trimchars
= default_trim_chars
;
2891 int trimcharslen
= default_trim_chars_len
;
2894 if (trimcharsObjPtr
) {
2895 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2898 newstr
= JimFindTrimLeft(str
, len
, trimchars
, trimcharslen
);
2899 if (newstr
== str
) {
2903 return Jim_NewStringObj(interp
, newstr
, len
- (newstr
- str
));
2906 static Jim_Obj
*JimStringTrimRight(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2909 const char *trimchars
= default_trim_chars
;
2910 int trimcharslen
= default_trim_chars_len
;
2911 const char *nontrim
;
2913 if (trimcharsObjPtr
) {
2914 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2917 SetStringFromAny(interp
, strObjPtr
);
2919 len
= Jim_Length(strObjPtr
);
2920 nontrim
= JimFindTrimRight(strObjPtr
->bytes
, len
, trimchars
, trimcharslen
);
2922 if (nontrim
== NULL
) {
2923 /* All trim, so return a zero-length string */
2924 return Jim_NewEmptyStringObj(interp
);
2926 if (nontrim
== strObjPtr
->bytes
+ len
) {
2927 /* All non-trim, so return the original object */
2931 if (Jim_IsShared(strObjPtr
)) {
2932 strObjPtr
= Jim_NewStringObj(interp
, strObjPtr
->bytes
, (nontrim
- strObjPtr
->bytes
));
2935 /* Can modify this string in place */
2936 strObjPtr
->bytes
[nontrim
- strObjPtr
->bytes
] = 0;
2937 strObjPtr
->length
= (nontrim
- strObjPtr
->bytes
);
2943 static Jim_Obj
*JimStringTrim(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2945 /* First trim left. */
2946 Jim_Obj
*objPtr
= JimStringTrimLeft(interp
, strObjPtr
, trimcharsObjPtr
);
2948 /* Now trim right */
2949 strObjPtr
= JimStringTrimRight(interp
, objPtr
, trimcharsObjPtr
);
2951 /* Note: refCount check is needed since objPtr may be emptyObj */
2952 if (objPtr
!= strObjPtr
&& objPtr
->refCount
== 0) {
2953 /* We don't want this object to be leaked */
2954 Jim_FreeNewObj(interp
, objPtr
);
2960 /* Some platforms don't have isascii - need a non-macro version */
2962 #define jim_isascii isascii
2964 static int jim_isascii(int c
)
2966 return !(c
& ~0x7f);
2970 static int JimStringIs(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*strClass
, int strict
)
2972 static const char * const strclassnames
[] = {
2973 "integer", "alpha", "alnum", "ascii", "digit",
2974 "double", "lower", "upper", "space", "xdigit",
2975 "control", "print", "graph", "punct", "boolean",
2979 STR_IS_INTEGER
, STR_IS_ALPHA
, STR_IS_ALNUM
, STR_IS_ASCII
, STR_IS_DIGIT
,
2980 STR_IS_DOUBLE
, STR_IS_LOWER
, STR_IS_UPPER
, STR_IS_SPACE
, STR_IS_XDIGIT
,
2981 STR_IS_CONTROL
, STR_IS_PRINT
, STR_IS_GRAPH
, STR_IS_PUNCT
, STR_IS_BOOLEAN
,
2987 int (*isclassfunc
)(int c
) = NULL
;
2989 if (Jim_GetEnum(interp
, strClass
, strclassnames
, &strclass
, "class", JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
2993 str
= Jim_GetString(strObjPtr
, &len
);
2995 Jim_SetResultBool(interp
, !strict
);
3000 case STR_IS_INTEGER
:
3003 Jim_SetResultBool(interp
, JimGetWideNoErr(interp
, strObjPtr
, &w
) == JIM_OK
);
3010 Jim_SetResultBool(interp
, Jim_GetDouble(interp
, strObjPtr
, &d
) == JIM_OK
&& errno
!= ERANGE
);
3014 case STR_IS_BOOLEAN
:
3017 Jim_SetResultBool(interp
, Jim_GetBoolean(interp
, strObjPtr
, &b
) == JIM_OK
);
3021 case STR_IS_ALPHA
: isclassfunc
= isalpha
; break;
3022 case STR_IS_ALNUM
: isclassfunc
= isalnum
; break;
3023 case STR_IS_ASCII
: isclassfunc
= jim_isascii
; break;
3024 case STR_IS_DIGIT
: isclassfunc
= isdigit
; break;
3025 case STR_IS_LOWER
: isclassfunc
= islower
; break;
3026 case STR_IS_UPPER
: isclassfunc
= isupper
; break;
3027 case STR_IS_SPACE
: isclassfunc
= isspace
; break;
3028 case STR_IS_XDIGIT
: isclassfunc
= isxdigit
; break;
3029 case STR_IS_CONTROL
: isclassfunc
= iscntrl
; break;
3030 case STR_IS_PRINT
: isclassfunc
= isprint
; break;
3031 case STR_IS_GRAPH
: isclassfunc
= isgraph
; break;
3032 case STR_IS_PUNCT
: isclassfunc
= ispunct
; break;
3037 for (i
= 0; i
< len
; i
++) {
3038 if (!isclassfunc(UCHAR(str
[i
]))) {
3039 Jim_SetResultBool(interp
, 0);
3043 Jim_SetResultBool(interp
, 1);
3047 /* -----------------------------------------------------------------------------
3048 * Compared String Object
3049 * ---------------------------------------------------------------------------*/
3051 /* This is strange object that allows comparison of a C literal string
3052 * with a Jim object in a very short time if the same comparison is done
3053 * multiple times. For example every time the [if] command is executed,
3054 * Jim has to check if a given argument is "else".
3055 * If the code has no errors, this comparison is true most of the time,
3056 * so we can cache the pointer of the string of the last matching
3057 * comparison inside the object. Because most C compilers perform literal sharing,
3058 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
3059 * this works pretty well even if comparisons are at different places
3060 * inside the C code. */
3062 static const Jim_ObjType comparedStringObjType
= {
3067 JIM_TYPE_REFERENCES
,
3070 /* The only way this object is exposed to the API is via the following
3071 * function. Returns true if the string and the object string repr.
3072 * are the same, otherwise zero is returned.
3074 * Note: this isn't binary safe, but it hardly needs to be.*/
3075 int Jim_CompareStringImmediate(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
)
3077 if (objPtr
->typePtr
== &comparedStringObjType
&& objPtr
->internalRep
.ptr
== str
) {
3081 if (strcmp(str
, Jim_String(objPtr
)) != 0)
3084 if (objPtr
->typePtr
!= &comparedStringObjType
) {
3085 Jim_FreeIntRep(interp
, objPtr
);
3086 objPtr
->typePtr
= &comparedStringObjType
;
3088 objPtr
->internalRep
.ptr
= (char *)str
; /*ATTENTION: const cast */
3093 static int qsortCompareStringPointers(const void *a
, const void *b
)
3095 char *const *sa
= (char *const *)a
;
3096 char *const *sb
= (char *const *)b
;
3098 return strcmp(*sa
, *sb
);
3102 /* -----------------------------------------------------------------------------
3105 * This object is just a string from the language point of view, but
3106 * the internal representation contains the filename and line number
3107 * where this token was read. This information is used by
3108 * Jim_EvalObj() if the object passed happens to be of type "source".
3110 * This allows propagation of the information about line numbers and file
3111 * names and gives error messages with absolute line numbers.
3113 * Note that this object uses the internal representation of the Jim_Object,
3114 * so there is almost no memory overhead. (One Jim_Obj for each filename).
3116 * Also the object will be converted to something else if the given
3117 * token it represents in the source file is not something to be
3118 * evaluated (not a script), and will be specialized in some other way,
3119 * so the time overhead is also almost zero.
3120 * ---------------------------------------------------------------------------*/
3122 static void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
3123 static void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
3125 static const Jim_ObjType sourceObjType
= {
3127 FreeSourceInternalRep
,
3128 DupSourceInternalRep
,
3130 JIM_TYPE_REFERENCES
,
3133 void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3135 Jim_DecrRefCount(interp
, objPtr
->internalRep
.sourceValue
.fileNameObj
);
3138 void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
3140 dupPtr
->internalRep
.sourceValue
= srcPtr
->internalRep
.sourceValue
;
3141 Jim_IncrRefCount(dupPtr
->internalRep
.sourceValue
.fileNameObj
);
3144 static void JimSetSourceInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
3145 Jim_Obj
*fileNameObj
, int lineNumber
)
3147 JimPanic((Jim_IsShared(objPtr
), "JimSetSourceInfo called with shared object"));
3148 JimPanic((objPtr
->typePtr
!= NULL
, "JimSetSourceInfo called with typed object"));
3149 Jim_IncrRefCount(fileNameObj
);
3150 objPtr
->internalRep
.sourceValue
.fileNameObj
= fileNameObj
;
3151 objPtr
->internalRep
.sourceValue
.lineNumber
= lineNumber
;
3152 objPtr
->typePtr
= &sourceObjType
;
3155 /* -----------------------------------------------------------------------------
3158 * This object is used only in the Script internal represenation.
3159 * For each line of the script, it holds the number of tokens on the line
3160 * and the source line number.
3162 static const Jim_ObjType scriptLineObjType
= {
3170 static Jim_Obj
*JimNewScriptLineObj(Jim_Interp
*interp
, int argc
, int line
)
3174 #ifdef DEBUG_SHOW_SCRIPT
3176 snprintf(buf
, sizeof(buf
), "line=%d, argc=%d", line
, argc
);
3177 objPtr
= Jim_NewStringObj(interp
, buf
, -1);
3179 objPtr
= Jim_NewEmptyStringObj(interp
);
3181 objPtr
->typePtr
= &scriptLineObjType
;
3182 objPtr
->internalRep
.scriptLineValue
.argc
= argc
;
3183 objPtr
->internalRep
.scriptLineValue
.line
= line
;
3188 /* -----------------------------------------------------------------------------
3191 * This object holds the parsed internal representation of a script.
3192 * This representation is help within an allocated ScriptObj (see below)
3194 static void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
3195 static void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
3197 static const Jim_ObjType scriptObjType
= {
3199 FreeScriptInternalRep
,
3200 DupScriptInternalRep
,
3202 JIM_TYPE_REFERENCES
,
3205 /* Each token of a script is represented by a ScriptToken.
3206 * The ScriptToken contains a type and a Jim_Obj. The Jim_Obj
3207 * can be specialized by commands operating on it.
3209 typedef struct ScriptToken
3215 /* This is the script object internal representation. An array of
3216 * ScriptToken structures, including a pre-computed representation of the
3217 * command length and arguments.
3219 * For example the script:
3222 * set $i $x$y [foo]BAR
3224 * will produce a ScriptObj with the following ScriptToken's:
3239 * "puts hello" has two args (LIN 2), composed of single tokens.
3240 * (Note that the WRD token is omitted for the common case of a single token.)
3242 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
3243 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
3245 * The precomputation of the command structure makes Jim_Eval() faster,
3246 * and simpler because there aren't dynamic lengths / allocations.
3248 * -- {expand}/{*} handling --
3250 * Expand is handled in a special way.
3252 * If a "word" begins with {*}, the word token count is -ve.
3254 * For example the command:
3258 * Will produce the following cmdstruct array:
3265 * Note that the 'LIN' token also contains the source information for the
3266 * first word of the line for error reporting purposes
3268 * -- the substFlags field of the structure --
3270 * The scriptObj structure is used to represent both "script" objects
3271 * and "subst" objects. In the second case, there are no LIN and WRD
3272 * tokens. Instead SEP and EOL tokens are added as-is.
3273 * In addition, the field 'substFlags' is used to represent the flags used to turn
3274 * the string into the internal representation.
3275 * If these flags do not match what the application requires,
3276 * the scriptObj is created again. For example the script:
3278 * subst -nocommands $string
3279 * subst -novariables $string
3281 * Will (re)create the internal representation of the $string object
3284 typedef struct ScriptObj
3286 ScriptToken
*token
; /* Tokens array. */
3287 Jim_Obj
*fileNameObj
; /* Filename */
3288 int len
; /* Length of token[] */
3289 int substFlags
; /* flags used for the compilation of "subst" objects */
3290 int inUse
; /* Used to share a ScriptObj. Currently
3291 only used by Jim_EvalObj() as protection against
3292 shimmering of the currently evaluated object. */
3293 int firstline
; /* Line number of the first line */
3294 int linenr
; /* Error line number, if any */
3295 int missing
; /* Missing char if script failed to parse, (or space or backslash if OK) */
3298 static void JimSetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3299 static int JimParseCheckMissing(Jim_Interp
*interp
, int ch
);
3300 static ScriptObj
*JimGetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
3302 void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3305 struct ScriptObj
*script
= (void *)objPtr
->internalRep
.ptr
;
3307 if (--script
->inUse
!= 0)
3309 for (i
= 0; i
< script
->len
; i
++) {
3310 Jim_DecrRefCount(interp
, script
->token
[i
].objPtr
);
3312 Jim_Free(script
->token
);
3313 Jim_DecrRefCount(interp
, script
->fileNameObj
);
3317 void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
3319 JIM_NOTUSED(interp
);
3320 JIM_NOTUSED(srcPtr
);
3322 /* Just return a simple string. We don't try to preserve the source info
3323 * since in practice scripts are never duplicated
3325 dupPtr
->typePtr
= NULL
;
3328 /* A simple parse token.
3329 * As the script is parsed, the created tokens point into the script string rep.
3333 const char *token
; /* Pointer to the start of the token */
3334 int len
; /* Length of this token */
3335 int type
; /* Token type */
3336 int line
; /* Line number */
3339 /* A list of parsed tokens representing a script.
3340 * Tokens are added to this list as the script is parsed.
3341 * It grows as needed.
3345 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3346 ParseToken
*list
; /* Array of tokens */
3347 int size
; /* Current size of the list */
3348 int count
; /* Number of entries used */
3349 ParseToken static_list
[20]; /* Small initial token space to avoid allocation */
3352 static void ScriptTokenListInit(ParseTokenList
*tokenlist
)
3354 tokenlist
->list
= tokenlist
->static_list
;
3355 tokenlist
->size
= sizeof(tokenlist
->static_list
) / sizeof(ParseToken
);
3356 tokenlist
->count
= 0;
3359 static void ScriptTokenListFree(ParseTokenList
*tokenlist
)
3361 if (tokenlist
->list
!= tokenlist
->static_list
) {
3362 Jim_Free(tokenlist
->list
);
3367 * Adds the new token to the tokenlist.
3368 * The token has the given length, type and line number.
3369 * The token list is resized as necessary.
3371 static void ScriptAddToken(ParseTokenList
*tokenlist
, const char *token
, int len
, int type
,
3376 if (tokenlist
->count
== tokenlist
->size
) {
3377 /* Resize the list */
3378 tokenlist
->size
*= 2;
3379 if (tokenlist
->list
!= tokenlist
->static_list
) {
3381 Jim_Realloc(tokenlist
->list
, tokenlist
->size
* sizeof(*tokenlist
->list
));
3384 /* The list needs to become allocated */
3385 tokenlist
->list
= Jim_Alloc(tokenlist
->size
* sizeof(*tokenlist
->list
));
3386 memcpy(tokenlist
->list
, tokenlist
->static_list
,
3387 tokenlist
->count
* sizeof(*tokenlist
->list
));
3390 t
= &tokenlist
->list
[tokenlist
->count
++];
3397 /* Counts the number of adjoining non-separator tokens.
3399 * Returns -ve if the first token is the expansion
3400 * operator (in which case the count doesn't include
3403 static int JimCountWordTokens(struct ScriptObj
*script
, ParseToken
*t
)
3408 /* Is the first word {*} or {expand}? */
3409 if (t
->type
== JIM_TT_STR
&& !TOKEN_IS_SEP(t
[1].type
)) {
3410 if ((t
->len
== 1 && *t
->token
== '*') || (t
->len
== 6 && strncmp(t
->token
, "expand", 6) == 0)) {
3411 /* Create an expand token */
3416 if (script
->missing
== ' ') {
3417 /* This is a "extra characters after close-brace" error. Report the first error */
3418 script
->missing
= '}';
3419 script
->linenr
= t
[1].line
;
3424 /* Now count non-separator words */
3425 while (!TOKEN_IS_SEP(t
->type
)) {
3430 return count
* expand
;
3434 * Create a script/subst object from the given token.
3436 static Jim_Obj
*JimMakeScriptObj(Jim_Interp
*interp
, const ParseToken
*t
)
3440 if (t
->type
== JIM_TT_ESC
&& memchr(t
->token
, '\\', t
->len
) != NULL
) {
3441 /* Convert backlash escapes. The result will never be longer than the original */
3443 char *str
= Jim_Alloc(len
+ 1);
3444 len
= JimEscape(str
, t
->token
, len
);
3445 objPtr
= Jim_NewStringObjNoAlloc(interp
, str
, len
);
3448 /* XXX: For strict Tcl compatibility, JIM_TT_STR should replace <backslash><newline><whitespace>
3449 * with a single space.
3451 objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
3457 * Takes a tokenlist and creates the allocated list of script tokens
3458 * in script->token, of length script->len.
3460 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3463 * Also sets script->line to the line number of the first token
3465 static void ScriptObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3466 ParseTokenList
*tokenlist
)
3469 struct ScriptToken
*token
;
3470 /* Number of tokens so far for the current command */
3472 /* This is the first token for the current command */
3473 ScriptToken
*linefirst
;
3477 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3478 printf("==== Tokens ====\n");
3479 for (i
= 0; i
< tokenlist
->count
; i
++) {
3480 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
->list
[i
].line
, jim_tt_name(tokenlist
->list
[i
].type
),
3481 tokenlist
->list
[i
].len
, tokenlist
->list
[i
].token
);
3485 /* May need up to one extra script token for each EOL in the worst case */
3486 count
= tokenlist
->count
;
3487 for (i
= 0; i
< tokenlist
->count
; i
++) {
3488 if (tokenlist
->list
[i
].type
== JIM_TT_EOL
) {
3492 linenr
= script
->firstline
= tokenlist
->list
[0].line
;
3494 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
3496 /* This is the first token for the current command */
3497 linefirst
= token
++;
3499 for (i
= 0; i
< tokenlist
->count
; ) {
3500 /* Look ahead to find out how many tokens make up the next word */
3503 /* Skip any leading separators */
3504 while (tokenlist
->list
[i
].type
== JIM_TT_SEP
) {
3508 wordtokens
= JimCountWordTokens(script
, tokenlist
->list
+ i
);
3510 if (wordtokens
== 0) {
3511 /* None, so at end of line */
3513 linefirst
->type
= JIM_TT_LINE
;
3514 linefirst
->objPtr
= JimNewScriptLineObj(interp
, lineargs
, linenr
);
3515 Jim_IncrRefCount(linefirst
->objPtr
);
3517 /* Reset for new line */
3519 linefirst
= token
++;
3524 else if (wordtokens
!= 1) {
3525 /* More than 1, or {*}, so insert a WORD token */
3526 token
->type
= JIM_TT_WORD
;
3527 token
->objPtr
= Jim_NewIntObj(interp
, wordtokens
);
3528 Jim_IncrRefCount(token
->objPtr
);
3530 if (wordtokens
< 0) {
3531 /* Skip the expand token */
3533 wordtokens
= -wordtokens
- 1;
3538 if (lineargs
== 0) {
3539 /* First real token on the line, so record the line number */
3540 linenr
= tokenlist
->list
[i
].line
;
3544 /* Add each non-separator word token to the line */
3545 while (wordtokens
--) {
3546 const ParseToken
*t
= &tokenlist
->list
[i
++];
3548 token
->type
= t
->type
;
3549 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3550 Jim_IncrRefCount(token
->objPtr
);
3552 /* Every object is initially a string of type 'source', but the
3553 * internal type may be specialized during execution of the
3555 JimSetSourceInfo(interp
, token
->objPtr
, script
->fileNameObj
, t
->line
);
3560 if (lineargs
== 0) {
3564 script
->len
= token
- script
->token
;
3566 JimPanic((script
->len
>= count
, "allocated script array is too short"));
3568 #ifdef DEBUG_SHOW_SCRIPT
3569 printf("==== Script (%s) ====\n", Jim_String(script
->fileNameObj
));
3570 for (i
= 0; i
< script
->len
; i
++) {
3571 const ScriptToken
*t
= &script
->token
[i
];
3572 printf("[%2d] %s %s\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
3578 /* Parses the given string object to determine if it represents a complete script.
3580 * This is useful for interactive shells implementation, for [info complete].
3582 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
3583 * '{' on scripts incomplete missing one or more '}' to be balanced.
3584 * '[' on scripts incomplete missing one or more ']' to be balanced.
3585 * '"' on scripts incomplete missing a '"' char.
3586 * '\\' on scripts with a trailing backslash.
3588 * If the script is complete, 1 is returned, otherwise 0.
3590 * If the script has extra characters after a close brace, this still returns 1,
3591 * but sets *stateCharPtr to '}'
3592 * Evaluating the script will give the error "extra characters after close-brace".
3594 int Jim_ScriptIsComplete(Jim_Interp
*interp
, Jim_Obj
*scriptObj
, char *stateCharPtr
)
3596 ScriptObj
*script
= JimGetScript(interp
, scriptObj
);
3598 *stateCharPtr
= script
->missing
;
3600 return script
->missing
== ' ' || script
->missing
== '}';
3604 * Sets an appropriate error message for a missing script/expression terminator.
3606 * Returns JIM_ERR if 'ch' represents an unmatched/missing character.
3608 * Note that a trailing backslash is not considered to be an error.
3610 static int JimParseCheckMissing(Jim_Interp
*interp
, int ch
)
3620 msg
= "unmatched \"[\"";
3623 msg
= "missing close-brace";
3626 msg
= "extra characters after close-brace";
3630 msg
= "missing quote";
3634 Jim_SetResultString(interp
, msg
, -1);
3639 * Similar to ScriptObjAddTokens(), but for subst objects.
3641 static void SubstObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3642 ParseTokenList
*tokenlist
)
3645 struct ScriptToken
*token
;
3647 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * tokenlist
->count
);
3649 for (i
= 0; i
< tokenlist
->count
; i
++) {
3650 const ParseToken
*t
= &tokenlist
->list
[i
];
3652 /* Create a token for 't' */
3653 token
->type
= t
->type
;
3654 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3655 Jim_IncrRefCount(token
->objPtr
);
3662 /* This method takes the string representation of an object
3663 * as a Tcl script, and generates the pre-parsed internal representation
3666 * On parse error, sets an error message and returns JIM_ERR
3667 * (Note: the object is still converted to a script, even if an error occurs)
3669 static void JimSetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3672 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
3673 struct JimParserCtx parser
;
3674 struct ScriptObj
*script
;
3675 ParseTokenList tokenlist
;
3678 /* Try to get information about filename / line number */
3679 if (objPtr
->typePtr
== &sourceObjType
) {
3680 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
3683 /* Initially parse the script into tokens (in tokenlist) */
3684 ScriptTokenListInit(&tokenlist
);
3686 JimParserInit(&parser
, scriptText
, scriptTextLen
, line
);
3687 while (!parser
.eof
) {
3688 JimParseScript(&parser
);
3689 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
3693 /* Add a final EOF token */
3694 ScriptAddToken(&tokenlist
, scriptText
+ scriptTextLen
, 0, JIM_TT_EOF
, 0);
3696 /* Create the "real" script tokens from the parsed tokens */
3697 script
= Jim_Alloc(sizeof(*script
));
3698 memset(script
, 0, sizeof(*script
));
3700 if (objPtr
->typePtr
== &sourceObjType
) {
3701 script
->fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
3704 script
->fileNameObj
= interp
->emptyObj
;
3706 Jim_IncrRefCount(script
->fileNameObj
);
3707 script
->missing
= parser
.missing
.ch
;
3708 script
->linenr
= parser
.missing
.line
;
3710 ScriptObjAddTokens(interp
, script
, &tokenlist
);
3712 /* No longer need the token list */
3713 ScriptTokenListFree(&tokenlist
);
3715 /* Free the old internal rep and set the new one. */
3716 Jim_FreeIntRep(interp
, objPtr
);
3717 Jim_SetIntRepPtr(objPtr
, script
);
3718 objPtr
->typePtr
= &scriptObjType
;
3721 static void JimAddErrorToStack(Jim_Interp
*interp
, ScriptObj
*script
);
3724 * Returns the parsed script.
3725 * Note that if there is any possibility that the script is not valid,
3726 * call JimScriptValid() to check
3728 static ScriptObj
*JimGetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3730 if (objPtr
== interp
->emptyObj
) {
3731 /* Avoid converting emptyObj to a script. use nullScriptObj instead. */
3732 objPtr
= interp
->nullScriptObj
;
3735 if (objPtr
->typePtr
!= &scriptObjType
|| ((struct ScriptObj
*)Jim_GetIntRepPtr(objPtr
))->substFlags
) {
3736 JimSetScriptFromAny(interp
, objPtr
);
3739 return (ScriptObj
*)Jim_GetIntRepPtr(objPtr
);
3743 * Returns 1 if the script is valid (parsed ok), otherwise returns 0
3744 * and leaves an error message in the interp result.
3747 static int JimScriptValid(Jim_Interp
*interp
, ScriptObj
*script
)
3749 if (JimParseCheckMissing(interp
, script
->missing
) == JIM_ERR
) {
3750 JimAddErrorToStack(interp
, script
);
3757 /* -----------------------------------------------------------------------------
3759 * ---------------------------------------------------------------------------*/
3760 void Jim_InterpIncrProcEpoch(Jim_Interp
*interp
)
3762 interp
->procEpoch
++;
3764 /* Now discard all out-of-date Jim_Cmd entries */
3765 while (interp
->oldCmdCache
) {
3766 Jim_Cmd
*next
= interp
->oldCmdCache
->prevCmd
;
3767 Jim_Free(interp
->oldCmdCache
);
3768 interp
->oldCmdCache
= next
;
3770 interp
->oldCmdCacheSize
= 0;
3773 static void JimIncrCmdRefCount(Jim_Cmd
*cmdPtr
)
3778 static void JimDecrCmdRefCount(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
)
3780 if (--cmdPtr
->inUse
== 0) {
3781 if (cmdPtr
->isproc
) {
3782 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.argListObjPtr
);
3783 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.bodyObjPtr
);
3784 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.nsObj
);
3785 if (cmdPtr
->u
.proc
.staticVars
) {
3786 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3787 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3792 if (cmdPtr
->u
.native
.delProc
) {
3793 cmdPtr
->u
.native
.delProc(interp
, cmdPtr
->u
.native
.privData
);
3796 if (cmdPtr
->prevCmd
) {
3797 /* Delete any pushed command too */
3798 JimDecrCmdRefCount(interp
, cmdPtr
->prevCmd
);
3801 if (interp
->quitting
) {
3805 /* Preserve the structure with inUse = 0 so that
3806 * cached references will continue to work.
3807 * These will be discarding at the next procEpoch increment
3808 * or once 1000 have been accumulated.
3810 cmdPtr
->prevCmd
= interp
->oldCmdCache
;
3811 interp
->oldCmdCache
= cmdPtr
;
3812 if (++interp
->oldCmdCacheSize
>= 1000) {
3813 Jim_InterpIncrProcEpoch(interp
);
3819 /* Variables HashTable Type.
3821 * Keys are dynamically allocated strings, Values are Jim_Var structures.
3823 static void JimVariablesHTValDestructor(void *interp
, void *val
)
3825 Jim_DecrRefCount(interp
, ((Jim_Var
*)val
)->objPtr
);
3829 static unsigned int JimObjectHTHashFunction(const void *key
)
3832 const char *str
= Jim_GetString((Jim_Obj
*)key
, &len
);
3833 return Jim_GenHashFunction((const unsigned char *)str
, len
);
3836 static int JimObjectHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
3838 return Jim_StringEqObj((Jim_Obj
*)key1
, (Jim_Obj
*)key2
);
3841 static void *JimObjectHTKeyValDup(void *privdata
, const void *val
)
3843 Jim_IncrRefCount((Jim_Obj
*)val
);
3847 static void JimObjectHTKeyValDestructor(void *interp
, void *val
)
3849 Jim_DecrRefCount(interp
, (Jim_Obj
*)val
);
3853 static const Jim_HashTableType JimVariablesHashTableType
= {
3854 JimObjectHTHashFunction
, /* hash function */
3855 JimObjectHTKeyValDup
, /* key dup */
3857 JimObjectHTKeyCompare
, /* key compare */
3858 JimObjectHTKeyValDestructor
, /* key destructor */
3859 JimVariablesHTValDestructor
/* val destructor */
3862 /* Commands HashTable Type.
3864 * Keys are Jim Objects where any leading namespace qualifier
3865 * is ignored. Values are Jim_Cmd structures.
3869 * Like Jim_GetString() but strips any leading namespace qualifier.
3871 static const char *Jim_GetStringNoQualifier(Jim_Obj
*objPtr
, int *length
)
3874 const char *str
= Jim_GetString(objPtr
, &len
);
3875 if (len
>= 2 && str
[0] == ':' && str
[1] == ':') {
3876 while (len
&& *str
== ':') {
3885 static unsigned int JimCommandsHT_HashFunction(const void *key
)
3888 const char *str
= Jim_GetStringNoQualifier((Jim_Obj
*)key
, &len
);
3889 return Jim_GenHashFunction((const unsigned char *)str
, len
);
3892 static int JimCommandsHT_KeyCompare(void *privdata
, const void *key1
, const void *key2
)
3895 const char *str1
= Jim_GetStringNoQualifier((Jim_Obj
*)key1
, &len1
);
3896 const char *str2
= Jim_GetStringNoQualifier((Jim_Obj
*)key2
, &len2
);
3897 return len1
== len2
&& memcmp(str1
, str2
, len1
) == 0;
3900 static void JimCommandsHT_ValDestructor(void *interp
, void *val
)
3902 JimDecrCmdRefCount(interp
, val
);
3905 static const Jim_HashTableType JimCommandsHashTableType
= {
3906 JimCommandsHT_HashFunction
, /* hash function */
3907 JimObjectHTKeyValDup
, /* key dup */
3909 JimCommandsHT_KeyCompare
, /* key compare */
3910 JimObjectHTKeyValDestructor
, /* key destructor */
3911 JimCommandsHT_ValDestructor
/* val destructor */
3914 /* ------------------------- Commands related functions --------------------- */
3917 * If nameObjPtr starts with "::", returns it.
3918 * Otherwise returns a new object with nameObjPtr prefixed with "::".
3919 * In this case, decrements the ref count of nameObjPtr.
3921 Jim_Obj
*Jim_MakeGlobalNamespaceName(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
)
3923 #ifdef jim_ext_namespace
3926 const char *name
= Jim_String(nameObjPtr
);
3927 if (name
[0] == ':' && name
[1] == ':') {
3930 Jim_IncrRefCount(nameObjPtr
);
3931 resultObj
= Jim_NewStringObj(interp
, "::", -1);
3932 Jim_AppendObj(interp
, resultObj
, nameObjPtr
);
3933 Jim_DecrRefCount(interp
, nameObjPtr
);
3942 * If the name in objPtr is not fully qualified, and a non-global namespace
3943 * is in effect, qualifies the name with the current namespace and returns the new name.
3944 * Otherwise returns objPtr.
3946 * In either case the ref count is incremented and should be decremented by the caller.
3947 * with Jim_DecrRefCount()
3949 static Jim_Obj
*JimQualifyName(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3951 #ifdef jim_ext_namespace
3952 if (Jim_Length(interp
->framePtr
->nsObj
)) {
3954 const char *name
= Jim_GetString(objPtr
, &len
);
3955 if (len
< 2 || name
[0] != ':' || name
[1] != ':') {
3956 /* OK. Need to qualify this name */
3957 objPtr
= Jim_DuplicateObj(interp
, interp
->framePtr
->nsObj
);
3958 Jim_AppendStrings(interp
, objPtr
, "::", name
, NULL
);
3962 Jim_IncrRefCount(objPtr
);
3967 * Note that nameObjPtr must already be namespace qualified.
3969 static int JimCreateCommand(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Cmd
*cmd
)
3971 /* It may already exist, so we try to delete the old one.
3972 * Note that reference count means that it won't be deleted yet if
3973 * it exists in the call stack.
3975 * BUT, if 'local' is in force, instead of deleting the existing
3976 * proc, we stash a reference to the old proc here.
3978 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->commands
, nameObjPtr
);
3980 /* There was an old cmd with the same name,
3981 * so this requires a 'proc epoch' update. */
3983 /* If a procedure with the same name didn't exist there is no need
3984 * to increment the 'proc epoch' because creation of a new procedure
3985 * can never affect existing cached commands. We don't do
3986 * negative caching. */
3987 //Jim_InterpIncrProcEpoch(interp);
3990 if (he
&& interp
->local
) {
3991 /* Push this command over the top of the previous one */
3992 cmd
->prevCmd
= Jim_GetHashEntryVal(he
);
3993 Jim_SetHashVal(&interp
->commands
, he
, cmd
);
3994 /* Need to increment the proc epoch here so that the new command will be used */
3995 Jim_InterpIncrProcEpoch(interp
);
3999 /* Replace the existing command */
4000 Jim_DeleteHashEntry(&interp
->commands
, nameObjPtr
);
4003 Jim_AddHashEntry(&interp
->commands
, nameObjPtr
, cmd
);
4008 int Jim_CreateCommandObj(Jim_Interp
*interp
, Jim_Obj
*cmdNameObj
,
4009 Jim_CmdProc
*cmdProc
, void *privData
, Jim_DelCmdProc
*delProc
)
4011 Jim_Cmd
*cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
4013 /* Store the new details for this command */
4014 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
4016 cmdPtr
->u
.native
.delProc
= delProc
;
4017 cmdPtr
->u
.native
.cmdProc
= cmdProc
;
4018 cmdPtr
->u
.native
.privData
= privData
;
4020 JimCreateCommand(interp
, cmdNameObj
, cmdPtr
);
4026 int Jim_CreateCommand(Jim_Interp
*interp
, const char *cmdNameStr
,
4027 Jim_CmdProc
*cmdProc
, void *privData
, Jim_DelCmdProc
*delProc
)
4029 return Jim_CreateCommandObj(interp
, Jim_NewStringObj(interp
, cmdNameStr
, -1), cmdProc
, privData
, delProc
);
4032 static int JimCreateProcedureStatics(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
, Jim_Obj
*staticsListObjPtr
)
4036 len
= Jim_ListLength(interp
, staticsListObjPtr
);
4041 cmdPtr
->u
.proc
.staticVars
= Jim_Alloc(sizeof(Jim_HashTable
));
4042 Jim_InitHashTable(cmdPtr
->u
.proc
.staticVars
, &JimVariablesHashTableType
, interp
);
4043 for (i
= 0; i
< len
; i
++) {
4044 Jim_Obj
*objPtr
, *initObjPtr
, *nameObjPtr
;
4048 objPtr
= Jim_ListGetIndex(interp
, staticsListObjPtr
, i
);
4049 /* Check if it's composed of two elements. */
4050 subLen
= Jim_ListLength(interp
, objPtr
);
4051 if (subLen
== 1 || subLen
== 2) {
4052 /* Try to get the variable value from the current
4054 nameObjPtr
= Jim_ListGetIndex(interp
, objPtr
, 0);
4056 initObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, JIM_NONE
);
4057 if (initObjPtr
== NULL
) {
4058 Jim_SetResultFormatted(interp
,
4059 "variable for initialization of static \"%#s\" not found in the local context",
4065 initObjPtr
= Jim_ListGetIndex(interp
, objPtr
, 1);
4068 varPtr
= Jim_Alloc(sizeof(*varPtr
));
4069 varPtr
->objPtr
= initObjPtr
;
4070 Jim_IncrRefCount(initObjPtr
);
4071 varPtr
->linkFramePtr
= NULL
;
4072 if (JimSetNewVariable(cmdPtr
->u
.proc
.staticVars
, nameObjPtr
, varPtr
) != JIM_OK
) {
4073 Jim_SetResultFormatted(interp
,
4074 "static variable name \"%#s\" duplicated in statics list", nameObjPtr
);
4075 Jim_DecrRefCount(interp
, initObjPtr
);
4081 Jim_SetResultFormatted(interp
, "too many fields in static specifier \"%#s\"",
4089 /* memrchr() is not standard */
4090 static const char *Jim_memrchr(const char *p
, int c
, int len
)
4093 for (i
= len
; i
> 0; i
--) {
4102 * If the command is a proc, sets/updates the cached namespace (nsObj)
4103 * based on the command name.
4105 static void JimUpdateProcNamespace(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
, Jim_Obj
*nameObjPtr
)
4107 #ifdef jim_ext_namespace
4108 if (cmdPtr
->isproc
) {
4110 const char *cmdname
= Jim_GetStringNoQualifier(nameObjPtr
, &len
);
4111 /* XXX: Really need JimNamespaceSplit() */
4112 const char *pt
= Jim_memrchr(cmdname
, ':', len
);
4113 if (pt
&& pt
!= cmdname
&& pt
[-1] == ':') {
4115 /* Now pt points to the base name .e.g. ::abc::def::ghi points to ghi
4116 * while cmdname points to abc
4118 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.nsObj
);
4119 cmdPtr
->u
.proc
.nsObj
= Jim_NewStringObj(interp
, cmdname
, pt
- cmdname
- 2);
4120 Jim_IncrRefCount(cmdPtr
->u
.proc
.nsObj
);
4122 Jim_Obj
*tempObj
= Jim_NewStringObj(interp
, pt
, len
- (pt
- cmdname
));
4123 if (Jim_FindHashEntry(&interp
->commands
, tempObj
)) {
4124 /* This command shadows a global command, so a proc epoch update is required */
4125 Jim_InterpIncrProcEpoch(interp
);
4127 Jim_FreeNewObj(interp
, tempObj
);
4133 static Jim_Cmd
*JimCreateProcedureCmd(Jim_Interp
*interp
, Jim_Obj
*argListObjPtr
,
4134 Jim_Obj
*staticsListObjPtr
, Jim_Obj
*bodyObjPtr
, Jim_Obj
*nsObj
)
4140 argListLen
= Jim_ListLength(interp
, argListObjPtr
);
4142 /* Allocate space for both the command pointer and the arg list */
4143 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
) + sizeof(struct Jim_ProcArg
) * argListLen
);
4144 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
4147 cmdPtr
->u
.proc
.argListObjPtr
= argListObjPtr
;
4148 cmdPtr
->u
.proc
.argListLen
= argListLen
;
4149 cmdPtr
->u
.proc
.bodyObjPtr
= bodyObjPtr
;
4150 cmdPtr
->u
.proc
.argsPos
= -1;
4151 cmdPtr
->u
.proc
.arglist
= (struct Jim_ProcArg
*)(cmdPtr
+ 1);
4152 cmdPtr
->u
.proc
.nsObj
= nsObj
? nsObj
: interp
->emptyObj
;
4153 Jim_IncrRefCount(argListObjPtr
);
4154 Jim_IncrRefCount(bodyObjPtr
);
4155 Jim_IncrRefCount(cmdPtr
->u
.proc
.nsObj
);
4157 /* Create the statics hash table. */
4158 if (staticsListObjPtr
&& JimCreateProcedureStatics(interp
, cmdPtr
, staticsListObjPtr
) != JIM_OK
) {
4162 /* Parse the args out into arglist, validating as we go */
4163 /* Examine the argument list for default parameters and 'args' */
4164 for (i
= 0; i
< argListLen
; i
++) {
4166 Jim_Obj
*nameObjPtr
;
4167 Jim_Obj
*defaultObjPtr
;
4170 /* Examine a parameter */
4171 argPtr
= Jim_ListGetIndex(interp
, argListObjPtr
, i
);
4172 len
= Jim_ListLength(interp
, argPtr
);
4174 Jim_SetResultString(interp
, "argument with no name", -1);
4176 JimDecrCmdRefCount(interp
, cmdPtr
);
4180 Jim_SetResultFormatted(interp
, "too many fields in argument specifier \"%#s\"", argPtr
);
4185 /* Optional parameter */
4186 nameObjPtr
= Jim_ListGetIndex(interp
, argPtr
, 0);
4187 defaultObjPtr
= Jim_ListGetIndex(interp
, argPtr
, 1);
4190 /* Required parameter */
4191 nameObjPtr
= argPtr
;
4192 defaultObjPtr
= NULL
;
4196 if (Jim_CompareStringImmediate(interp
, nameObjPtr
, "args")) {
4197 if (cmdPtr
->u
.proc
.argsPos
>= 0) {
4198 Jim_SetResultString(interp
, "'args' specified more than once", -1);
4201 cmdPtr
->u
.proc
.argsPos
= i
;
4205 cmdPtr
->u
.proc
.optArity
++;
4208 cmdPtr
->u
.proc
.reqArity
++;
4212 cmdPtr
->u
.proc
.arglist
[i
].nameObjPtr
= nameObjPtr
;
4213 cmdPtr
->u
.proc
.arglist
[i
].defaultObjPtr
= defaultObjPtr
;
4219 int Jim_DeleteCommand(Jim_Interp
*interp
, Jim_Obj
*nameObj
)
4223 nameObj
= JimQualifyName(interp
, nameObj
);
4225 if (Jim_DeleteHashEntry(&interp
->commands
, nameObj
) == JIM_ERR
) {
4226 Jim_SetResultFormatted(interp
, "can't delete \"%#s\": command doesn't exist", nameObj
);
4229 Jim_DecrRefCount(interp
, nameObj
);
4234 int Jim_RenameCommand(Jim_Interp
*interp
, Jim_Obj
*oldNameObj
, Jim_Obj
*newNameObj
)
4240 if (Jim_Length(newNameObj
) == 0) {
4241 return Jim_DeleteCommand(interp
, oldNameObj
);
4244 /* each name may need to have the current namespace added to it */
4246 oldNameObj
= JimQualifyName(interp
, oldNameObj
);
4247 newNameObj
= JimQualifyName(interp
, newNameObj
);
4249 /* Does it exist? */
4250 he
= Jim_FindHashEntry(&interp
->commands
, oldNameObj
);
4252 Jim_SetResultFormatted(interp
, "can't rename \"%#s\": command doesn't exist", oldNameObj
);
4254 else if (Jim_FindHashEntry(&interp
->commands
, newNameObj
)) {
4255 Jim_SetResultFormatted(interp
, "can't rename to \"%#s\": command already exists", newNameObj
);
4258 cmdPtr
= Jim_GetHashEntryVal(he
);
4259 if (cmdPtr
->prevCmd
) {
4260 /* If the command replaced another command with 'local', renaming it
4261 * would break the usage of upcall, so don't allow it.
4263 Jim_SetResultFormatted(interp
, "can't rename local command \"%#s\"", oldNameObj
);
4266 /* Add the new name first */
4267 JimIncrCmdRefCount(cmdPtr
);
4268 JimUpdateProcNamespace(interp
, cmdPtr
, newNameObj
);
4269 Jim_AddHashEntry(&interp
->commands
, newNameObj
, cmdPtr
);
4271 /* Now remove the old name */
4272 Jim_DeleteHashEntry(&interp
->commands
, oldNameObj
);
4274 /* Increment the epoch */
4275 Jim_InterpIncrProcEpoch(interp
);
4281 Jim_DecrRefCount(interp
, oldNameObj
);
4282 Jim_DecrRefCount(interp
, newNameObj
);
4287 /* -----------------------------------------------------------------------------
4289 * ---------------------------------------------------------------------------*/
4291 static void FreeCommandInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4293 Jim_DecrRefCount(interp
, objPtr
->internalRep
.cmdValue
.nsObj
);
4296 static void DupCommandInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4298 dupPtr
->internalRep
.cmdValue
= srcPtr
->internalRep
.cmdValue
;
4299 dupPtr
->typePtr
= srcPtr
->typePtr
;
4300 Jim_IncrRefCount(dupPtr
->internalRep
.cmdValue
.nsObj
);
4303 static const Jim_ObjType commandObjType
= {
4305 FreeCommandInternalRep
,
4306 DupCommandInternalRep
,
4308 JIM_TYPE_REFERENCES
,
4311 /* This function returns the command structure for the command name
4312 * stored in objPtr. It specializes the objPtr to contain
4313 * cached info instead of performing the lookup into the hash table
4314 * every time. The information cached may not be up-to-date, in this
4315 * case the lookup is performed and the cache updated.
4317 * Respects the 'upcall' setting.
4319 Jim_Cmd
*Jim_GetCommand(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4323 /* In order to be valid, the proc epoch must match and
4324 * the lookup must have occurred in the same namespace
4326 if (objPtr
->typePtr
== &commandObjType
4327 && objPtr
->internalRep
.cmdValue
.procEpoch
== interp
->procEpoch
4328 #ifdef jim_ext_namespace
4329 && Jim_StringEqObj(objPtr
->internalRep
.cmdValue
.nsObj
, interp
->framePtr
->nsObj
)
4331 && objPtr
->internalRep
.cmdValue
.cmdPtr
->inUse
) {
4332 /* Cached value is valid */
4333 cmd
= objPtr
->internalRep
.cmdValue
.cmdPtr
;
4336 Jim_Obj
*qualifiedNameObj
= JimQualifyName(interp
, objPtr
);
4337 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->commands
, qualifiedNameObj
);
4338 #ifdef jim_ext_namespace
4339 if (he
== NULL
&& Jim_Length(interp
->framePtr
->nsObj
)) {
4340 he
= Jim_FindHashEntry(&interp
->commands
, objPtr
);
4344 if (flags
& JIM_ERRMSG
) {
4345 Jim_SetResultFormatted(interp
, "invalid command name \"%#s\"", objPtr
);
4347 Jim_DecrRefCount(interp
, qualifiedNameObj
);
4350 cmd
= Jim_GetHashEntryVal(he
);
4352 /* Free the old internal rep and set the new one. */
4353 Jim_FreeIntRep(interp
, objPtr
);
4354 objPtr
->typePtr
= &commandObjType
;
4355 objPtr
->internalRep
.cmdValue
.procEpoch
= interp
->procEpoch
;
4356 objPtr
->internalRep
.cmdValue
.cmdPtr
= cmd
;
4357 objPtr
->internalRep
.cmdValue
.nsObj
= interp
->framePtr
->nsObj
;
4358 Jim_IncrRefCount(interp
->framePtr
->nsObj
);
4359 Jim_DecrRefCount(interp
, qualifiedNameObj
);
4361 while (cmd
->u
.proc
.upcall
) {
4367 /* -----------------------------------------------------------------------------
4369 * ---------------------------------------------------------------------------*/
4371 /* -----------------------------------------------------------------------------
4373 * ---------------------------------------------------------------------------*/
4375 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
4377 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
4379 static const Jim_ObjType variableObjType
= {
4384 JIM_TYPE_REFERENCES
,
4387 /* This method should be called only by the variable API.
4388 * It returns JIM_OK on success (variable already exists),
4389 * JIM_ERR if it does not exist, JIM_DICT_SUGAR if it's not
4390 * a variable name, but syntax glue for [dict] i.e. the last
4391 * character is ')' */
4392 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
4394 const char *varName
;
4395 Jim_CallFrame
*framePtr
;
4400 /* Check if the object is already an uptodate variable */
4401 if (objPtr
->typePtr
== &variableObjType
) {
4402 framePtr
= objPtr
->internalRep
.varValue
.global
? interp
->topFramePtr
: interp
->framePtr
;
4403 if (objPtr
->internalRep
.varValue
.callFrameId
== framePtr
->id
) {
4407 /* Need to re-resolve the variable in the updated callframe */
4409 else if (objPtr
->typePtr
== &dictSubstObjType
) {
4410 return JIM_DICT_SUGAR
;
4413 varName
= Jim_GetString(objPtr
, &len
);
4415 /* Make sure it's not syntax glue to get/set dict. */
4416 if (len
&& varName
[len
- 1] == ')' && strchr(varName
, '(') != NULL
) {
4417 return JIM_DICT_SUGAR
;
4420 if (varName
[0] == ':' && varName
[1] == ':') {
4421 while (*varName
== ':') {
4426 framePtr
= interp
->topFramePtr
;
4427 /* XXX should use length */
4428 Jim_Obj
*tempObj
= Jim_NewStringObj(interp
, varName
, len
);
4429 var
= JimFindVariable(&framePtr
->vars
, tempObj
);
4430 Jim_FreeNewObj(interp
, tempObj
);
4434 framePtr
= interp
->framePtr
;
4435 /* Resolve this name in the variables hash table */
4436 var
= JimFindVariable(&framePtr
->vars
, objPtr
);
4437 if (var
== NULL
&& framePtr
->staticVars
) {
4438 /* Try with static vars. */
4439 var
= JimFindVariable(framePtr
->staticVars
, objPtr
);
4447 /* Free the old internal repr and set the new one. */
4448 Jim_FreeIntRep(interp
, objPtr
);
4449 objPtr
->typePtr
= &variableObjType
;
4450 objPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
4451 objPtr
->internalRep
.varValue
.varPtr
= var
;
4452 objPtr
->internalRep
.varValue
.global
= global
;
4456 /* -------------------- Variables related functions ------------------------- */
4457 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, Jim_Obj
*valObjPtr
);
4458 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, int flags
);
4460 static int JimSetNewVariable(Jim_HashTable
*ht
, Jim_Obj
*nameObjPtr
, Jim_Var
*var
)
4462 return Jim_AddHashEntry(ht
, nameObjPtr
, var
);
4465 static Jim_Var
*JimFindVariable(Jim_HashTable
*ht
, Jim_Obj
*nameObjPtr
)
4467 Jim_HashEntry
*he
= Jim_FindHashEntry(ht
, nameObjPtr
);
4469 return (Jim_Var
*)Jim_GetHashEntryVal(he
);
4474 static int JimUnsetVariable(Jim_HashTable
*ht
, Jim_Obj
*nameObjPtr
)
4476 return Jim_DeleteHashEntry(ht
, nameObjPtr
);
4479 static Jim_Var
*JimCreateVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
4482 Jim_CallFrame
*framePtr
;
4486 /* New variable to create */
4487 Jim_Var
*var
= Jim_Alloc(sizeof(*var
));
4489 var
->objPtr
= valObjPtr
;
4490 Jim_IncrRefCount(valObjPtr
);
4491 var
->linkFramePtr
= NULL
;
4493 name
= Jim_GetString(nameObjPtr
, &len
);
4494 if (name
[0] == ':' && name
[1] == ':') {
4495 while (*name
== ':') {
4499 framePtr
= interp
->topFramePtr
;
4501 JimSetNewVariable(&framePtr
->vars
, Jim_NewStringObj(interp
, name
, len
), var
);
4504 framePtr
= interp
->framePtr
;
4506 JimSetNewVariable(&framePtr
->vars
, nameObjPtr
, var
);
4509 /* Make the object int rep a variable */
4510 Jim_FreeIntRep(interp
, nameObjPtr
);
4511 nameObjPtr
->typePtr
= &variableObjType
;
4512 nameObjPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
4513 nameObjPtr
->internalRep
.varValue
.varPtr
= var
;
4514 nameObjPtr
->internalRep
.varValue
.global
= global
;
4519 /* For now that's dummy. Variables lookup should be optimized
4520 * in many ways, with caching of lookups, and possibly with
4521 * a table of pre-allocated vars in every CallFrame for local vars.
4522 * All the caching should also have an 'epoch' mechanism similar
4523 * to the one used by Tcl for procedures lookup caching. */
4526 * Set the variable nameObjPtr to value valObjptr.
4528 int Jim_SetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
4533 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4534 case JIM_DICT_SUGAR
:
4535 return JimDictSugarSet(interp
, nameObjPtr
, valObjPtr
);
4538 JimCreateVariable(interp
, nameObjPtr
, valObjPtr
);
4542 var
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4543 if (var
->linkFramePtr
== NULL
) {
4544 Jim_IncrRefCount(valObjPtr
);
4545 Jim_DecrRefCount(interp
, var
->objPtr
);
4546 var
->objPtr
= valObjPtr
;
4548 else { /* Else handle the link */
4549 Jim_CallFrame
*savedCallFrame
;
4551 savedCallFrame
= interp
->framePtr
;
4552 interp
->framePtr
= var
->linkFramePtr
;
4553 err
= Jim_SetVariable(interp
, var
->objPtr
, valObjPtr
);
4554 interp
->framePtr
= savedCallFrame
;
4562 int Jim_SetVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4564 Jim_Obj
*nameObjPtr
;
4567 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4568 Jim_IncrRefCount(nameObjPtr
);
4569 result
= Jim_SetVariable(interp
, nameObjPtr
, objPtr
);
4570 Jim_DecrRefCount(interp
, nameObjPtr
);
4574 int Jim_SetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4576 Jim_CallFrame
*savedFramePtr
;
4579 savedFramePtr
= interp
->framePtr
;
4580 interp
->framePtr
= interp
->topFramePtr
;
4581 result
= Jim_SetVariableStr(interp
, name
, objPtr
);
4582 interp
->framePtr
= savedFramePtr
;
4586 int Jim_SetVariableStrWithStr(Jim_Interp
*interp
, const char *name
, const char *val
)
4591 valObjPtr
= Jim_NewStringObj(interp
, val
, -1);
4592 Jim_IncrRefCount(valObjPtr
);
4593 result
= Jim_SetVariableStr(interp
, name
, valObjPtr
);
4594 Jim_DecrRefCount(interp
, valObjPtr
);
4598 int Jim_SetVariableLink(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
4599 Jim_Obj
*targetNameObjPtr
, Jim_CallFrame
*targetCallFrame
)
4601 const char *varName
;
4602 const char *targetName
;
4603 Jim_CallFrame
*framePtr
;
4608 /* Check for an existing variable or link */
4609 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4610 case JIM_DICT_SUGAR
:
4611 /* XXX: This message seem unnecessarily verbose, but it matches Tcl */
4612 Jim_SetResultFormatted(interp
, "bad variable name \"%#s\": upvar won't create a scalar variable that looks like an array element", nameObjPtr
);
4616 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4618 if (varPtr
->linkFramePtr
== NULL
) {
4619 Jim_SetResultFormatted(interp
, "variable \"%#s\" already exists", nameObjPtr
);
4623 /* It exists, but is a link, so first delete the link */
4624 varPtr
->linkFramePtr
= NULL
;
4628 /* Resolve the call frames for both variables */
4629 /* XXX: SetVariableFromAny() already did this! */
4630 varName
= Jim_GetString(nameObjPtr
, &varnamelen
);
4632 if (varName
[0] == ':' && varName
[1] == ':') {
4633 while (*varName
== ':') {
4637 /* Linking a global var does nothing */
4638 framePtr
= interp
->topFramePtr
;
4641 framePtr
= interp
->framePtr
;
4644 targetName
= Jim_GetString(targetNameObjPtr
, &len
);
4645 if (targetName
[0] == ':' && targetName
[1] == ':') {
4646 while (*targetName
== ':') {
4650 targetNameObjPtr
= Jim_NewStringObj(interp
, targetName
, len
);
4651 targetCallFrame
= interp
->topFramePtr
;
4653 Jim_IncrRefCount(targetNameObjPtr
);
4655 if (framePtr
->level
< targetCallFrame
->level
) {
4656 Jim_SetResultFormatted(interp
,
4657 "bad variable name \"%#s\": upvar won't create namespace variable that refers to procedure variable",
4659 Jim_DecrRefCount(interp
, targetNameObjPtr
);
4663 /* Check for cycles. */
4664 if (framePtr
== targetCallFrame
) {
4665 Jim_Obj
*objPtr
= targetNameObjPtr
;
4667 /* Cycles are only possible with 'uplevel 0' */
4669 if (Jim_Length(objPtr
) == varnamelen
&& memcmp(Jim_String(objPtr
), varName
, varnamelen
) == 0) {
4670 Jim_SetResultString(interp
, "can't upvar from variable to itself", -1);
4671 Jim_DecrRefCount(interp
, targetNameObjPtr
);
4674 if (SetVariableFromAny(interp
, objPtr
) != JIM_OK
)
4676 varPtr
= objPtr
->internalRep
.varValue
.varPtr
;
4677 if (varPtr
->linkFramePtr
!= targetCallFrame
)
4679 objPtr
= varPtr
->objPtr
;
4683 /* Perform the binding */
4684 Jim_SetVariable(interp
, nameObjPtr
, targetNameObjPtr
);
4685 /* We are now sure 'nameObjPtr' type is variableObjType */
4686 nameObjPtr
->internalRep
.varValue
.varPtr
->linkFramePtr
= targetCallFrame
;
4687 Jim_DecrRefCount(interp
, targetNameObjPtr
);
4691 /* Return the Jim_Obj pointer associated with a variable name,
4692 * or NULL if the variable was not found in the current context.
4693 * The same optimization discussed in the comment to the
4694 * 'SetVariable' function should apply here.
4696 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4697 * in a dictionary which is shared, the array variable value is duplicated first.
4698 * This allows the array element to be updated (e.g. append, lappend) without
4699 * affecting other references to the dictionary.
4701 Jim_Obj
*Jim_GetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4703 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4705 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4707 if (varPtr
->linkFramePtr
== NULL
) {
4708 return varPtr
->objPtr
;
4713 /* The variable is a link? Resolve it. */
4714 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
4716 interp
->framePtr
= varPtr
->linkFramePtr
;
4717 objPtr
= Jim_GetVariable(interp
, varPtr
->objPtr
, flags
);
4718 interp
->framePtr
= savedCallFrame
;
4722 /* Error, so fall through to the error message */
4727 case JIM_DICT_SUGAR
:
4728 /* [dict] syntax sugar. */
4729 return JimDictSugarGet(interp
, nameObjPtr
, flags
);
4731 if (flags
& JIM_ERRMSG
) {
4732 Jim_SetResultFormatted(interp
, "can't read \"%#s\": no such variable", nameObjPtr
);
4737 Jim_Obj
*Jim_GetGlobalVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4739 Jim_CallFrame
*savedFramePtr
;
4742 savedFramePtr
= interp
->framePtr
;
4743 interp
->framePtr
= interp
->topFramePtr
;
4744 objPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4745 interp
->framePtr
= savedFramePtr
;
4750 Jim_Obj
*Jim_GetVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4752 Jim_Obj
*nameObjPtr
, *varObjPtr
;
4754 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4755 Jim_IncrRefCount(nameObjPtr
);
4756 varObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4757 Jim_DecrRefCount(interp
, nameObjPtr
);
4761 Jim_Obj
*Jim_GetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4763 Jim_CallFrame
*savedFramePtr
;
4766 savedFramePtr
= interp
->framePtr
;
4767 interp
->framePtr
= interp
->topFramePtr
;
4768 objPtr
= Jim_GetVariableStr(interp
, name
, flags
);
4769 interp
->framePtr
= savedFramePtr
;
4774 /* Unset a variable.
4775 * Note: On success unset invalidates all the (cached) variable objects
4776 * by incrementing callFrameEpoch
4778 int Jim_UnsetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4782 Jim_CallFrame
*framePtr
;
4784 retval
= SetVariableFromAny(interp
, nameObjPtr
);
4785 if (retval
== JIM_DICT_SUGAR
) {
4786 /* [dict] syntax sugar. */
4787 return JimDictSugarSet(interp
, nameObjPtr
, NULL
);
4789 else if (retval
== JIM_OK
) {
4790 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4792 /* If it's a link call UnsetVariable recursively */
4793 if (varPtr
->linkFramePtr
) {
4794 framePtr
= interp
->framePtr
;
4795 interp
->framePtr
= varPtr
->linkFramePtr
;
4796 retval
= Jim_UnsetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
4797 interp
->framePtr
= framePtr
;
4800 if (nameObjPtr
->internalRep
.varValue
.global
) {
4802 const char *name
= Jim_GetString(nameObjPtr
, &len
);
4803 while (*name
== ':') {
4807 framePtr
= interp
->topFramePtr
;
4808 Jim_Obj
*tempObj
= Jim_NewStringObj(interp
, name
, len
);
4809 retval
= JimUnsetVariable(&framePtr
->vars
, tempObj
);
4810 Jim_FreeNewObj(interp
, tempObj
);
4813 framePtr
= interp
->framePtr
;
4814 retval
= JimUnsetVariable(&framePtr
->vars
, nameObjPtr
);
4817 if (retval
== JIM_OK
) {
4818 /* Change the callframe id, invalidating var lookup caching */
4819 framePtr
->id
= interp
->callFrameEpoch
++;
4823 if (retval
!= JIM_OK
&& (flags
& JIM_ERRMSG
)) {
4824 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such variable", nameObjPtr
);
4829 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4831 /* Given a variable name for [dict] operation syntax sugar,
4832 * this function returns two objects, the first with the name
4833 * of the variable to set, and the second with the respective key.
4834 * For example "foo(bar)" will return objects with string repr. of
4837 * The returned objects have refcount = 1. The function can't fail. */
4838 static void JimDictSugarParseVarKey(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
4839 Jim_Obj
**varPtrPtr
, Jim_Obj
**keyPtrPtr
)
4841 const char *str
, *p
;
4843 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4845 str
= Jim_GetString(objPtr
, &len
);
4847 p
= strchr(str
, '(');
4848 JimPanic((p
== NULL
, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str
));
4850 varObjPtr
= Jim_NewStringObj(interp
, str
, p
- str
);
4853 keyLen
= (str
+ len
) - p
;
4854 if (str
[len
- 1] == ')') {
4858 /* Create the objects with the variable name and key. */
4859 keyObjPtr
= Jim_NewStringObj(interp
, p
, keyLen
);
4861 Jim_IncrRefCount(varObjPtr
);
4862 Jim_IncrRefCount(keyObjPtr
);
4863 *varPtrPtr
= varObjPtr
;
4864 *keyPtrPtr
= keyObjPtr
;
4867 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4868 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4869 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*valObjPtr
)
4873 SetDictSubstFromAny(interp
, objPtr
);
4875 err
= Jim_SetDictKeysVector(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4876 &objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, 1, valObjPtr
, JIM_MUSTEXIST
);
4878 if (err
== JIM_OK
) {
4879 /* Don't keep an extra ref to the result */
4880 Jim_SetEmptyResult(interp
);
4884 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4885 if (Jim_GetVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
, JIM_NONE
)) {
4886 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such element in array",
4891 /* Make the error more informative and Tcl-compatible */
4892 Jim_SetResultFormatted(interp
, "can't %s \"%#s\": variable isn't array",
4893 (valObjPtr
? "set" : "unset"), objPtr
);
4899 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4901 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4902 * and stored back to the variable before expansion.
4904 static Jim_Obj
*JimDictExpandArrayVariable(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
,
4905 Jim_Obj
*keyObjPtr
, int flags
)
4907 Jim_Obj
*dictObjPtr
;
4908 Jim_Obj
*resObjPtr
= NULL
;
4911 dictObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
4916 ret
= Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4917 if (ret
!= JIM_OK
) {
4918 Jim_SetResultFormatted(interp
,
4919 "can't read \"%#s(%#s)\": %s array", varObjPtr
, keyObjPtr
,
4920 ret
< 0 ? "variable isn't" : "no such element in");
4922 else if ((flags
& JIM_UNSHARED
) && Jim_IsShared(dictObjPtr
)) {
4923 /* Update the variable to have an unshared copy */
4924 Jim_SetVariable(interp
, varObjPtr
, Jim_DuplicateObj(interp
, dictObjPtr
));
4930 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4931 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4933 SetDictSubstFromAny(interp
, objPtr
);
4935 return JimDictExpandArrayVariable(interp
,
4936 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4937 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, flags
);
4940 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4942 void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4944 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
4945 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
4948 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4950 /* Copy the internal rep */
4951 dupPtr
->internalRep
= srcPtr
->internalRep
;
4952 /* Need to increment the ref counts */
4953 Jim_IncrRefCount(dupPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
4954 Jim_IncrRefCount(dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
4957 /* Note: The object *must* be in dict-sugar format */
4958 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4960 if (objPtr
->typePtr
!= &dictSubstObjType
) {
4961 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4963 if (objPtr
->typePtr
== &interpolatedObjType
) {
4964 /* An interpolated object in dict-sugar form */
4966 varObjPtr
= objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
;
4967 keyObjPtr
= objPtr
->internalRep
.dictSubstValue
.indexObjPtr
;
4969 Jim_IncrRefCount(varObjPtr
);
4970 Jim_IncrRefCount(keyObjPtr
);
4973 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
4976 Jim_FreeIntRep(interp
, objPtr
);
4977 objPtr
->typePtr
= &dictSubstObjType
;
4978 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= varObjPtr
;
4979 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= keyObjPtr
;
4983 /* This function is used to expand [dict get] sugar in the form
4984 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4985 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4986 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4987 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4988 * the [dict]ionary contained in variable VARNAME. */
4989 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4991 Jim_Obj
*resObjPtr
= NULL
;
4992 Jim_Obj
*substKeyObjPtr
= NULL
;
4994 SetDictSubstFromAny(interp
, objPtr
);
4996 if (Jim_SubstObj(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
,
4997 &substKeyObjPtr
, JIM_NONE
)
5001 Jim_IncrRefCount(substKeyObjPtr
);
5003 JimDictExpandArrayVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
5005 Jim_DecrRefCount(interp
, substKeyObjPtr
);
5010 /* -----------------------------------------------------------------------------
5012 * ---------------------------------------------------------------------------*/
5014 static Jim_CallFrame
*JimCreateCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*parent
, Jim_Obj
*nsObj
)
5018 if (interp
->freeFramesList
) {
5019 cf
= interp
->freeFramesList
;
5020 interp
->freeFramesList
= cf
->next
;
5024 cf
->procArgsObjPtr
= NULL
;
5025 cf
->procBodyObjPtr
= NULL
;
5027 cf
->staticVars
= NULL
;
5028 cf
->localCommands
= NULL
;
5029 cf
->tailcallObj
= NULL
;
5030 cf
->tailcallCmd
= NULL
;
5033 cf
= Jim_Alloc(sizeof(*cf
));
5034 memset(cf
, 0, sizeof(*cf
));
5036 Jim_InitHashTable(&cf
->vars
, &JimVariablesHashTableType
, interp
);
5039 cf
->id
= interp
->callFrameEpoch
++;
5040 cf
->parent
= parent
;
5041 cf
->level
= parent
? parent
->level
+ 1 : 0;
5043 Jim_IncrRefCount(nsObj
);
5048 static int JimDeleteLocalProcs(Jim_Interp
*interp
, Jim_Stack
*localCommands
)
5050 /* Delete any local procs */
5051 if (localCommands
) {
5052 Jim_Obj
*cmdNameObj
;
5054 while ((cmdNameObj
= Jim_StackPop(localCommands
)) != NULL
) {
5055 Jim_HashTable
*ht
= &interp
->commands
;
5056 Jim_HashEntry
*he
= Jim_FindHashEntry(ht
, cmdNameObj
);
5058 Jim_Cmd
*cmd
= Jim_GetHashEntryVal(he
);
5060 Jim_Cmd
*prevCmd
= cmd
->prevCmd
;
5061 cmd
->prevCmd
= NULL
;
5063 /* Delete the old command */
5064 JimDecrCmdRefCount(interp
, cmd
);
5066 /* And restore the original */
5067 Jim_SetHashVal(ht
, he
, prevCmd
);
5070 Jim_DeleteHashEntry(ht
, cmdNameObj
);
5073 Jim_DecrRefCount(interp
, cmdNameObj
);
5075 Jim_FreeStack(localCommands
);
5076 Jim_Free(localCommands
);
5082 * Run any $jim::defer scripts for the current call frame.
5084 * retcode is the return code from the current proc.
5086 * Returns the new return code.
5088 static int JimInvokeDefer(Jim_Interp
*interp
, int retcode
)
5092 /* Fast check for the likely case that the variable doesn't exist */
5093 if (JimFindVariable(&interp
->framePtr
->vars
, interp
->defer
) == NULL
) {
5096 objPtr
= Jim_GetVariable(interp
, interp
->defer
, JIM_NONE
);
5101 int listLen
= Jim_ListLength(interp
, objPtr
);
5102 Jim_Obj
*resultObjPtr
;
5104 Jim_IncrRefCount(objPtr
);
5106 /* Need to save away the current interp result and
5107 * restore it if appropriate
5109 resultObjPtr
= Jim_GetResult(interp
);
5110 Jim_IncrRefCount(resultObjPtr
);
5111 Jim_SetEmptyResult(interp
);
5113 /* Invoke in reverse order */
5114 for (i
= listLen
; i
> 0; i
--) {
5115 /* If a defer script returns an error, don't evaluate remaining scripts */
5116 Jim_Obj
*scriptObjPtr
= Jim_ListGetIndex(interp
, objPtr
, i
- 1);
5117 ret
= Jim_EvalObj(interp
, scriptObjPtr
);
5118 if (ret
!= JIM_OK
) {
5123 if (ret
== JIM_OK
|| retcode
== JIM_ERR
) {
5124 /* defer script had no error, or proc had an error so restore proc result */
5125 Jim_SetResult(interp
, resultObjPtr
);
5131 Jim_DecrRefCount(interp
, resultObjPtr
);
5132 Jim_DecrRefCount(interp
, objPtr
);
5137 #define JIM_FCF_FULL 0 /* Always free the vars hash table */
5138 #define JIM_FCF_REUSE 1 /* Reuse the vars hash table if possible */
5139 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int action
)
5141 JimDeleteLocalProcs(interp
, cf
->localCommands
);
5143 if (cf
->procArgsObjPtr
)
5144 Jim_DecrRefCount(interp
, cf
->procArgsObjPtr
);
5145 if (cf
->procBodyObjPtr
)
5146 Jim_DecrRefCount(interp
, cf
->procBodyObjPtr
);
5147 Jim_DecrRefCount(interp
, cf
->nsObj
);
5148 if (action
== JIM_FCF_FULL
|| cf
->vars
.size
!= JIM_HT_INITIAL_SIZE
)
5149 Jim_FreeHashTable(&cf
->vars
);
5151 Jim_ClearHashTable(&cf
->vars
);
5153 cf
->next
= interp
->freeFramesList
;
5154 interp
->freeFramesList
= cf
;
5158 /* -----------------------------------------------------------------------------
5160 * ---------------------------------------------------------------------------*/
5161 #if defined(JIM_REFERENCES) && !defined(JIM_BOOTSTRAP)
5163 /* References HashTable Type.
5165 * Keys are unsigned long integers, dynamically allocated for now but in the
5166 * future it's worth to cache this 4 bytes objects. Values are pointers
5167 * to Jim_References. */
5168 static void JimReferencesHTValDestructor(void *interp
, void *val
)
5170 Jim_Reference
*refPtr
= (void *)val
;
5172 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
5173 if (refPtr
->finalizerCmdNamePtr
!= NULL
) {
5174 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
5179 static unsigned int JimReferencesHTHashFunction(const void *key
)
5181 /* Only the least significant bits are used. */
5182 const unsigned long *widePtr
= key
;
5183 unsigned int intValue
= (unsigned int)*widePtr
;
5185 return Jim_IntHashFunction(intValue
);
5188 static void *JimReferencesHTKeyDup(void *privdata
, const void *key
)
5190 void *copy
= Jim_Alloc(sizeof(unsigned long));
5192 JIM_NOTUSED(privdata
);
5194 memcpy(copy
, key
, sizeof(unsigned long));
5198 static int JimReferencesHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
5200 JIM_NOTUSED(privdata
);
5202 return memcmp(key1
, key2
, sizeof(unsigned long)) == 0;
5205 static void JimReferencesHTKeyDestructor(void *privdata
, void *key
)
5207 JIM_NOTUSED(privdata
);
5212 static const Jim_HashTableType JimReferencesHashTableType
= {
5213 JimReferencesHTHashFunction
, /* hash function */
5214 JimReferencesHTKeyDup
, /* key dup */
5216 JimReferencesHTKeyCompare
, /* key compare */
5217 JimReferencesHTKeyDestructor
, /* key destructor */
5218 JimReferencesHTValDestructor
/* val destructor */
5221 /* -----------------------------------------------------------------------------
5222 * Reference object type and References API
5223 * ---------------------------------------------------------------------------*/
5225 /* The string representation of references has two features in order
5226 * to make the GC faster. The first is that every reference starts
5227 * with a non common character '<', in order to make the string matching
5228 * faster. The second is that the reference string rep is 42 characters
5229 * in length, this means that it is not necessary to check any object with a string
5230 * repr < 42, and usually there aren't many of these objects. */
5232 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
5234 static int JimFormatReference(char *buf
, Jim_Reference
*refPtr
, unsigned long id
)
5236 const char *fmt
= "<reference.<%s>.%020lu>";
5238 sprintf(buf
, fmt
, refPtr
->tag
, id
);
5239 return JIM_REFERENCE_SPACE
;
5242 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
);
5244 static const Jim_ObjType referenceObjType
= {
5248 UpdateStringOfReference
,
5249 JIM_TYPE_REFERENCES
,
5252 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
)
5254 char buf
[JIM_REFERENCE_SPACE
+ 1];
5256 JimFormatReference(buf
, objPtr
->internalRep
.refValue
.refPtr
, objPtr
->internalRep
.refValue
.id
);
5257 JimSetStringBytes(objPtr
, buf
);
5260 /* returns true if 'c' is a valid reference tag character.
5261 * i.e. inside the range [_a-zA-Z0-9] */
5262 static int isrefchar(int c
)
5264 return (c
== '_' || isalnum(c
));
5267 static int SetReferenceFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5269 unsigned long value
;
5271 const char *str
, *start
, *end
;
5273 Jim_Reference
*refPtr
;
5277 /* Get the string representation */
5278 str
= Jim_GetString(objPtr
, &len
);
5279 /* Check if it looks like a reference */
5280 if (len
< JIM_REFERENCE_SPACE
)
5284 end
= str
+ len
- 1;
5285 while (*start
== ' ')
5287 while (*end
== ' ' && end
> start
)
5289 if (end
- start
+ 1 != JIM_REFERENCE_SPACE
)
5291 /* <reference.<1234567>.%020> */
5292 if (memcmp(start
, "<reference.<", 12) != 0)
5294 if (start
[12 + JIM_REFERENCE_TAGLEN
] != '>' || end
[0] != '>')
5296 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
5297 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
5298 if (!isrefchar(start
[12 + i
]))
5301 /* Extract info from the reference. */
5302 memcpy(refId
, start
+ 14 + JIM_REFERENCE_TAGLEN
, 20);
5304 /* Try to convert the ID into an unsigned long */
5305 value
= strtoul(refId
, &endptr
, 10);
5306 if (JimCheckConversion(refId
, endptr
) != JIM_OK
)
5308 /* Check if the reference really exists! */
5309 he
= Jim_FindHashEntry(&interp
->references
, &value
);
5311 Jim_SetResultFormatted(interp
, "invalid reference id \"%#s\"", objPtr
);
5314 refPtr
= Jim_GetHashEntryVal(he
);
5315 /* Free the old internal repr and set the new one. */
5316 Jim_FreeIntRep(interp
, objPtr
);
5317 objPtr
->typePtr
= &referenceObjType
;
5318 objPtr
->internalRep
.refValue
.id
= value
;
5319 objPtr
->internalRep
.refValue
.refPtr
= refPtr
;
5323 Jim_SetResultFormatted(interp
, "expected reference but got \"%#s\"", objPtr
);
5327 /* Returns a new reference pointing to objPtr, having cmdNamePtr
5328 * as finalizer command (or NULL if there is no finalizer).
5329 * The returned reference object has refcount = 0. */
5330 Jim_Obj
*Jim_NewReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*tagPtr
, Jim_Obj
*cmdNamePtr
)
5332 struct Jim_Reference
*refPtr
;
5338 /* Perform the Garbage Collection if needed. */
5339 Jim_CollectIfNeeded(interp
);
5341 refPtr
= Jim_Alloc(sizeof(*refPtr
));
5342 refPtr
->objPtr
= objPtr
;
5343 Jim_IncrRefCount(objPtr
);
5344 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
5346 Jim_IncrRefCount(cmdNamePtr
);
5347 id
= interp
->referenceNextId
++;
5348 Jim_AddHashEntry(&interp
->references
, &id
, refPtr
);
5349 refObjPtr
= Jim_NewObj(interp
);
5350 refObjPtr
->typePtr
= &referenceObjType
;
5351 refObjPtr
->bytes
= NULL
;
5352 refObjPtr
->internalRep
.refValue
.id
= id
;
5353 refObjPtr
->internalRep
.refValue
.refPtr
= refPtr
;
5354 interp
->referenceNextId
++;
5355 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
5356 * that does not pass the 'isrefchar' test is replaced with '_' */
5357 tag
= Jim_GetString(tagPtr
, &tagLen
);
5358 if (tagLen
> JIM_REFERENCE_TAGLEN
)
5359 tagLen
= JIM_REFERENCE_TAGLEN
;
5360 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
5361 if (i
< tagLen
&& isrefchar(tag
[i
]))
5362 refPtr
->tag
[i
] = tag
[i
];
5364 refPtr
->tag
[i
] = '_';
5366 refPtr
->tag
[JIM_REFERENCE_TAGLEN
] = '\0';
5370 Jim_Reference
*Jim_GetReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5372 if (objPtr
->typePtr
!= &referenceObjType
&& SetReferenceFromAny(interp
, objPtr
) == JIM_ERR
)
5374 return objPtr
->internalRep
.refValue
.refPtr
;
5377 int Jim_SetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*cmdNamePtr
)
5379 Jim_Reference
*refPtr
;
5381 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
5383 Jim_IncrRefCount(cmdNamePtr
);
5384 if (refPtr
->finalizerCmdNamePtr
)
5385 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
5386 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
5390 int Jim_GetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
**cmdNamePtrPtr
)
5392 Jim_Reference
*refPtr
;
5394 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
5396 *cmdNamePtrPtr
= refPtr
->finalizerCmdNamePtr
;
5400 /* -----------------------------------------------------------------------------
5401 * References Garbage Collection
5402 * ---------------------------------------------------------------------------*/
5404 /* This the hash table type for the "MARK" phase of the GC */
5405 static const Jim_HashTableType JimRefMarkHashTableType
= {
5406 JimReferencesHTHashFunction
, /* hash function */
5407 JimReferencesHTKeyDup
, /* key dup */
5409 JimReferencesHTKeyCompare
, /* key compare */
5410 JimReferencesHTKeyDestructor
, /* key destructor */
5411 NULL
/* val destructor */
5414 /* Performs the garbage collection. */
5415 int Jim_Collect(Jim_Interp
*interp
)
5418 Jim_HashTable marks
;
5419 Jim_HashTableIterator htiter
;
5423 /* Avoid recursive calls */
5424 if (interp
->lastCollectId
== (unsigned long)~0) {
5425 /* Jim_Collect() already running. Return just now. */
5428 interp
->lastCollectId
= ~0;
5430 /* Mark all the references found into the 'mark' hash table.
5431 * The references are searched in every live object that
5432 * is of a type that can contain references. */
5433 Jim_InitHashTable(&marks
, &JimRefMarkHashTableType
, NULL
);
5434 objPtr
= interp
->liveList
;
5436 if (objPtr
->typePtr
== NULL
|| objPtr
->typePtr
->flags
& JIM_TYPE_REFERENCES
) {
5437 const char *str
, *p
;
5440 /* If the object is of type reference, to get the
5441 * Id is simple... */
5442 if (objPtr
->typePtr
== &referenceObjType
) {
5443 Jim_AddHashEntry(&marks
, &objPtr
->internalRep
.refValue
.id
, NULL
);
5445 printf("MARK (reference): %d refcount: %d\n",
5446 (int)objPtr
->internalRep
.refValue
.id
, objPtr
->refCount
);
5448 objPtr
= objPtr
->nextObjPtr
;
5451 /* Get the string repr of the object we want
5452 * to scan for references. */
5453 p
= str
= Jim_GetString(objPtr
, &len
);
5454 /* Skip objects too little to contain references. */
5455 if (len
< JIM_REFERENCE_SPACE
) {
5456 objPtr
= objPtr
->nextObjPtr
;
5460 /* Maybe the entire string is a reference that is also in the commands table with a refcount of 1.
5461 * If so, this can be collected */
5462 if (objPtr
->refCount
== 1) {
5463 if (Jim_FindHashEntry(&interp
->commands
, objPtr
)) {
5465 printf("Found %s which is a command with refcount=1, so not marking\n", Jim_String(objPtr
));
5467 /* Yes, a command with refcount of 1 */
5468 objPtr
= objPtr
->nextObjPtr
;
5473 /* Extract references from the object string repr. */
5478 if ((p
= strstr(p
, "<reference.<")) == NULL
)
5480 /* Check if it's a valid reference. */
5481 if (len
- (p
- str
) < JIM_REFERENCE_SPACE
)
5483 if (p
[41] != '>' || p
[19] != '>' || p
[20] != '.')
5485 for (i
= 21; i
<= 40; i
++)
5486 if (!isdigit(UCHAR(p
[i
])))
5489 id
= strtoul(p
+ 21, NULL
, 10);
5491 /* Ok, a reference for the given ID
5492 * was found. Mark it. */
5493 Jim_AddHashEntry(&marks
, &id
, NULL
);
5495 printf("MARK: %d\n", (int)id
);
5497 p
+= JIM_REFERENCE_SPACE
;
5500 objPtr
= objPtr
->nextObjPtr
;
5503 /* Run the references hash table to destroy every reference that
5504 * is not referenced outside (not present in the mark HT). */
5505 JimInitHashTableIterator(&interp
->references
, &htiter
);
5506 while ((he
= Jim_NextHashEntry(&htiter
)) != NULL
) {
5507 const unsigned long *refId
;
5508 Jim_Reference
*refPtr
;
5511 /* Check if in the mark phase we encountered
5512 * this reference. */
5513 if (Jim_FindHashEntry(&marks
, refId
) == NULL
) {
5515 printf("COLLECTING %d\n", (int)*refId
);
5518 /* Drop the reference, but call the
5519 * finalizer first if registered. */
5520 refPtr
= Jim_GetHashEntryVal(he
);
5521 if (refPtr
->finalizerCmdNamePtr
) {
5522 char *refstr
= Jim_Alloc(JIM_REFERENCE_SPACE
+ 1);
5523 Jim_Obj
*objv
[3], *oldResult
;
5525 JimFormatReference(refstr
, refPtr
, *refId
);
5527 objv
[0] = refPtr
->finalizerCmdNamePtr
;
5528 objv
[1] = Jim_NewStringObjNoAlloc(interp
, refstr
, JIM_REFERENCE_SPACE
);
5529 objv
[2] = refPtr
->objPtr
;
5531 /* Drop the reference itself */
5532 /* Avoid the finaliser being freed here */
5533 Jim_IncrRefCount(objv
[0]);
5534 /* Don't remove the reference from the hash table just yet
5535 * since that will free refPtr, and hence refPtr->objPtr
5538 /* Call the finalizer. Errors ignored. (should we use bgerror?) */
5539 oldResult
= interp
->result
;
5540 Jim_IncrRefCount(oldResult
);
5541 Jim_EvalObjVector(interp
, 3, objv
);
5542 Jim_SetResult(interp
, oldResult
);
5543 Jim_DecrRefCount(interp
, oldResult
);
5545 Jim_DecrRefCount(interp
, objv
[0]);
5547 Jim_DeleteHashEntry(&interp
->references
, refId
);
5550 Jim_FreeHashTable(&marks
);
5551 interp
->lastCollectId
= interp
->referenceNextId
;
5552 interp
->lastCollectTime
= JimClock();
5556 #define JIM_COLLECT_ID_PERIOD 5000000
5557 #define JIM_COLLECT_TIME_PERIOD 300000
5559 void Jim_CollectIfNeeded(Jim_Interp
*interp
)
5561 unsigned long elapsedId
;
5562 jim_wide elapsedTime
;
5564 elapsedId
= interp
->referenceNextId
- interp
->lastCollectId
;
5565 elapsedTime
= JimClock() - interp
->lastCollectTime
;
5568 if (elapsedId
> JIM_COLLECT_ID_PERIOD
|| elapsedTime
> JIM_COLLECT_TIME_PERIOD
) {
5569 Jim_Collect(interp
);
5572 #endif /* JIM_REFERENCES && !JIM_BOOTSTRAP */
5574 int Jim_IsBigEndian(void)
5581 return uval
.c
[0] == 1;
5584 /* -----------------------------------------------------------------------------
5585 * Interpreter related functions
5586 * ---------------------------------------------------------------------------*/
5588 Jim_Interp
*Jim_CreateInterp(void)
5590 Jim_Interp
*i
= Jim_Alloc(sizeof(*i
));
5592 memset(i
, 0, sizeof(*i
));
5594 i
->maxCallFrameDepth
= JIM_MAX_CALLFRAME_DEPTH
;
5595 i
->maxEvalDepth
= JIM_MAX_EVAL_DEPTH
;
5596 i
->lastCollectTime
= JimClock();
5598 /* Note that we can create objects only after the
5599 * interpreter liveList and freeList pointers are
5600 * initialized to NULL. */
5601 Jim_InitHashTable(&i
->commands
, &JimCommandsHashTableType
, i
);
5602 #ifdef JIM_REFERENCES
5603 Jim_InitHashTable(&i
->references
, &JimReferencesHashTableType
, i
);
5605 Jim_InitHashTable(&i
->assocData
, &JimAssocDataHashTableType
, i
);
5606 Jim_InitHashTable(&i
->packages
, &JimPackageHashTableType
, NULL
);
5607 i
->emptyObj
= Jim_NewEmptyStringObj(i
);
5608 i
->trueObj
= Jim_NewIntObj(i
, 1);
5609 i
->falseObj
= Jim_NewIntObj(i
, 0);
5610 i
->framePtr
= i
->topFramePtr
= JimCreateCallFrame(i
, NULL
, i
->emptyObj
);
5611 i
->errorFileNameObj
= i
->emptyObj
;
5612 i
->result
= i
->emptyObj
;
5613 i
->stackTrace
= Jim_NewListObj(i
, NULL
, 0);
5614 i
->unknown
= Jim_NewStringObj(i
, "unknown", -1);
5615 i
->defer
= Jim_NewStringObj(i
, "jim::defer", -1);
5616 i
->errorProc
= i
->emptyObj
;
5617 i
->currentScriptObj
= Jim_NewEmptyStringObj(i
);
5618 i
->nullScriptObj
= Jim_NewEmptyStringObj(i
);
5619 Jim_IncrRefCount(i
->emptyObj
);
5620 Jim_IncrRefCount(i
->errorFileNameObj
);
5621 Jim_IncrRefCount(i
->result
);
5622 Jim_IncrRefCount(i
->stackTrace
);
5623 Jim_IncrRefCount(i
->unknown
);
5624 Jim_IncrRefCount(i
->defer
);
5625 Jim_IncrRefCount(i
->currentScriptObj
);
5626 Jim_IncrRefCount(i
->nullScriptObj
);
5627 Jim_IncrRefCount(i
->errorProc
);
5628 Jim_IncrRefCount(i
->trueObj
);
5629 Jim_IncrRefCount(i
->falseObj
);
5631 /* Initialize key variables every interpreter should contain */
5632 Jim_SetVariableStrWithStr(i
, JIM_LIBPATH
, TCL_LIBRARY
);
5633 Jim_SetVariableStrWithStr(i
, JIM_INTERACTIVE
, "0");
5635 Jim_SetVariableStrWithStr(i
, "tcl_platform(engine)", "Jim");
5636 Jim_SetVariableStrWithStr(i
, "tcl_platform(os)", TCL_PLATFORM_OS
);
5637 Jim_SetVariableStrWithStr(i
, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM
);
5638 Jim_SetVariableStrWithStr(i
, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR
);
5639 Jim_SetVariableStrWithStr(i
, "tcl_platform(byteOrder)", Jim_IsBigEndian() ? "bigEndian" : "littleEndian");
5640 Jim_SetVariableStrWithStr(i
, "tcl_platform(threaded)", "0");
5641 Jim_SetVariableStr(i
, "tcl_platform(pointerSize)", Jim_NewIntObj(i
, sizeof(void *)));
5642 Jim_SetVariableStr(i
, "tcl_platform(wordSize)", Jim_NewIntObj(i
, sizeof(jim_wide
)));
5647 void Jim_FreeInterp(Jim_Interp
*i
)
5649 Jim_CallFrame
*cf
, *cfx
;
5651 Jim_Obj
*objPtr
, *nextObjPtr
;
5655 /* Free the active call frames list - must be done before i->commands is destroyed */
5656 for (cf
= i
->framePtr
; cf
; cf
= cfx
) {
5657 /* Note that we ignore any errors */
5658 JimInvokeDefer(i
, JIM_OK
);
5660 JimFreeCallFrame(i
, cf
, JIM_FCF_FULL
);
5663 Jim_DecrRefCount(i
, i
->emptyObj
);
5664 Jim_DecrRefCount(i
, i
->trueObj
);
5665 Jim_DecrRefCount(i
, i
->falseObj
);
5666 Jim_DecrRefCount(i
, i
->result
);
5667 Jim_DecrRefCount(i
, i
->stackTrace
);
5668 Jim_DecrRefCount(i
, i
->errorProc
);
5669 Jim_DecrRefCount(i
, i
->unknown
);
5670 Jim_DecrRefCount(i
, i
->defer
);
5671 Jim_DecrRefCount(i
, i
->errorFileNameObj
);
5672 Jim_DecrRefCount(i
, i
->currentScriptObj
);
5673 Jim_DecrRefCount(i
, i
->nullScriptObj
);
5675 Jim_InterpIncrProcEpoch(i
);
5677 Jim_FreeHashTable(&i
->commands
);
5678 #ifdef JIM_REFERENCES
5679 Jim_FreeHashTable(&i
->references
);
5681 Jim_FreeHashTable(&i
->packages
);
5682 Jim_Free(i
->prngState
);
5683 Jim_FreeHashTable(&i
->assocData
);
5685 /* Check that the live object list is empty, otherwise
5686 * there is a memory leak. */
5687 #ifdef JIM_MAINTAINER
5688 if (i
->liveList
!= NULL
) {
5689 objPtr
= i
->liveList
;
5691 printf("\n-------------------------------------\n");
5692 printf("Objects still in the free list:\n");
5694 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "string";
5697 if (objPtr
->bytes
&& strlen(objPtr
->bytes
) > 20) {
5698 printf("%p (%d) %-10s: '%.20s...'\n",
5699 (void *)objPtr
, objPtr
->refCount
, type
, objPtr
->bytes
);
5702 printf("%p (%d) %-10s: '%s'\n",
5703 (void *)objPtr
, objPtr
->refCount
, type
, objPtr
->bytes
? objPtr
->bytes
: "(null)");
5705 if (objPtr
->typePtr
== &sourceObjType
) {
5706 printf("FILE %s LINE %d\n",
5707 Jim_String(objPtr
->internalRep
.sourceValue
.fileNameObj
),
5708 objPtr
->internalRep
.sourceValue
.lineNumber
);
5710 objPtr
= objPtr
->nextObjPtr
;
5712 printf("-------------------------------------\n\n");
5713 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5717 /* Free all the freed objects. */
5718 objPtr
= i
->freeList
;
5720 nextObjPtr
= objPtr
->nextObjPtr
;
5722 objPtr
= nextObjPtr
;
5725 /* Free the free call frames list */
5726 for (cf
= i
->freeFramesList
; cf
; cf
= cfx
) {
5729 Jim_FreeHashTable(&cf
->vars
);
5733 /* Free the interpreter structure. */
5737 /* Returns the call frame relative to the level represented by
5738 * levelObjPtr. If levelObjPtr == NULL, the level is assumed to be '1'.
5740 * This function accepts the 'level' argument in the form
5741 * of the commands [uplevel] and [upvar].
5743 * Returns NULL on error.
5745 * Note: for a function accepting a relative integer as level suitable
5746 * for implementation of [info level ?level?], see JimGetCallFrameByInteger()
5748 Jim_CallFrame
*Jim_GetCallFrameByLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5752 Jim_CallFrame
*framePtr
;
5755 str
= Jim_String(levelObjPtr
);
5756 if (str
[0] == '#') {
5759 level
= jim_strtol(str
+ 1, &endptr
);
5760 if (str
[1] == '\0' || endptr
[0] != '\0') {
5765 if (Jim_GetLong(interp
, levelObjPtr
, &level
) != JIM_OK
|| level
< 0) {
5769 /* Convert from a relative to an absolute level */
5770 level
= interp
->framePtr
->level
- level
;
5775 str
= "1"; /* Needed to format the error message. */
5776 level
= interp
->framePtr
->level
- 1;
5780 return interp
->topFramePtr
;
5784 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parent
) {
5785 if (framePtr
->level
== level
) {
5791 Jim_SetResultFormatted(interp
, "bad level \"%s\"", str
);
5795 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5796 * as a relative integer like in the [info level ?level?] command.
5798 static Jim_CallFrame
*JimGetCallFrameByInteger(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5801 Jim_CallFrame
*framePtr
;
5803 if (Jim_GetLong(interp
, levelObjPtr
, &level
) == JIM_OK
) {
5805 /* Convert from a relative to an absolute level */
5806 level
= interp
->framePtr
->level
+ level
;
5810 return interp
->topFramePtr
;
5814 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parent
) {
5815 if (framePtr
->level
== level
) {
5821 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
5825 static void JimResetStackTrace(Jim_Interp
*interp
)
5827 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5828 interp
->stackTrace
= Jim_NewListObj(interp
, NULL
, 0);
5829 Jim_IncrRefCount(interp
->stackTrace
);
5832 static void JimSetStackTrace(Jim_Interp
*interp
, Jim_Obj
*stackTraceObj
)
5836 /* Increment reference first in case these are the same object */
5837 Jim_IncrRefCount(stackTraceObj
);
5838 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5839 interp
->stackTrace
= stackTraceObj
;
5840 interp
->errorFlag
= 1;
5842 /* This is a bit ugly.
5843 * If the filename of the last entry of the stack trace is empty,
5844 * the next stack level should be added.
5846 len
= Jim_ListLength(interp
, interp
->stackTrace
);
5848 if (Jim_Length(Jim_ListGetIndex(interp
, interp
->stackTrace
, len
- 2)) == 0) {
5849 interp
->addStackTrace
= 1;
5854 static void JimAppendStackTrace(Jim_Interp
*interp
, const char *procname
,
5855 Jim_Obj
*fileNameObj
, int linenr
)
5857 if (strcmp(procname
, "unknown") == 0) {
5860 if (!*procname
&& !Jim_Length(fileNameObj
)) {
5861 /* No useful info here */
5865 if (Jim_IsShared(interp
->stackTrace
)) {
5866 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5867 interp
->stackTrace
= Jim_DuplicateObj(interp
, interp
->stackTrace
);
5868 Jim_IncrRefCount(interp
->stackTrace
);
5871 /* If we have no procname but the previous element did, merge with that frame */
5872 if (!*procname
&& Jim_Length(fileNameObj
)) {
5873 /* Just a filename. Check the previous entry */
5874 int len
= Jim_ListLength(interp
, interp
->stackTrace
);
5877 Jim_Obj
*objPtr
= Jim_ListGetIndex(interp
, interp
->stackTrace
, len
- 3);
5878 if (Jim_Length(objPtr
)) {
5879 /* Yes, the previous level had procname */
5880 objPtr
= Jim_ListGetIndex(interp
, interp
->stackTrace
, len
- 2);
5881 if (Jim_Length(objPtr
) == 0) {
5882 /* But no filename, so merge the new info with that frame */
5883 ListSetIndex(interp
, interp
->stackTrace
, len
- 2, fileNameObj
, 0);
5884 ListSetIndex(interp
, interp
->stackTrace
, len
- 1, Jim_NewIntObj(interp
, linenr
), 0);
5891 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewStringObj(interp
, procname
, -1));
5892 Jim_ListAppendElement(interp
, interp
->stackTrace
, fileNameObj
);
5893 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewIntObj(interp
, linenr
));
5896 int Jim_SetAssocData(Jim_Interp
*interp
, const char *key
, Jim_InterpDeleteProc
* delProc
,
5899 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) Jim_Alloc(sizeof(AssocDataValue
));
5901 assocEntryPtr
->delProc
= delProc
;
5902 assocEntryPtr
->data
= data
;
5903 return Jim_AddHashEntry(&interp
->assocData
, key
, assocEntryPtr
);
5906 void *Jim_GetAssocData(Jim_Interp
*interp
, const char *key
)
5908 Jim_HashEntry
*entryPtr
= Jim_FindHashEntry(&interp
->assocData
, key
);
5910 if (entryPtr
!= NULL
) {
5911 AssocDataValue
*assocEntryPtr
= Jim_GetHashEntryVal(entryPtr
);
5912 return assocEntryPtr
->data
;
5917 int Jim_DeleteAssocData(Jim_Interp
*interp
, const char *key
)
5919 return Jim_DeleteHashEntry(&interp
->assocData
, key
);
5922 int Jim_GetExitCode(Jim_Interp
*interp
)
5924 return interp
->exitCode
;
5927 /* -----------------------------------------------------------------------------
5929 * ---------------------------------------------------------------------------*/
5930 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
);
5931 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
5933 static const Jim_ObjType intObjType
= {
5941 /* A coerced double is closer to an int than a double.
5942 * It is an int value temporarily masquerading as a double value.
5943 * i.e. it has the same string value as an int and Jim_GetWide()
5944 * succeeds, but also Jim_GetDouble() returns the value directly.
5946 static const Jim_ObjType coercedDoubleObjType
= {
5955 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
)
5957 char buf
[JIM_INTEGER_SPACE
+ 1];
5958 jim_wide wideValue
= JimWideValue(objPtr
);
5961 if (wideValue
== 0) {
5965 char tmp
[JIM_INTEGER_SPACE
];
5969 if (wideValue
< 0) {
5972 /* C89 is implementation defined as to whether (-106 % 10) is -6 or 4,
5973 * whereas C99 is always -6
5974 * coverity[dead_error_line]
5976 tmp
[num
++] = (i
> 0) ? (10 - i
) : -i
;
5981 tmp
[num
++] = wideValue
% 10;
5985 for (i
= 0; i
< num
; i
++) {
5986 buf
[pos
++] = '0' + tmp
[num
- i
- 1];
5991 JimSetStringBytes(objPtr
, buf
);
5994 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
5999 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
6001 objPtr
->typePtr
= &intObjType
;
6005 /* Get the string representation */
6006 str
= Jim_String(objPtr
);
6007 /* Try to convert into a jim_wide */
6008 if (Jim_StringToWide(str
, &wideValue
, 0) != JIM_OK
) {
6009 if (flags
& JIM_ERRMSG
) {
6010 Jim_SetResultFormatted(interp
, "expected integer but got \"%#s\"", objPtr
);
6014 if ((wideValue
== JIM_WIDE_MIN
|| wideValue
== JIM_WIDE_MAX
) && errno
== ERANGE
) {
6015 Jim_SetResultString(interp
, "Integer value too big to be represented", -1);
6018 /* Free the old internal repr and set the new one. */
6019 Jim_FreeIntRep(interp
, objPtr
);
6020 objPtr
->typePtr
= &intObjType
;
6021 objPtr
->internalRep
.wideValue
= wideValue
;
6025 #ifdef JIM_OPTIMIZATION
6026 static int JimIsWide(Jim_Obj
*objPtr
)
6028 return objPtr
->typePtr
== &intObjType
;
6032 int Jim_GetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
6034 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
6036 *widePtr
= JimWideValue(objPtr
);
6040 /* Get a wide but does not set an error if the format is bad. */
6041 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
6043 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_NONE
) == JIM_ERR
)
6045 *widePtr
= JimWideValue(objPtr
);
6049 int Jim_GetLong(Jim_Interp
*interp
, Jim_Obj
*objPtr
, long *longPtr
)
6054 retval
= Jim_GetWide(interp
, objPtr
, &wideValue
);
6055 if (retval
== JIM_OK
) {
6056 *longPtr
= (long)wideValue
;
6062 Jim_Obj
*Jim_NewIntObj(Jim_Interp
*interp
, jim_wide wideValue
)
6066 objPtr
= Jim_NewObj(interp
);
6067 objPtr
->typePtr
= &intObjType
;
6068 objPtr
->bytes
= NULL
;
6069 objPtr
->internalRep
.wideValue
= wideValue
;
6073 /* -----------------------------------------------------------------------------
6075 * ---------------------------------------------------------------------------*/
6076 #define JIM_DOUBLE_SPACE 30
6078 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
);
6079 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6081 static const Jim_ObjType doubleObjType
= {
6085 UpdateStringOfDouble
,
6091 #define isnan(X) ((X) != (X))
6095 #define isinf(X) (1.0 / (X) == 0.0)
6098 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
)
6100 double value
= objPtr
->internalRep
.doubleValue
;
6103 JimSetStringBytes(objPtr
, "NaN");
6108 JimSetStringBytes(objPtr
, "-Inf");
6111 JimSetStringBytes(objPtr
, "Inf");
6116 char buf
[JIM_DOUBLE_SPACE
+ 1];
6118 int len
= sprintf(buf
, "%.12g", value
);
6120 /* Add a final ".0" if necessary */
6121 for (i
= 0; i
< len
; i
++) {
6122 if (buf
[i
] == '.' || buf
[i
] == 'e') {
6123 #if defined(JIM_SPRINTF_DOUBLE_NEEDS_FIX)
6124 /* If 'buf' ends in e-0nn or e+0nn, remove
6125 * the 0 after the + or - and reduce the length by 1
6127 char *e
= strchr(buf
, 'e');
6128 if (e
&& (e
[1] == '-' || e
[1] == '+') && e
[2] == '0') {
6131 memmove(e
, e
+ 1, len
- (e
- buf
));
6137 if (buf
[i
] == '\0') {
6142 JimSetStringBytes(objPtr
, buf
);
6146 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6152 #ifdef HAVE_LONG_LONG
6153 /* Assume a 53 bit mantissa */
6154 #define MIN_INT_IN_DOUBLE -(1LL << 53)
6155 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
6157 if (objPtr
->typePtr
== &intObjType
6158 && JimWideValue(objPtr
) >= MIN_INT_IN_DOUBLE
6159 && JimWideValue(objPtr
) <= MAX_INT_IN_DOUBLE
) {
6161 /* Direct conversion to coerced double */
6162 objPtr
->typePtr
= &coercedDoubleObjType
;
6166 /* Preserve the string representation.
6167 * Needed so we can convert back to int without loss
6169 str
= Jim_String(objPtr
);
6171 if (Jim_StringToWide(str
, &wideValue
, 10) == JIM_OK
) {
6172 /* Managed to convert to an int, so we can use this as a cooerced double */
6173 Jim_FreeIntRep(interp
, objPtr
);
6174 objPtr
->typePtr
= &coercedDoubleObjType
;
6175 objPtr
->internalRep
.wideValue
= wideValue
;
6179 /* Try to convert into a double */
6180 if (Jim_StringToDouble(str
, &doubleValue
) != JIM_OK
) {
6181 Jim_SetResultFormatted(interp
, "expected floating-point number but got \"%#s\"", objPtr
);
6184 /* Free the old internal repr and set the new one. */
6185 Jim_FreeIntRep(interp
, objPtr
);
6187 objPtr
->typePtr
= &doubleObjType
;
6188 objPtr
->internalRep
.doubleValue
= doubleValue
;
6192 int Jim_GetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double *doublePtr
)
6194 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
6195 *doublePtr
= JimWideValue(objPtr
);
6198 if (objPtr
->typePtr
!= &doubleObjType
&& SetDoubleFromAny(interp
, objPtr
) == JIM_ERR
)
6201 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
6202 *doublePtr
= JimWideValue(objPtr
);
6205 *doublePtr
= objPtr
->internalRep
.doubleValue
;
6210 Jim_Obj
*Jim_NewDoubleObj(Jim_Interp
*interp
, double doubleValue
)
6214 objPtr
= Jim_NewObj(interp
);
6215 objPtr
->typePtr
= &doubleObjType
;
6216 objPtr
->bytes
= NULL
;
6217 objPtr
->internalRep
.doubleValue
= doubleValue
;
6221 /* -----------------------------------------------------------------------------
6222 * Boolean conversion
6223 * ---------------------------------------------------------------------------*/
6224 static int SetBooleanFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
6226 int Jim_GetBoolean(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int * booleanPtr
)
6228 if (objPtr
->typePtr
!= &intObjType
&& SetBooleanFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
6230 *booleanPtr
= (int) JimWideValue(objPtr
);
6234 static int SetBooleanFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
6236 static const char * const falses
[] = {
6237 "0", "false", "no", "off", NULL
6239 static const char * const trues
[] = {
6240 "1", "true", "yes", "on", NULL
6246 if (Jim_GetEnum(interp
, objPtr
, falses
, &index
, NULL
, 0) == JIM_OK
) {
6248 } else if (Jim_GetEnum(interp
, objPtr
, trues
, &index
, NULL
, 0) == JIM_OK
) {
6251 if (flags
& JIM_ERRMSG
) {
6252 Jim_SetResultFormatted(interp
, "expected boolean but got \"%#s\"", objPtr
);
6257 /* Free the old internal repr and set the new one. */
6258 Jim_FreeIntRep(interp
, objPtr
);
6259 objPtr
->typePtr
= &intObjType
;
6260 objPtr
->internalRep
.wideValue
= boolean
;
6264 /* -----------------------------------------------------------------------------
6266 * ---------------------------------------------------------------------------*/
6267 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
);
6268 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
);
6269 static void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6270 static void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
6271 static void UpdateStringOfList(struct Jim_Obj
*objPtr
);
6272 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6274 /* Note that while the elements of the list may contain references,
6275 * the list object itself can't. This basically means that the
6276 * list object string representation as a whole can't contain references
6277 * that are not presents in the single elements. */
6278 static const Jim_ObjType listObjType
= {
6280 FreeListInternalRep
,
6286 void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6290 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
6291 Jim_DecrRefCount(interp
, objPtr
->internalRep
.listValue
.ele
[i
]);
6293 Jim_Free(objPtr
->internalRep
.listValue
.ele
);
6296 void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
6300 JIM_NOTUSED(interp
);
6302 dupPtr
->internalRep
.listValue
.len
= srcPtr
->internalRep
.listValue
.len
;
6303 dupPtr
->internalRep
.listValue
.maxLen
= srcPtr
->internalRep
.listValue
.maxLen
;
6304 dupPtr
->internalRep
.listValue
.ele
=
6305 Jim_Alloc(sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.maxLen
);
6306 memcpy(dupPtr
->internalRep
.listValue
.ele
, srcPtr
->internalRep
.listValue
.ele
,
6307 sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.len
);
6308 for (i
= 0; i
< dupPtr
->internalRep
.listValue
.len
; i
++) {
6309 Jim_IncrRefCount(dupPtr
->internalRep
.listValue
.ele
[i
]);
6311 dupPtr
->typePtr
= &listObjType
;
6314 /* The following function checks if a given string can be encoded
6315 * into a list element without any kind of quoting, surrounded by braces,
6316 * or using escapes to quote. */
6317 #define JIM_ELESTR_SIMPLE 0
6318 #define JIM_ELESTR_BRACE 1
6319 #define JIM_ELESTR_QUOTE 2
6320 static unsigned char ListElementQuotingType(const char *s
, int len
)
6322 int i
, level
, blevel
, trySimple
= 1;
6324 /* Try with the SIMPLE case */
6326 return JIM_ELESTR_BRACE
;
6327 if (s
[0] == '"' || s
[0] == '{') {
6331 for (i
= 0; i
< len
; i
++) {
6352 return JIM_ELESTR_SIMPLE
;
6355 /* Test if it's possible to do with braces */
6356 if (s
[len
- 1] == '\\')
6357 return JIM_ELESTR_QUOTE
;
6360 for (i
= 0; i
< len
; i
++) {
6368 return JIM_ELESTR_QUOTE
;
6377 if (s
[i
+ 1] == '\n')
6378 return JIM_ELESTR_QUOTE
;
6379 else if (s
[i
+ 1] != '\0')
6385 return JIM_ELESTR_QUOTE
;
6390 return JIM_ELESTR_BRACE
;
6391 for (i
= 0; i
< len
; i
++) {
6405 return JIM_ELESTR_BRACE
;
6409 return JIM_ELESTR_SIMPLE
;
6411 return JIM_ELESTR_QUOTE
;
6414 /* Backslashes-escapes the null-terminated string 's' into the buffer at 'q'
6415 * The buffer must be at least strlen(s) * 2 + 1 bytes long for the worst-case
6417 * Returns the length of the result.
6419 static int BackslashQuoteString(const char *s
, int len
, char *q
)
6472 static void JimMakeListStringRep(Jim_Obj
*objPtr
, Jim_Obj
**objv
, int objc
)
6474 #define STATIC_QUOTING_LEN 32
6475 int i
, bufLen
, realLength
;
6478 unsigned char *quotingType
, staticQuoting
[STATIC_QUOTING_LEN
];
6480 /* Estimate the space needed. */
6481 if (objc
> STATIC_QUOTING_LEN
) {
6482 quotingType
= Jim_Alloc(objc
);
6485 quotingType
= staticQuoting
;
6488 for (i
= 0; i
< objc
; i
++) {
6491 strRep
= Jim_GetString(objv
[i
], &len
);
6492 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
6493 switch (quotingType
[i
]) {
6494 case JIM_ELESTR_SIMPLE
:
6495 if (i
!= 0 || strRep
[0] != '#') {
6499 /* Special case '#' on first element needs braces */
6500 quotingType
[i
] = JIM_ELESTR_BRACE
;
6502 case JIM_ELESTR_BRACE
:
6505 case JIM_ELESTR_QUOTE
:
6509 bufLen
++; /* elements separator. */
6513 /* Generate the string rep. */
6514 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
6516 for (i
= 0; i
< objc
; i
++) {
6519 strRep
= Jim_GetString(objv
[i
], &len
);
6521 switch (quotingType
[i
]) {
6522 case JIM_ELESTR_SIMPLE
:
6523 memcpy(p
, strRep
, len
);
6527 case JIM_ELESTR_BRACE
:
6529 memcpy(p
, strRep
, len
);
6532 realLength
+= len
+ 2;
6534 case JIM_ELESTR_QUOTE
:
6535 if (i
== 0 && strRep
[0] == '#') {
6539 qlen
= BackslashQuoteString(strRep
, len
, p
);
6544 /* Add a separating space */
6545 if (i
+ 1 != objc
) {
6550 *p
= '\0'; /* nul term. */
6551 objPtr
->length
= realLength
;
6553 if (quotingType
!= staticQuoting
) {
6554 Jim_Free(quotingType
);
6558 static void UpdateStringOfList(struct Jim_Obj
*objPtr
)
6560 JimMakeListStringRep(objPtr
, objPtr
->internalRep
.listValue
.ele
, objPtr
->internalRep
.listValue
.len
);
6563 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
6565 struct JimParserCtx parser
;
6568 Jim_Obj
*fileNameObj
;
6571 if (objPtr
->typePtr
== &listObjType
) {
6575 /* Optimise dict -> list for object with no string rep. Note that this may only save a little time, but
6576 * it also preserves any source location of the dict elements
6577 * which can be very useful
6579 if (Jim_IsDict(objPtr
) && objPtr
->bytes
== NULL
) {
6580 Jim_Obj
**listObjPtrPtr
;
6584 listObjPtrPtr
= JimDictPairs(objPtr
, &len
);
6585 for (i
= 0; i
< len
; i
++) {
6586 Jim_IncrRefCount(listObjPtrPtr
[i
]);
6589 /* Now just switch the internal rep */
6590 Jim_FreeIntRep(interp
, objPtr
);
6591 objPtr
->typePtr
= &listObjType
;
6592 objPtr
->internalRep
.listValue
.len
= len
;
6593 objPtr
->internalRep
.listValue
.maxLen
= len
;
6594 objPtr
->internalRep
.listValue
.ele
= listObjPtrPtr
;
6599 /* Try to preserve information about filename / line number */
6600 if (objPtr
->typePtr
== &sourceObjType
) {
6601 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
6602 linenr
= objPtr
->internalRep
.sourceValue
.lineNumber
;
6605 fileNameObj
= interp
->emptyObj
;
6608 Jim_IncrRefCount(fileNameObj
);
6610 /* Get the string representation */
6611 str
= Jim_GetString(objPtr
, &strLen
);
6613 /* Free the old internal repr just now and initialize the
6614 * new one just now. The string->list conversion can't fail. */
6615 Jim_FreeIntRep(interp
, objPtr
);
6616 objPtr
->typePtr
= &listObjType
;
6617 objPtr
->internalRep
.listValue
.len
= 0;
6618 objPtr
->internalRep
.listValue
.maxLen
= 0;
6619 objPtr
->internalRep
.listValue
.ele
= NULL
;
6621 /* Convert into a list */
6623 JimParserInit(&parser
, str
, strLen
, linenr
);
6624 while (!parser
.eof
) {
6625 Jim_Obj
*elementPtr
;
6627 JimParseList(&parser
);
6628 if (parser
.tt
!= JIM_TT_STR
&& parser
.tt
!= JIM_TT_ESC
)
6630 elementPtr
= JimParserGetTokenObj(interp
, &parser
);
6631 JimSetSourceInfo(interp
, elementPtr
, fileNameObj
, parser
.tline
);
6632 ListAppendElement(objPtr
, elementPtr
);
6635 Jim_DecrRefCount(interp
, fileNameObj
);
6639 Jim_Obj
*Jim_NewListObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
6643 objPtr
= Jim_NewObj(interp
);
6644 objPtr
->typePtr
= &listObjType
;
6645 objPtr
->bytes
= NULL
;
6646 objPtr
->internalRep
.listValue
.ele
= NULL
;
6647 objPtr
->internalRep
.listValue
.len
= 0;
6648 objPtr
->internalRep
.listValue
.maxLen
= 0;
6651 ListInsertElements(objPtr
, 0, len
, elements
);
6657 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
6658 * length of the vector. Note that the user of this function should make
6659 * sure that the list object can't shimmer while the vector returned
6660 * is in use, this vector is the one stored inside the internal representation
6661 * of the list object. This function is not exported, extensions should
6662 * always access to the List object elements using Jim_ListIndex(). */
6663 static void JimListGetElements(Jim_Interp
*interp
, Jim_Obj
*listObj
, int *listLen
,
6666 *listLen
= Jim_ListLength(interp
, listObj
);
6667 *listVec
= listObj
->internalRep
.listValue
.ele
;
6670 /* Sorting uses ints, but commands may return wide */
6671 static int JimSign(jim_wide w
)
6682 /* ListSortElements type values */
6698 int (*subfn
)(Jim_Obj
**, Jim_Obj
**);
6701 static struct lsort_info
*sort_info
;
6703 static int ListSortIndexHelper(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
6705 Jim_Obj
*lObj
, *rObj
;
6707 if (Jim_ListIndex(sort_info
->interp
, *lhsObj
, sort_info
->index
, &lObj
, JIM_ERRMSG
) != JIM_OK
||
6708 Jim_ListIndex(sort_info
->interp
, *rhsObj
, sort_info
->index
, &rObj
, JIM_ERRMSG
) != JIM_OK
) {
6709 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
6711 return sort_info
->subfn(&lObj
, &rObj
);
6714 /* Sort the internal rep of a list. */
6715 static int ListSortString(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
6717 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 0) * sort_info
->order
;
6720 static int ListSortStringNoCase(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
6722 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 1) * sort_info
->order
;
6725 static int ListSortInteger(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
6727 jim_wide lhs
= 0, rhs
= 0;
6729 if (Jim_GetWide(sort_info
->interp
, *lhsObj
, &lhs
) != JIM_OK
||
6730 Jim_GetWide(sort_info
->interp
, *rhsObj
, &rhs
) != JIM_OK
) {
6731 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
6734 return JimSign(lhs
- rhs
) * sort_info
->order
;
6737 static int ListSortReal(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
6739 double lhs
= 0, rhs
= 0;
6741 if (Jim_GetDouble(sort_info
->interp
, *lhsObj
, &lhs
) != JIM_OK
||
6742 Jim_GetDouble(sort_info
->interp
, *rhsObj
, &rhs
) != JIM_OK
) {
6743 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
6749 return sort_info
->order
;
6751 return -sort_info
->order
;
6754 static int ListSortCommand(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
6756 Jim_Obj
*compare_script
;
6761 /* This must be a valid list */
6762 compare_script
= Jim_DuplicateObj(sort_info
->interp
, sort_info
->command
);
6763 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *lhsObj
);
6764 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *rhsObj
);
6766 rc
= Jim_EvalObj(sort_info
->interp
, compare_script
);
6768 if (rc
!= JIM_OK
|| Jim_GetWide(sort_info
->interp
, Jim_GetResult(sort_info
->interp
), &ret
) != JIM_OK
) {
6769 longjmp(sort_info
->jmpbuf
, rc
);
6772 return JimSign(ret
) * sort_info
->order
;
6775 /* Remove duplicate elements from the (sorted) list in-place, according to the
6776 * comparison function, comp.
6778 * Note that the last unique value is kept, not the first
6780 static void ListRemoveDuplicates(Jim_Obj
*listObjPtr
, int (*comp
)(Jim_Obj
**lhs
, Jim_Obj
**rhs
))
6784 Jim_Obj
**ele
= listObjPtr
->internalRep
.listValue
.ele
;
6786 for (src
= 1; src
< listObjPtr
->internalRep
.listValue
.len
; src
++) {
6787 if (comp(&ele
[dst
], &ele
[src
]) == 0) {
6788 /* Match, so replace the dest with the current source */
6789 Jim_DecrRefCount(sort_info
->interp
, ele
[dst
]);
6792 /* No match, so keep the current source and move to the next destination */
6795 ele
[dst
] = ele
[src
];
6798 /* At end of list, keep the final element unless all elements were kept */
6800 if (dst
< listObjPtr
->internalRep
.listValue
.len
) {
6801 ele
[dst
] = ele
[src
];
6804 /* Set the new length */
6805 listObjPtr
->internalRep
.listValue
.len
= dst
;
6808 /* Sort a list *in place*. MUST be called with a non-shared list. */
6809 static int ListSortElements(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, struct lsort_info
*info
)
6811 struct lsort_info
*prev_info
;
6813 typedef int (qsort_comparator
) (const void *, const void *);
6814 int (*fn
) (Jim_Obj
**, Jim_Obj
**);
6819 JimPanic((Jim_IsShared(listObjPtr
), "ListSortElements called with shared object"));
6820 SetListFromAny(interp
, listObjPtr
);
6822 /* Allow lsort to be called reentrantly */
6823 prev_info
= sort_info
;
6826 vector
= listObjPtr
->internalRep
.listValue
.ele
;
6827 len
= listObjPtr
->internalRep
.listValue
.len
;
6828 switch (info
->type
) {
6829 case JIM_LSORT_ASCII
:
6830 fn
= ListSortString
;
6832 case JIM_LSORT_NOCASE
:
6833 fn
= ListSortStringNoCase
;
6835 case JIM_LSORT_INTEGER
:
6836 fn
= ListSortInteger
;
6838 case JIM_LSORT_REAL
:
6841 case JIM_LSORT_COMMAND
:
6842 fn
= ListSortCommand
;
6845 fn
= NULL
; /* avoid warning */
6846 JimPanic((1, "ListSort called with invalid sort type"));
6847 return -1; /* Should not be run but keeps static analysers happy */
6850 if (info
->indexed
) {
6851 /* Need to interpose a "list index" function */
6853 fn
= ListSortIndexHelper
;
6856 if ((rc
= setjmp(info
->jmpbuf
)) == 0) {
6857 qsort(vector
, len
, sizeof(Jim_Obj
*), (qsort_comparator
*) fn
);
6859 if (info
->unique
&& len
> 1) {
6860 ListRemoveDuplicates(listObjPtr
, fn
);
6863 Jim_InvalidateStringRep(listObjPtr
);
6865 sort_info
= prev_info
;
6870 /* This is the low-level function to insert elements into a list.
6871 * The higher-level Jim_ListInsertElements() performs shared object
6872 * check and invalidates the string repr. This version is used
6873 * in the internals of the List Object and is not exported.
6875 * NOTE: this function can be called only against objects
6876 * with internal type of List.
6878 * An insertion point (idx) of -1 means end-of-list.
6880 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
)
6882 int currentLen
= listPtr
->internalRep
.listValue
.len
;
6883 int requiredLen
= currentLen
+ elemc
;
6887 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
6888 if (requiredLen
< 2) {
6889 /* Don't do allocations of under 4 pointers. */
6896 listPtr
->internalRep
.listValue
.ele
= Jim_Realloc(listPtr
->internalRep
.listValue
.ele
,
6897 sizeof(Jim_Obj
*) * requiredLen
);
6899 listPtr
->internalRep
.listValue
.maxLen
= requiredLen
;
6904 point
= listPtr
->internalRep
.listValue
.ele
+ idx
;
6905 memmove(point
+ elemc
, point
, (currentLen
- idx
) * sizeof(Jim_Obj
*));
6906 for (i
= 0; i
< elemc
; ++i
) {
6907 point
[i
] = elemVec
[i
];
6908 Jim_IncrRefCount(point
[i
]);
6910 listPtr
->internalRep
.listValue
.len
+= elemc
;
6913 /* Convenience call to ListInsertElements() to append a single element.
6915 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6917 ListInsertElements(listPtr
, -1, 1, &objPtr
);
6920 /* Appends every element of appendListPtr into listPtr.
6921 * Both have to be of the list type.
6922 * Convenience call to ListInsertElements()
6924 static void ListAppendList(Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6926 ListInsertElements(listPtr
, -1,
6927 appendListPtr
->internalRep
.listValue
.len
, appendListPtr
->internalRep
.listValue
.ele
);
6930 void Jim_ListAppendElement(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6932 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendElement called with shared object"));
6933 SetListFromAny(interp
, listPtr
);
6934 Jim_InvalidateStringRep(listPtr
);
6935 ListAppendElement(listPtr
, objPtr
);
6938 void Jim_ListAppendList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6940 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendList called with shared object"));
6941 SetListFromAny(interp
, listPtr
);
6942 SetListFromAny(interp
, appendListPtr
);
6943 Jim_InvalidateStringRep(listPtr
);
6944 ListAppendList(listPtr
, appendListPtr
);
6947 int Jim_ListLength(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6949 SetListFromAny(interp
, objPtr
);
6950 return objPtr
->internalRep
.listValue
.len
;
6953 void Jim_ListInsertElements(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6954 int objc
, Jim_Obj
*const *objVec
)
6956 JimPanic((Jim_IsShared(listPtr
), "Jim_ListInsertElement called with shared object"));
6957 SetListFromAny(interp
, listPtr
);
6958 if (idx
>= 0 && idx
> listPtr
->internalRep
.listValue
.len
)
6959 idx
= listPtr
->internalRep
.listValue
.len
;
6962 Jim_InvalidateStringRep(listPtr
);
6963 ListInsertElements(listPtr
, idx
, objc
, objVec
);
6966 Jim_Obj
*Jim_ListGetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
)
6968 SetListFromAny(interp
, listPtr
);
6969 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6970 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6974 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6975 return listPtr
->internalRep
.listValue
.ele
[idx
];
6978 int Jim_ListIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
, Jim_Obj
**objPtrPtr
, int flags
)
6980 *objPtrPtr
= Jim_ListGetIndex(interp
, listPtr
, idx
);
6981 if (*objPtrPtr
== NULL
) {
6982 if (flags
& JIM_ERRMSG
) {
6983 Jim_SetResultString(interp
, "list index out of range", -1);
6990 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6991 Jim_Obj
*newObjPtr
, int flags
)
6993 SetListFromAny(interp
, listPtr
);
6994 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6995 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6996 if (flags
& JIM_ERRMSG
) {
6997 Jim_SetResultString(interp
, "list index out of range", -1);
7002 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
7003 Jim_DecrRefCount(interp
, listPtr
->internalRep
.listValue
.ele
[idx
]);
7004 listPtr
->internalRep
.listValue
.ele
[idx
] = newObjPtr
;
7005 Jim_IncrRefCount(newObjPtr
);
7009 /* Modify the list stored in the variable named 'varNamePtr'
7010 * setting the element specified by the 'indexc' indexes objects in 'indexv',
7011 * with the new element 'newObjptr'. (implements the [lset] command) */
7012 int Jim_ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
7013 Jim_Obj
*const *indexv
, int indexc
, Jim_Obj
*newObjPtr
)
7015 Jim_Obj
*varObjPtr
, *objPtr
, *listObjPtr
;
7018 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
| JIM_UNSHARED
);
7021 if ((shared
= Jim_IsShared(objPtr
)))
7022 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
7023 for (i
= 0; i
< indexc
- 1; i
++) {
7024 listObjPtr
= objPtr
;
7025 if (Jim_GetIndex(interp
, indexv
[i
], &idx
) != JIM_OK
)
7027 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_ERRMSG
) != JIM_OK
) {
7030 if (Jim_IsShared(objPtr
)) {
7031 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
7032 ListSetIndex(interp
, listObjPtr
, idx
, objPtr
, JIM_NONE
);
7034 Jim_InvalidateStringRep(listObjPtr
);
7036 if (Jim_GetIndex(interp
, indexv
[indexc
- 1], &idx
) != JIM_OK
)
7038 if (ListSetIndex(interp
, objPtr
, idx
, newObjPtr
, JIM_ERRMSG
) == JIM_ERR
)
7040 Jim_InvalidateStringRep(objPtr
);
7041 Jim_InvalidateStringRep(varObjPtr
);
7042 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
7044 Jim_SetResult(interp
, varObjPtr
);
7048 Jim_FreeNewObj(interp
, varObjPtr
);
7053 Jim_Obj
*Jim_ListJoin(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, const char *joinStr
, int joinStrLen
)
7056 int listLen
= Jim_ListLength(interp
, listObjPtr
);
7057 Jim_Obj
*resObjPtr
= Jim_NewEmptyStringObj(interp
);
7059 for (i
= 0; i
< listLen
; ) {
7060 Jim_AppendObj(interp
, resObjPtr
, Jim_ListGetIndex(interp
, listObjPtr
, i
));
7061 if (++i
!= listLen
) {
7062 Jim_AppendString(interp
, resObjPtr
, joinStr
, joinStrLen
);
7068 Jim_Obj
*Jim_ConcatObj(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
7072 /* If all the objects in objv are lists,
7073 * it's possible to return a list as result, that's the
7074 * concatenation of all the lists. */
7075 for (i
= 0; i
< objc
; i
++) {
7076 if (!Jim_IsList(objv
[i
]))
7080 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
7082 for (i
= 0; i
< objc
; i
++)
7083 ListAppendList(objPtr
, objv
[i
]);
7087 /* Else... we have to glue strings together */
7088 int len
= 0, objLen
;
7091 /* Compute the length */
7092 for (i
= 0; i
< objc
; i
++) {
7093 len
+= Jim_Length(objv
[i
]);
7097 /* Create the string rep, and a string object holding it. */
7098 p
= bytes
= Jim_Alloc(len
+ 1);
7099 for (i
= 0; i
< objc
; i
++) {
7100 const char *s
= Jim_GetString(objv
[i
], &objLen
);
7102 /* Remove leading space */
7103 while (objLen
&& isspace(UCHAR(*s
))) {
7108 /* And trailing space */
7109 while (objLen
&& isspace(UCHAR(s
[objLen
- 1]))) {
7110 /* Handle trailing backslash-space case */
7111 if (objLen
> 1 && s
[objLen
- 2] == '\\') {
7117 memcpy(p
, s
, objLen
);
7119 if (i
+ 1 != objc
) {
7123 /* Drop the space calculated for this
7124 * element that is instead null. */
7130 return Jim_NewStringObjNoAlloc(interp
, bytes
, len
);
7134 /* Returns a list composed of the elements in the specified range.
7135 * first and start are directly accepted as Jim_Objects and
7136 * processed for the end?-index? case. */
7137 Jim_Obj
*Jim_ListRange(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*firstObjPtr
,
7138 Jim_Obj
*lastObjPtr
)
7143 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
7144 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
7146 len
= Jim_ListLength(interp
, listObjPtr
); /* will convert into list */
7147 first
= JimRelToAbsIndex(len
, first
);
7148 last
= JimRelToAbsIndex(len
, last
);
7149 JimRelToAbsRange(len
, &first
, &last
, &rangeLen
);
7150 if (first
== 0 && last
== len
) {
7153 return Jim_NewListObj(interp
, listObjPtr
->internalRep
.listValue
.ele
+ first
, rangeLen
);
7156 /* -----------------------------------------------------------------------------
7158 * ---------------------------------------------------------------------------*/
7159 static void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
7160 static void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
7161 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
);
7162 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
7164 /* Dict HashTable Type.
7166 * Keys and Values are Jim objects. */
7168 static const Jim_HashTableType JimDictHashTableType
= {
7169 JimObjectHTHashFunction
, /* hash function */
7170 JimObjectHTKeyValDup
, /* key dup */
7171 JimObjectHTKeyValDup
, /* val dup */
7172 JimObjectHTKeyCompare
, /* key compare */
7173 JimObjectHTKeyValDestructor
, /* key destructor */
7174 JimObjectHTKeyValDestructor
/* val destructor */
7177 /* Note that while the elements of the dict may contain references,
7178 * the list object itself can't. This basically means that the
7179 * dict object string representation as a whole can't contain references
7180 * that are not presents in the single elements. */
7181 static const Jim_ObjType dictObjType
= {
7183 FreeDictInternalRep
,
7189 void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
7191 JIM_NOTUSED(interp
);
7193 Jim_FreeHashTable(objPtr
->internalRep
.ptr
);
7194 Jim_Free(objPtr
->internalRep
.ptr
);
7197 void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
7199 Jim_HashTable
*ht
, *dupHt
;
7200 Jim_HashTableIterator htiter
;
7203 /* Create a new hash table */
7204 ht
= srcPtr
->internalRep
.ptr
;
7205 dupHt
= Jim_Alloc(sizeof(*dupHt
));
7206 Jim_InitHashTable(dupHt
, &JimDictHashTableType
, interp
);
7208 Jim_ExpandHashTable(dupHt
, ht
->size
);
7209 /* Copy every element from the source to the dup hash table */
7210 JimInitHashTableIterator(ht
, &htiter
);
7211 while ((he
= Jim_NextHashEntry(&htiter
)) != NULL
) {
7212 Jim_AddHashEntry(dupHt
, he
->key
, he
->u
.val
);
7215 dupPtr
->internalRep
.ptr
= dupHt
;
7216 dupPtr
->typePtr
= &dictObjType
;
7219 static Jim_Obj
**JimDictPairs(Jim_Obj
*dictPtr
, int *len
)
7222 Jim_HashTableIterator htiter
;
7227 ht
= dictPtr
->internalRep
.ptr
;
7229 /* Turn the hash table into a flat vector of Jim_Objects. */
7230 objv
= Jim_Alloc((ht
->used
* 2) * sizeof(Jim_Obj
*));
7231 JimInitHashTableIterator(ht
, &htiter
);
7233 while ((he
= Jim_NextHashEntry(&htiter
)) != NULL
) {
7234 objv
[i
++] = Jim_GetHashEntryKey(he
);
7235 objv
[i
++] = Jim_GetHashEntryVal(he
);
7241 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
)
7243 /* Turn the hash table into a flat vector of Jim_Objects. */
7245 Jim_Obj
**objv
= JimDictPairs(objPtr
, &len
);
7247 /* And now generate the string rep as a list */
7248 JimMakeListStringRep(objPtr
, objv
, len
);
7253 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
7257 if (objPtr
->typePtr
== &dictObjType
) {
7261 if (Jim_IsList(objPtr
) && Jim_IsShared(objPtr
)) {
7262 /* A shared list, so get the string representation now to avoid
7263 * changing the order in case of fast conversion to dict.
7268 /* For simplicity, convert a non-list object to a list and then to a dict */
7269 listlen
= Jim_ListLength(interp
, objPtr
);
7271 Jim_SetResultString(interp
, "missing value to go with key", -1);
7275 /* Converting from a list to a dict can't fail */
7279 ht
= Jim_Alloc(sizeof(*ht
));
7280 Jim_InitHashTable(ht
, &JimDictHashTableType
, interp
);
7282 for (i
= 0; i
< listlen
; i
+= 2) {
7283 Jim_Obj
*keyObjPtr
= Jim_ListGetIndex(interp
, objPtr
, i
);
7284 Jim_Obj
*valObjPtr
= Jim_ListGetIndex(interp
, objPtr
, i
+ 1);
7286 Jim_ReplaceHashEntry(ht
, keyObjPtr
, valObjPtr
);
7289 Jim_FreeIntRep(interp
, objPtr
);
7290 objPtr
->typePtr
= &dictObjType
;
7291 objPtr
->internalRep
.ptr
= ht
;
7297 /* Dict object API */
7299 /* Add an element to a dict. objPtr must be of the "dict" type.
7300 * The higher-level exported function is Jim_DictAddElement().
7301 * If an element with the specified key already exists, the value
7302 * associated is replaced with the new one.
7304 * if valueObjPtr == NULL, the key is instead removed if it exists. */
7305 static int DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
7306 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
7308 Jim_HashTable
*ht
= objPtr
->internalRep
.ptr
;
7310 if (valueObjPtr
== NULL
) { /* unset */
7311 return Jim_DeleteHashEntry(ht
, keyObjPtr
);
7313 Jim_ReplaceHashEntry(ht
, keyObjPtr
, valueObjPtr
);
7317 /* Add an element, higher-level interface for DictAddElement().
7318 * If valueObjPtr == NULL, the key is removed if it exists. */
7319 int Jim_DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
7320 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
7322 JimPanic((Jim_IsShared(objPtr
), "Jim_DictAddElement called with shared object"));
7323 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
7326 Jim_InvalidateStringRep(objPtr
);
7327 return DictAddElement(interp
, objPtr
, keyObjPtr
, valueObjPtr
);
7330 Jim_Obj
*Jim_NewDictObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
7335 JimPanic((len
% 2, "Jim_NewDictObj() 'len' argument must be even"));
7337 objPtr
= Jim_NewObj(interp
);
7338 objPtr
->typePtr
= &dictObjType
;
7339 objPtr
->bytes
= NULL
;
7340 objPtr
->internalRep
.ptr
= Jim_Alloc(sizeof(Jim_HashTable
));
7341 Jim_InitHashTable(objPtr
->internalRep
.ptr
, &JimDictHashTableType
, interp
);
7342 for (i
= 0; i
< len
; i
+= 2)
7343 DictAddElement(interp
, objPtr
, elements
[i
], elements
[i
+ 1]);
7347 /* Return the value associated to the specified dict key
7348 * Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
7350 * Sets *objPtrPtr to non-NULL only upon success.
7352 int Jim_DictKey(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
*keyPtr
,
7353 Jim_Obj
**objPtrPtr
, int flags
)
7358 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
) {
7361 ht
= dictPtr
->internalRep
.ptr
;
7362 if ((he
= Jim_FindHashEntry(ht
, keyPtr
)) == NULL
) {
7363 if (flags
& JIM_ERRMSG
) {
7364 Jim_SetResultFormatted(interp
, "key \"%#s\" not known in dictionary", keyPtr
);
7369 *objPtrPtr
= Jim_GetHashEntryVal(he
);
7374 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
7375 int Jim_DictPairs(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
***objPtrPtr
, int *len
)
7377 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
) {
7380 *objPtrPtr
= JimDictPairs(dictPtr
, len
);
7386 /* Return the value associated to the specified dict keys */
7387 int Jim_DictKeysVector(Jim_Interp
*interp
, Jim_Obj
*dictPtr
,
7388 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
**objPtrPtr
, int flags
)
7393 *objPtrPtr
= dictPtr
;
7397 for (i
= 0; i
< keyc
; i
++) {
7400 int rc
= Jim_DictKey(interp
, dictPtr
, keyv
[i
], &objPtr
, flags
);
7406 *objPtrPtr
= dictPtr
;
7410 /* Modify the dict stored into the variable named 'varNamePtr'
7411 * setting the element specified by the 'keyc' keys objects in 'keyv',
7412 * with the new value of the element 'newObjPtr'.
7414 * If newObjPtr == NULL the operation is to remove the given key
7415 * from the dictionary.
7417 * If flags & JIM_ERRMSG, then failure to remove the key is considered an error
7418 * and JIM_ERR is returned. Otherwise it is ignored and JIM_OK is returned.
7420 int Jim_SetDictKeysVector(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
7421 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*newObjPtr
, int flags
)
7423 Jim_Obj
*varObjPtr
, *objPtr
, *dictObjPtr
;
7426 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, flags
);
7427 if (objPtr
== NULL
) {
7428 if (newObjPtr
== NULL
&& (flags
& JIM_MUSTEXIST
)) {
7429 /* Cannot remove a key from non existing var */
7432 varObjPtr
= objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
7433 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
7434 Jim_FreeNewObj(interp
, varObjPtr
);
7438 if ((shared
= Jim_IsShared(objPtr
)))
7439 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
7440 for (i
= 0; i
< keyc
; i
++) {
7441 dictObjPtr
= objPtr
;
7443 /* Check if it's a valid dictionary */
7444 if (SetDictFromAny(interp
, dictObjPtr
) != JIM_OK
) {
7448 if (i
== keyc
- 1) {
7449 /* Last key: Note that error on unset with missing last key is OK */
7450 if (Jim_DictAddElement(interp
, objPtr
, keyv
[keyc
- 1], newObjPtr
) != JIM_OK
) {
7451 if (newObjPtr
|| (flags
& JIM_MUSTEXIST
)) {
7458 /* Check if the given key exists. */
7459 Jim_InvalidateStringRep(dictObjPtr
);
7460 if (Jim_DictKey(interp
, dictObjPtr
, keyv
[i
], &objPtr
,
7461 newObjPtr
? JIM_NONE
: JIM_ERRMSG
) == JIM_OK
) {
7462 /* This key exists at the current level.
7463 * Make sure it's not shared!. */
7464 if (Jim_IsShared(objPtr
)) {
7465 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
7466 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
7470 /* Key not found. If it's an [unset] operation
7471 * this is an error. Only the last key may not
7473 if (newObjPtr
== NULL
) {
7476 /* Otherwise set an empty dictionary
7477 * as key's value. */
7478 objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
7479 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
7482 /* XXX: Is this necessary? */
7483 Jim_InvalidateStringRep(objPtr
);
7484 Jim_InvalidateStringRep(varObjPtr
);
7485 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
) {
7488 Jim_SetResult(interp
, varObjPtr
);
7492 Jim_FreeNewObj(interp
, varObjPtr
);
7497 /* -----------------------------------------------------------------------------
7499 * ---------------------------------------------------------------------------*/
7500 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
);
7501 static int SetIndexFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
7503 static const Jim_ObjType indexObjType
= {
7507 UpdateStringOfIndex
,
7511 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
)
7513 if (objPtr
->internalRep
.intValue
== -1) {
7514 JimSetStringBytes(objPtr
, "end");
7517 char buf
[JIM_INTEGER_SPACE
+ 1];
7518 if (objPtr
->internalRep
.intValue
>= 0 || objPtr
->internalRep
.intValue
== -INT_MAX
) {
7519 sprintf(buf
, "%d", objPtr
->internalRep
.intValue
);
7523 sprintf(buf
, "end%d", objPtr
->internalRep
.intValue
+ 1);
7525 JimSetStringBytes(objPtr
, buf
);
7529 static int SetIndexFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
7535 /* Get the string representation */
7536 str
= Jim_String(objPtr
);
7538 /* Try to convert into an index */
7539 if (strncmp(str
, "end", 3) == 0) {
7545 idx
= jim_strtol(str
, &endptr
);
7547 if (endptr
== str
) {
7553 /* Now str may include or +<num> or -<num> */
7554 if (*str
== '+' || *str
== '-') {
7555 int sign
= (*str
== '+' ? 1 : -1);
7557 idx
+= sign
* jim_strtol(++str
, &endptr
);
7558 if (str
== endptr
|| *endptr
) {
7563 /* The only thing left should be spaces */
7564 while (isspace(UCHAR(*str
))) {
7575 /* end-1 is repesented as -2 */
7583 /* Free the old internal repr and set the new one. */
7584 Jim_FreeIntRep(interp
, objPtr
);
7585 objPtr
->typePtr
= &indexObjType
;
7586 objPtr
->internalRep
.intValue
= idx
;
7590 Jim_SetResultFormatted(interp
,
7591 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr
);
7595 int Jim_GetIndex(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *indexPtr
)
7597 /* Avoid shimmering if the object is an integer. */
7598 if (objPtr
->typePtr
== &intObjType
) {
7599 jim_wide val
= JimWideValue(objPtr
);
7602 *indexPtr
= -INT_MAX
;
7603 else if (val
> INT_MAX
)
7604 *indexPtr
= INT_MAX
;
7606 *indexPtr
= (int)val
;
7609 if (objPtr
->typePtr
!= &indexObjType
&& SetIndexFromAny(interp
, objPtr
) == JIM_ERR
)
7611 *indexPtr
= objPtr
->internalRep
.intValue
;
7615 /* -----------------------------------------------------------------------------
7616 * Return Code Object.
7617 * ---------------------------------------------------------------------------*/
7619 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
7620 static const char * const jimReturnCodes
[] = {
7632 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes) - 1)
7634 static const Jim_ObjType returnCodeObjType
= {
7642 /* Converts a (standard) return code to a string. Returns "?" for
7643 * non-standard return codes.
7645 const char *Jim_ReturnCode(int code
)
7647 if (code
< 0 || code
>= (int)jimReturnCodesSize
) {
7651 return jimReturnCodes
[code
];
7655 static int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
7660 /* Try to convert into an integer */
7661 if (JimGetWideNoErr(interp
, objPtr
, &wideValue
) != JIM_ERR
)
7662 returnCode
= (int)wideValue
;
7663 else if (Jim_GetEnum(interp
, objPtr
, jimReturnCodes
, &returnCode
, NULL
, JIM_NONE
) != JIM_OK
) {
7664 Jim_SetResultFormatted(interp
, "expected return code but got \"%#s\"", objPtr
);
7667 /* Free the old internal repr and set the new one. */
7668 Jim_FreeIntRep(interp
, objPtr
);
7669 objPtr
->typePtr
= &returnCodeObjType
;
7670 objPtr
->internalRep
.intValue
= returnCode
;
7674 int Jim_GetReturnCode(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *intPtr
)
7676 if (objPtr
->typePtr
!= &returnCodeObjType
&& SetReturnCodeFromAny(interp
, objPtr
) == JIM_ERR
)
7678 *intPtr
= objPtr
->internalRep
.intValue
;
7682 /* -----------------------------------------------------------------------------
7683 * Expression Parsing
7684 * ---------------------------------------------------------------------------*/
7685 static int JimParseExprOperator(struct JimParserCtx
*pc
);
7686 static int JimParseExprNumber(struct JimParserCtx
*pc
);
7687 static int JimParseExprIrrational(struct JimParserCtx
*pc
);
7688 static int JimParseExprBoolean(struct JimParserCtx
*pc
);
7690 /* expr operator opcodes. */
7693 /* Continues on from the JIM_TT_ space */
7695 /* Binary operators (numbers) */
7696 JIM_EXPROP_MUL
= JIM_TT_EXPR_OP
, /* 20 */
7711 JIM_EXPROP_BITAND
, /* 35 */
7714 JIM_EXPROP_LOGICAND
, /* 38 */
7715 JIM_EXPROP_LOGICOR
, /* 39 */
7716 JIM_EXPROP_TERNARY
, /* 40 */
7717 JIM_EXPROP_COLON
, /* 41 */
7718 JIM_EXPROP_POW
, /* 42 */
7720 /* Binary operators (strings) */
7721 JIM_EXPROP_STREQ
, /* 43 */
7726 /* Unary operators (numbers) */
7727 JIM_EXPROP_NOT
, /* 47 */
7729 JIM_EXPROP_UNARYMINUS
,
7730 JIM_EXPROP_UNARYPLUS
,
7733 JIM_EXPROP_FUNC_INT
, /* 51 */
7734 JIM_EXPROP_FUNC_WIDE
,
7735 JIM_EXPROP_FUNC_ABS
,
7736 JIM_EXPROP_FUNC_DOUBLE
,
7737 JIM_EXPROP_FUNC_ROUND
,
7738 JIM_EXPROP_FUNC_RAND
,
7739 JIM_EXPROP_FUNC_SRAND
,
7741 /* math functions from libm */
7742 JIM_EXPROP_FUNC_SIN
, /* 65 */
7743 JIM_EXPROP_FUNC_COS
,
7744 JIM_EXPROP_FUNC_TAN
,
7745 JIM_EXPROP_FUNC_ASIN
,
7746 JIM_EXPROP_FUNC_ACOS
,
7747 JIM_EXPROP_FUNC_ATAN
,
7748 JIM_EXPROP_FUNC_ATAN2
,
7749 JIM_EXPROP_FUNC_SINH
,
7750 JIM_EXPROP_FUNC_COSH
,
7751 JIM_EXPROP_FUNC_TANH
,
7752 JIM_EXPROP_FUNC_CEIL
,
7753 JIM_EXPROP_FUNC_FLOOR
,
7754 JIM_EXPROP_FUNC_EXP
,
7755 JIM_EXPROP_FUNC_LOG
,
7756 JIM_EXPROP_FUNC_LOG10
,
7757 JIM_EXPROP_FUNC_SQRT
,
7758 JIM_EXPROP_FUNC_POW
,
7759 JIM_EXPROP_FUNC_HYPOT
,
7760 JIM_EXPROP_FUNC_FMOD
,
7763 /* A expression node is either a term or an operator
7764 * If a node is an operator, 'op' points to the details of the operator and it's terms.
7766 struct JimExprNode
{
7767 int type
; /* JIM_TT_xxx */
7768 struct Jim_Obj
*objPtr
; /* The object for a term, or NULL for an operator */
7770 struct JimExprNode
*left
; /* For all operators */
7771 struct JimExprNode
*right
; /* For binary operators */
7772 struct JimExprNode
*ternary
; /* For ternary operator only */
7775 /* Operators table */
7776 typedef struct Jim_ExprOperator
7779 int (*funcop
) (Jim_Interp
*interp
, struct JimExprNode
*opnode
);
7780 unsigned char precedence
;
7781 unsigned char arity
;
7783 unsigned char namelen
;
7786 static int JimExprGetTerm(Jim_Interp
*interp
, struct JimExprNode
*node
, Jim_Obj
**objPtrPtr
);
7787 static int JimExprGetTermBoolean(Jim_Interp
*interp
, struct JimExprNode
*node
);
7788 static int JimExprEvalTermNode(Jim_Interp
*interp
, struct JimExprNode
*node
);
7790 static int JimExprOpNumUnary(Jim_Interp
*interp
, struct JimExprNode
*node
)
7795 jim_wide wA
, wC
= 0;
7798 if ((rc
= JimExprGetTerm(interp
, node
->left
, &A
)) != JIM_OK
) {
7802 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) && JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
) {
7803 switch (node
->type
) {
7804 case JIM_EXPROP_FUNC_INT
:
7805 case JIM_EXPROP_FUNC_WIDE
:
7806 case JIM_EXPROP_FUNC_ROUND
:
7807 case JIM_EXPROP_UNARYPLUS
:
7810 case JIM_EXPROP_FUNC_DOUBLE
:
7814 case JIM_EXPROP_FUNC_ABS
:
7815 wC
= wA
>= 0 ? wA
: -wA
;
7817 case JIM_EXPROP_UNARYMINUS
:
7820 case JIM_EXPROP_NOT
:
7827 else if ((rc
= Jim_GetDouble(interp
, A
, &dA
)) == JIM_OK
) {
7828 switch (node
->type
) {
7829 case JIM_EXPROP_FUNC_INT
:
7830 case JIM_EXPROP_FUNC_WIDE
:
7833 case JIM_EXPROP_FUNC_ROUND
:
7834 wC
= dA
< 0 ? (dA
- 0.5) : (dA
+ 0.5);
7836 case JIM_EXPROP_FUNC_DOUBLE
:
7837 case JIM_EXPROP_UNARYPLUS
:
7841 case JIM_EXPROP_FUNC_ABS
:
7842 #ifdef JIM_MATH_FUNCTIONS
7845 dC
= dA
>= 0 ? dA
: -dA
;
7849 case JIM_EXPROP_UNARYMINUS
:
7853 case JIM_EXPROP_NOT
:
7863 Jim_SetResultInt(interp
, wC
);
7866 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, dC
));
7870 Jim_DecrRefCount(interp
, A
);
7875 static double JimRandDouble(Jim_Interp
*interp
)
7878 JimRandomBytes(interp
, &x
, sizeof(x
));
7880 return (double)x
/ (unsigned long)~0;
7883 static int JimExprOpIntUnary(Jim_Interp
*interp
, struct JimExprNode
*node
)
7889 if ((rc
= JimExprGetTerm(interp
, node
->left
, &A
)) != JIM_OK
) {
7893 rc
= Jim_GetWide(interp
, A
, &wA
);
7895 switch (node
->type
) {
7896 case JIM_EXPROP_BITNOT
:
7897 Jim_SetResultInt(interp
, ~wA
);
7899 case JIM_EXPROP_FUNC_SRAND
:
7900 JimPrngSeed(interp
, (unsigned char *)&wA
, sizeof(wA
));
7901 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7908 Jim_DecrRefCount(interp
, A
);
7913 static int JimExprOpNone(Jim_Interp
*interp
, struct JimExprNode
*node
)
7915 JimPanic((node
->type
!= JIM_EXPROP_FUNC_RAND
, "JimExprOpNone only support rand()"));
7917 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7922 #ifdef JIM_MATH_FUNCTIONS
7923 static int JimExprOpDoubleUnary(Jim_Interp
*interp
, struct JimExprNode
*node
)
7929 if ((rc
= JimExprGetTerm(interp
, node
->left
, &A
)) != JIM_OK
) {
7933 rc
= Jim_GetDouble(interp
, A
, &dA
);
7935 switch (node
->type
) {
7936 case JIM_EXPROP_FUNC_SIN
:
7939 case JIM_EXPROP_FUNC_COS
:
7942 case JIM_EXPROP_FUNC_TAN
:
7945 case JIM_EXPROP_FUNC_ASIN
:
7948 case JIM_EXPROP_FUNC_ACOS
:
7951 case JIM_EXPROP_FUNC_ATAN
:
7954 case JIM_EXPROP_FUNC_SINH
:
7957 case JIM_EXPROP_FUNC_COSH
:
7960 case JIM_EXPROP_FUNC_TANH
:
7963 case JIM_EXPROP_FUNC_CEIL
:
7966 case JIM_EXPROP_FUNC_FLOOR
:
7969 case JIM_EXPROP_FUNC_EXP
:
7972 case JIM_EXPROP_FUNC_LOG
:
7975 case JIM_EXPROP_FUNC_LOG10
:
7978 case JIM_EXPROP_FUNC_SQRT
:
7984 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, dC
));
7987 Jim_DecrRefCount(interp
, A
);
7993 /* A binary operation on two ints */
7994 static int JimExprOpIntBin(Jim_Interp
*interp
, struct JimExprNode
*node
)
8000 if ((rc
= JimExprGetTerm(interp
, node
->left
, &A
)) != JIM_OK
) {
8003 if ((rc
= JimExprGetTerm(interp
, node
->right
, &B
)) != JIM_OK
) {
8004 Jim_DecrRefCount(interp
, A
);
8010 if (Jim_GetWide(interp
, A
, &wA
) == JIM_OK
&& Jim_GetWide(interp
, B
, &wB
) == JIM_OK
) {
8015 switch (node
->type
) {
8016 case JIM_EXPROP_LSHIFT
:
8019 case JIM_EXPROP_RSHIFT
:
8022 case JIM_EXPROP_BITAND
:
8025 case JIM_EXPROP_BITXOR
:
8028 case JIM_EXPROP_BITOR
:
8031 case JIM_EXPROP_MOD
:
8034 Jim_SetResultString(interp
, "Division by zero", -1);
8041 * This code is tricky: C doesn't guarantee much
8042 * about the quotient or remainder, but Tcl does.
8043 * The remainder always has the same sign as the
8044 * divisor and a smaller absolute value.
8062 case JIM_EXPROP_ROTL
:
8063 case JIM_EXPROP_ROTR
:{
8064 /* uint32_t would be better. But not everyone has inttypes.h? */
8065 unsigned long uA
= (unsigned long)wA
;
8066 unsigned long uB
= (unsigned long)wB
;
8067 const unsigned int S
= sizeof(unsigned long) * 8;
8069 /* Shift left by the word size or more is undefined. */
8072 if (node
->type
== JIM_EXPROP_ROTR
) {
8075 wC
= (unsigned long)(uA
<< uB
) | (uA
>> (S
- uB
));
8081 Jim_SetResultInt(interp
, wC
);
8084 Jim_DecrRefCount(interp
, A
);
8085 Jim_DecrRefCount(interp
, B
);
8091 /* A binary operation on two ints or two doubles (or two strings for some ops) */
8092 static int JimExprOpBin(Jim_Interp
*interp
, struct JimExprNode
*node
)
8095 double dA
, dB
, dC
= 0;
8096 jim_wide wA
, wB
, wC
= 0;
8099 if ((rc
= JimExprGetTerm(interp
, node
->left
, &A
)) != JIM_OK
) {
8102 if ((rc
= JimExprGetTerm(interp
, node
->right
, &B
)) != JIM_OK
) {
8103 Jim_DecrRefCount(interp
, A
);
8107 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) &&
8108 (B
->typePtr
!= &doubleObjType
|| B
->bytes
) &&
8109 JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
&& JimGetWideNoErr(interp
, B
, &wB
) == JIM_OK
) {
8113 switch (node
->type
) {
8114 case JIM_EXPROP_POW
:
8115 case JIM_EXPROP_FUNC_POW
:
8116 if (wA
== 0 && wB
< 0) {
8117 Jim_SetResultString(interp
, "exponentiation of zero by negative power", -1);
8121 wC
= JimPowWide(wA
, wB
);
8123 case JIM_EXPROP_ADD
:
8126 case JIM_EXPROP_SUB
:
8129 case JIM_EXPROP_MUL
:
8132 case JIM_EXPROP_DIV
:
8134 Jim_SetResultString(interp
, "Division by zero", -1);
8142 * This code is tricky: C doesn't guarantee much
8143 * about the quotient or remainder, but Tcl does.
8144 * The remainder always has the same sign as the
8145 * divisor and a smaller absolute value.
8163 case JIM_EXPROP_LTE
:
8166 case JIM_EXPROP_GTE
:
8169 case JIM_EXPROP_NUMEQ
:
8172 case JIM_EXPROP_NUMNE
:
8177 if (Jim_GetDouble(interp
, A
, &dA
) == JIM_OK
&& Jim_GetDouble(interp
, B
, &dB
) == JIM_OK
) {
8178 switch (node
->type
) {
8179 #ifndef JIM_MATH_FUNCTIONS
8180 case JIM_EXPROP_POW
:
8181 case JIM_EXPROP_FUNC_POW
:
8182 case JIM_EXPROP_FUNC_ATAN2
:
8183 case JIM_EXPROP_FUNC_HYPOT
:
8184 case JIM_EXPROP_FUNC_FMOD
:
8185 Jim_SetResultString(interp
, "unsupported", -1);
8189 case JIM_EXPROP_POW
:
8190 case JIM_EXPROP_FUNC_POW
:
8193 case JIM_EXPROP_FUNC_ATAN2
:
8196 case JIM_EXPROP_FUNC_HYPOT
:
8199 case JIM_EXPROP_FUNC_FMOD
:
8203 case JIM_EXPROP_ADD
:
8206 case JIM_EXPROP_SUB
:
8209 case JIM_EXPROP_MUL
:
8212 case JIM_EXPROP_DIV
:
8215 dC
= dA
< 0 ? -INFINITY
: INFINITY
;
8217 dC
= (dA
< 0 ? -1.0 : 1.0) * strtod("Inf", NULL
);
8230 case JIM_EXPROP_LTE
:
8233 case JIM_EXPROP_GTE
:
8236 case JIM_EXPROP_NUMEQ
:
8239 case JIM_EXPROP_NUMNE
:
8245 /* Handle the string case */
8247 /* XXX: Could optimise the eq/ne case by checking lengths */
8248 int i
= Jim_StringCompareObj(interp
, A
, B
, 0);
8250 switch (node
->type
) {
8257 case JIM_EXPROP_LTE
:
8260 case JIM_EXPROP_GTE
:
8263 case JIM_EXPROP_NUMEQ
:
8266 case JIM_EXPROP_NUMNE
:
8271 /* If we get here, it is an error */
8274 Jim_DecrRefCount(interp
, A
);
8275 Jim_DecrRefCount(interp
, B
);
8278 Jim_SetResultInt(interp
, wC
);
8281 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, dC
));
8285 static int JimSearchList(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*valObj
)
8290 listlen
= Jim_ListLength(interp
, listObjPtr
);
8291 for (i
= 0; i
< listlen
; i
++) {
8292 if (Jim_StringEqObj(Jim_ListGetIndex(interp
, listObjPtr
, i
), valObj
)) {
8301 static int JimExprOpStrBin(Jim_Interp
*interp
, struct JimExprNode
*node
)
8307 if ((rc
= JimExprGetTerm(interp
, node
->left
, &A
)) != JIM_OK
) {
8310 if ((rc
= JimExprGetTerm(interp
, node
->right
, &B
)) != JIM_OK
) {
8311 Jim_DecrRefCount(interp
, A
);
8315 switch (node
->type
) {
8316 case JIM_EXPROP_STREQ
:
8317 case JIM_EXPROP_STRNE
:
8318 wC
= Jim_StringEqObj(A
, B
);
8319 if (node
->type
== JIM_EXPROP_STRNE
) {
8323 case JIM_EXPROP_STRIN
:
8324 wC
= JimSearchList(interp
, B
, A
);
8326 case JIM_EXPROP_STRNI
:
8327 wC
= !JimSearchList(interp
, B
, A
);
8332 Jim_SetResultInt(interp
, wC
);
8334 Jim_DecrRefCount(interp
, A
);
8335 Jim_DecrRefCount(interp
, B
);
8340 static int ExprBool(Jim_Interp
*interp
, Jim_Obj
*obj
)
8347 /* In case the object is interp->result with refcount 1*/
8348 Jim_IncrRefCount(obj
);
8350 if (Jim_GetLong(interp
, obj
, &l
) == JIM_OK
) {
8353 else if (Jim_GetDouble(interp
, obj
, &d
) == JIM_OK
) {
8356 else if (Jim_GetBoolean(interp
, obj
, &b
) == JIM_OK
) {
8360 Jim_DecrRefCount(interp
, obj
);
8364 static int JimExprOpAnd(Jim_Interp
*interp
, struct JimExprNode
*node
)
8367 int result
= JimExprGetTermBoolean(interp
, node
->left
);
8370 /* true so evaluate right */
8371 result
= JimExprGetTermBoolean(interp
, node
->right
);
8376 Jim_SetResultInt(interp
, result
);
8380 static int JimExprOpOr(Jim_Interp
*interp
, struct JimExprNode
*node
)
8383 int result
= JimExprGetTermBoolean(interp
, node
->left
);
8386 /* false so evaluate right */
8387 result
= JimExprGetTermBoolean(interp
, node
->right
);
8392 Jim_SetResultInt(interp
, result
);
8396 static int JimExprOpTernary(Jim_Interp
*interp
, struct JimExprNode
*node
)
8399 int result
= JimExprGetTermBoolean(interp
, node
->left
);
8402 /* true so select right */
8403 return JimExprEvalTermNode(interp
, node
->right
);
8405 else if (result
== 0) {
8406 /* false so select ternary */
8407 return JimExprEvalTermNode(interp
, node
->ternary
);
8415 OP_FUNC
= 0x0001, /* function syntax */
8416 OP_RIGHT_ASSOC
= 0x0002, /* right associative */
8419 /* name - precedence - arity - opcode
8421 * This array *must* be kept in sync with the JIM_EXPROP enum.
8423 * The following macros pre-compute the string length at compile time.
8425 #define OPRINIT_ATTR(N, P, ARITY, F, ATTR) {N, F, P, ARITY, ATTR, sizeof(N) - 1}
8426 #define OPRINIT(N, P, ARITY, F) OPRINIT_ATTR(N, P, ARITY, F, 0)
8428 static const struct Jim_ExprOperator Jim_ExprOperators
[] = {
8429 OPRINIT("*", 110, 2, JimExprOpBin
),
8430 OPRINIT("/", 110, 2, JimExprOpBin
),
8431 OPRINIT("%", 110, 2, JimExprOpIntBin
),
8433 OPRINIT("-", 100, 2, JimExprOpBin
),
8434 OPRINIT("+", 100, 2, JimExprOpBin
),
8436 OPRINIT("<<", 90, 2, JimExprOpIntBin
),
8437 OPRINIT(">>", 90, 2, JimExprOpIntBin
),
8439 OPRINIT("<<<", 90, 2, JimExprOpIntBin
),
8440 OPRINIT(">>>", 90, 2, JimExprOpIntBin
),
8442 OPRINIT("<", 80, 2, JimExprOpBin
),
8443 OPRINIT(">", 80, 2, JimExprOpBin
),
8444 OPRINIT("<=", 80, 2, JimExprOpBin
),
8445 OPRINIT(">=", 80, 2, JimExprOpBin
),
8447 OPRINIT("==", 70, 2, JimExprOpBin
),
8448 OPRINIT("!=", 70, 2, JimExprOpBin
),
8450 OPRINIT("&", 50, 2, JimExprOpIntBin
),
8451 OPRINIT("^", 49, 2, JimExprOpIntBin
),
8452 OPRINIT("|", 48, 2, JimExprOpIntBin
),
8454 OPRINIT("&&", 10, 2, JimExprOpAnd
),
8455 OPRINIT("||", 9, 2, JimExprOpOr
),
8456 OPRINIT_ATTR("?", 5, 3, JimExprOpTernary
, OP_RIGHT_ASSOC
),
8457 OPRINIT_ATTR(":", 5, 3, NULL
, OP_RIGHT_ASSOC
),
8459 /* Precedence is higher than * and / but lower than ! and ~, and right-associative */
8460 OPRINIT_ATTR("**", 120, 2, JimExprOpBin
, OP_RIGHT_ASSOC
),
8462 OPRINIT("eq", 60, 2, JimExprOpStrBin
),
8463 OPRINIT("ne", 60, 2, JimExprOpStrBin
),
8465 OPRINIT("in", 55, 2, JimExprOpStrBin
),
8466 OPRINIT("ni", 55, 2, JimExprOpStrBin
),
8468 OPRINIT_ATTR("!", 150, 1, JimExprOpNumUnary
, OP_RIGHT_ASSOC
),
8469 OPRINIT_ATTR("~", 150, 1, JimExprOpIntUnary
, OP_RIGHT_ASSOC
),
8470 OPRINIT_ATTR(" -", 150, 1, JimExprOpNumUnary
, OP_RIGHT_ASSOC
),
8471 OPRINIT_ATTR(" +", 150, 1, JimExprOpNumUnary
, OP_RIGHT_ASSOC
),
8475 OPRINIT_ATTR("int", 200, 1, JimExprOpNumUnary
, OP_FUNC
),
8476 OPRINIT_ATTR("wide", 200, 1, JimExprOpNumUnary
, OP_FUNC
),
8477 OPRINIT_ATTR("abs", 200, 1, JimExprOpNumUnary
, OP_FUNC
),
8478 OPRINIT_ATTR("double", 200, 1, JimExprOpNumUnary
, OP_FUNC
),
8479 OPRINIT_ATTR("round", 200, 1, JimExprOpNumUnary
, OP_FUNC
),
8480 OPRINIT_ATTR("rand", 200, 0, JimExprOpNone
, OP_FUNC
),
8481 OPRINIT_ATTR("srand", 200, 1, JimExprOpIntUnary
, OP_FUNC
),
8483 #ifdef JIM_MATH_FUNCTIONS
8484 OPRINIT_ATTR("sin", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8485 OPRINIT_ATTR("cos", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8486 OPRINIT_ATTR("tan", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8487 OPRINIT_ATTR("asin", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8488 OPRINIT_ATTR("acos", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8489 OPRINIT_ATTR("atan", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8490 OPRINIT_ATTR("atan2", 200, 2, JimExprOpBin
, OP_FUNC
),
8491 OPRINIT_ATTR("sinh", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8492 OPRINIT_ATTR("cosh", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8493 OPRINIT_ATTR("tanh", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8494 OPRINIT_ATTR("ceil", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8495 OPRINIT_ATTR("floor", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8496 OPRINIT_ATTR("exp", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8497 OPRINIT_ATTR("log", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8498 OPRINIT_ATTR("log10", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8499 OPRINIT_ATTR("sqrt", 200, 1, JimExprOpDoubleUnary
, OP_FUNC
),
8500 OPRINIT_ATTR("pow", 200, 2, JimExprOpBin
, OP_FUNC
),
8501 OPRINIT_ATTR("hypot", 200, 2, JimExprOpBin
, OP_FUNC
),
8502 OPRINIT_ATTR("fmod", 200, 2, JimExprOpBin
, OP_FUNC
),
8508 #define JIM_EXPR_OPERATORS_NUM \
8509 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
8511 static int JimParseExpression(struct JimParserCtx
*pc
)
8513 /* Discard spaces and quoted newline */
8514 while (isspace(UCHAR(*pc
->p
)) || (*(pc
->p
) == '\\' && *(pc
->p
+ 1) == '\n')) {
8515 if (*pc
->p
== '\n') {
8523 pc
->tline
= pc
->linenr
;
8528 pc
->tt
= JIM_TT_EOL
;
8534 pc
->tt
= JIM_TT_SUBEXPR_START
;
8537 pc
->tt
= JIM_TT_SUBEXPR_END
;
8540 pc
->tt
= JIM_TT_SUBEXPR_COMMA
;
8547 return JimParseCmd(pc
);
8549 if (JimParseVar(pc
) == JIM_ERR
)
8550 return JimParseExprOperator(pc
);
8552 /* Don't allow expr sugar in expressions */
8553 if (pc
->tt
== JIM_TT_EXPRSUGAR
) {
8570 return JimParseExprNumber(pc
);
8572 return JimParseQuote(pc
);
8574 return JimParseBrace(pc
);
8580 if (JimParseExprIrrational(pc
) == JIM_ERR
)
8581 if (JimParseExprBoolean(pc
) == JIM_ERR
)
8582 return JimParseExprOperator(pc
);
8588 if (JimParseExprBoolean(pc
) == JIM_ERR
)
8589 return JimParseExprOperator(pc
);
8592 return JimParseExprOperator(pc
);
8598 static int JimParseExprNumber(struct JimParserCtx
*pc
)
8602 /* Assume an integer for now */
8603 pc
->tt
= JIM_TT_EXPR_INT
;
8605 jim_strtoull(pc
->p
, (char **)&pc
->p
);
8606 /* Tried as an integer, but perhaps it parses as a double */
8607 if (strchr("eENnIi.", *pc
->p
) || pc
->p
== pc
->tstart
) {
8608 /* Some stupid compilers insist they are cleverer that
8609 * we are. Even a (void) cast doesn't prevent this warning!
8611 if (strtod(pc
->tstart
, &end
)) { /* nothing */ }
8612 if (end
== pc
->tstart
)
8615 /* Yes, double captured more chars */
8616 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
8620 pc
->tend
= pc
->p
- 1;
8621 pc
->len
-= (pc
->p
- pc
->tstart
);
8625 static int JimParseExprIrrational(struct JimParserCtx
*pc
)
8627 const char *irrationals
[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL
};
8630 for (i
= 0; irrationals
[i
]; i
++) {
8631 const char *irr
= irrationals
[i
];
8633 if (strncmp(irr
, pc
->p
, 3) == 0) {
8636 pc
->tend
= pc
->p
- 1;
8637 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
8644 static int JimParseExprBoolean(struct JimParserCtx
*pc
)
8646 const char *booleans
[] = { "false", "no", "off", "true", "yes", "on", NULL
};
8647 const int lengths
[] = { 5, 2, 3, 4, 3, 2, 0 };
8650 for (i
= 0; booleans
[i
]; i
++) {
8651 const char *boolean
= booleans
[i
];
8652 int length
= lengths
[i
];
8654 if (strncmp(boolean
, pc
->p
, length
) == 0) {
8657 pc
->tend
= pc
->p
- 1;
8658 pc
->tt
= JIM_TT_EXPR_BOOLEAN
;
8665 static const struct Jim_ExprOperator
*JimExprOperatorInfoByOpcode(int opcode
)
8667 static Jim_ExprOperator dummy_op
;
8668 if (opcode
< JIM_TT_EXPR_OP
) {
8671 return &Jim_ExprOperators
[opcode
- JIM_TT_EXPR_OP
];
8674 static int JimParseExprOperator(struct JimParserCtx
*pc
)
8677 const struct Jim_ExprOperator
*bestOp
= NULL
;
8680 /* Try to get the longest match. */
8681 for (i
= 0; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++) {
8682 const struct Jim_ExprOperator
*op
= &Jim_ExprOperators
[i
];
8684 if (op
->name
[0] != pc
->p
[0]) {
8688 if (op
->namelen
> bestLen
&& strncmp(op
->name
, pc
->p
, op
->namelen
) == 0) {
8690 bestLen
= op
->namelen
;
8693 if (bestOp
== NULL
) {
8697 /* Validate paretheses around function arguments */
8698 if (bestOp
->attr
& OP_FUNC
) {
8699 const char *p
= pc
->p
+ bestLen
;
8700 int len
= pc
->len
- bestLen
;
8702 while (len
&& isspace(UCHAR(*p
))) {
8710 pc
->tend
= pc
->p
+ bestLen
- 1;
8714 pc
->tt
= (bestOp
- Jim_ExprOperators
) + JIM_TT_EXPR_OP
;
8718 const char *jim_tt_name(int type
)
8720 static const char * const tt_names
[JIM_TT_EXPR_OP
] =
8721 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", ",,,", "INT",
8722 "DBL", "BOO", "$()" };
8723 if (type
< JIM_TT_EXPR_OP
) {
8724 return tt_names
[type
];
8726 else if (type
== JIM_EXPROP_UNARYMINUS
) {
8729 else if (type
== JIM_EXPROP_UNARYPLUS
) {
8733 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(type
);
8734 static char buf
[20];
8739 sprintf(buf
, "(%d)", type
);
8744 /* -----------------------------------------------------------------------------
8746 * ---------------------------------------------------------------------------*/
8747 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
8748 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
8749 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
8751 static const Jim_ObjType exprObjType
= {
8753 FreeExprInternalRep
,
8756 JIM_TYPE_REFERENCES
,
8759 /* expr tree structure */
8762 struct JimExprNode
*expr
; /* The first operator or term */
8763 struct JimExprNode
*nodes
; /* Storage of all nodes in the tree */
8764 int len
; /* Number of nodes in use */
8765 int inUse
; /* Used for sharing. */
8768 static void ExprTreeFreeNodes(Jim_Interp
*interp
, struct JimExprNode
*nodes
, int num
)
8771 for (i
= 0; i
< num
; i
++) {
8772 if (nodes
[i
].objPtr
) {
8773 Jim_DecrRefCount(interp
, nodes
[i
].objPtr
);
8779 static void ExprTreeFree(Jim_Interp
*interp
, struct ExprTree
*expr
)
8781 ExprTreeFreeNodes(interp
, expr
->nodes
, expr
->len
);
8785 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8787 struct ExprTree
*expr
= (void *)objPtr
->internalRep
.ptr
;
8790 if (--expr
->inUse
!= 0) {
8794 ExprTreeFree(interp
, expr
);
8798 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8800 JIM_NOTUSED(interp
);
8801 JIM_NOTUSED(srcPtr
);
8803 /* Just returns an simple string. */
8804 dupPtr
->typePtr
= NULL
;
8807 struct ExprBuilder
{
8808 int parencount
; /* count of outstanding parentheses */
8809 int level
; /* recursion depth */
8810 ParseToken
*token
; /* The current token */
8811 ParseToken
*first_token
; /* The first token */
8812 Jim_Stack stack
; /* stack of pending terms */
8813 Jim_Obj
*exprObjPtr
; /* the original expression */
8814 Jim_Obj
*fileNameObj
; /* filename of the original expression */
8815 struct JimExprNode
*nodes
; /* storage for all nodes */
8816 struct JimExprNode
*next
; /* storage for the next node */
8819 #ifdef DEBUG_SHOW_EXPR
8820 static void JimShowExprNode(struct JimExprNode
*node
, int level
)
8823 for (i
= 0; i
< level
; i
++) {
8826 if (TOKEN_IS_EXPR_OP(node
->type
)) {
8827 printf("%s\n", jim_tt_name(node
->type
));
8829 JimShowExprNode(node
->left
, level
+ 1);
8832 JimShowExprNode(node
->right
, level
+ 1);
8834 if (node
->ternary
) {
8835 JimShowExprNode(node
->ternary
, level
+ 1);
8839 printf("[%s] %s\n", jim_tt_name(node
->type
), Jim_String(node
->objPtr
));
8844 #define EXPR_UNTIL_CLOSE 0x0001
8845 #define EXPR_FUNC_ARGS 0x0002
8846 #define EXPR_TERNARY 0x0004
8849 * Parse the subexpression at builder->token and return with the node on the stack.
8850 * builder->token is advanced to the next unconsumed token.
8851 * Returns JIM_OK if OK or JIM_ERR on error and leaves a message in the interpreter result.
8853 * 'precedence' is the precedence of the current operator. Tokens are consumed until an operator
8854 * with an equal or lower precedence is reached (or strictly lower if right associative).
8856 * If EXPR_UNTIL_CLOSE is set, the subexpression extends up to and including the next close parenthesis.
8857 * If EXPR_FUNC_ARGS is set, multiple subexpressions (terms) are expected separated by comma
8858 * If EXPR_TERNARY is set, two subexpressions (terms) are expected separated by colon
8860 * 'exp_numterms' indicates how many terms are expected. Normally this is 1, but may be more for EXPR_FUNC_ARGS and EXPR_TERNARY.
8862 static int ExprTreeBuildTree(Jim_Interp
*interp
, struct ExprBuilder
*builder
, int precedence
, int flags
, int exp_numterms
)
8865 struct JimExprNode
*node
;
8866 /* Calculate the stack length expected after pushing the number of expected terms */
8867 int exp_stacklen
= builder
->stack
.len
+ exp_numterms
;
8869 if (builder
->level
++ > 200) {
8870 Jim_SetResultString(interp
, "Expression too complex", -1);
8874 while (builder
->token
->type
!= JIM_TT_EOL
) {
8875 ParseToken
*t
= builder
->token
++;
8878 if (t
== builder
->first_token
) {
8879 prevtt
= JIM_TT_NONE
;
8882 prevtt
= t
[-1].type
;
8885 if (t
->type
== JIM_TT_SUBEXPR_START
) {
8886 if (builder
->stack
.len
== exp_stacklen
) {
8887 Jim_SetResultFormatted(interp
, "unexpected open parenthesis in expression: \"%#s\"", builder
->exprObjPtr
);
8890 builder
->parencount
++;
8891 rc
= ExprTreeBuildTree(interp
, builder
, 0, EXPR_UNTIL_CLOSE
, 1);
8895 /* A complete subexpression is on the stack */
8897 else if (t
->type
== JIM_TT_SUBEXPR_END
) {
8898 if (!(flags
& EXPR_UNTIL_CLOSE
)) {
8899 if (builder
->stack
.len
== exp_stacklen
&& builder
->level
> 1) {
8904 Jim_SetResultFormatted(interp
, "unexpected closing parenthesis in expression: \"%#s\"", builder
->exprObjPtr
);
8907 builder
->parencount
--;
8908 if (builder
->stack
.len
== exp_stacklen
) {
8909 /* Return with the expected number of subexpressions on the stack */
8913 else if (t
->type
== JIM_TT_SUBEXPR_COMMA
) {
8914 if (!(flags
& EXPR_FUNC_ARGS
)) {
8915 if (builder
->stack
.len
== exp_stacklen
) {
8916 /* handle the comma back at the parent level */
8921 Jim_SetResultFormatted(interp
, "unexpected comma in expression: \"%#s\"", builder
->exprObjPtr
);
8925 /* If we see more terms than expected, it is an error */
8926 if (builder
->stack
.len
> exp_stacklen
) {
8927 Jim_SetResultFormatted(interp
, "too many arguments to math function");
8931 /* just go onto the next arg */
8933 else if (t
->type
== JIM_EXPROP_COLON
) {
8934 if (!(flags
& EXPR_TERNARY
)) {
8935 if (builder
->level
!= 1) {
8936 /* handle the comma back at the parent level */
8941 Jim_SetResultFormatted(interp
, ": without ? in expression: \"%#s\"", builder
->exprObjPtr
);
8944 if (builder
->stack
.len
== exp_stacklen
) {
8945 /* handle the comma back at the parent level */
8950 /* just go onto the next term */
8952 else if (TOKEN_IS_EXPR_OP(t
->type
)) {
8953 const struct Jim_ExprOperator
*op
;
8955 /* Convert -/+ to unary minus or unary plus if necessary */
8956 if (TOKEN_IS_EXPR_OP(prevtt
) || TOKEN_IS_EXPR_START(prevtt
)) {
8957 if (t
->type
== JIM_EXPROP_SUB
) {
8958 t
->type
= JIM_EXPROP_UNARYMINUS
;
8960 else if (t
->type
== JIM_EXPROP_ADD
) {
8961 t
->type
= JIM_EXPROP_UNARYPLUS
;
8965 op
= JimExprOperatorInfoByOpcode(t
->type
);
8967 if (op
->precedence
< precedence
|| (!(op
->attr
& OP_RIGHT_ASSOC
) && op
->precedence
== precedence
)) {
8968 /* next op is lower precedence, or equal and left associative, so done here */
8973 if (op
->attr
& OP_FUNC
) {
8974 if (builder
->token
->type
!= JIM_TT_SUBEXPR_START
) {
8975 Jim_SetResultString(interp
, "missing arguments for math function", -1);
8979 if (op
->arity
== 0) {
8980 if (builder
->token
->type
!= JIM_TT_SUBEXPR_END
) {
8981 Jim_SetResultString(interp
, "too many arguments for math function", -1);
8987 builder
->parencount
++;
8989 /* This will push left and return right */
8990 rc
= ExprTreeBuildTree(interp
, builder
, 0, EXPR_FUNC_ARGS
| EXPR_UNTIL_CLOSE
, op
->arity
);
8992 else if (t
->type
== JIM_EXPROP_TERNARY
) {
8993 /* Collect the two arguments to the ternary operator */
8994 rc
= ExprTreeBuildTree(interp
, builder
, op
->precedence
, EXPR_TERNARY
, 2);
8997 /* Recursively handle everything on the right until we see a precendence <= op->precedence or == and right associative
8998 * and push that on the term stack
9000 rc
= ExprTreeBuildTree(interp
, builder
, op
->precedence
, 0, 1);
9008 node
= builder
->next
++;
9009 node
->type
= t
->type
;
9011 if (op
->arity
>= 3) {
9012 node
->ternary
= Jim_StackPop(&builder
->stack
);
9013 if (node
->ternary
== NULL
) {
9014 goto missingoperand
;
9017 if (op
->arity
>= 2) {
9018 node
->right
= Jim_StackPop(&builder
->stack
);
9019 if (node
->right
== NULL
) {
9020 goto missingoperand
;
9023 if (op
->arity
>= 1) {
9024 node
->left
= Jim_StackPop(&builder
->stack
);
9025 if (node
->left
== NULL
) {
9027 Jim_SetResultFormatted(interp
, "missing operand to %s in expression: \"%#s\"", op
->name
, builder
->exprObjPtr
);
9034 /* Now push the node */
9035 Jim_StackPush(&builder
->stack
, node
);
9038 Jim_Obj
*objPtr
= NULL
;
9040 /* This is a simple non-operator term, so create and push the appropriate object */
9042 /* Two consecutive terms without an operator is invalid */
9043 if (!TOKEN_IS_EXPR_START(prevtt
) && !TOKEN_IS_EXPR_OP(prevtt
)) {
9044 Jim_SetResultFormatted(interp
, "missing operator in expression: \"%#s\"", builder
->exprObjPtr
);
9048 /* Immediately create a double or int object? */
9049 if (t
->type
== JIM_TT_EXPR_INT
|| t
->type
== JIM_TT_EXPR_DOUBLE
) {
9051 if (t
->type
== JIM_TT_EXPR_INT
) {
9052 objPtr
= Jim_NewIntObj(interp
, jim_strtoull(t
->token
, &endptr
));
9055 objPtr
= Jim_NewDoubleObj(interp
, strtod(t
->token
, &endptr
));
9057 if (endptr
!= t
->token
+ t
->len
) {
9058 /* Conversion failed, so just store it as a string */
9059 Jim_FreeNewObj(interp
, objPtr
);
9065 /* Everything else is stored a simple string term */
9066 objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
9067 if (t
->type
== JIM_TT_CMD
) {
9068 /* Only commands need source info */
9069 JimSetSourceInfo(interp
, objPtr
, builder
->fileNameObj
, t
->line
);
9073 /* Now push a term node */
9074 node
= builder
->next
++;
9075 node
->objPtr
= objPtr
;
9076 Jim_IncrRefCount(node
->objPtr
);
9077 node
->type
= t
->type
;
9078 Jim_StackPush(&builder
->stack
, node
);
9082 if (builder
->stack
.len
== exp_stacklen
) {
9087 if ((flags
& EXPR_FUNC_ARGS
)) {
9088 Jim_SetResultFormatted(interp
, "too %s arguments for math function", (builder
->stack
.len
< exp_stacklen
) ? "few" : "many");
9091 if (builder
->stack
.len
< exp_stacklen
) {
9092 if (builder
->level
== 0) {
9093 Jim_SetResultFormatted(interp
, "empty expression");
9096 Jim_SetResultFormatted(interp
, "syntax error in expression \"%#s\": premature end of expression", builder
->exprObjPtr
);
9100 Jim_SetResultFormatted(interp
, "extra terms after expression");
9107 static struct ExprTree
*ExprTreeCreateTree(Jim_Interp
*interp
, const ParseTokenList
*tokenlist
, Jim_Obj
*exprObjPtr
, Jim_Obj
*fileNameObj
)
9109 struct ExprTree
*expr
;
9110 struct ExprBuilder builder
;
9112 struct JimExprNode
*top
= NULL
;
9114 builder
.parencount
= 0;
9116 builder
.token
= builder
.first_token
= tokenlist
->list
;
9117 builder
.exprObjPtr
= exprObjPtr
;
9118 builder
.fileNameObj
= fileNameObj
;
9119 /* The bytecode will never produce more nodes than there are tokens - 1 (for EOL)*/
9120 builder
.nodes
= Jim_Alloc(sizeof(struct JimExprNode
) * (tokenlist
->count
- 1));
9121 memset(builder
.nodes
, 0, sizeof(struct JimExprNode
) * (tokenlist
->count
- 1));
9122 builder
.next
= builder
.nodes
;
9123 Jim_InitStack(&builder
.stack
);
9125 rc
= ExprTreeBuildTree(interp
, &builder
, 0, 0, 1);
9128 top
= Jim_StackPop(&builder
.stack
);
9130 if (builder
.parencount
) {
9131 Jim_SetResultString(interp
, "missing close parenthesis", -1);
9136 /* Free the stack used for the compilation. */
9137 Jim_FreeStack(&builder
.stack
);
9140 ExprTreeFreeNodes(interp
, builder
.nodes
, builder
.next
- builder
.nodes
);
9144 expr
= Jim_Alloc(sizeof(*expr
));
9147 expr
->nodes
= builder
.nodes
;
9148 expr
->len
= builder
.next
- builder
.nodes
;
9150 assert(expr
->len
<= tokenlist
->count
- 1);
9155 /* This method takes the string representation of an expression
9156 * and generates a program for the expr engine */
9157 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
9160 const char *exprText
;
9161 struct JimParserCtx parser
;
9162 struct ExprTree
*expr
;
9163 ParseTokenList tokenlist
;
9165 Jim_Obj
*fileNameObj
;
9168 /* Try to get information about filename / line number */
9169 if (objPtr
->typePtr
== &sourceObjType
) {
9170 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
9171 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
9174 fileNameObj
= interp
->emptyObj
;
9177 Jim_IncrRefCount(fileNameObj
);
9179 exprText
= Jim_GetString(objPtr
, &exprTextLen
);
9181 /* Initially tokenise the expression into tokenlist */
9182 ScriptTokenListInit(&tokenlist
);
9184 JimParserInit(&parser
, exprText
, exprTextLen
, line
);
9185 while (!parser
.eof
) {
9186 if (JimParseExpression(&parser
) != JIM_OK
) {
9187 ScriptTokenListFree(&tokenlist
);
9188 Jim_SetResultFormatted(interp
, "syntax error in expression: \"%#s\"", objPtr
);
9193 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
9197 #ifdef DEBUG_SHOW_EXPR_TOKENS
9200 printf("==== Expr Tokens (%s) ====\n", Jim_String(fileNameObj
));
9201 for (i
= 0; i
< tokenlist
.count
; i
++) {
9202 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
.list
[i
].line
, jim_tt_name(tokenlist
.list
[i
].type
),
9203 tokenlist
.list
[i
].len
, tokenlist
.list
[i
].token
);
9208 if (JimParseCheckMissing(interp
, parser
.missing
.ch
) == JIM_ERR
) {
9209 ScriptTokenListFree(&tokenlist
);
9210 Jim_DecrRefCount(interp
, fileNameObj
);
9214 /* Now create the expression bytecode from the tokenlist */
9215 expr
= ExprTreeCreateTree(interp
, &tokenlist
, objPtr
, fileNameObj
);
9217 /* No longer need the token list */
9218 ScriptTokenListFree(&tokenlist
);
9224 #ifdef DEBUG_SHOW_EXPR
9225 printf("==== Expr ====\n");
9226 JimShowExprNode(expr
->expr
, 0);
9232 /* Free the old internal rep and set the new one. */
9233 Jim_DecrRefCount(interp
, fileNameObj
);
9234 Jim_FreeIntRep(interp
, objPtr
);
9235 Jim_SetIntRepPtr(objPtr
, expr
);
9236 objPtr
->typePtr
= &exprObjType
;
9240 static struct ExprTree
*JimGetExpression(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
9242 if (objPtr
->typePtr
!= &exprObjType
) {
9243 if (SetExprFromAny(interp
, objPtr
) != JIM_OK
) {
9247 return (struct ExprTree
*) Jim_GetIntRepPtr(objPtr
);
9250 #ifdef JIM_OPTIMIZATION
9251 static Jim_Obj
*JimExprIntValOrVar(Jim_Interp
*interp
, struct JimExprNode
*node
)
9253 if (node
->type
== JIM_TT_EXPR_INT
)
9254 return node
->objPtr
;
9255 else if (node
->type
== JIM_TT_VAR
)
9256 return Jim_GetVariable(interp
, node
->objPtr
, JIM_NONE
);
9257 else if (node
->type
== JIM_TT_DICTSUGAR
)
9258 return JimExpandDictSugar(interp
, node
->objPtr
);
9264 /* -----------------------------------------------------------------------------
9265 * Expressions evaluation.
9266 * Jim uses a recursive evaluation engine for expressions,
9267 * that takes advantage of the fact that expr's operators
9268 * can't be redefined.
9270 * Jim_EvalExpression() uses the expression tree compiled by
9271 * SetExprFromAny() method of the "expression" object.
9273 * On success a Tcl Object containing the result of the evaluation
9274 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
9276 * On error the function returns a retcode != to JIM_OK and set a suitable
9277 * error on the interp.
9278 * ---------------------------------------------------------------------------*/
9280 static int JimExprEvalTermNode(Jim_Interp
*interp
, struct JimExprNode
*node
)
9282 if (TOKEN_IS_EXPR_OP(node
->type
)) {
9283 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(node
->type
);
9284 return op
->funcop(interp
, node
);
9290 switch (node
->type
) {
9291 case JIM_TT_EXPR_INT
:
9292 case JIM_TT_EXPR_DOUBLE
:
9293 case JIM_TT_EXPR_BOOLEAN
:
9295 Jim_SetResult(interp
, node
->objPtr
);
9299 objPtr
= Jim_GetVariable(interp
, node
->objPtr
, JIM_ERRMSG
);
9301 Jim_SetResult(interp
, objPtr
);
9306 case JIM_TT_DICTSUGAR
:
9307 objPtr
= JimExpandDictSugar(interp
, node
->objPtr
);
9309 Jim_SetResult(interp
, objPtr
);
9315 if (Jim_SubstObj(interp
, node
->objPtr
, &objPtr
, JIM_NONE
) == JIM_OK
) {
9316 Jim_SetResult(interp
, objPtr
);
9322 return Jim_EvalObj(interp
, node
->objPtr
);
9325 /* Should never get here */
9331 static int JimExprGetTerm(Jim_Interp
*interp
, struct JimExprNode
*node
, Jim_Obj
**objPtrPtr
)
9333 int rc
= JimExprEvalTermNode(interp
, node
);
9335 *objPtrPtr
= Jim_GetResult(interp
);
9336 Jim_IncrRefCount(*objPtrPtr
);
9341 static int JimExprGetTermBoolean(Jim_Interp
*interp
, struct JimExprNode
*node
)
9343 if (JimExprEvalTermNode(interp
, node
) == JIM_OK
) {
9344 return ExprBool(interp
, Jim_GetResult(interp
));
9349 int Jim_EvalExpression(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
)
9351 struct ExprTree
*expr
;
9352 int retcode
= JIM_OK
;
9354 Jim_IncrRefCount(exprObjPtr
); /* Make sure it's shared. */
9355 expr
= JimGetExpression(interp
, exprObjPtr
);
9361 #ifdef JIM_OPTIMIZATION
9362 /* Check for one of the following common expressions used by while/for
9367 * $a < CONST, $a < $b
9368 * $a <= CONST, $a <= $b
9369 * $a > CONST, $a > $b
9370 * $a >= CONST, $a >= $b
9371 * $a != CONST, $a != $b
9372 * $a == CONST, $a == $b
9377 /* STEP 1 -- Check if there are the conditions to run the specialized
9378 * version of while */
9380 switch (expr
->len
) {
9382 objPtr
= JimExprIntValOrVar(interp
, expr
->expr
);
9384 Jim_SetResult(interp
, objPtr
);
9390 if (expr
->expr
->type
== JIM_EXPROP_NOT
) {
9391 objPtr
= JimExprIntValOrVar(interp
, expr
->expr
->left
);
9393 if (objPtr
&& JimIsWide(objPtr
)) {
9394 Jim_SetResult(interp
, JimWideValue(objPtr
) ? interp
->falseObj
: interp
->trueObj
);
9401 objPtr
= JimExprIntValOrVar(interp
, expr
->expr
->left
);
9402 if (objPtr
&& JimIsWide(objPtr
)) {
9403 Jim_Obj
*objPtr2
= JimExprIntValOrVar(interp
, expr
->expr
->right
);
9404 if (objPtr2
&& JimIsWide(objPtr2
)) {
9405 jim_wide wideValueA
= JimWideValue(objPtr
);
9406 jim_wide wideValueB
= JimWideValue(objPtr2
);
9408 switch (expr
->expr
->type
) {
9410 cmpRes
= wideValueA
< wideValueB
;
9412 case JIM_EXPROP_LTE
:
9413 cmpRes
= wideValueA
<= wideValueB
;
9416 cmpRes
= wideValueA
> wideValueB
;
9418 case JIM_EXPROP_GTE
:
9419 cmpRes
= wideValueA
>= wideValueB
;
9421 case JIM_EXPROP_NUMEQ
:
9422 cmpRes
= wideValueA
== wideValueB
;
9424 case JIM_EXPROP_NUMNE
:
9425 cmpRes
= wideValueA
!= wideValueB
;
9430 Jim_SetResult(interp
, cmpRes
? interp
->trueObj
: interp
->falseObj
);
9440 /* In order to avoid the internal repr being freed due to
9441 * shimmering of the exprObjPtr's object, we increment the use count
9442 * and keep our own pointer outside the object.
9446 /* Evaluate with the recursive expr engine */
9447 retcode
= JimExprEvalTermNode(interp
, expr
->expr
);
9449 /* Now transfer ownership of expr back into the object in case it shimmered away */
9450 Jim_FreeIntRep(interp
, exprObjPtr
);
9451 exprObjPtr
->typePtr
= &exprObjType
;
9452 Jim_SetIntRepPtr(exprObjPtr
, expr
);
9455 Jim_DecrRefCount(interp
, exprObjPtr
);
9460 int Jim_GetBoolFromExpr(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, int *boolPtr
)
9462 int retcode
= Jim_EvalExpression(interp
, exprObjPtr
);
9464 if (retcode
== JIM_OK
) {
9465 switch (ExprBool(interp
, Jim_GetResult(interp
))) {
9482 /* -----------------------------------------------------------------------------
9483 * ScanFormat String Object
9484 * ---------------------------------------------------------------------------*/
9486 /* This Jim_Obj will held a parsed representation of a format string passed to
9487 * the Jim_ScanString command. For error diagnostics, the scanformat string has
9488 * to be parsed in its entirely first and then, if correct, can be used for
9489 * scanning. To avoid endless re-parsing, the parsed representation will be
9490 * stored in an internal representation and re-used for performance reason. */
9492 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
9493 * scanformat string. This part will later be used to extract information
9494 * out from the string to be parsed by Jim_ScanString */
9496 typedef struct ScanFmtPartDescr
9498 const char *arg
; /* Specification of a CHARSET conversion */
9499 const char *prefix
; /* Prefix to be scanned literally before conversion */
9500 size_t width
; /* Maximal width of input to be converted */
9501 int pos
; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
9502 char type
; /* Type of conversion (e.g. c, d, f) */
9503 char modifier
; /* Modify type (e.g. l - long, h - short */
9506 /* The ScanFmtStringObj will hold the internal representation of a scanformat
9507 * string parsed and separated in part descriptions. Furthermore it contains
9508 * the original string representation of the scanformat string to allow for
9509 * fast update of the Jim_Obj's string representation part.
9511 * As an add-on the internal object representation adds some scratch pad area
9512 * for usage by Jim_ScanString to avoid endless allocating and freeing of
9513 * memory for purpose of string scanning.
9515 * The error member points to a static allocated string in case of a mal-
9516 * formed scanformat string or it contains '0' (NULL) in case of a valid
9517 * parse representation.
9519 * The whole memory of the internal representation is allocated as a single
9520 * area of memory that will be internally separated. So freeing and duplicating
9521 * of such an object is cheap */
9523 typedef struct ScanFmtStringObj
9525 jim_wide size
; /* Size of internal repr in bytes */
9526 char *stringRep
; /* Original string representation */
9527 size_t count
; /* Number of ScanFmtPartDescr contained */
9528 size_t convCount
; /* Number of conversions that will assign */
9529 size_t maxPos
; /* Max position index if XPG3 is used */
9530 const char *error
; /* Ptr to error text (NULL if no error */
9531 char *scratch
; /* Some scratch pad used by Jim_ScanString */
9532 ScanFmtPartDescr descr
[1]; /* The vector of partial descriptions */
9536 static void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
9537 static void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
9538 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
);
9540 static const Jim_ObjType scanFmtStringObjType
= {
9542 FreeScanFmtInternalRep
,
9543 DupScanFmtInternalRep
,
9544 UpdateStringOfScanFmt
,
9548 void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
9550 JIM_NOTUSED(interp
);
9551 Jim_Free((char *)objPtr
->internalRep
.ptr
);
9552 objPtr
->internalRep
.ptr
= 0;
9555 void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
9557 size_t size
= (size_t) ((ScanFmtStringObj
*) srcPtr
->internalRep
.ptr
)->size
;
9558 ScanFmtStringObj
*newVec
= (ScanFmtStringObj
*) Jim_Alloc(size
);
9560 JIM_NOTUSED(interp
);
9561 memcpy(newVec
, srcPtr
->internalRep
.ptr
, size
);
9562 dupPtr
->internalRep
.ptr
= newVec
;
9563 dupPtr
->typePtr
= &scanFmtStringObjType
;
9566 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
)
9568 JimSetStringBytes(objPtr
, ((ScanFmtStringObj
*) objPtr
->internalRep
.ptr
)->stringRep
);
9571 /* SetScanFmtFromAny will parse a given string and create the internal
9572 * representation of the format specification. In case of an error
9573 * the error data member of the internal representation will be set
9574 * to an descriptive error text and the function will be left with
9575 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
9578 static int SetScanFmtFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
9580 ScanFmtStringObj
*fmtObj
;
9582 int maxCount
, i
, approxSize
, lastPos
= -1;
9583 const char *fmt
= Jim_String(objPtr
);
9584 int maxFmtLen
= Jim_Length(objPtr
);
9585 const char *fmtEnd
= fmt
+ maxFmtLen
;
9588 Jim_FreeIntRep(interp
, objPtr
);
9589 /* Count how many conversions could take place maximally */
9590 for (i
= 0, maxCount
= 0; i
< maxFmtLen
; ++i
)
9593 /* Calculate an approximation of the memory necessary */
9594 approxSize
= sizeof(ScanFmtStringObj
) /* Size of the container */
9595 +(maxCount
+ 1) * sizeof(ScanFmtPartDescr
) /* Size of all partials */
9596 +maxFmtLen
* sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
9597 + maxFmtLen
* sizeof(char) + 1 /* Original stringrep */
9598 + maxFmtLen
* sizeof(char) /* Arg for CHARSETs */
9599 +(maxCount
+ 1) * sizeof(char) /* '\0' for every partial */
9600 +1; /* safety byte */
9601 fmtObj
= (ScanFmtStringObj
*) Jim_Alloc(approxSize
);
9602 memset(fmtObj
, 0, approxSize
);
9603 fmtObj
->size
= approxSize
;
9605 fmtObj
->scratch
= (char *)&fmtObj
->descr
[maxCount
+ 1];
9606 fmtObj
->stringRep
= fmtObj
->scratch
+ maxFmtLen
+ 3 + 1;
9607 memcpy(fmtObj
->stringRep
, fmt
, maxFmtLen
);
9608 buffer
= fmtObj
->stringRep
+ maxFmtLen
+ 1;
9609 objPtr
->internalRep
.ptr
= fmtObj
;
9610 objPtr
->typePtr
= &scanFmtStringObjType
;
9611 for (i
= 0, curr
= 0; fmt
< fmtEnd
; ++fmt
) {
9612 int width
= 0, skip
;
9613 ScanFmtPartDescr
*descr
= &fmtObj
->descr
[curr
];
9616 descr
->width
= 0; /* Assume width unspecified */
9617 /* Overread and store any "literal" prefix */
9618 if (*fmt
!= '%' || fmt
[1] == '%') {
9620 descr
->prefix
= &buffer
[i
];
9621 for (; fmt
< fmtEnd
; ++fmt
) {
9631 /* Skip the conversion introducing '%' sign */
9633 /* End reached due to non-conversion literal only? */
9636 descr
->pos
= 0; /* Assume "natural" positioning */
9638 descr
->pos
= -1; /* Okay, conversion will not be assigned */
9642 fmtObj
->convCount
++; /* Otherwise count as assign-conversion */
9643 /* Check if next token is a number (could be width or pos */
9644 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9646 /* Was the number a XPG3 position specifier? */
9647 if (descr
->pos
!= -1 && *fmt
== '$') {
9653 /* Look if "natural" postioning and XPG3 one was mixed */
9654 if ((lastPos
== 0 && descr
->pos
> 0)
9655 || (lastPos
> 0 && descr
->pos
== 0)) {
9656 fmtObj
->error
= "cannot mix \"%\" and \"%n$\" conversion specifiers";
9659 /* Look if this position was already used */
9660 for (prev
= 0; prev
< curr
; ++prev
) {
9661 if (fmtObj
->descr
[prev
].pos
== -1)
9663 if (fmtObj
->descr
[prev
].pos
== descr
->pos
) {
9665 "variable is assigned by multiple \"%n$\" conversion specifiers";
9669 if (descr
->pos
< 0) {
9671 "\"%n$\" conversion specifier is negative";
9674 /* Try to find a width after the XPG3 specifier */
9675 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9676 descr
->width
= width
;
9679 if (descr
->pos
> 0 && (size_t) descr
->pos
> fmtObj
->maxPos
)
9680 fmtObj
->maxPos
= descr
->pos
;
9683 /* Number was not a XPG3, so it has to be a width */
9684 descr
->width
= width
;
9687 /* If positioning mode was undetermined yet, fix this */
9689 lastPos
= descr
->pos
;
9690 /* Handle CHARSET conversion type ... */
9692 int swapped
= 1, beg
= i
, end
, j
;
9695 descr
->arg
= &buffer
[i
];
9698 buffer
[i
++] = *fmt
++;
9700 buffer
[i
++] = *fmt
++;
9701 while (*fmt
&& *fmt
!= ']')
9702 buffer
[i
++] = *fmt
++;
9704 fmtObj
->error
= "unmatched [ in format string";
9709 /* In case a range fence was given "backwards", swap it */
9712 for (j
= beg
+ 1; j
< end
- 1; ++j
) {
9713 if (buffer
[j
] == '-' && buffer
[j
- 1] > buffer
[j
+ 1]) {
9714 char tmp
= buffer
[j
- 1];
9716 buffer
[j
- 1] = buffer
[j
+ 1];
9717 buffer
[j
+ 1] = tmp
;
9724 /* Remember any valid modifier if given */
9725 if (fmt
< fmtEnd
&& strchr("hlL", *fmt
))
9726 descr
->modifier
= tolower((int)*fmt
++);
9728 if (fmt
>= fmtEnd
) {
9729 fmtObj
->error
= "missing scan conversion character";
9734 if (strchr("efgcsndoxui", *fmt
) == 0) {
9735 fmtObj
->error
= "bad scan conversion character";
9738 else if (*fmt
== 'c' && descr
->width
!= 0) {
9739 fmtObj
->error
= "field width may not be specified in %c " "conversion";
9742 else if (*fmt
== 'u' && descr
->modifier
== 'l') {
9743 fmtObj
->error
= "unsigned wide not supported";
9753 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9755 #define FormatGetCnvCount(_fo_) \
9756 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9757 #define FormatGetMaxPos(_fo_) \
9758 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9759 #define FormatGetError(_fo_) \
9760 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9762 /* JimScanAString is used to scan an unspecified string that ends with
9763 * next WS, or a string that is specified via a charset.
9766 static Jim_Obj
*JimScanAString(Jim_Interp
*interp
, const char *sdescr
, const char *str
)
9768 char *buffer
= Jim_StrDup(str
);
9775 if (!sdescr
&& isspace(UCHAR(*str
)))
9776 break; /* EOS via WS if unspecified */
9778 n
= utf8_tounicode(str
, &c
);
9779 if (sdescr
&& !JimCharsetMatch(sdescr
, strlen(sdescr
), c
, JIM_CHARSET_SCAN
))
9785 return Jim_NewStringObjNoAlloc(interp
, buffer
, p
- buffer
);
9788 /* ScanOneEntry will scan one entry out of the string passed as argument.
9789 * It use the sscanf() function for this task. After extracting and
9790 * converting of the value, the count of scanned characters will be
9791 * returned of -1 in case of no conversion tool place and string was
9792 * already scanned thru */
9794 static int ScanOneEntry(Jim_Interp
*interp
, const char *str
, int pos
, int str_bytelen
,
9795 ScanFmtStringObj
* fmtObj
, long idx
, Jim_Obj
**valObjPtr
)
9798 const ScanFmtPartDescr
*descr
= &fmtObj
->descr
[idx
];
9800 size_t anchor
= pos
;
9802 Jim_Obj
*tmpObj
= NULL
;
9804 /* First pessimistically assume, we will not scan anything :-) */
9806 if (descr
->prefix
) {
9807 /* There was a prefix given before the conversion, skip it and adjust
9808 * the string-to-be-parsed accordingly */
9809 for (i
= 0; pos
< str_bytelen
&& descr
->prefix
[i
]; ++i
) {
9810 /* If prefix require, skip WS */
9811 if (isspace(UCHAR(descr
->prefix
[i
])))
9812 while (pos
< str_bytelen
&& isspace(UCHAR(str
[pos
])))
9814 else if (descr
->prefix
[i
] != str
[pos
])
9815 break; /* Prefix do not match here, leave the loop */
9817 ++pos
; /* Prefix matched so far, next round */
9819 if (pos
>= str_bytelen
) {
9820 return -1; /* All of str consumed: EOF condition */
9822 else if (descr
->prefix
[i
] != 0)
9823 return 0; /* Not whole prefix consumed, no conversion possible */
9825 /* For all but following conversion, skip leading WS */
9826 if (descr
->type
!= 'c' && descr
->type
!= '[' && descr
->type
!= 'n')
9827 while (isspace(UCHAR(str
[pos
])))
9830 /* Determine how much skipped/scanned so far */
9831 scanned
= pos
- anchor
;
9833 /* %c is a special, simple case. no width */
9834 if (descr
->type
== 'n') {
9835 /* Return pseudo conversion means: how much scanned so far? */
9836 *valObjPtr
= Jim_NewIntObj(interp
, anchor
+ scanned
);
9838 else if (pos
>= str_bytelen
) {
9839 /* Cannot scan anything, as str is totally consumed */
9842 else if (descr
->type
== 'c') {
9844 scanned
+= utf8_tounicode(&str
[pos
], &c
);
9845 *valObjPtr
= Jim_NewIntObj(interp
, c
);
9849 /* Processing of conversions follows ... */
9850 if (descr
->width
> 0) {
9851 /* Do not try to scan as fas as possible but only the given width.
9852 * To ensure this, we copy the part that should be scanned. */
9853 size_t sLen
= utf8_strlen(&str
[pos
], str_bytelen
- pos
);
9854 size_t tLen
= descr
->width
> sLen
? sLen
: descr
->width
;
9856 tmpObj
= Jim_NewStringObjUtf8(interp
, str
+ pos
, tLen
);
9857 tok
= tmpObj
->bytes
;
9860 /* As no width was given, simply refer to the original string */
9863 switch (descr
->type
) {
9869 char *endp
; /* Position where the number finished */
9872 int base
= descr
->type
== 'o' ? 8
9873 : descr
->type
== 'x' ? 16 : descr
->type
== 'i' ? 0 : 10;
9875 /* Try to scan a number with the given base */
9877 w
= jim_strtoull(tok
, &endp
);
9880 w
= strtoull(tok
, &endp
, base
);
9884 /* There was some number sucessfully scanned! */
9885 *valObjPtr
= Jim_NewIntObj(interp
, w
);
9887 /* Adjust the number-of-chars scanned so far */
9888 scanned
+= endp
- tok
;
9891 /* Nothing was scanned. We have to determine if this
9892 * happened due to e.g. prefix mismatch or input str
9894 scanned
= *tok
? 0 : -1;
9900 *valObjPtr
= JimScanAString(interp
, descr
->arg
, tok
);
9901 scanned
+= Jim_Length(*valObjPtr
);
9908 double value
= strtod(tok
, &endp
);
9911 /* There was some number sucessfully scanned! */
9912 *valObjPtr
= Jim_NewDoubleObj(interp
, value
);
9913 /* Adjust the number-of-chars scanned so far */
9914 scanned
+= endp
- tok
;
9917 /* Nothing was scanned. We have to determine if this
9918 * happened due to e.g. prefix mismatch or input str
9920 scanned
= *tok
? 0 : -1;
9925 /* If a substring was allocated (due to pre-defined width) do not
9926 * forget to free it */
9928 Jim_FreeNewObj(interp
, tmpObj
);
9934 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9935 * string and returns all converted (and not ignored) values in a list back
9936 * to the caller. If an error occured, a NULL pointer will be returned */
9938 Jim_Obj
*Jim_ScanString(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*fmtObjPtr
, int flags
)
9942 const char *str
= Jim_String(strObjPtr
);
9943 int str_bytelen
= Jim_Length(strObjPtr
);
9944 Jim_Obj
*resultList
= 0;
9945 Jim_Obj
**resultVec
= 0;
9947 Jim_Obj
*emptyStr
= 0;
9948 ScanFmtStringObj
*fmtObj
;
9950 /* This should never happen. The format object should already be of the correct type */
9951 JimPanic((fmtObjPtr
->typePtr
!= &scanFmtStringObjType
, "Jim_ScanString() for non-scan format"));
9953 fmtObj
= (ScanFmtStringObj
*) fmtObjPtr
->internalRep
.ptr
;
9954 /* Check if format specification was valid */
9955 if (fmtObj
->error
!= 0) {
9956 if (flags
& JIM_ERRMSG
)
9957 Jim_SetResultString(interp
, fmtObj
->error
, -1);
9960 /* Allocate a new "shared" empty string for all unassigned conversions */
9961 emptyStr
= Jim_NewEmptyStringObj(interp
);
9962 Jim_IncrRefCount(emptyStr
);
9963 /* Create a list and fill it with empty strings up to max specified XPG3 */
9964 resultList
= Jim_NewListObj(interp
, NULL
, 0);
9965 if (fmtObj
->maxPos
> 0) {
9966 for (i
= 0; i
< fmtObj
->maxPos
; ++i
)
9967 Jim_ListAppendElement(interp
, resultList
, emptyStr
);
9968 JimListGetElements(interp
, resultList
, &resultc
, &resultVec
);
9970 /* Now handle every partial format description */
9971 for (i
= 0, pos
= 0; i
< fmtObj
->count
; ++i
) {
9972 ScanFmtPartDescr
*descr
= &(fmtObj
->descr
[i
]);
9975 /* Only last type may be "literal" w/o conversion - skip it! */
9976 if (descr
->type
== 0)
9978 /* As long as any conversion could be done, we will proceed */
9980 scanned
= ScanOneEntry(interp
, str
, pos
, str_bytelen
, fmtObj
, i
, &value
);
9981 /* In case our first try results in EOF, we will leave */
9982 if (scanned
== -1 && i
== 0)
9984 /* Advance next pos-to-be-scanned for the amount scanned already */
9987 /* value == 0 means no conversion took place so take empty string */
9989 value
= Jim_NewEmptyStringObj(interp
);
9990 /* If value is a non-assignable one, skip it */
9991 if (descr
->pos
== -1) {
9992 Jim_FreeNewObj(interp
, value
);
9994 else if (descr
->pos
== 0)
9995 /* Otherwise append it to the result list if no XPG3 was given */
9996 Jim_ListAppendElement(interp
, resultList
, value
);
9997 else if (resultVec
[descr
->pos
- 1] == emptyStr
) {
9998 /* But due to given XPG3, put the value into the corr. slot */
9999 Jim_DecrRefCount(interp
, resultVec
[descr
->pos
- 1]);
10000 Jim_IncrRefCount(value
);
10001 resultVec
[descr
->pos
- 1] = value
;
10004 /* Otherwise, the slot was already used - free obj and ERROR */
10005 Jim_FreeNewObj(interp
, value
);
10009 Jim_DecrRefCount(interp
, emptyStr
);
10012 Jim_DecrRefCount(interp
, emptyStr
);
10013 Jim_FreeNewObj(interp
, resultList
);
10014 return (Jim_Obj
*)EOF
;
10016 Jim_DecrRefCount(interp
, emptyStr
);
10017 Jim_FreeNewObj(interp
, resultList
);
10021 /* -----------------------------------------------------------------------------
10022 * Pseudo Random Number Generation
10023 * ---------------------------------------------------------------------------*/
10024 /* Initialize the sbox with the numbers from 0 to 255 */
10025 static void JimPrngInit(Jim_Interp
*interp
)
10027 #define PRNG_SEED_SIZE 256
10029 unsigned int *seed
;
10030 time_t t
= time(NULL
);
10032 interp
->prngState
= Jim_Alloc(sizeof(Jim_PrngState
));
10034 seed
= Jim_Alloc(PRNG_SEED_SIZE
* sizeof(*seed
));
10035 for (i
= 0; i
< PRNG_SEED_SIZE
; i
++) {
10036 seed
[i
] = (rand() ^ t
^ clock());
10038 JimPrngSeed(interp
, (unsigned char *)seed
, PRNG_SEED_SIZE
* sizeof(*seed
));
10042 /* Generates N bytes of random data */
10043 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
)
10045 Jim_PrngState
*prng
;
10046 unsigned char *destByte
= (unsigned char *)dest
;
10047 unsigned int si
, sj
, x
;
10049 /* initialization, only needed the first time */
10050 if (interp
->prngState
== NULL
)
10051 JimPrngInit(interp
);
10052 prng
= interp
->prngState
;
10053 /* generates 'len' bytes of pseudo-random numbers */
10054 for (x
= 0; x
< len
; x
++) {
10055 prng
->i
= (prng
->i
+ 1) & 0xff;
10056 si
= prng
->sbox
[prng
->i
];
10057 prng
->j
= (prng
->j
+ si
) & 0xff;
10058 sj
= prng
->sbox
[prng
->j
];
10059 prng
->sbox
[prng
->i
] = sj
;
10060 prng
->sbox
[prng
->j
] = si
;
10061 *destByte
++ = prng
->sbox
[(si
+ sj
) & 0xff];
10065 /* Re-seed the generator with user-provided bytes */
10066 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
)
10069 Jim_PrngState
*prng
;
10071 /* initialization, only needed the first time */
10072 if (interp
->prngState
== NULL
)
10073 JimPrngInit(interp
);
10074 prng
= interp
->prngState
;
10076 /* Set the sbox[i] with i */
10077 for (i
= 0; i
< 256; i
++)
10079 /* Now use the seed to perform a random permutation of the sbox */
10080 for (i
= 0; i
< seedLen
; i
++) {
10083 t
= prng
->sbox
[i
& 0xFF];
10084 prng
->sbox
[i
& 0xFF] = prng
->sbox
[seed
[i
]];
10085 prng
->sbox
[seed
[i
]] = t
;
10087 prng
->i
= prng
->j
= 0;
10089 /* discard at least the first 256 bytes of stream.
10090 * borrow the seed buffer for this
10092 for (i
= 0; i
< 256; i
+= seedLen
) {
10093 JimRandomBytes(interp
, seed
, seedLen
);
10098 static int Jim_IncrCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10100 jim_wide wideValue
, increment
= 1;
10101 Jim_Obj
*intObjPtr
;
10103 if (argc
!= 2 && argc
!= 3) {
10104 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?increment?");
10108 if (Jim_GetWide(interp
, argv
[2], &increment
) != JIM_OK
)
10111 intObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
10113 /* Set missing variable to 0 */
10116 else if (Jim_GetWide(interp
, intObjPtr
, &wideValue
) != JIM_OK
) {
10119 if (!intObjPtr
|| Jim_IsShared(intObjPtr
)) {
10120 intObjPtr
= Jim_NewIntObj(interp
, wideValue
+ increment
);
10121 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
10122 Jim_FreeNewObj(interp
, intObjPtr
);
10127 /* Can do it the quick way */
10128 Jim_InvalidateStringRep(intObjPtr
);
10129 JimWideValue(intObjPtr
) = wideValue
+ increment
;
10131 /* The following step is required in order to invalidate the
10132 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
10133 if (argv
[1]->typePtr
!= &variableObjType
) {
10134 /* Note that this can't fail since GetVariable already succeeded */
10135 Jim_SetVariable(interp
, argv
[1], intObjPtr
);
10138 Jim_SetResult(interp
, intObjPtr
);
10143 /* -----------------------------------------------------------------------------
10145 * ---------------------------------------------------------------------------*/
10146 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
10147 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
10149 /* Handle calls to the [unknown] command */
10150 static int JimUnknown(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10154 /* If JimUnknown() is recursively called too many times...
10157 if (interp
->unknown_called
> 50) {
10161 /* The object interp->unknown just contains
10162 * the "unknown" string, it is used in order to
10163 * avoid to lookup the unknown command every time
10164 * but instead to cache the result. */
10166 /* If the [unknown] command does not exist ... */
10167 if (Jim_GetCommand(interp
, interp
->unknown
, JIM_NONE
) == NULL
)
10170 interp
->unknown_called
++;
10171 /* XXX: Are we losing fileNameObj and linenr? */
10172 retcode
= Jim_EvalObjPrefix(interp
, interp
->unknown
, argc
, argv
);
10173 interp
->unknown_called
--;
10178 static int JimInvokeCommand(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
10182 void *prevPrivData
;
10183 Jim_Obj
*tailcallObj
= NULL
;
10188 for (j
= 0; j
< objc
; j
++) {
10189 printf(" '%s'", Jim_String(objv
[j
]));
10194 cmdPtr
= Jim_GetCommand(interp
, objv
[0], JIM_ERRMSG
);
10195 if (cmdPtr
== NULL
) {
10196 return JimUnknown(interp
, objc
, objv
);
10198 JimIncrCmdRefCount(cmdPtr
);
10200 if (interp
->evalDepth
== interp
->maxEvalDepth
) {
10201 Jim_SetResultString(interp
, "Infinite eval recursion", -1);
10205 interp
->evalDepth
++;
10206 prevPrivData
= interp
->cmdPrivData
;
10210 /* Call it -- Make sure result is an empty object. */
10211 Jim_SetEmptyResult(interp
);
10212 if (cmdPtr
->isproc
) {
10213 retcode
= JimCallProcedure(interp
, cmdPtr
, objc
, objv
);
10216 interp
->cmdPrivData
= cmdPtr
->u
.native
.privData
;
10217 retcode
= cmdPtr
->u
.native
.cmdProc(interp
, objc
, objv
);
10221 /* clean up previous tailcall if we were invoking one */
10222 Jim_DecrRefCount(interp
, tailcallObj
);
10223 tailcallObj
= NULL
;
10226 /* If a tailcall is returned for this frame, loop to invoke the new command */
10227 if (retcode
== JIM_EVAL
&& interp
->framePtr
->tailcallObj
) {
10228 JimDecrCmdRefCount(interp
, cmdPtr
);
10230 /* Replace the current command with the new tailcall command */
10231 cmdPtr
= interp
->framePtr
->tailcallCmd
;
10232 interp
->framePtr
->tailcallCmd
= NULL
;
10233 tailcallObj
= interp
->framePtr
->tailcallObj
;
10234 interp
->framePtr
->tailcallObj
= NULL
;
10235 /* We can access the internal rep here because the object can only
10236 * be constructed by the tailcall command
10238 objc
= tailcallObj
->internalRep
.listValue
.len
;
10239 objv
= tailcallObj
->internalRep
.listValue
.ele
;
10243 interp
->cmdPrivData
= prevPrivData
;
10244 interp
->evalDepth
--;
10247 JimDecrCmdRefCount(interp
, cmdPtr
);
10249 if (interp
->framePtr
->tailcallObj
) {
10250 /* We might have skipped invoking a tailcall, perhaps because of an error
10251 * in defer handling so cleanup now
10253 JimDecrCmdRefCount(interp
, interp
->framePtr
->tailcallCmd
);
10254 Jim_DecrRefCount(interp
, interp
->framePtr
->tailcallObj
);
10255 interp
->framePtr
->tailcallCmd
= NULL
;
10256 interp
->framePtr
->tailcallObj
= NULL
;
10262 /* Eval the object vector 'objv' composed of 'objc' elements.
10263 * Every element is used as single argument.
10264 * Jim_EvalObj() will call this function every time its object
10265 * argument is of "list" type, with no string representation.
10267 * This is possible because the string representation of a
10268 * list object generated by the UpdateStringOfList is made
10269 * in a way that ensures that every list element is a different
10270 * command argument. */
10271 int Jim_EvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
10275 /* Incr refcount of arguments. */
10276 for (i
= 0; i
< objc
; i
++)
10277 Jim_IncrRefCount(objv
[i
]);
10279 retcode
= JimInvokeCommand(interp
, objc
, objv
);
10281 /* Decr refcount of arguments and return the retcode */
10282 for (i
= 0; i
< objc
; i
++)
10283 Jim_DecrRefCount(interp
, objv
[i
]);
10289 * Invokes 'prefix' as a command with the objv array as arguments.
10291 int Jim_EvalObjPrefix(Jim_Interp
*interp
, Jim_Obj
*prefix
, int objc
, Jim_Obj
*const *objv
)
10294 Jim_Obj
**nargv
= Jim_Alloc((objc
+ 1) * sizeof(*nargv
));
10297 memcpy(&nargv
[1], &objv
[0], sizeof(nargv
[0]) * objc
);
10298 ret
= Jim_EvalObjVector(interp
, objc
+ 1, nargv
);
10303 static void JimAddErrorToStack(Jim_Interp
*interp
, ScriptObj
*script
)
10305 if (!interp
->errorFlag
) {
10306 /* This is the first error, so save the file/line information and reset the stack */
10307 interp
->errorFlag
= 1;
10308 Jim_IncrRefCount(script
->fileNameObj
);
10309 Jim_DecrRefCount(interp
, interp
->errorFileNameObj
);
10310 interp
->errorFileNameObj
= script
->fileNameObj
;
10311 interp
->errorLine
= script
->linenr
;
10313 JimResetStackTrace(interp
);
10314 /* Always add a level where the error first occurs */
10315 interp
->addStackTrace
++;
10318 /* Now if this is an "interesting" level, add it to the stack trace */
10319 if (interp
->addStackTrace
> 0) {
10320 /* Add the stack info for the current level */
10322 JimAppendStackTrace(interp
, Jim_String(interp
->errorProc
), script
->fileNameObj
, script
->linenr
);
10324 /* Note: if we didn't have a filename for this level,
10325 * don't clear the addStackTrace flag
10326 * so we can pick it up at the next level
10328 if (Jim_Length(script
->fileNameObj
)) {
10329 interp
->addStackTrace
= 0;
10332 Jim_DecrRefCount(interp
, interp
->errorProc
);
10333 interp
->errorProc
= interp
->emptyObj
;
10334 Jim_IncrRefCount(interp
->errorProc
);
10338 static int JimSubstOneToken(Jim_Interp
*interp
, const ScriptToken
*token
, Jim_Obj
**objPtrPtr
)
10343 switch (token
->type
) {
10346 objPtr
= token
->objPtr
;
10349 objPtr
= Jim_GetVariable(interp
, token
->objPtr
, JIM_ERRMSG
);
10351 case JIM_TT_DICTSUGAR
:
10352 objPtr
= JimExpandDictSugar(interp
, token
->objPtr
);
10354 case JIM_TT_EXPRSUGAR
:
10355 ret
= Jim_EvalExpression(interp
, token
->objPtr
);
10356 if (ret
== JIM_OK
) {
10357 objPtr
= Jim_GetResult(interp
);
10364 ret
= Jim_EvalObj(interp
, token
->objPtr
);
10365 if (ret
== JIM_OK
|| ret
== JIM_RETURN
) {
10366 objPtr
= interp
->result
;
10368 /* includes JIM_BREAK, JIM_CONTINUE */
10374 "default token type (%d) reached " "in Jim_SubstObj().", token
->type
));
10379 *objPtrPtr
= objPtr
;
10385 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
10386 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
10387 * The returned object has refcount = 0.
10389 static Jim_Obj
*JimInterpolateTokens(Jim_Interp
*interp
, const ScriptToken
* token
, int tokens
, int flags
)
10393 Jim_Obj
*sintv
[JIM_EVAL_SINTV_LEN
];
10397 if (tokens
<= JIM_EVAL_SINTV_LEN
)
10400 intv
= Jim_Alloc(sizeof(Jim_Obj
*) * tokens
);
10402 /* Compute every token forming the argument
10403 * in the intv objects vector. */
10404 for (i
= 0; i
< tokens
; i
++) {
10405 switch (JimSubstOneToken(interp
, &token
[i
], &intv
[i
])) {
10410 if (flags
& JIM_SUBST_FLAG
) {
10415 /* XXX: Should probably set an error about break outside loop */
10416 /* fall through to error */
10418 if (flags
& JIM_SUBST_FLAG
) {
10422 /* XXX: Ditto continue outside loop */
10423 /* fall through to error */
10426 Jim_DecrRefCount(interp
, intv
[i
]);
10428 if (intv
!= sintv
) {
10433 Jim_IncrRefCount(intv
[i
]);
10434 Jim_String(intv
[i
]);
10435 totlen
+= intv
[i
]->length
;
10438 /* Fast path return for a single token */
10439 if (tokens
== 1 && intv
[0] && intv
== sintv
) {
10440 /* Reverse the Jim_IncrRefCount() above, but don't free the object */
10441 intv
[0]->refCount
--;
10445 /* Concatenate every token in an unique
10447 objPtr
= Jim_NewStringObjNoAlloc(interp
, NULL
, 0);
10449 if (tokens
== 4 && token
[0].type
== JIM_TT_ESC
&& token
[1].type
== JIM_TT_ESC
10450 && token
[2].type
== JIM_TT_VAR
) {
10451 /* May be able to do fast interpolated object -> dictSubst */
10452 objPtr
->typePtr
= &interpolatedObjType
;
10453 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= token
[0].objPtr
;
10454 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= intv
[2];
10455 Jim_IncrRefCount(intv
[2]);
10457 else if (tokens
&& intv
[0] && intv
[0]->typePtr
== &sourceObjType
) {
10458 /* The first interpolated token is source, so preserve the source info */
10459 JimSetSourceInfo(interp
, objPtr
, intv
[0]->internalRep
.sourceValue
.fileNameObj
, intv
[0]->internalRep
.sourceValue
.lineNumber
);
10463 s
= objPtr
->bytes
= Jim_Alloc(totlen
+ 1);
10464 objPtr
->length
= totlen
;
10465 for (i
= 0; i
< tokens
; i
++) {
10467 memcpy(s
, intv
[i
]->bytes
, intv
[i
]->length
);
10468 s
+= intv
[i
]->length
;
10469 Jim_DecrRefCount(interp
, intv
[i
]);
10472 objPtr
->bytes
[totlen
] = '\0';
10473 /* Free the intv vector if not static. */
10474 if (intv
!= sintv
) {
10482 /* listPtr *must* be a list.
10483 * The contents of the list is evaluated with the first element as the command and
10484 * the remaining elements as the arguments.
10486 static int JimEvalObjList(Jim_Interp
*interp
, Jim_Obj
*listPtr
)
10488 int retcode
= JIM_OK
;
10490 JimPanic((Jim_IsList(listPtr
) == 0, "JimEvalObjList() invoked on non-list."));
10492 if (listPtr
->internalRep
.listValue
.len
) {
10493 Jim_IncrRefCount(listPtr
);
10494 retcode
= JimInvokeCommand(interp
,
10495 listPtr
->internalRep
.listValue
.len
,
10496 listPtr
->internalRep
.listValue
.ele
);
10497 Jim_DecrRefCount(interp
, listPtr
);
10502 int Jim_EvalObjList(Jim_Interp
*interp
, Jim_Obj
*listPtr
)
10504 SetListFromAny(interp
, listPtr
);
10505 return JimEvalObjList(interp
, listPtr
);
10508 int Jim_EvalObj(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
10512 ScriptToken
*token
;
10513 int retcode
= JIM_OK
;
10514 Jim_Obj
*sargv
[JIM_EVAL_SARGV_LEN
], **argv
= NULL
;
10515 Jim_Obj
*prevScriptObj
;
10517 /* If the object is of type "list", with no string rep we can call
10518 * a specialized version of Jim_EvalObj() */
10519 if (Jim_IsList(scriptObjPtr
) && scriptObjPtr
->bytes
== NULL
) {
10520 return JimEvalObjList(interp
, scriptObjPtr
);
10523 Jim_IncrRefCount(scriptObjPtr
); /* Make sure it's shared. */
10524 script
= JimGetScript(interp
, scriptObjPtr
);
10525 if (!JimScriptValid(interp
, script
)) {
10526 Jim_DecrRefCount(interp
, scriptObjPtr
);
10530 /* Reset the interpreter result. This is useful to
10531 * return the empty result in the case of empty program. */
10532 Jim_SetEmptyResult(interp
);
10534 token
= script
->token
;
10536 #ifdef JIM_OPTIMIZATION
10537 /* Check for one of the following common scripts used by for, while
10542 if (script
->len
== 0) {
10543 Jim_DecrRefCount(interp
, scriptObjPtr
);
10546 if (script
->len
== 3
10547 && token
[1].objPtr
->typePtr
== &commandObjType
10548 && token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->isproc
== 0
10549 && token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->u
.native
.cmdProc
== Jim_IncrCoreCommand
10550 && token
[2].objPtr
->typePtr
== &variableObjType
) {
10552 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, token
[2].objPtr
, JIM_NONE
);
10554 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
10555 JimWideValue(objPtr
)++;
10556 Jim_InvalidateStringRep(objPtr
);
10557 Jim_DecrRefCount(interp
, scriptObjPtr
);
10558 Jim_SetResult(interp
, objPtr
);
10564 /* Now we have to make sure the internal repr will not be
10565 * freed on shimmering.
10567 * Think for example to this:
10569 * set x {llength $x; ... some more code ...}; eval $x
10571 * In order to preserve the internal rep, we increment the
10572 * inUse field of the script internal rep structure. */
10575 /* Stash the current script */
10576 prevScriptObj
= interp
->currentScriptObj
;
10577 interp
->currentScriptObj
= scriptObjPtr
;
10579 interp
->errorFlag
= 0;
10582 /* Execute every command sequentially until the end of the script
10583 * or an error occurs.
10585 for (i
= 0; i
< script
->len
&& retcode
== JIM_OK
; ) {
10589 /* First token of the line is always JIM_TT_LINE */
10590 argc
= token
[i
].objPtr
->internalRep
.scriptLineValue
.argc
;
10591 script
->linenr
= token
[i
].objPtr
->internalRep
.scriptLineValue
.line
;
10593 /* Allocate the arguments vector if required */
10594 if (argc
> JIM_EVAL_SARGV_LEN
)
10595 argv
= Jim_Alloc(sizeof(Jim_Obj
*) * argc
);
10597 /* Skip the JIM_TT_LINE token */
10600 /* Populate the arguments objects.
10601 * If an error occurs, retcode will be set and
10602 * 'j' will be set to the number of args expanded
10604 for (j
= 0; j
< argc
; j
++) {
10605 long wordtokens
= 1;
10607 Jim_Obj
*wordObjPtr
= NULL
;
10609 if (token
[i
].type
== JIM_TT_WORD
) {
10610 wordtokens
= JimWideValue(token
[i
++].objPtr
);
10611 if (wordtokens
< 0) {
10613 wordtokens
= -wordtokens
;
10617 if (wordtokens
== 1) {
10618 /* Fast path if the token does not
10619 * need interpolation */
10621 switch (token
[i
].type
) {
10624 wordObjPtr
= token
[i
].objPtr
;
10627 wordObjPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
10629 case JIM_TT_EXPRSUGAR
:
10630 retcode
= Jim_EvalExpression(interp
, token
[i
].objPtr
);
10631 if (retcode
== JIM_OK
) {
10632 wordObjPtr
= Jim_GetResult(interp
);
10638 case JIM_TT_DICTSUGAR
:
10639 wordObjPtr
= JimExpandDictSugar(interp
, token
[i
].objPtr
);
10642 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
10643 if (retcode
== JIM_OK
) {
10644 wordObjPtr
= Jim_GetResult(interp
);
10648 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10652 /* For interpolation we call a helper
10653 * function to do the work for us. */
10654 wordObjPtr
= JimInterpolateTokens(interp
, token
+ i
, wordtokens
, JIM_NONE
);
10658 if (retcode
== JIM_OK
) {
10664 Jim_IncrRefCount(wordObjPtr
);
10668 argv
[j
] = wordObjPtr
;
10671 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10672 int len
= Jim_ListLength(interp
, wordObjPtr
);
10673 int newargc
= argc
+ len
- 1;
10677 if (argv
== sargv
) {
10678 if (newargc
> JIM_EVAL_SARGV_LEN
) {
10679 argv
= Jim_Alloc(sizeof(*argv
) * newargc
);
10680 memcpy(argv
, sargv
, sizeof(*argv
) * j
);
10684 /* Need to realloc to make room for (len - 1) more entries */
10685 argv
= Jim_Realloc(argv
, sizeof(*argv
) * newargc
);
10689 /* Now copy in the expanded version */
10690 for (k
= 0; k
< len
; k
++) {
10691 argv
[j
++] = wordObjPtr
->internalRep
.listValue
.ele
[k
];
10692 Jim_IncrRefCount(wordObjPtr
->internalRep
.listValue
.ele
[k
]);
10695 /* The original object reference is no longer needed,
10696 * after the expansion it is no longer present on
10697 * the argument vector, but the single elements are
10699 Jim_DecrRefCount(interp
, wordObjPtr
);
10701 /* And update the indexes */
10707 if (retcode
== JIM_OK
&& argc
) {
10708 /* Invoke the command */
10709 retcode
= JimInvokeCommand(interp
, argc
, argv
);
10710 /* Check for a signal after each command */
10711 if (Jim_CheckSignal(interp
)) {
10712 retcode
= JIM_SIGNAL
;
10716 /* Finished with the command, so decrement ref counts of each argument */
10718 Jim_DecrRefCount(interp
, argv
[j
]);
10721 if (argv
!= sargv
) {
10727 /* Possibly add to the error stack trace */
10728 if (retcode
== JIM_ERR
) {
10729 JimAddErrorToStack(interp
, script
);
10731 /* Propagate the addStackTrace value through 'return -code error' */
10732 else if (retcode
!= JIM_RETURN
|| interp
->returnCode
!= JIM_ERR
) {
10733 /* No need to add stack trace */
10734 interp
->addStackTrace
= 0;
10737 /* Restore the current script */
10738 interp
->currentScriptObj
= prevScriptObj
;
10740 /* Note that we don't have to decrement inUse, because the
10741 * following code transfers our use of the reference again to
10742 * the script object. */
10743 Jim_FreeIntRep(interp
, scriptObjPtr
);
10744 scriptObjPtr
->typePtr
= &scriptObjType
;
10745 Jim_SetIntRepPtr(scriptObjPtr
, script
);
10746 Jim_DecrRefCount(interp
, scriptObjPtr
);
10751 static int JimSetProcArg(Jim_Interp
*interp
, Jim_Obj
*argNameObj
, Jim_Obj
*argValObj
)
10754 /* If argObjPtr begins with '&', do an automatic upvar */
10755 const char *varname
= Jim_String(argNameObj
);
10756 if (*varname
== '&') {
10757 /* First check that the target variable exists */
10759 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
10761 interp
->framePtr
= interp
->framePtr
->parent
;
10762 objPtr
= Jim_GetVariable(interp
, argValObj
, JIM_ERRMSG
);
10763 interp
->framePtr
= savedCallFrame
;
10768 /* It exists, so perform the binding. */
10769 objPtr
= Jim_NewStringObj(interp
, varname
+ 1, -1);
10770 Jim_IncrRefCount(objPtr
);
10771 retcode
= Jim_SetVariableLink(interp
, objPtr
, argValObj
, interp
->framePtr
->parent
);
10772 Jim_DecrRefCount(interp
, objPtr
);
10775 retcode
= Jim_SetVariable(interp
, argNameObj
, argValObj
);
10781 * Sets the interp result to be an error message indicating the required proc args.
10783 static void JimSetProcWrongArgs(Jim_Interp
*interp
, Jim_Obj
*procNameObj
, Jim_Cmd
*cmd
)
10785 /* Create a nice error message, consistent with Tcl 8.5 */
10786 Jim_Obj
*argmsg
= Jim_NewStringObj(interp
, "", 0);
10789 for (i
= 0; i
< cmd
->u
.proc
.argListLen
; i
++) {
10790 Jim_AppendString(interp
, argmsg
, " ", 1);
10792 if (i
== cmd
->u
.proc
.argsPos
) {
10793 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10795 Jim_AppendString(interp
, argmsg
, "?", 1);
10796 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].defaultObjPtr
);
10797 Jim_AppendString(interp
, argmsg
, " ...?", -1);
10800 /* We have plain args */
10801 Jim_AppendString(interp
, argmsg
, "?arg...?", -1);
10805 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10806 Jim_AppendString(interp
, argmsg
, "?", 1);
10807 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10808 Jim_AppendString(interp
, argmsg
, "?", 1);
10811 const char *arg
= Jim_String(cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10815 Jim_AppendString(interp
, argmsg
, arg
, -1);
10819 Jim_SetResultFormatted(interp
, "wrong # args: should be \"%#s%#s\"", procNameObj
, argmsg
);
10822 #ifdef jim_ext_namespace
10826 int Jim_EvalNamespace(Jim_Interp
*interp
, Jim_Obj
*scriptObj
, Jim_Obj
*nsObj
)
10828 Jim_CallFrame
*callFramePtr
;
10831 /* Create a new callframe */
10832 callFramePtr
= JimCreateCallFrame(interp
, interp
->framePtr
, nsObj
);
10833 callFramePtr
->argv
= &interp
->emptyObj
;
10834 callFramePtr
->argc
= 0;
10835 callFramePtr
->procArgsObjPtr
= NULL
;
10836 callFramePtr
->procBodyObjPtr
= scriptObj
;
10837 callFramePtr
->staticVars
= NULL
;
10838 callFramePtr
->fileNameObj
= interp
->emptyObj
;
10839 callFramePtr
->line
= 0;
10840 Jim_IncrRefCount(scriptObj
);
10841 interp
->framePtr
= callFramePtr
;
10843 /* Check if there are too nested calls */
10844 if (interp
->framePtr
->level
== interp
->maxCallFrameDepth
) {
10845 Jim_SetResultString(interp
, "Too many nested calls. Infinite recursion?", -1);
10849 /* Eval the body */
10850 retcode
= Jim_EvalObj(interp
, scriptObj
);
10853 /* Destroy the callframe */
10854 interp
->framePtr
= interp
->framePtr
->parent
;
10855 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_REUSE
);
10861 /* Call a procedure implemented in Tcl.
10862 * It's possible to speed-up a lot this function, currently
10863 * the callframes are not cached, but allocated and
10864 * destroied every time. What is expecially costly is
10865 * to create/destroy the local vars hash table every time.
10867 * This can be fixed just implementing callframes caching
10868 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10869 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, int argc
, Jim_Obj
*const *argv
)
10871 Jim_CallFrame
*callFramePtr
;
10872 int i
, d
, retcode
, optargs
;
10876 if (argc
- 1 < cmd
->u
.proc
.reqArity
||
10877 (cmd
->u
.proc
.argsPos
< 0 && argc
- 1 > cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
)) {
10878 JimSetProcWrongArgs(interp
, argv
[0], cmd
);
10882 if (Jim_Length(cmd
->u
.proc
.bodyObjPtr
) == 0) {
10883 /* Optimise for procedure with no body - useful for optional debugging */
10887 /* Check if there are too nested calls */
10888 if (interp
->framePtr
->level
== interp
->maxCallFrameDepth
) {
10889 Jim_SetResultString(interp
, "Too many nested calls. Infinite recursion?", -1);
10893 /* Create a new callframe */
10894 callFramePtr
= JimCreateCallFrame(interp
, interp
->framePtr
, cmd
->u
.proc
.nsObj
);
10895 callFramePtr
->argv
= argv
;
10896 callFramePtr
->argc
= argc
;
10897 callFramePtr
->procArgsObjPtr
= cmd
->u
.proc
.argListObjPtr
;
10898 callFramePtr
->procBodyObjPtr
= cmd
->u
.proc
.bodyObjPtr
;
10899 callFramePtr
->staticVars
= cmd
->u
.proc
.staticVars
;
10901 /* Remember where we were called from. */
10902 script
= JimGetScript(interp
, interp
->currentScriptObj
);
10903 callFramePtr
->fileNameObj
= script
->fileNameObj
;
10904 callFramePtr
->line
= script
->linenr
;
10906 Jim_IncrRefCount(cmd
->u
.proc
.argListObjPtr
);
10907 Jim_IncrRefCount(cmd
->u
.proc
.bodyObjPtr
);
10908 interp
->framePtr
= callFramePtr
;
10910 /* How many optional args are available */
10911 optargs
= (argc
- 1 - cmd
->u
.proc
.reqArity
);
10913 /* Step 'i' along the actual args, and step 'd' along the formal args */
10915 for (d
= 0; d
< cmd
->u
.proc
.argListLen
; d
++) {
10916 Jim_Obj
*nameObjPtr
= cmd
->u
.proc
.arglist
[d
].nameObjPtr
;
10917 if (d
== cmd
->u
.proc
.argsPos
) {
10919 Jim_Obj
*listObjPtr
;
10921 if (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
< argc
- 1) {
10922 argsLen
= argc
- 1 - (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
);
10924 listObjPtr
= Jim_NewListObj(interp
, &argv
[i
], argsLen
);
10926 /* It is possible to rename args. */
10927 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
) {
10928 nameObjPtr
=cmd
->u
.proc
.arglist
[d
].defaultObjPtr
;
10930 retcode
= Jim_SetVariable(interp
, nameObjPtr
, listObjPtr
);
10931 if (retcode
!= JIM_OK
) {
10939 /* Optional or required? */
10940 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
== NULL
|| optargs
-- > 0) {
10941 retcode
= JimSetProcArg(interp
, nameObjPtr
, argv
[i
++]);
10944 /* Ran out, so use the default */
10945 retcode
= Jim_SetVariable(interp
, nameObjPtr
, cmd
->u
.proc
.arglist
[d
].defaultObjPtr
);
10947 if (retcode
!= JIM_OK
) {
10952 /* Eval the body */
10953 retcode
= Jim_EvalObj(interp
, cmd
->u
.proc
.bodyObjPtr
);
10957 /* Invoke $jim::defer then destroy the callframe */
10958 retcode
= JimInvokeDefer(interp
, retcode
);
10959 interp
->framePtr
= interp
->framePtr
->parent
;
10960 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_REUSE
);
10962 /* Handle the JIM_RETURN return code */
10963 if (retcode
== JIM_RETURN
) {
10964 if (--interp
->returnLevel
<= 0) {
10965 retcode
= interp
->returnCode
;
10966 interp
->returnCode
= JIM_OK
;
10967 interp
->returnLevel
= 0;
10970 else if (retcode
== JIM_ERR
) {
10971 interp
->addStackTrace
++;
10972 Jim_DecrRefCount(interp
, interp
->errorProc
);
10973 interp
->errorProc
= argv
[0];
10974 Jim_IncrRefCount(interp
->errorProc
);
10980 int Jim_EvalSource(Jim_Interp
*interp
, const char *filename
, int lineno
, const char *script
)
10983 Jim_Obj
*scriptObjPtr
;
10985 scriptObjPtr
= Jim_NewStringObj(interp
, script
, -1);
10986 Jim_IncrRefCount(scriptObjPtr
);
10989 Jim_Obj
*prevScriptObj
;
10991 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), lineno
);
10993 prevScriptObj
= interp
->currentScriptObj
;
10994 interp
->currentScriptObj
= scriptObjPtr
;
10996 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10998 interp
->currentScriptObj
= prevScriptObj
;
11001 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
11003 Jim_DecrRefCount(interp
, scriptObjPtr
);
11007 int Jim_Eval(Jim_Interp
*interp
, const char *script
)
11009 return Jim_EvalObj(interp
, Jim_NewStringObj(interp
, script
, -1));
11012 /* Execute script in the scope of the global level */
11013 int Jim_EvalGlobal(Jim_Interp
*interp
, const char *script
)
11016 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
11018 interp
->framePtr
= interp
->topFramePtr
;
11019 retval
= Jim_Eval(interp
, script
);
11020 interp
->framePtr
= savedFramePtr
;
11025 int Jim_EvalFileGlobal(Jim_Interp
*interp
, const char *filename
)
11028 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
11030 interp
->framePtr
= interp
->topFramePtr
;
11031 retval
= Jim_EvalFile(interp
, filename
);
11032 interp
->framePtr
= savedFramePtr
;
11037 #include <sys/stat.h>
11039 int Jim_EvalFile(Jim_Interp
*interp
, const char *filename
)
11043 Jim_Obj
*scriptObjPtr
;
11044 Jim_Obj
*prevScriptObj
;
11049 if (stat(filename
, &sb
) != 0 || (fp
= fopen(filename
, "rt")) == NULL
) {
11050 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", filename
, strerror(errno
));
11053 if (sb
.st_size
== 0) {
11058 buf
= Jim_Alloc(sb
.st_size
+ 1);
11059 readlen
= fread(buf
, 1, sb
.st_size
, fp
);
11063 Jim_SetResultFormatted(interp
, "failed to load file \"%s\": %s", filename
, strerror(errno
));
11069 scriptObjPtr
= Jim_NewStringObjNoAlloc(interp
, buf
, readlen
);
11070 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), 1);
11071 Jim_IncrRefCount(scriptObjPtr
);
11073 prevScriptObj
= interp
->currentScriptObj
;
11074 interp
->currentScriptObj
= scriptObjPtr
;
11076 retcode
= Jim_EvalObj(interp
, scriptObjPtr
);
11078 /* Handle the JIM_RETURN return code */
11079 if (retcode
== JIM_RETURN
) {
11080 if (--interp
->returnLevel
<= 0) {
11081 retcode
= interp
->returnCode
;
11082 interp
->returnCode
= JIM_OK
;
11083 interp
->returnLevel
= 0;
11086 if (retcode
== JIM_ERR
) {
11087 /* EvalFile changes context, so add a stack frame here */
11088 interp
->addStackTrace
++;
11091 interp
->currentScriptObj
= prevScriptObj
;
11093 Jim_DecrRefCount(interp
, scriptObjPtr
);
11098 /* -----------------------------------------------------------------------------
11100 * ---------------------------------------------------------------------------*/
11101 static void JimParseSubst(struct JimParserCtx
*pc
, int flags
)
11103 pc
->tstart
= pc
->p
;
11104 pc
->tline
= pc
->linenr
;
11106 if (pc
->len
== 0) {
11108 pc
->tt
= JIM_TT_EOL
;
11112 if (*pc
->p
== '[' && !(flags
& JIM_SUBST_NOCMD
)) {
11116 if (*pc
->p
== '$' && !(flags
& JIM_SUBST_NOVAR
)) {
11117 if (JimParseVar(pc
) == JIM_OK
) {
11120 /* Not a var, so treat as a string */
11121 pc
->tstart
= pc
->p
;
11122 flags
|= JIM_SUBST_NOVAR
;
11125 if (*pc
->p
== '$' && !(flags
& JIM_SUBST_NOVAR
)) {
11128 if (*pc
->p
== '[' && !(flags
& JIM_SUBST_NOCMD
)) {
11131 if (*pc
->p
== '\\' && pc
->len
> 1) {
11138 pc
->tend
= pc
->p
- 1;
11139 pc
->tt
= (flags
& JIM_SUBST_NOESC
) ? JIM_TT_STR
: JIM_TT_ESC
;
11142 /* The subst object type reuses most of the data structures and functions
11143 * of the script object. Script's data structures are a bit more complex
11144 * for what is needed for [subst]itution tasks, but the reuse helps to
11145 * deal with a single data structure at the cost of some more memory
11146 * usage for substitutions. */
11148 /* This method takes the string representation of an object
11149 * as a Tcl string where to perform [subst]itution, and generates
11150 * the pre-parsed internal representation. */
11151 static int SetSubstFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, int flags
)
11154 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
11155 struct JimParserCtx parser
;
11156 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
11157 ParseTokenList tokenlist
;
11159 /* Initially parse the subst into tokens (in tokenlist) */
11160 ScriptTokenListInit(&tokenlist
);
11162 JimParserInit(&parser
, scriptText
, scriptTextLen
, 1);
11164 JimParseSubst(&parser
, flags
);
11166 /* Note that subst doesn't need the EOL token */
11169 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
11173 /* Create the "real" subst/script tokens from the initial token list */
11175 script
->substFlags
= flags
;
11176 script
->fileNameObj
= interp
->emptyObj
;
11177 Jim_IncrRefCount(script
->fileNameObj
);
11178 SubstObjAddTokens(interp
, script
, &tokenlist
);
11180 /* No longer need the token list */
11181 ScriptTokenListFree(&tokenlist
);
11183 #ifdef DEBUG_SHOW_SUBST
11187 printf("==== Subst ====\n");
11188 for (i
= 0; i
< script
->len
; i
++) {
11189 printf("[%2d] %s '%s'\n", i
, jim_tt_name(script
->token
[i
].type
),
11190 Jim_String(script
->token
[i
].objPtr
));
11195 /* Free the old internal rep and set the new one. */
11196 Jim_FreeIntRep(interp
, objPtr
);
11197 Jim_SetIntRepPtr(objPtr
, script
);
11198 objPtr
->typePtr
= &scriptObjType
;
11202 static ScriptObj
*Jim_GetSubst(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
11204 if (objPtr
->typePtr
!= &scriptObjType
|| ((ScriptObj
*)Jim_GetIntRepPtr(objPtr
))->substFlags
!= flags
)
11205 SetSubstFromAny(interp
, objPtr
, flags
);
11206 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
11209 /* Performs commands,variables,blackslashes substitution,
11210 * storing the result object (with refcount 0) into
11212 int Jim_SubstObj(Jim_Interp
*interp
, Jim_Obj
*substObjPtr
, Jim_Obj
**resObjPtrPtr
, int flags
)
11216 JimPanic((substObjPtr
->refCount
== 0, "Jim_SubstObj() called with zero refcount object"));
11218 script
= Jim_GetSubst(interp
, substObjPtr
, flags
);
11220 Jim_IncrRefCount(substObjPtr
); /* Make sure it's shared. */
11221 /* In order to preserve the internal rep, we increment the
11222 * inUse field of the script internal rep structure. */
11225 *resObjPtrPtr
= JimInterpolateTokens(interp
, script
->token
, script
->len
, flags
);
11228 Jim_DecrRefCount(interp
, substObjPtr
);
11229 if (*resObjPtrPtr
== NULL
) {
11235 /* -----------------------------------------------------------------------------
11236 * Core commands utility functions
11237 * ---------------------------------------------------------------------------*/
11238 void Jim_WrongNumArgs(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, const char *msg
)
11241 Jim_Obj
*listObjPtr
;
11243 JimPanic((argc
== 0, "Jim_WrongNumArgs() called with argc=0"));
11245 listObjPtr
= Jim_NewListObj(interp
, argv
, argc
);
11248 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, msg
, -1));
11250 Jim_IncrRefCount(listObjPtr
);
11251 objPtr
= Jim_ListJoin(interp
, listObjPtr
, " ", 1);
11252 Jim_DecrRefCount(interp
, listObjPtr
);
11254 Jim_SetResultFormatted(interp
, "wrong # args: should be \"%#s\"", objPtr
);
11258 * May add the key and/or value to the list.
11260 typedef void JimHashtableIteratorCallbackType(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
11261 Jim_HashEntry
*he
, int type
);
11263 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
11266 * For each key of the hash table 'ht' with object keys that
11267 * matches the glob pattern (all if NULL), invoke the callback to add entries to a list.
11268 * Returns the list.
11270 static Jim_Obj
*JimHashtablePatternMatch(Jim_Interp
*interp
, Jim_HashTable
*ht
, Jim_Obj
*patternObjPtr
,
11271 JimHashtableIteratorCallbackType
*callback
, int type
)
11274 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11276 /* Check for the non-pattern case. We can do this much more efficiently. */
11277 if (patternObjPtr
&& JimTrivialMatch(Jim_String(patternObjPtr
))) {
11278 he
= Jim_FindHashEntry(ht
, patternObjPtr
);
11280 callback(interp
, listObjPtr
, he
, type
);
11284 Jim_HashTableIterator htiter
;
11285 JimInitHashTableIterator(ht
, &htiter
);
11286 while ((he
= Jim_NextHashEntry(&htiter
)) != NULL
) {
11287 if (!patternObjPtr
|| Jim_StringMatchObj(interp
, patternObjPtr
, he
->key
, 0)) {
11288 callback(interp
, listObjPtr
, he
, type
);
11295 /* Keep these in order */
11296 #define JIM_CMDLIST_COMMANDS 0
11297 #define JIM_CMDLIST_PROCS 1
11298 #define JIM_CMDLIST_CHANNELS 2
11301 * Adds matching command names (procs, channels) to the list.
11303 static void JimCommandMatch(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
11304 Jim_HashEntry
*he
, int type
)
11306 Jim_Cmd
*cmdPtr
= Jim_GetHashEntryVal(he
);
11309 if (type
== JIM_CMDLIST_PROCS
&& !cmdPtr
->isproc
) {
11314 objPtr
= (Jim_Obj
*)he
->key
;
11315 Jim_IncrRefCount(objPtr
);
11317 if (type
!= JIM_CMDLIST_CHANNELS
|| Jim_AioFilehandle(interp
, objPtr
)) {
11318 Jim_ListAppendElement(interp
, listObjPtr
, objPtr
);
11320 Jim_DecrRefCount(interp
, objPtr
);
11323 static Jim_Obj
*JimCommandsList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int type
)
11325 return JimHashtablePatternMatch(interp
, &interp
->commands
, patternObjPtr
, JimCommandMatch
, type
);
11328 /* Keep these in order */
11329 #define JIM_VARLIST_GLOBALS 0
11330 #define JIM_VARLIST_LOCALS 1
11331 #define JIM_VARLIST_VARS 2
11332 #define JIM_VARLIST_MASK 0x000f
11334 #define JIM_VARLIST_VALUES 0x1000
11337 * Adds matching variable names to the list.
11339 static void JimVariablesMatch(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
11340 Jim_HashEntry
*he
, int type
)
11342 Jim_Var
*varPtr
= Jim_GetHashEntryVal(he
);
11344 if ((type
& JIM_VARLIST_MASK
) != JIM_VARLIST_LOCALS
|| varPtr
->linkFramePtr
== NULL
) {
11345 Jim_ListAppendElement(interp
, listObjPtr
, (Jim_Obj
*)he
->key
);
11346 if (type
& JIM_VARLIST_VALUES
) {
11347 Jim_ListAppendElement(interp
, listObjPtr
, varPtr
->objPtr
);
11352 /* mode is JIM_VARLIST_xxx */
11353 static Jim_Obj
*JimVariablesList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int mode
)
11355 if (mode
== JIM_VARLIST_LOCALS
&& interp
->framePtr
== interp
->topFramePtr
) {
11356 /* For [info locals], if we are at top level an empty list
11357 * is returned. I don't agree, but we aim at compatibility (SS) */
11358 return interp
->emptyObj
;
11361 Jim_CallFrame
*framePtr
= (mode
== JIM_VARLIST_GLOBALS
) ? interp
->topFramePtr
: interp
->framePtr
;
11362 return JimHashtablePatternMatch(interp
, &framePtr
->vars
, patternObjPtr
, JimVariablesMatch
,
11367 static int JimInfoLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
11368 Jim_Obj
**objPtrPtr
, int info_level_cmd
)
11370 Jim_CallFrame
*targetCallFrame
;
11372 targetCallFrame
= JimGetCallFrameByInteger(interp
, levelObjPtr
);
11373 if (targetCallFrame
== NULL
) {
11376 /* No proc call at toplevel callframe */
11377 if (targetCallFrame
== interp
->topFramePtr
) {
11378 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
11381 if (info_level_cmd
) {
11382 *objPtrPtr
= Jim_NewListObj(interp
, targetCallFrame
->argv
, targetCallFrame
->argc
);
11385 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
11387 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->argv
[0]);
11388 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->fileNameObj
);
11389 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, targetCallFrame
->line
));
11390 *objPtrPtr
= listObj
;
11395 /* -----------------------------------------------------------------------------
11397 * ---------------------------------------------------------------------------*/
11399 /* fake [puts] -- not the real puts, just for debugging. */
11400 static int Jim_PutsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11402 if (argc
!= 2 && argc
!= 3) {
11403 Jim_WrongNumArgs(interp
, 1, argv
, "?-nonewline? string");
11407 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-nonewline")) {
11408 Jim_SetResultString(interp
, "The second argument must " "be -nonewline", -1);
11412 fputs(Jim_String(argv
[2]), stdout
);
11416 puts(Jim_String(argv
[1]));
11421 /* Helper for [+] and [*] */
11422 static int JimAddMulHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
11424 jim_wide wideValue
, res
;
11425 double doubleValue
, doubleRes
;
11428 res
= (op
== JIM_EXPROP_ADD
) ? 0 : 1;
11430 for (i
= 1; i
< argc
; i
++) {
11431 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
)
11433 if (op
== JIM_EXPROP_ADD
)
11438 Jim_SetResultInt(interp
, res
);
11441 doubleRes
= (double)res
;
11442 for (; i
< argc
; i
++) {
11443 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
11445 if (op
== JIM_EXPROP_ADD
)
11446 doubleRes
+= doubleValue
;
11448 doubleRes
*= doubleValue
;
11450 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
11454 /* Helper for [-] and [/] */
11455 static int JimSubDivHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
11457 jim_wide wideValue
, res
= 0;
11458 double doubleValue
, doubleRes
= 0;
11462 Jim_WrongNumArgs(interp
, 1, argv
, "number ?number ... number?");
11465 else if (argc
== 2) {
11466 /* The arity = 2 case is different. For [- x] returns -x,
11467 * while [/ x] returns 1/x. */
11468 if (Jim_GetWide(interp
, argv
[1], &wideValue
) != JIM_OK
) {
11469 if (Jim_GetDouble(interp
, argv
[1], &doubleValue
) != JIM_OK
) {
11473 if (op
== JIM_EXPROP_SUB
)
11474 doubleRes
= -doubleValue
;
11476 doubleRes
= 1.0 / doubleValue
;
11477 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
11481 if (op
== JIM_EXPROP_SUB
) {
11483 Jim_SetResultInt(interp
, res
);
11486 doubleRes
= 1.0 / wideValue
;
11487 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
11492 if (Jim_GetWide(interp
, argv
[1], &res
) != JIM_OK
) {
11493 if (Jim_GetDouble(interp
, argv
[1], &doubleRes
)
11502 for (i
= 2; i
< argc
; i
++) {
11503 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
) {
11504 doubleRes
= (double)res
;
11507 if (op
== JIM_EXPROP_SUB
)
11510 if (wideValue
== 0) {
11511 Jim_SetResultString(interp
, "Division by zero", -1);
11517 Jim_SetResultInt(interp
, res
);
11520 for (; i
< argc
; i
++) {
11521 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
11523 if (op
== JIM_EXPROP_SUB
)
11524 doubleRes
-= doubleValue
;
11526 doubleRes
/= doubleValue
;
11528 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
11534 static int Jim_AddCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11536 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_ADD
);
11540 static int Jim_MulCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11542 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_MUL
);
11546 static int Jim_SubCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11548 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_SUB
);
11552 static int Jim_DivCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11554 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_DIV
);
11558 static int Jim_SetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11560 if (argc
!= 2 && argc
!= 3) {
11561 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?newValue?");
11567 objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11570 Jim_SetResult(interp
, objPtr
);
11573 /* argc == 3 case. */
11574 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
11576 Jim_SetResult(interp
, argv
[2]);
11582 * unset ?-nocomplain? ?--? ?varName ...?
11584 static int Jim_UnsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11590 if (Jim_CompareStringImmediate(interp
, argv
[i
], "--")) {
11594 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-nocomplain")) {
11603 if (Jim_UnsetVariable(interp
, argv
[i
], complain
? JIM_ERRMSG
: JIM_NONE
) != JIM_OK
11613 static int Jim_WhileCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11616 Jim_WrongNumArgs(interp
, 1, argv
, "condition body");
11620 /* The general purpose implementation of while starts here */
11622 int boolean
, retval
;
11624 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[1], &boolean
)) != JIM_OK
)
11629 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
11643 Jim_SetEmptyResult(interp
);
11648 static int Jim_ForCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11652 Jim_Obj
*varNamePtr
= NULL
;
11653 Jim_Obj
*stopVarNamePtr
= NULL
;
11656 Jim_WrongNumArgs(interp
, 1, argv
, "start test next body");
11660 /* Do the initialisation */
11661 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
) {
11665 /* And do the first test now. Better for optimisation
11666 * if we can do next/test at the bottom of the loop
11668 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11670 /* Ready to do the body as follows:
11672 * body // check retcode
11673 * next // check retcode
11674 * test // check retcode/test bool
11678 #ifdef JIM_OPTIMIZATION
11679 /* Check if the for is on the form:
11680 * for ... {$i < CONST} {incr i}
11681 * for ... {$i < $j} {incr i}
11683 if (retval
== JIM_OK
&& boolean
) {
11684 ScriptObj
*incrScript
;
11685 struct ExprTree
*expr
;
11686 jim_wide stop
, currentVal
;
11690 /* Do it only if there aren't shared arguments */
11691 expr
= JimGetExpression(interp
, argv
[2]);
11692 incrScript
= JimGetScript(interp
, argv
[3]);
11694 /* Ensure proper lengths to start */
11695 if (incrScript
== NULL
|| incrScript
->len
!= 3 || !expr
|| expr
->len
!= 3) {
11698 /* Ensure proper token types. */
11699 if (incrScript
->token
[1].type
!= JIM_TT_ESC
) {
11703 if (expr
->expr
->type
== JIM_EXPROP_LT
) {
11706 else if (expr
->expr
->type
== JIM_EXPROP_LTE
) {
11713 if (expr
->expr
->left
->type
!= JIM_TT_VAR
) {
11717 if (expr
->expr
->right
->type
!= JIM_TT_VAR
&& expr
->expr
->right
->type
!= JIM_TT_EXPR_INT
) {
11721 /* Update command must be incr */
11722 if (!Jim_CompareStringImmediate(interp
, incrScript
->token
[1].objPtr
, "incr")) {
11726 /* incr, expression must be about the same variable */
11727 if (!Jim_StringEqObj(incrScript
->token
[2].objPtr
, expr
->expr
->left
->objPtr
)) {
11731 /* Get the stop condition (must be a variable or integer) */
11732 if (expr
->expr
->right
->type
== JIM_TT_EXPR_INT
) {
11733 if (Jim_GetWide(interp
, expr
->expr
->right
->objPtr
, &stop
) == JIM_ERR
) {
11738 stopVarNamePtr
= expr
->expr
->right
->objPtr
;
11739 Jim_IncrRefCount(stopVarNamePtr
);
11740 /* Keep the compiler happy */
11744 /* Initialization */
11745 varNamePtr
= expr
->expr
->left
->objPtr
;
11746 Jim_IncrRefCount(varNamePtr
);
11748 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_NONE
);
11749 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
) {
11753 /* --- OPTIMIZED FOR --- */
11754 while (retval
== JIM_OK
) {
11755 /* === Check condition === */
11756 /* Note that currentVal is already set here */
11758 /* Immediate or Variable? get the 'stop' value if the latter. */
11759 if (stopVarNamePtr
) {
11760 objPtr
= Jim_GetVariable(interp
, stopVarNamePtr
, JIM_NONE
);
11761 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, &stop
) != JIM_OK
) {
11766 if (currentVal
>= stop
+ cmpOffset
) {
11771 retval
= Jim_EvalObj(interp
, argv
[4]);
11772 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11775 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
11778 if (objPtr
== NULL
) {
11782 if (!Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11783 currentVal
= ++JimWideValue(objPtr
);
11784 Jim_InvalidateStringRep(objPtr
);
11787 if (Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
||
11788 Jim_SetVariable(interp
, varNamePtr
, Jim_NewIntObj(interp
,
11789 ++currentVal
)) != JIM_OK
) {
11800 while (boolean
&& (retval
== JIM_OK
|| retval
== JIM_CONTINUE
)) {
11802 retval
= Jim_EvalObj(interp
, argv
[4]);
11804 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11806 JIM_IF_OPTIM(evalnext
:)
11807 retval
= Jim_EvalObj(interp
, argv
[3]);
11808 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11810 JIM_IF_OPTIM(testcond
:)
11811 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11816 if (stopVarNamePtr
) {
11817 Jim_DecrRefCount(interp
, stopVarNamePtr
);
11820 Jim_DecrRefCount(interp
, varNamePtr
);
11823 if (retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
|| retval
== JIM_OK
) {
11824 Jim_SetEmptyResult(interp
);
11832 static int Jim_LoopCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11838 Jim_Obj
*bodyObjPtr
;
11840 if (argc
!= 5 && argc
!= 6) {
11841 Jim_WrongNumArgs(interp
, 1, argv
, "var first limit ?incr? body");
11845 if (Jim_GetWide(interp
, argv
[2], &i
) != JIM_OK
||
11846 Jim_GetWide(interp
, argv
[3], &limit
) != JIM_OK
||
11847 (argc
== 6 && Jim_GetWide(interp
, argv
[4], &incr
) != JIM_OK
)) {
11850 bodyObjPtr
= (argc
== 5) ? argv
[4] : argv
[5];
11852 retval
= Jim_SetVariable(interp
, argv
[1], argv
[2]);
11854 while (((i
< limit
&& incr
> 0) || (i
> limit
&& incr
< 0)) && retval
== JIM_OK
) {
11855 retval
= Jim_EvalObj(interp
, bodyObjPtr
);
11856 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11857 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11864 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11865 if (argv
[1]->typePtr
!= &variableObjType
) {
11866 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11870 JimWideValue(objPtr
) = i
;
11871 Jim_InvalidateStringRep(objPtr
);
11873 /* The following step is required in order to invalidate the
11874 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11875 if (argv
[1]->typePtr
!= &variableObjType
) {
11876 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11883 objPtr
= Jim_NewIntObj(interp
, i
);
11884 retval
= Jim_SetVariable(interp
, argv
[1], objPtr
);
11885 if (retval
!= JIM_OK
) {
11886 Jim_FreeNewObj(interp
, objPtr
);
11892 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
) {
11893 Jim_SetEmptyResult(interp
);
11899 /* List iterators make it easy to iterate over a list.
11900 * At some point iterators will be expanded to support generators.
11908 * Initialise the iterator at the start of the list.
11910 static void JimListIterInit(Jim_ListIter
*iter
, Jim_Obj
*objPtr
)
11912 iter
->objPtr
= objPtr
;
11917 * Returns the next object from the list, or NULL on end-of-list.
11919 static Jim_Obj
*JimListIterNext(Jim_Interp
*interp
, Jim_ListIter
*iter
)
11921 if (iter
->idx
>= Jim_ListLength(interp
, iter
->objPtr
)) {
11924 return iter
->objPtr
->internalRep
.listValue
.ele
[iter
->idx
++];
11928 * Returns 1 if end-of-list has been reached.
11930 static int JimListIterDone(Jim_Interp
*interp
, Jim_ListIter
*iter
)
11932 return iter
->idx
>= Jim_ListLength(interp
, iter
->objPtr
);
11935 /* foreach + lmap implementation. */
11936 static int JimForeachMapHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int doMap
)
11938 int result
= JIM_OK
;
11940 Jim_ListIter twoiters
[2]; /* Avoid allocation for a single list */
11941 Jim_ListIter
*iters
;
11943 Jim_Obj
*resultObj
;
11945 if (argc
< 4 || argc
% 2 != 0) {
11946 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varList list ...? script");
11949 script
= argv
[argc
- 1]; /* Last argument is a script */
11950 numargs
= (argc
- 1 - 1); /* argc - 'foreach' - script */
11952 if (numargs
== 2) {
11956 iters
= Jim_Alloc(numargs
* sizeof(*iters
));
11958 for (i
= 0; i
< numargs
; i
++) {
11959 JimListIterInit(&iters
[i
], argv
[i
+ 1]);
11960 if (i
% 2 == 0 && JimListIterDone(interp
, &iters
[i
])) {
11964 if (result
!= JIM_OK
) {
11965 Jim_SetResultString(interp
, "foreach varlist is empty", -1);
11966 goto empty_varlist
;
11970 resultObj
= Jim_NewListObj(interp
, NULL
, 0);
11973 resultObj
= interp
->emptyObj
;
11975 Jim_IncrRefCount(resultObj
);
11978 /* Have we expired all lists? */
11979 for (i
= 0; i
< numargs
; i
+= 2) {
11980 if (!JimListIterDone(interp
, &iters
[i
+ 1])) {
11984 if (i
== numargs
) {
11989 /* For each list */
11990 for (i
= 0; i
< numargs
; i
+= 2) {
11994 JimListIterInit(&iters
[i
], argv
[i
+ 1]);
11995 while ((varName
= JimListIterNext(interp
, &iters
[i
])) != NULL
) {
11996 Jim_Obj
*valObj
= JimListIterNext(interp
, &iters
[i
+ 1]);
11998 /* Ran out, so store the empty string */
11999 valObj
= interp
->emptyObj
;
12001 /* Avoid shimmering */
12002 Jim_IncrRefCount(valObj
);
12003 result
= Jim_SetVariable(interp
, varName
, valObj
);
12004 Jim_DecrRefCount(interp
, valObj
);
12005 if (result
!= JIM_OK
) {
12010 switch (result
= Jim_EvalObj(interp
, script
)) {
12013 Jim_ListAppendElement(interp
, resultObj
, interp
->result
);
12026 Jim_SetResult(interp
, resultObj
);
12028 Jim_DecrRefCount(interp
, resultObj
);
12037 static int Jim_ForeachCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12039 return JimForeachMapHelper(interp
, argc
, argv
, 0);
12043 static int Jim_LmapCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12045 return JimForeachMapHelper(interp
, argc
, argv
, 1);
12049 static int Jim_LassignCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12051 int result
= JIM_ERR
;
12054 Jim_Obj
*resultObj
;
12057 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varName ...?");
12061 JimListIterInit(&iter
, argv
[1]);
12063 for (i
= 2; i
< argc
; i
++) {
12064 Jim_Obj
*valObj
= JimListIterNext(interp
, &iter
);
12065 result
= Jim_SetVariable(interp
, argv
[i
], valObj
? valObj
: interp
->emptyObj
);
12066 if (result
!= JIM_OK
) {
12071 resultObj
= Jim_NewListObj(interp
, NULL
, 0);
12072 while (!JimListIterDone(interp
, &iter
)) {
12073 Jim_ListAppendElement(interp
, resultObj
, JimListIterNext(interp
, &iter
));
12076 Jim_SetResult(interp
, resultObj
);
12082 static int Jim_IfCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12084 int boolean
, retval
, current
= 1, falsebody
= 0;
12088 /* Far not enough arguments given! */
12089 if (current
>= argc
)
12091 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[current
++], &boolean
))
12094 /* There lacks something, isn't it? */
12095 if (current
>= argc
)
12097 if (Jim_CompareStringImmediate(interp
, argv
[current
], "then"))
12099 /* Tsk tsk, no then-clause? */
12100 if (current
>= argc
)
12103 return Jim_EvalObj(interp
, argv
[current
]);
12104 /* Ok: no else-clause follows */
12105 if (++current
>= argc
) {
12106 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
12109 falsebody
= current
++;
12110 if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "else")) {
12111 /* IIICKS - else-clause isn't last cmd? */
12112 if (current
!= argc
- 1)
12114 return Jim_EvalObj(interp
, argv
[current
]);
12116 else if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "elseif"))
12117 /* Ok: elseif follows meaning all the stuff
12118 * again (how boring...) */
12120 /* OOPS - else-clause is not last cmd? */
12121 else if (falsebody
!= argc
- 1)
12123 return Jim_EvalObj(interp
, argv
[falsebody
]);
12128 Jim_WrongNumArgs(interp
, 1, argv
, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
12133 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)
12134 * flags may contain JIM_NOCASE and/or JIM_OPT_END
12136 int Jim_CommandMatchObj(Jim_Interp
*interp
, Jim_Obj
*commandObj
, Jim_Obj
*patternObj
,
12137 Jim_Obj
*stringObj
, int flags
)
12144 parms
[argc
++] = commandObj
;
12145 if (flags
& JIM_NOCASE
) {
12146 parms
[argc
++] = Jim_NewStringObj(interp
, "-nocase", -1);
12148 if (flags
& JIM_OPT_END
) {
12149 parms
[argc
++] = Jim_NewStringObj(interp
, "--", -1);
12151 parms
[argc
++] = patternObj
;
12152 parms
[argc
++] = stringObj
;
12154 rc
= Jim_EvalObjVector(interp
, argc
, parms
);
12156 if (rc
!= JIM_OK
|| Jim_GetLong(interp
, Jim_GetResult(interp
), &eq
) != JIM_OK
) {
12164 static int Jim_SwitchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12166 enum { SWITCH_EXACT
, SWITCH_GLOB
, SWITCH_RE
, SWITCH_CMD
};
12167 int matchOpt
= SWITCH_EXACT
, opt
= 1, patCount
, i
;
12168 int match_flags
= 0;
12169 Jim_Obj
*command
= NULL
, *scriptObj
= NULL
, *strObj
;
12170 Jim_Obj
**caseList
;
12174 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string "
12175 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
12178 for (opt
= 1; opt
< argc
; ++opt
) {
12179 const char *option
= Jim_String(argv
[opt
]);
12181 if (*option
!= '-')
12183 else if (strncmp(option
, "--", 2) == 0) {
12187 else if (strncmp(option
, "-exact", 2) == 0)
12188 matchOpt
= SWITCH_EXACT
;
12189 else if (strncmp(option
, "-glob", 2) == 0)
12190 matchOpt
= SWITCH_GLOB
;
12191 else if (strncmp(option
, "-regexp", 2) == 0) {
12192 matchOpt
= SWITCH_RE
;
12193 match_flags
|= JIM_OPT_END
;
12195 else if (strncmp(option
, "-command", 2) == 0) {
12196 matchOpt
= SWITCH_CMD
;
12197 if ((argc
- opt
) < 2)
12199 command
= argv
[++opt
];
12202 Jim_SetResultFormatted(interp
,
12203 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
12207 if ((argc
- opt
) < 2)
12210 strObj
= argv
[opt
++];
12211 patCount
= argc
- opt
;
12212 if (patCount
== 1) {
12213 JimListGetElements(interp
, argv
[opt
], &patCount
, &caseList
);
12216 caseList
= (Jim_Obj
**)&argv
[opt
];
12217 if (patCount
== 0 || patCount
% 2 != 0)
12219 for (i
= 0; scriptObj
== NULL
&& i
< patCount
; i
+= 2) {
12220 Jim_Obj
*patObj
= caseList
[i
];
12222 if (!Jim_CompareStringImmediate(interp
, patObj
, "default")
12223 || i
< (patCount
- 2)) {
12224 switch (matchOpt
) {
12226 if (Jim_StringEqObj(strObj
, patObj
))
12227 scriptObj
= caseList
[i
+ 1];
12230 if (Jim_StringMatchObj(interp
, patObj
, strObj
, 0))
12231 scriptObj
= caseList
[i
+ 1];
12234 command
= Jim_NewStringObj(interp
, "regexp", -1);
12235 /* Fall thru intentionally */
12237 int rc
= Jim_CommandMatchObj(interp
, command
, patObj
, strObj
, match_flags
);
12239 /* After the execution of a command we need to
12240 * make sure to reconvert the object into a list
12241 * again. Only for the single-list style [switch]. */
12242 if (argc
- opt
== 1) {
12243 JimListGetElements(interp
, argv
[opt
], &patCount
, &caseList
);
12245 /* command is here already decref'd */
12250 scriptObj
= caseList
[i
+ 1];
12256 scriptObj
= caseList
[i
+ 1];
12259 for (; i
< patCount
&& Jim_CompareStringImmediate(interp
, scriptObj
, "-"); i
+= 2)
12260 scriptObj
= caseList
[i
+ 1];
12261 if (scriptObj
&& Jim_CompareStringImmediate(interp
, scriptObj
, "-")) {
12262 Jim_SetResultFormatted(interp
, "no body specified for pattern \"%#s\"", caseList
[i
- 2]);
12265 Jim_SetEmptyResult(interp
);
12267 return Jim_EvalObj(interp
, scriptObj
);
12273 static int Jim_ListCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12275 Jim_Obj
*listObjPtr
;
12277 listObjPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
12278 Jim_SetResult(interp
, listObjPtr
);
12283 static int Jim_LindexCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12285 Jim_Obj
*objPtr
, *listObjPtr
;
12290 Jim_WrongNumArgs(interp
, 1, argv
, "list ?index ...?");
12294 Jim_IncrRefCount(objPtr
);
12295 for (i
= 2; i
< argc
; i
++) {
12296 listObjPtr
= objPtr
;
12297 if (Jim_GetIndex(interp
, argv
[i
], &idx
) != JIM_OK
) {
12298 Jim_DecrRefCount(interp
, listObjPtr
);
12301 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_NONE
) != JIM_OK
) {
12302 /* Returns an empty object if the index
12303 * is out of range. */
12304 Jim_DecrRefCount(interp
, listObjPtr
);
12305 Jim_SetEmptyResult(interp
);
12308 Jim_IncrRefCount(objPtr
);
12309 Jim_DecrRefCount(interp
, listObjPtr
);
12311 Jim_SetResult(interp
, objPtr
);
12312 Jim_DecrRefCount(interp
, objPtr
);
12317 static int Jim_LlengthCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12320 Jim_WrongNumArgs(interp
, 1, argv
, "list");
12323 Jim_SetResultInt(interp
, Jim_ListLength(interp
, argv
[1]));
12328 static int Jim_LsearchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12330 static const char * const options
[] = {
12331 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
12335 { OPT_BOOL
, OPT_NOT
, OPT_NOCASE
, OPT_EXACT
, OPT_GLOB
, OPT_REGEXP
, OPT_ALL
, OPT_INLINE
,
12341 int opt_inline
= 0;
12342 int opt_match
= OPT_EXACT
;
12345 Jim_Obj
*listObjPtr
= NULL
;
12346 Jim_Obj
*commandObj
= NULL
;
12347 int match_flags
= 0;
12351 Jim_WrongNumArgs(interp
, 1, argv
,
12352 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
12356 for (i
= 1; i
< argc
- 2; i
++) {
12359 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
12371 match_flags
|= JIM_NOCASE
;
12381 opt_match
= option
;
12382 match_flags
|= JIM_OPT_END
;
12385 if (i
>= argc
- 2) {
12388 commandObj
= argv
[++i
];
12392 opt_match
= option
;
12404 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12406 if (opt_match
== OPT_REGEXP
) {
12407 commandObj
= Jim_NewStringObj(interp
, "regexp", -1);
12410 Jim_IncrRefCount(commandObj
);
12413 listlen
= Jim_ListLength(interp
, argv
[0]);
12414 for (i
= 0; i
< listlen
; i
++) {
12416 Jim_Obj
*objPtr
= Jim_ListGetIndex(interp
, argv
[0], i
);
12418 switch (opt_match
) {
12420 eq
= Jim_StringCompareObj(interp
, argv
[1], objPtr
, match_flags
) == 0;
12424 eq
= Jim_StringMatchObj(interp
, argv
[1], objPtr
, match_flags
);
12429 eq
= Jim_CommandMatchObj(interp
, commandObj
, argv
[1], objPtr
, match_flags
);
12432 Jim_FreeNewObj(interp
, listObjPtr
);
12440 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
12441 if (!eq
&& opt_bool
&& opt_not
&& !opt_all
) {
12445 if ((!opt_bool
&& eq
== !opt_not
) || (opt_bool
&& (eq
|| opt_all
))) {
12446 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
12447 Jim_Obj
*resultObj
;
12450 resultObj
= Jim_NewIntObj(interp
, eq
^ opt_not
);
12452 else if (!opt_inline
) {
12453 resultObj
= Jim_NewIntObj(interp
, i
);
12456 resultObj
= objPtr
;
12460 Jim_ListAppendElement(interp
, listObjPtr
, resultObj
);
12463 Jim_SetResult(interp
, resultObj
);
12470 Jim_SetResult(interp
, listObjPtr
);
12475 Jim_SetResultBool(interp
, opt_not
);
12477 else if (!opt_inline
) {
12478 Jim_SetResultInt(interp
, -1);
12484 Jim_DecrRefCount(interp
, commandObj
);
12490 static int Jim_LappendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12492 Jim_Obj
*listObjPtr
;
12497 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
12500 listObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
12502 /* Create the list if it does not exist */
12503 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12506 else if (Jim_IsShared(listObjPtr
)) {
12507 listObjPtr
= Jim_DuplicateObj(interp
, listObjPtr
);
12510 for (i
= 2; i
< argc
; i
++)
12511 Jim_ListAppendElement(interp
, listObjPtr
, argv
[i
]);
12512 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
12514 Jim_FreeNewObj(interp
, listObjPtr
);
12517 Jim_SetResult(interp
, listObjPtr
);
12522 static int Jim_LinsertCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12528 Jim_WrongNumArgs(interp
, 1, argv
, "list index ?element ...?");
12532 if (Jim_IsShared(listPtr
))
12533 listPtr
= Jim_DuplicateObj(interp
, listPtr
);
12534 if (Jim_GetIndex(interp
, argv
[2], &idx
) != JIM_OK
)
12536 len
= Jim_ListLength(interp
, listPtr
);
12540 idx
= len
+ idx
+ 1;
12541 Jim_ListInsertElements(interp
, listPtr
, idx
, argc
- 3, &argv
[3]);
12542 Jim_SetResult(interp
, listPtr
);
12545 if (listPtr
!= argv
[1]) {
12546 Jim_FreeNewObj(interp
, listPtr
);
12552 static int Jim_LreplaceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12554 int first
, last
, len
, rangeLen
;
12556 Jim_Obj
*newListObj
;
12559 Jim_WrongNumArgs(interp
, 1, argv
, "list first last ?element ...?");
12562 if (Jim_GetIndex(interp
, argv
[2], &first
) != JIM_OK
||
12563 Jim_GetIndex(interp
, argv
[3], &last
) != JIM_OK
) {
12568 len
= Jim_ListLength(interp
, listObj
);
12570 first
= JimRelToAbsIndex(len
, first
);
12571 last
= JimRelToAbsIndex(len
, last
);
12572 JimRelToAbsRange(len
, &first
, &last
, &rangeLen
);
12574 /* Now construct a new list which consists of:
12575 * <elements before first> <supplied elements> <elements after last>
12578 /* Trying to replace past the end of the list means end of list
12585 /* Add the first set of elements */
12586 newListObj
= Jim_NewListObj(interp
, listObj
->internalRep
.listValue
.ele
, first
);
12588 /* Add supplied elements */
12589 ListInsertElements(newListObj
, -1, argc
- 4, argv
+ 4);
12591 /* Add the remaining elements */
12592 ListInsertElements(newListObj
, -1, len
- first
- rangeLen
, listObj
->internalRep
.listValue
.ele
+ first
+ rangeLen
);
12594 Jim_SetResult(interp
, newListObj
);
12599 static int Jim_LsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12602 Jim_WrongNumArgs(interp
, 1, argv
, "listVar ?index...? newVal");
12605 else if (argc
== 3) {
12606 /* With no indexes, simply implements [set] */
12607 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
12609 Jim_SetResult(interp
, argv
[2]);
12612 return Jim_ListSetIndex(interp
, argv
[1], argv
+ 2, argc
- 3, argv
[argc
- 1]);
12616 static int Jim_LsortCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const argv
[])
12618 static const char * const options
[] = {
12619 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-real", "-index", "-unique", NULL
12622 { OPT_ASCII
, OPT_NOCASE
, OPT_INCREASING
, OPT_DECREASING
, OPT_COMMAND
, OPT_INTEGER
, OPT_REAL
, OPT_INDEX
, OPT_UNIQUE
};
12628 struct lsort_info info
;
12631 Jim_WrongNumArgs(interp
, 1, argv
, "?options? list");
12635 info
.type
= JIM_LSORT_ASCII
;
12639 info
.command
= NULL
;
12640 info
.interp
= interp
;
12642 for (i
= 1; i
< (argc
- 1); i
++) {
12645 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ENUM_ABBREV
| JIM_ERRMSG
)
12650 info
.type
= JIM_LSORT_ASCII
;
12653 info
.type
= JIM_LSORT_NOCASE
;
12656 info
.type
= JIM_LSORT_INTEGER
;
12659 info
.type
= JIM_LSORT_REAL
;
12661 case OPT_INCREASING
:
12664 case OPT_DECREASING
:
12671 if (i
>= (argc
- 2)) {
12672 Jim_SetResultString(interp
, "\"-command\" option must be followed by comparison command", -1);
12675 info
.type
= JIM_LSORT_COMMAND
;
12676 info
.command
= argv
[i
+ 1];
12680 if (i
>= (argc
- 2)) {
12681 Jim_SetResultString(interp
, "\"-index\" option must be followed by list index", -1);
12684 if (Jim_GetIndex(interp
, argv
[i
+ 1], &info
.index
) != JIM_OK
) {
12692 resObj
= argv
[argc
- 1];
12693 if ((shared
= Jim_IsShared(resObj
)))
12694 resObj
= Jim_DuplicateObj(interp
, resObj
);
12695 retCode
= ListSortElements(interp
, resObj
, &info
);
12696 if (retCode
== JIM_OK
) {
12697 Jim_SetResult(interp
, resObj
);
12700 Jim_FreeNewObj(interp
, resObj
);
12706 static int Jim_AppendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12708 Jim_Obj
*stringObjPtr
;
12712 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value ...?");
12716 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
12722 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
12723 if (!stringObjPtr
) {
12724 /* Create the string if it doesn't exist */
12725 stringObjPtr
= Jim_NewEmptyStringObj(interp
);
12728 else if (Jim_IsShared(stringObjPtr
)) {
12730 stringObjPtr
= Jim_DuplicateObj(interp
, stringObjPtr
);
12732 for (i
= 2; i
< argc
; i
++) {
12733 Jim_AppendObj(interp
, stringObjPtr
, argv
[i
]);
12735 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
) != JIM_OK
) {
12737 Jim_FreeNewObj(interp
, stringObjPtr
);
12742 Jim_SetResult(interp
, stringObjPtr
);
12746 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12748 * Returns a zero-refcount list describing the expression at 'node'
12750 static Jim_Obj
*JimGetExprAsList(Jim_Interp
*interp
, struct JimExprNode
*node
)
12752 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12754 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, jim_tt_name(node
->type
), -1));
12755 if (TOKEN_IS_EXPR_OP(node
->type
)) {
12757 Jim_ListAppendElement(interp
, listObjPtr
, JimGetExprAsList(interp
, node
->left
));
12760 Jim_ListAppendElement(interp
, listObjPtr
, JimGetExprAsList(interp
, node
->right
));
12762 if (node
->ternary
) {
12763 Jim_ListAppendElement(interp
, listObjPtr
, JimGetExprAsList(interp
, node
->ternary
));
12767 Jim_ListAppendElement(interp
, listObjPtr
, node
->objPtr
);
12771 #endif /* JIM_DEBUG_COMMAND && !JIM_BOOTSTRAP */
12774 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12775 static int Jim_DebugCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12777 static const char * const options
[] = {
12778 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12784 OPT_REFCOUNT
, OPT_OBJCOUNT
, OPT_OBJECTS
, OPT_INVSTR
, OPT_SCRIPTLEN
,
12785 OPT_EXPRLEN
, OPT_EXPRBC
, OPT_SHOW
,
12790 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?...?");
12793 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
)
12794 return Jim_CheckShowCommands(interp
, argv
[1], options
);
12795 if (option
== OPT_REFCOUNT
) {
12797 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12800 Jim_SetResultInt(interp
, argv
[2]->refCount
);
12803 else if (option
== OPT_OBJCOUNT
) {
12804 int freeobj
= 0, liveobj
= 0;
12809 Jim_WrongNumArgs(interp
, 2, argv
, "");
12812 /* Count the number of free objects. */
12813 objPtr
= interp
->freeList
;
12816 objPtr
= objPtr
->nextObjPtr
;
12818 /* Count the number of live objects. */
12819 objPtr
= interp
->liveList
;
12822 objPtr
= objPtr
->nextObjPtr
;
12824 /* Set the result string and return. */
12825 sprintf(buf
, "free %d used %d", freeobj
, liveobj
);
12826 Jim_SetResultString(interp
, buf
, -1);
12829 else if (option
== OPT_OBJECTS
) {
12830 Jim_Obj
*objPtr
, *listObjPtr
, *subListObjPtr
;
12833 Jim_WrongNumArgs(interp
, 2, argv
, "");
12837 /* Count the number of live objects. */
12838 objPtr
= interp
->liveList
;
12839 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12842 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "";
12844 subListObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12845 sprintf(buf
, "%p", objPtr
);
12846 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
12847 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, type
, -1));
12848 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewIntObj(interp
, objPtr
->refCount
));
12849 Jim_ListAppendElement(interp
, subListObjPtr
, objPtr
);
12850 Jim_ListAppendElement(interp
, listObjPtr
, subListObjPtr
);
12851 objPtr
= objPtr
->nextObjPtr
;
12853 Jim_SetResult(interp
, listObjPtr
);
12856 else if (option
== OPT_INVSTR
) {
12860 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12864 if (objPtr
->typePtr
!= NULL
)
12865 Jim_InvalidateStringRep(objPtr
);
12866 Jim_SetEmptyResult(interp
);
12869 else if (option
== OPT_SHOW
) {
12874 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12877 s
= Jim_GetString(argv
[2], &len
);
12879 charlen
= utf8_strlen(s
, len
);
12884 snprintf(buf
, sizeof(buf
), "refcount: %d, type: %s\n"
12886 argv
[2]->refCount
, JimObjTypeName(argv
[2]), charlen
);
12887 Jim_SetResultFormatted(interp
, "%s <<%s>>\n", buf
, s
);
12888 snprintf(buf
, sizeof(buf
), "bytes (%d):", len
);
12889 Jim_AppendString(interp
, Jim_GetResult(interp
), buf
, -1);
12891 snprintf(buf
, sizeof(buf
), " %02x", (unsigned char)*s
++);
12892 Jim_AppendString(interp
, Jim_GetResult(interp
), buf
, -1);
12896 else if (option
== OPT_SCRIPTLEN
) {
12900 Jim_WrongNumArgs(interp
, 2, argv
, "script");
12903 script
= JimGetScript(interp
, argv
[2]);
12904 if (script
== NULL
)
12906 Jim_SetResultInt(interp
, script
->len
);
12909 else if (option
== OPT_EXPRLEN
) {
12910 struct ExprTree
*expr
;
12913 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12916 expr
= JimGetExpression(interp
, argv
[2]);
12919 Jim_SetResultInt(interp
, expr
->len
);
12922 else if (option
== OPT_EXPRBC
) {
12923 struct ExprTree
*expr
;
12926 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12929 expr
= JimGetExpression(interp
, argv
[2]);
12932 Jim_SetResult(interp
, JimGetExprAsList(interp
, expr
->expr
));
12936 Jim_SetResultString(interp
,
12937 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12942 #endif /* JIM_DEBUG_COMMAND && !JIM_BOOTSTRAP */
12945 static int Jim_EvalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12950 Jim_WrongNumArgs(interp
, 1, argv
, "arg ?arg ...?");
12955 rc
= Jim_EvalObj(interp
, argv
[1]);
12958 rc
= Jim_EvalObj(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12961 if (rc
== JIM_ERR
) {
12962 /* eval is "interesting", so add a stack frame here */
12963 interp
->addStackTrace
++;
12969 static int Jim_UplevelCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12973 Jim_CallFrame
*savedCallFrame
, *targetCallFrame
;
12976 /* Save the old callframe pointer */
12977 savedCallFrame
= interp
->framePtr
;
12979 /* Lookup the target frame pointer */
12980 str
= Jim_String(argv
[1]);
12981 if ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#') {
12982 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, argv
[1]);
12987 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12989 if (targetCallFrame
== NULL
) {
12993 Jim_WrongNumArgs(interp
, 1, argv
- 1, "?level? command ?arg ...?");
12996 /* Eval the code in the target callframe. */
12997 interp
->framePtr
= targetCallFrame
;
12999 retcode
= Jim_EvalObj(interp
, argv
[1]);
13002 retcode
= Jim_EvalObj(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
13004 interp
->framePtr
= savedCallFrame
;
13008 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
13014 static int Jim_ExprCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13019 retcode
= Jim_EvalExpression(interp
, argv
[1]);
13021 else if (argc
> 2) {
13024 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
13025 Jim_IncrRefCount(objPtr
);
13026 retcode
= Jim_EvalExpression(interp
, objPtr
);
13027 Jim_DecrRefCount(interp
, objPtr
);
13030 Jim_WrongNumArgs(interp
, 1, argv
, "expression ?...?");
13033 if (retcode
!= JIM_OK
)
13039 static int Jim_BreakCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13042 Jim_WrongNumArgs(interp
, 1, argv
, "");
13049 static int Jim_ContinueCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13052 Jim_WrongNumArgs(interp
, 1, argv
, "");
13055 return JIM_CONTINUE
;
13059 static int Jim_ReturnCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13062 Jim_Obj
*stackTraceObj
= NULL
;
13063 Jim_Obj
*errorCodeObj
= NULL
;
13064 int returnCode
= JIM_OK
;
13067 for (i
= 1; i
< argc
- 1; i
+= 2) {
13068 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-code")) {
13069 if (Jim_GetReturnCode(interp
, argv
[i
+ 1], &returnCode
) == JIM_ERR
) {
13073 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorinfo")) {
13074 stackTraceObj
= argv
[i
+ 1];
13076 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorcode")) {
13077 errorCodeObj
= argv
[i
+ 1];
13079 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-level")) {
13080 if (Jim_GetLong(interp
, argv
[i
+ 1], &level
) != JIM_OK
|| level
< 0) {
13081 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", argv
[i
+ 1]);
13090 if (i
!= argc
- 1 && i
!= argc
) {
13091 Jim_WrongNumArgs(interp
, 1, argv
,
13092 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
13095 /* If a stack trace is supplied and code is error, set the stack trace */
13096 if (stackTraceObj
&& returnCode
== JIM_ERR
) {
13097 JimSetStackTrace(interp
, stackTraceObj
);
13099 /* If an error code list is supplied, set the global $errorCode */
13100 if (errorCodeObj
&& returnCode
== JIM_ERR
) {
13101 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCodeObj
);
13103 interp
->returnCode
= returnCode
;
13104 interp
->returnLevel
= level
;
13106 if (i
== argc
- 1) {
13107 Jim_SetResult(interp
, argv
[i
]);
13109 return level
== 0 ? returnCode
: JIM_RETURN
;
13113 static int Jim_TailcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13115 if (interp
->framePtr
->level
== 0) {
13116 Jim_SetResultString(interp
, "tailcall can only be called from a proc or lambda", -1);
13119 else if (argc
>= 2) {
13120 /* Need to resolve the tailcall command in the current context */
13121 Jim_CallFrame
*cf
= interp
->framePtr
->parent
;
13123 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, argv
[1], JIM_ERRMSG
);
13124 if (cmdPtr
== NULL
) {
13128 JimPanic((cf
->tailcallCmd
!= NULL
, "Already have a tailcallCmd"));
13130 /* And stash this pre-resolved command */
13131 JimIncrCmdRefCount(cmdPtr
);
13132 cf
->tailcallCmd
= cmdPtr
;
13134 /* And stash the command list */
13135 JimPanic((cf
->tailcallObj
!= NULL
, "Already have a tailcallobj"));
13137 cf
->tailcallObj
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
13138 Jim_IncrRefCount(cf
->tailcallObj
);
13140 /* When the stack unwinds to the previous proc, the stashed command will be evaluated */
13146 static int JimAliasCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13149 Jim_Obj
*prefixListObj
= Jim_CmdPrivData(interp
);
13151 /* prefixListObj is a list to which the args need to be appended */
13152 cmdList
= Jim_DuplicateObj(interp
, prefixListObj
);
13153 Jim_ListInsertElements(interp
, cmdList
, Jim_ListLength(interp
, cmdList
), argc
- 1, argv
+ 1);
13155 return JimEvalObjList(interp
, cmdList
);
13158 static void JimAliasCmdDelete(Jim_Interp
*interp
, void *privData
)
13160 Jim_Obj
*prefixListObj
= privData
;
13161 Jim_DecrRefCount(interp
, prefixListObj
);
13164 static int Jim_AliasCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13166 Jim_Obj
*prefixListObj
;
13169 Jim_WrongNumArgs(interp
, 1, argv
, "newname command ?args ...?");
13173 prefixListObj
= Jim_NewListObj(interp
, argv
+ 2, argc
- 2);
13174 Jim_IncrRefCount(prefixListObj
);
13175 Jim_SetResult(interp
, argv
[1]);
13177 return Jim_CreateCommandObj(interp
, argv
[1], JimAliasCmd
, prefixListObj
, JimAliasCmdDelete
);
13181 static int Jim_ProcCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13185 if (argc
!= 4 && argc
!= 5) {
13186 Jim_WrongNumArgs(interp
, 1, argv
, "name arglist ?statics? body");
13191 cmd
= JimCreateProcedureCmd(interp
, argv
[2], NULL
, argv
[3], NULL
);
13194 cmd
= JimCreateProcedureCmd(interp
, argv
[2], argv
[3], argv
[4], NULL
);
13198 /* Add the new command */
13199 Jim_Obj
*nameObjPtr
= JimQualifyName(interp
, argv
[1]);
13200 JimCreateCommand(interp
, nameObjPtr
, cmd
);
13202 /* Calculate and set the namespace for this proc */
13203 JimUpdateProcNamespace(interp
, cmd
, nameObjPtr
);
13204 Jim_DecrRefCount(interp
, nameObjPtr
);
13206 /* Unlike Tcl, set the name of the proc as the result */
13207 Jim_SetResult(interp
, argv
[1]);
13214 static int Jim_LocalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13219 Jim_WrongNumArgs(interp
, 1, argv
, "cmd ?args ...?");
13223 /* Evaluate the arguments with 'local' in force */
13225 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
13229 /* If OK, and the result is a proc, add it to the list of local procs */
13230 if (retcode
== 0) {
13231 Jim_Obj
*cmdNameObj
= Jim_GetResult(interp
);
13233 if (Jim_GetCommand(interp
, cmdNameObj
, JIM_ERRMSG
) == NULL
) {
13236 if (interp
->framePtr
->localCommands
== NULL
) {
13237 interp
->framePtr
->localCommands
= Jim_Alloc(sizeof(*interp
->framePtr
->localCommands
));
13238 Jim_InitStack(interp
->framePtr
->localCommands
);
13240 Jim_IncrRefCount(cmdNameObj
);
13241 Jim_StackPush(interp
->framePtr
->localCommands
, cmdNameObj
);
13248 static int Jim_UpcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13251 Jim_WrongNumArgs(interp
, 1, argv
, "cmd ?args ...?");
13257 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, argv
[1], JIM_ERRMSG
);
13258 if (cmdPtr
== NULL
|| !cmdPtr
->isproc
|| !cmdPtr
->prevCmd
) {
13259 Jim_SetResultFormatted(interp
, "no previous command: \"%#s\"", argv
[1]);
13262 /* OK. Mark this command as being in an upcall */
13263 cmdPtr
->u
.proc
.upcall
++;
13264 JimIncrCmdRefCount(cmdPtr
);
13266 /* Invoke the command as normal */
13267 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
13269 /* No longer in an upcall */
13270 cmdPtr
->u
.proc
.upcall
--;
13271 JimDecrCmdRefCount(interp
, cmdPtr
);
13278 static int Jim_ApplyCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13281 Jim_WrongNumArgs(interp
, 1, argv
, "lambdaExpr ?arg ...?");
13287 Jim_Obj
*argListObjPtr
;
13288 Jim_Obj
*bodyObjPtr
;
13289 Jim_Obj
*nsObj
= NULL
;
13292 int len
= Jim_ListLength(interp
, argv
[1]);
13293 if (len
!= 2 && len
!= 3) {
13294 Jim_SetResultFormatted(interp
, "can't interpret \"%#s\" as a lambda expression", argv
[1]);
13299 #ifdef jim_ext_namespace
13300 /* Note that the namespace is always treated as global */
13301 nsObj
= Jim_ListGetIndex(interp
, argv
[1], 2);
13303 Jim_SetResultString(interp
, "namespaces not enabled", -1);
13307 argListObjPtr
= Jim_ListGetIndex(interp
, argv
[1], 0);
13308 bodyObjPtr
= Jim_ListGetIndex(interp
, argv
[1], 1);
13310 cmd
= JimCreateProcedureCmd(interp
, argListObjPtr
, NULL
, bodyObjPtr
, nsObj
);
13313 /* Create a new argv array with a dummy argv[0], for error messages */
13314 nargv
= Jim_Alloc((argc
- 2 + 1) * sizeof(*nargv
));
13315 nargv
[0] = Jim_NewStringObj(interp
, "apply lambdaExpr", -1);
13316 Jim_IncrRefCount(nargv
[0]);
13317 memcpy(&nargv
[1], argv
+ 2, (argc
- 2) * sizeof(*nargv
));
13318 ret
= JimCallProcedure(interp
, cmd
, argc
- 2 + 1, nargv
);
13319 Jim_DecrRefCount(interp
, nargv
[0]);
13322 JimDecrCmdRefCount(interp
, cmd
);
13331 static int Jim_ConcatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13333 Jim_SetResult(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
13338 static int Jim_UpvarCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13341 Jim_CallFrame
*targetCallFrame
;
13343 /* Lookup the target frame pointer */
13344 if (argc
> 3 && (argc
% 2 == 0)) {
13345 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, argv
[1]);
13350 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
13352 if (targetCallFrame
== NULL
) {
13356 /* Check for arity */
13358 Jim_WrongNumArgs(interp
, 1, argv
, "?level? otherVar localVar ?otherVar localVar ...?");
13362 /* Now... for every other/local couple: */
13363 for (i
= 1; i
< argc
; i
+= 2) {
13364 if (Jim_SetVariableLink(interp
, argv
[i
+ 1], argv
[i
], targetCallFrame
) != JIM_OK
)
13371 static int Jim_GlobalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13376 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
13379 /* Link every var to the toplevel having the same name */
13380 if (interp
->framePtr
->level
== 0)
13381 return JIM_OK
; /* global at toplevel... */
13382 for (i
= 1; i
< argc
; i
++) {
13383 /* global ::blah does nothing */
13384 const char *name
= Jim_String(argv
[i
]);
13385 if (name
[0] != ':' || name
[1] != ':') {
13386 if (Jim_SetVariableLink(interp
, argv
[i
], argv
[i
], interp
->topFramePtr
) != JIM_OK
)
13393 /* does the [string map] operation. On error NULL is returned,
13394 * otherwise a new string object with the result, having refcount = 0,
13396 static Jim_Obj
*JimStringMap(Jim_Interp
*interp
, Jim_Obj
*mapListObjPtr
,
13397 Jim_Obj
*objPtr
, int nocase
)
13400 const char *str
, *noMatchStart
= NULL
;
13402 Jim_Obj
*resultObjPtr
;
13404 numMaps
= Jim_ListLength(interp
, mapListObjPtr
);
13406 Jim_SetResultString(interp
, "list must contain an even number of elements", -1);
13410 str
= Jim_String(objPtr
);
13411 strLen
= Jim_Utf8Length(interp
, objPtr
);
13414 resultObjPtr
= Jim_NewStringObj(interp
, "", 0);
13416 for (i
= 0; i
< numMaps
; i
+= 2) {
13417 Jim_Obj
*eachObjPtr
;
13421 eachObjPtr
= Jim_ListGetIndex(interp
, mapListObjPtr
, i
);
13422 k
= Jim_String(eachObjPtr
);
13423 kl
= Jim_Utf8Length(interp
, eachObjPtr
);
13425 if (strLen
>= kl
&& kl
) {
13427 rc
= JimStringCompareUtf8(str
, kl
, k
, kl
, nocase
);
13429 if (noMatchStart
) {
13430 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
13431 noMatchStart
= NULL
;
13433 Jim_AppendObj(interp
, resultObjPtr
, Jim_ListGetIndex(interp
, mapListObjPtr
, i
+ 1));
13434 str
+= utf8_index(str
, kl
);
13440 if (i
== numMaps
) { /* no match */
13442 if (noMatchStart
== NULL
)
13443 noMatchStart
= str
;
13444 str
+= utf8_tounicode(str
, &c
);
13448 if (noMatchStart
) {
13449 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
13451 return resultObjPtr
;
13455 static int Jim_StringCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13460 static const char * const options
[] = {
13461 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "replace",
13462 "map", "repeat", "reverse", "index", "first", "last", "cat",
13463 "trim", "trimleft", "trimright", "tolower", "toupper", "totitle", NULL
13467 OPT_BYTELENGTH
, OPT_LENGTH
, OPT_COMPARE
, OPT_MATCH
, OPT_EQUAL
, OPT_IS
, OPT_BYTERANGE
, OPT_RANGE
, OPT_REPLACE
,
13468 OPT_MAP
, OPT_REPEAT
, OPT_REVERSE
, OPT_INDEX
, OPT_FIRST
, OPT_LAST
, OPT_CAT
,
13469 OPT_TRIM
, OPT_TRIMLEFT
, OPT_TRIMRIGHT
, OPT_TOLOWER
, OPT_TOUPPER
, OPT_TOTITLE
13471 static const char * const nocase_options
[] = {
13474 static const char * const nocase_length_options
[] = {
13475 "-nocase", "-length", NULL
13479 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
13482 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
,
13483 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
)
13484 return Jim_CheckShowCommands(interp
, argv
[1], options
);
13488 case OPT_BYTELENGTH
:
13490 Jim_WrongNumArgs(interp
, 2, argv
, "string");
13493 if (option
== OPT_LENGTH
) {
13494 len
= Jim_Utf8Length(interp
, argv
[2]);
13497 len
= Jim_Length(argv
[2]);
13499 Jim_SetResultInt(interp
, len
);
13505 /* optimise the one-arg case */
13511 objPtr
= Jim_NewStringObj(interp
, "", 0);
13513 for (i
= 2; i
< argc
; i
++) {
13514 Jim_AppendObj(interp
, objPtr
, argv
[i
]);
13517 Jim_SetResult(interp
, objPtr
);
13524 /* n is the number of remaining option args */
13525 long opt_length
= -1;
13530 if (Jim_GetEnum(interp
, argv
[i
++], nocase_length_options
, &subopt
, NULL
,
13531 JIM_ENUM_ABBREV
) != JIM_OK
) {
13533 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? ?-length int? string1 string2");
13544 goto badcompareargs
;
13546 if (Jim_GetLong(interp
, argv
[i
++], &opt_length
) != JIM_OK
) {
13553 goto badcompareargs
;
13556 if (opt_length
< 0 && option
!= OPT_COMPARE
&& opt_case
) {
13557 /* Fast version - [string equal], case sensitive, no length */
13558 Jim_SetResultBool(interp
, Jim_StringEqObj(argv
[0], argv
[1]));
13561 const char *s1
= Jim_String(argv
[0]);
13562 int l1
= Jim_Utf8Length(interp
, argv
[0]);
13563 const char *s2
= Jim_String(argv
[1]);
13564 int l2
= Jim_Utf8Length(interp
, argv
[1]);
13565 if (opt_length
>= 0) {
13566 if (l1
> opt_length
) {
13569 if (l2
> opt_length
) {
13573 n
= JimStringCompareUtf8(s1
, l1
, s2
, l2
, !opt_case
);
13574 Jim_SetResultInt(interp
, option
== OPT_COMPARE
? n
: n
== 0);
13582 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
13583 JIM_ENUM_ABBREV
) != JIM_OK
)) {
13584 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? pattern string");
13587 if (opt_case
== 0) {
13590 Jim_SetResultBool(interp
, Jim_StringMatchObj(interp
, argv
[2], argv
[3], !opt_case
));
13598 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
13599 JIM_ENUM_ABBREV
) != JIM_OK
)) {
13600 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? mapList string");
13604 if (opt_case
== 0) {
13607 objPtr
= JimStringMap(interp
, argv
[2], argv
[3], !opt_case
);
13608 if (objPtr
== NULL
) {
13611 Jim_SetResult(interp
, objPtr
);
13616 case OPT_BYTERANGE
:{
13620 Jim_WrongNumArgs(interp
, 2, argv
, "string first last");
13623 if (option
== OPT_RANGE
) {
13624 objPtr
= Jim_StringRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
13628 objPtr
= Jim_StringByteRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
13631 if (objPtr
== NULL
) {
13634 Jim_SetResult(interp
, objPtr
);
13641 if (argc
!= 5 && argc
!= 6) {
13642 Jim_WrongNumArgs(interp
, 2, argv
, "string first last ?string?");
13645 objPtr
= JimStringReplaceObj(interp
, argv
[2], argv
[3], argv
[4], argc
== 6 ? argv
[5] : NULL
);
13646 if (objPtr
== NULL
) {
13649 Jim_SetResult(interp
, objPtr
);
13659 Jim_WrongNumArgs(interp
, 2, argv
, "string count");
13662 if (Jim_GetWide(interp
, argv
[3], &count
) != JIM_OK
) {
13665 objPtr
= Jim_NewStringObj(interp
, "", 0);
13668 Jim_AppendObj(interp
, objPtr
, argv
[2]);
13671 Jim_SetResult(interp
, objPtr
);
13681 Jim_WrongNumArgs(interp
, 2, argv
, "string");
13685 str
= Jim_GetString(argv
[2], &len
);
13686 buf
= Jim_Alloc(len
+ 1);
13689 for (i
= 0; i
< len
; ) {
13691 int l
= utf8_tounicode(str
, &c
);
13692 memcpy(p
- l
, str
, l
);
13697 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
13706 Jim_WrongNumArgs(interp
, 2, argv
, "string index");
13709 if (Jim_GetIndex(interp
, argv
[3], &idx
) != JIM_OK
) {
13712 str
= Jim_String(argv
[2]);
13713 len
= Jim_Utf8Length(interp
, argv
[2]);
13714 if (idx
!= INT_MIN
&& idx
!= INT_MAX
) {
13715 idx
= JimRelToAbsIndex(len
, idx
);
13717 if (idx
< 0 || idx
>= len
|| str
== NULL
) {
13718 Jim_SetResultString(interp
, "", 0);
13720 else if (len
== Jim_Length(argv
[2])) {
13721 /* ASCII optimisation */
13722 Jim_SetResultString(interp
, str
+ idx
, 1);
13726 int i
= utf8_index(str
, idx
);
13727 Jim_SetResultString(interp
, str
+ i
, utf8_tounicode(str
+ i
, &c
));
13734 int idx
= 0, l1
, l2
;
13735 const char *s1
, *s2
;
13737 if (argc
!= 4 && argc
!= 5) {
13738 Jim_WrongNumArgs(interp
, 2, argv
, "subString string ?index?");
13741 s1
= Jim_String(argv
[2]);
13742 s2
= Jim_String(argv
[3]);
13743 l1
= Jim_Utf8Length(interp
, argv
[2]);
13744 l2
= Jim_Utf8Length(interp
, argv
[3]);
13746 if (Jim_GetIndex(interp
, argv
[4], &idx
) != JIM_OK
) {
13749 idx
= JimRelToAbsIndex(l2
, idx
);
13751 else if (option
== OPT_LAST
) {
13754 if (option
== OPT_FIRST
) {
13755 Jim_SetResultInt(interp
, JimStringFirst(s1
, l1
, s2
, l2
, idx
));
13759 Jim_SetResultInt(interp
, JimStringLastUtf8(s1
, l1
, s2
, idx
));
13761 Jim_SetResultInt(interp
, JimStringLast(s1
, l1
, s2
, idx
));
13769 case OPT_TRIMRIGHT
:{
13770 Jim_Obj
*trimchars
;
13772 if (argc
!= 3 && argc
!= 4) {
13773 Jim_WrongNumArgs(interp
, 2, argv
, "string ?trimchars?");
13776 trimchars
= (argc
== 4 ? argv
[3] : NULL
);
13777 if (option
== OPT_TRIM
) {
13778 Jim_SetResult(interp
, JimStringTrim(interp
, argv
[2], trimchars
));
13780 else if (option
== OPT_TRIMLEFT
) {
13781 Jim_SetResult(interp
, JimStringTrimLeft(interp
, argv
[2], trimchars
));
13783 else if (option
== OPT_TRIMRIGHT
) {
13784 Jim_SetResult(interp
, JimStringTrimRight(interp
, argv
[2], trimchars
));
13793 Jim_WrongNumArgs(interp
, 2, argv
, "string");
13796 if (option
== OPT_TOLOWER
) {
13797 Jim_SetResult(interp
, JimStringToLower(interp
, argv
[2]));
13799 else if (option
== OPT_TOUPPER
) {
13800 Jim_SetResult(interp
, JimStringToUpper(interp
, argv
[2]));
13803 Jim_SetResult(interp
, JimStringToTitle(interp
, argv
[2]));
13808 if (argc
== 4 || (argc
== 5 && Jim_CompareStringImmediate(interp
, argv
[3], "-strict"))) {
13809 return JimStringIs(interp
, argv
[argc
- 1], argv
[2], argc
== 5);
13811 Jim_WrongNumArgs(interp
, 2, argv
, "class ?-strict? str");
13818 static int Jim_TimeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13821 jim_wide start
, elapsed
;
13823 const char *fmt
= "%" JIM_WIDE_MODIFIER
" microseconds per iteration";
13826 Jim_WrongNumArgs(interp
, 1, argv
, "script ?count?");
13830 if (Jim_GetLong(interp
, argv
[2], &count
) != JIM_OK
)
13836 start
= JimClock();
13840 retval
= Jim_EvalObj(interp
, argv
[1]);
13841 if (retval
!= JIM_OK
) {
13845 elapsed
= JimClock() - start
;
13846 sprintf(buf
, fmt
, count
== 0 ? 0 : elapsed
/ count
);
13847 Jim_SetResultString(interp
, buf
, -1);
13852 static int Jim_ExitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13857 Jim_WrongNumArgs(interp
, 1, argv
, "?exitCode?");
13861 if (Jim_GetLong(interp
, argv
[1], &exitCode
) != JIM_OK
)
13863 Jim_SetResult(interp
, argv
[1]);
13865 interp
->exitCode
= exitCode
;
13870 static int Jim_CatchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13876 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
13877 jim_wide ignore_mask
= (1 << JIM_EXIT
) | (1 << JIM_EVAL
) | (1 << JIM_SIGNAL
);
13878 static const int max_ignore_code
= sizeof(ignore_mask
) * 8;
13880 /* Reset the error code before catch.
13881 * Note that this is not strictly correct.
13883 Jim_SetGlobalVariableStr(interp
, "errorCode", Jim_NewStringObj(interp
, "NONE", -1));
13885 for (i
= 1; i
< argc
- 1; i
++) {
13886 const char *arg
= Jim_String(argv
[i
]);
13890 /* It's a pity we can't use Jim_GetEnum here :-( */
13891 if (strcmp(arg
, "--") == 0) {
13899 if (strncmp(arg
, "-no", 3) == 0) {
13908 if (Jim_StringToWide(arg
, &option
, 10) != JIM_OK
) {
13912 option
= Jim_FindByName(arg
, jimReturnCodes
, jimReturnCodesSize
);
13919 ignore_mask
|= ((jim_wide
)1 << option
);
13922 ignore_mask
&= (~((jim_wide
)1 << option
));
13927 if (argc
< 1 || argc
> 3) {
13929 Jim_WrongNumArgs(interp
, 1, argv
,
13930 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13935 if ((ignore_mask
& (1 << JIM_SIGNAL
)) == 0) {
13939 interp
->signal_level
+= sig
;
13940 if (Jim_CheckSignal(interp
)) {
13941 /* If a signal is set, don't even try to execute the body */
13942 exitCode
= JIM_SIGNAL
;
13945 exitCode
= Jim_EvalObj(interp
, argv
[0]);
13946 /* Don't want any caught error included in a later stack trace */
13947 interp
->errorFlag
= 0;
13949 interp
->signal_level
-= sig
;
13951 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13952 if (exitCode
>= 0 && exitCode
< max_ignore_code
&& (((unsigned jim_wide
)1 << exitCode
) & ignore_mask
)) {
13953 /* Not caught, pass it up */
13957 if (sig
&& exitCode
== JIM_SIGNAL
) {
13958 /* Catch the signal at this level */
13959 if (interp
->signal_set_result
) {
13960 interp
->signal_set_result(interp
, interp
->sigmask
);
13963 Jim_SetResultInt(interp
, interp
->sigmask
);
13965 interp
->sigmask
= 0;
13969 if (Jim_SetVariable(interp
, argv
[1], Jim_GetResult(interp
)) != JIM_OK
) {
13973 Jim_Obj
*optListObj
= Jim_NewListObj(interp
, NULL
, 0);
13975 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-code", -1));
13976 Jim_ListAppendElement(interp
, optListObj
,
13977 Jim_NewIntObj(interp
, exitCode
== JIM_RETURN
? interp
->returnCode
: exitCode
));
13978 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-level", -1));
13979 Jim_ListAppendElement(interp
, optListObj
, Jim_NewIntObj(interp
, interp
->returnLevel
));
13980 if (exitCode
== JIM_ERR
) {
13981 Jim_Obj
*errorCode
;
13982 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorinfo",
13984 Jim_ListAppendElement(interp
, optListObj
, interp
->stackTrace
);
13986 errorCode
= Jim_GetGlobalVariableStr(interp
, "errorCode", JIM_NONE
);
13988 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorcode", -1));
13989 Jim_ListAppendElement(interp
, optListObj
, errorCode
);
13992 if (Jim_SetVariable(interp
, argv
[2], optListObj
) != JIM_OK
) {
13997 Jim_SetResultInt(interp
, exitCode
);
14001 #if defined(JIM_REFERENCES) && !defined(JIM_BOOTSTRAP)
14004 static int Jim_RefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14006 if (argc
!= 3 && argc
!= 4) {
14007 Jim_WrongNumArgs(interp
, 1, argv
, "string tag ?finalizer?");
14011 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], NULL
));
14014 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], argv
[3]));
14020 static int Jim_GetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14022 Jim_Reference
*refPtr
;
14025 Jim_WrongNumArgs(interp
, 1, argv
, "reference");
14028 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
14030 Jim_SetResult(interp
, refPtr
->objPtr
);
14035 static int Jim_SetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14037 Jim_Reference
*refPtr
;
14040 Jim_WrongNumArgs(interp
, 1, argv
, "reference newValue");
14043 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
14045 Jim_IncrRefCount(argv
[2]);
14046 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
14047 refPtr
->objPtr
= argv
[2];
14048 Jim_SetResult(interp
, argv
[2]);
14053 static int Jim_CollectCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14056 Jim_WrongNumArgs(interp
, 1, argv
, "");
14059 Jim_SetResultInt(interp
, Jim_Collect(interp
));
14061 /* Free all the freed objects. */
14062 while (interp
->freeList
) {
14063 Jim_Obj
*nextObjPtr
= interp
->freeList
->nextObjPtr
;
14064 Jim_Free(interp
->freeList
);
14065 interp
->freeList
= nextObjPtr
;
14071 /* [finalize] reference ?newValue? */
14072 static int Jim_FinalizeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14074 if (argc
!= 2 && argc
!= 3) {
14075 Jim_WrongNumArgs(interp
, 1, argv
, "reference ?finalizerProc?");
14079 Jim_Obj
*cmdNamePtr
;
14081 if (Jim_GetFinalizer(interp
, argv
[1], &cmdNamePtr
) != JIM_OK
)
14083 if (cmdNamePtr
!= NULL
) /* otherwise the null string is returned. */
14084 Jim_SetResult(interp
, cmdNamePtr
);
14087 if (Jim_SetFinalizer(interp
, argv
[1], argv
[2]) != JIM_OK
)
14089 Jim_SetResult(interp
, argv
[2]);
14094 /* [info references] */
14095 static int JimInfoReferences(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14097 Jim_Obj
*listObjPtr
;
14098 Jim_HashTableIterator htiter
;
14101 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14103 JimInitHashTableIterator(&interp
->references
, &htiter
);
14104 while ((he
= Jim_NextHashEntry(&htiter
)) != NULL
) {
14105 char buf
[JIM_REFERENCE_SPACE
+ 1];
14106 Jim_Reference
*refPtr
= Jim_GetHashEntryVal(he
);
14107 const unsigned long *refId
= he
->key
;
14109 JimFormatReference(buf
, refPtr
, *refId
);
14110 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
14112 Jim_SetResult(interp
, listObjPtr
);
14115 #endif /* JIM_REFERENCES && !JIM_BOOTSTRAP */
14118 static int Jim_RenameCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14121 Jim_WrongNumArgs(interp
, 1, argv
, "oldName newName");
14125 return Jim_RenameCommand(interp
, argv
[1], argv
[2]);
14128 #define JIM_DICTMATCH_KEYS 0x0001
14129 #define JIM_DICTMATCH_VALUES 0x002
14132 * match_type must be one of JIM_DICTMATCH_KEYS or JIM_DICTMATCH_VALUES
14133 * return_types should be either or both
14135 int Jim_DictMatchTypes(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*patternObj
, int match_type
, int return_types
)
14138 Jim_Obj
*listObjPtr
;
14139 Jim_HashTableIterator htiter
;
14141 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
14145 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14147 JimInitHashTableIterator(objPtr
->internalRep
.ptr
, &htiter
);
14148 while ((he
= Jim_NextHashEntry(&htiter
)) != NULL
) {
14150 Jim_Obj
*matchObj
= (match_type
== JIM_DICTMATCH_KEYS
) ? (Jim_Obj
*)he
->key
: Jim_GetHashEntryVal(he
);
14151 if (!Jim_StringMatchObj(interp
, patternObj
, matchObj
, 0)) {
14156 if (return_types
& JIM_DICTMATCH_KEYS
) {
14157 Jim_ListAppendElement(interp
, listObjPtr
, (Jim_Obj
*)he
->key
);
14159 if (return_types
& JIM_DICTMATCH_VALUES
) {
14160 Jim_ListAppendElement(interp
, listObjPtr
, Jim_GetHashEntryVal(he
));
14164 Jim_SetResult(interp
, listObjPtr
);
14168 int Jim_DictSize(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
14170 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
14173 return ((Jim_HashTable
*)objPtr
->internalRep
.ptr
)->used
;
14177 * Must be called with at least one object.
14178 * Returns the new dictionary, or NULL on error.
14180 Jim_Obj
*Jim_DictMerge(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
14182 Jim_Obj
*objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
14185 JimPanic((objc
== 0, "Jim_DictMerge called with objc=0"));
14187 /* Note that we don't optimise the trivial case of a single argument */
14189 for (i
= 0; i
< objc
; i
++) {
14191 Jim_HashTableIterator htiter
;
14194 if (SetDictFromAny(interp
, objv
[i
]) != JIM_OK
) {
14195 Jim_FreeNewObj(interp
, objPtr
);
14198 ht
= objv
[i
]->internalRep
.ptr
;
14199 JimInitHashTableIterator(ht
, &htiter
);
14200 while ((he
= Jim_NextHashEntry(&htiter
)) != NULL
) {
14201 Jim_ReplaceHashEntry(objPtr
->internalRep
.ptr
, Jim_GetHashEntryKey(he
), Jim_GetHashEntryVal(he
));
14207 int Jim_DictInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
14213 int nonzero_count
= 0;
14215 int bucket_counts
[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
14217 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
14221 ht
= (Jim_HashTable
*)objPtr
->internalRep
.ptr
;
14223 /* Note that this uses internal knowledge of the hash table */
14224 snprintf(buffer
, sizeof(buffer
), "%d entries in table, %d buckets\n", ht
->used
, ht
->size
);
14225 output
= Jim_NewStringObj(interp
, buffer
, -1);
14227 for (i
= 0; i
< ht
->size
; i
++) {
14228 Jim_HashEntry
*he
= ht
->table
[i
];
14235 bucket_counts
[10]++;
14238 bucket_counts
[entries
]++;
14245 for (i
= 0; i
< 10; i
++) {
14246 snprintf(buffer
, sizeof(buffer
), "number of buckets with %d entries: %d\n", i
, bucket_counts
[i
]);
14247 Jim_AppendString(interp
, output
, buffer
, -1);
14249 snprintf(buffer
, sizeof(buffer
), "number of buckets with 10 or more entries: %d\n", bucket_counts
[10]);
14250 Jim_AppendString(interp
, output
, buffer
, -1);
14251 snprintf(buffer
, sizeof(buffer
), "average search distance for entry: %.1f", nonzero_count
? (double)sum
/ nonzero_count
: 0.0);
14252 Jim_AppendString(interp
, output
, buffer
, -1);
14253 Jim_SetResult(interp
, output
);
14257 static int Jim_EvalEnsemble(Jim_Interp
*interp
, const char *basecmd
, const char *subcmd
, int argc
, Jim_Obj
*const *argv
)
14259 Jim_Obj
*prefixObj
= Jim_NewStringObj(interp
, basecmd
, -1);
14261 Jim_AppendString(interp
, prefixObj
, " ", 1);
14262 Jim_AppendString(interp
, prefixObj
, subcmd
, -1);
14264 return Jim_EvalObjPrefix(interp
, prefixObj
, argc
, argv
);
14268 * Implements the [dict with] command
14270 static int JimDictWith(Jim_Interp
*interp
, Jim_Obj
*dictVarName
, Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*scriptObj
)
14275 Jim_Obj
**dictValues
;
14279 /* Open up the appropriate level of the dictionary */
14280 dictObj
= Jim_GetVariable(interp
, dictVarName
, JIM_ERRMSG
);
14281 if (dictObj
== NULL
|| Jim_DictKeysVector(interp
, dictObj
, keyv
, keyc
, &objPtr
, JIM_ERRMSG
) != JIM_OK
) {
14284 /* Set the local variables */
14285 if (Jim_DictPairs(interp
, objPtr
, &dictValues
, &len
) == JIM_ERR
) {
14288 for (i
= 0; i
< len
; i
+= 2) {
14289 if (Jim_SetVariable(interp
, dictValues
[i
], dictValues
[i
+ 1]) == JIM_ERR
) {
14290 Jim_Free(dictValues
);
14295 /* As an optimisation, if the script is empty, no need to evaluate it or update the dict */
14296 if (Jim_Length(scriptObj
)) {
14297 ret
= Jim_EvalObj(interp
, scriptObj
);
14299 /* Now if the dictionary still exists, update it based on the local variables */
14300 if (ret
== JIM_OK
&& Jim_GetVariable(interp
, dictVarName
, 0) != NULL
) {
14301 /* We need a copy of keyv with one extra element at the end for Jim_SetDictKeysVector() */
14302 Jim_Obj
**newkeyv
= Jim_Alloc(sizeof(*newkeyv
) * (keyc
+ 1));
14303 for (i
= 0; i
< keyc
; i
++) {
14304 newkeyv
[i
] = keyv
[i
];
14307 for (i
= 0; i
< len
; i
+= 2) {
14308 /* This will be NULL if the variable no longer exists, thus deleting the variable */
14309 objPtr
= Jim_GetVariable(interp
, dictValues
[i
], 0);
14310 newkeyv
[keyc
] = dictValues
[i
];
14311 Jim_SetDictKeysVector(interp
, dictVarName
, newkeyv
, keyc
+ 1, objPtr
, 0);
14317 Jim_Free(dictValues
);
14323 static int Jim_DictCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14326 int types
= JIM_DICTMATCH_KEYS
;
14328 static const char * const options
[] = {
14329 "create", "get", "set", "unset", "exists", "keys", "size", "info",
14330 "merge", "with", "append", "lappend", "incr", "remove", "values", "for",
14331 "replace", "update", NULL
14335 OPT_CREATE
, OPT_GET
, OPT_SET
, OPT_UNSET
, OPT_EXISTS
, OPT_KEYS
, OPT_SIZE
, OPT_INFO
,
14336 OPT_MERGE
, OPT_WITH
, OPT_APPEND
, OPT_LAPPEND
, OPT_INCR
, OPT_REMOVE
, OPT_VALUES
, OPT_FOR
,
14337 OPT_REPLACE
, OPT_UPDATE
,
14341 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?arguments ...?");
14345 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
) {
14346 return Jim_CheckShowCommands(interp
, argv
[1], options
);
14352 Jim_WrongNumArgs(interp
, 2, argv
, "dictionary ?key ...?");
14355 if (Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, &objPtr
,
14356 JIM_ERRMSG
) != JIM_OK
) {
14359 Jim_SetResult(interp
, objPtr
);
14364 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...? value");
14367 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 4, argv
[argc
- 1], JIM_ERRMSG
);
14371 Jim_WrongNumArgs(interp
, 2, argv
, "dictionary key ?key ...?");
14375 int rc
= Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, &objPtr
, JIM_NONE
);
14379 Jim_SetResultBool(interp
, rc
== JIM_OK
);
14385 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...?");
14388 if (Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, NULL
, JIM_NONE
) != JIM_OK
) {
14394 types
= JIM_DICTMATCH_VALUES
;
14397 if (argc
!= 3 && argc
!= 4) {
14398 Jim_WrongNumArgs(interp
, 2, argv
, "dictionary ?pattern?");
14401 return Jim_DictMatchTypes(interp
, argv
[2], argc
== 4 ? argv
[3] : NULL
, types
, types
);
14405 Jim_WrongNumArgs(interp
, 2, argv
, "dictionary");
14408 else if (Jim_DictSize(interp
, argv
[2]) < 0) {
14411 Jim_SetResultInt(interp
, Jim_DictSize(interp
, argv
[2]));
14418 objPtr
= Jim_DictMerge(interp
, argc
- 2, argv
+ 2);
14419 if (objPtr
== NULL
) {
14422 Jim_SetResult(interp
, objPtr
);
14426 if (argc
< 6 || argc
% 2) {
14427 /* Better error message */
14434 Jim_WrongNumArgs(interp
, 2, argv
, "?key value ...?");
14437 objPtr
= Jim_NewDictObj(interp
, argv
+ 2, argc
- 2);
14438 Jim_SetResult(interp
, objPtr
);
14443 Jim_WrongNumArgs(interp
, 2, argv
, "dictionary");
14446 return Jim_DictInfo(interp
, argv
[2]);
14450 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?key ...? script");
14453 return JimDictWith(interp
, argv
[2], argv
+ 3, argc
- 4, argv
[argc
- 1]);
14455 /* Handle command as an ensemble */
14456 return Jim_EvalEnsemble(interp
, "dict", options
[option
], argc
- 2, argv
+ 2);
14460 static int Jim_SubstCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14462 static const char * const options
[] = {
14463 "-nobackslashes", "-nocommands", "-novariables", NULL
14466 { OPT_NOBACKSLASHES
, OPT_NOCOMMANDS
, OPT_NOVARIABLES
};
14468 int flags
= JIM_SUBST_FLAG
;
14472 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string");
14475 for (i
= 1; i
< (argc
- 1); i
++) {
14478 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
,
14479 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
14483 case OPT_NOBACKSLASHES
:
14484 flags
|= JIM_SUBST_NOESC
;
14486 case OPT_NOCOMMANDS
:
14487 flags
|= JIM_SUBST_NOCMD
;
14489 case OPT_NOVARIABLES
:
14490 flags
|= JIM_SUBST_NOVAR
;
14494 if (Jim_SubstObj(interp
, argv
[argc
- 1], &objPtr
, flags
) != JIM_OK
) {
14497 Jim_SetResult(interp
, objPtr
);
14501 #ifdef jim_ext_namespace
14502 static int JimIsGlobalNamespace(Jim_Obj
*objPtr
)
14505 const char *str
= Jim_GetString(objPtr
, &len
);
14506 return len
>= 2 && str
[0] == ':' && str
[1] == ':';
14511 static int Jim_InfoCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14517 static const char * const commands
[] = {
14518 "body", "statics", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
14519 "vars", "version", "patchlevel", "complete", "args", "hostname",
14520 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
14521 "references", "alias", NULL
14524 { INFO_BODY
, INFO_STATICS
, INFO_COMMANDS
, INFO_PROCS
, INFO_CHANNELS
, INFO_EXISTS
, INFO_GLOBALS
, INFO_LEVEL
,
14525 INFO_FRAME
, INFO_LOCALS
, INFO_VARS
, INFO_VERSION
, INFO_PATCHLEVEL
, INFO_COMPLETE
, INFO_ARGS
,
14526 INFO_HOSTNAME
, INFO_SCRIPT
, INFO_SOURCE
, INFO_STACKTRACE
, INFO_NAMEOFEXECUTABLE
,
14527 INFO_RETURNCODES
, INFO_REFERENCES
, INFO_ALIAS
,
14530 #ifdef jim_ext_namespace
14533 if (argc
> 2 && Jim_CompareStringImmediate(interp
, argv
[1], "-nons")) {
14534 /* This is for internal use only */
14542 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?args ...?");
14545 if (Jim_GetEnum(interp
, argv
[1], commands
, &cmd
, "subcommand", JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
14546 return Jim_CheckShowCommands(interp
, argv
[1], commands
);
14549 /* Test for the most common commands first, just in case it makes a difference */
14553 Jim_WrongNumArgs(interp
, 2, argv
, "varName");
14556 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, argv
[2], 0) != NULL
);
14563 Jim_WrongNumArgs(interp
, 2, argv
, "command");
14566 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
) {
14569 if (cmdPtr
->isproc
|| cmdPtr
->u
.native
.cmdProc
!= JimAliasCmd
) {
14570 Jim_SetResultFormatted(interp
, "command \"%#s\" is not an alias", argv
[2]);
14573 Jim_SetResult(interp
, (Jim_Obj
*)cmdPtr
->u
.native
.privData
);
14577 case INFO_CHANNELS
:
14578 mode
++; /* JIM_CMDLIST_CHANNELS */
14579 #ifndef jim_ext_aio
14580 Jim_SetResultString(interp
, "aio not enabled", -1);
14585 mode
++; /* JIM_CMDLIST_PROCS */
14587 case INFO_COMMANDS
:
14588 /* mode 0 => JIM_CMDLIST_COMMANDS */
14589 if (argc
!= 2 && argc
!= 3) {
14590 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
14593 #ifdef jim_ext_namespace
14595 if (Jim_Length(interp
->framePtr
->nsObj
) || (argc
== 3 && JimIsGlobalNamespace(argv
[2]))) {
14596 return Jim_EvalPrefix(interp
, "namespace info", argc
- 1, argv
+ 1);
14600 Jim_SetResult(interp
, JimCommandsList(interp
, (argc
== 3) ? argv
[2] : NULL
, mode
));
14604 mode
++; /* JIM_VARLIST_VARS */
14607 mode
++; /* JIM_VARLIST_LOCALS */
14610 /* mode 0 => JIM_VARLIST_GLOBALS */
14611 if (argc
!= 2 && argc
!= 3) {
14612 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
14615 #ifdef jim_ext_namespace
14617 if (Jim_Length(interp
->framePtr
->nsObj
) || (argc
== 3 && JimIsGlobalNamespace(argv
[2]))) {
14618 return Jim_EvalPrefix(interp
, "namespace info", argc
- 1, argv
+ 1);
14622 Jim_SetResult(interp
, JimVariablesList(interp
, argc
== 3 ? argv
[2] : NULL
, mode
));
14627 Jim_WrongNumArgs(interp
, 2, argv
, "");
14630 Jim_SetResult(interp
, JimGetScript(interp
, interp
->currentScriptObj
)->fileNameObj
);
14635 Jim_Obj
*resObjPtr
;
14636 Jim_Obj
*fileNameObj
;
14638 if (argc
!= 3 && argc
!= 5) {
14639 Jim_WrongNumArgs(interp
, 2, argv
, "source ?filename line?");
14643 if (Jim_GetWide(interp
, argv
[4], &line
) != JIM_OK
) {
14646 resObjPtr
= Jim_NewStringObj(interp
, Jim_String(argv
[2]), Jim_Length(argv
[2]));
14647 JimSetSourceInfo(interp
, resObjPtr
, argv
[3], line
);
14650 if (argv
[2]->typePtr
== &sourceObjType
) {
14651 fileNameObj
= argv
[2]->internalRep
.sourceValue
.fileNameObj
;
14652 line
= argv
[2]->internalRep
.sourceValue
.lineNumber
;
14654 else if (argv
[2]->typePtr
== &scriptObjType
) {
14655 ScriptObj
*script
= JimGetScript(interp
, argv
[2]);
14656 fileNameObj
= script
->fileNameObj
;
14657 line
= script
->firstline
;
14660 fileNameObj
= interp
->emptyObj
;
14663 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14664 Jim_ListAppendElement(interp
, resObjPtr
, fileNameObj
);
14665 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewIntObj(interp
, line
));
14667 Jim_SetResult(interp
, resObjPtr
);
14671 case INFO_STACKTRACE
:
14672 Jim_SetResult(interp
, interp
->stackTrace
);
14679 Jim_SetResultInt(interp
, interp
->framePtr
->level
);
14683 if (JimInfoLevel(interp
, argv
[2], &objPtr
, cmd
== INFO_LEVEL
) != JIM_OK
) {
14686 Jim_SetResult(interp
, objPtr
);
14690 Jim_WrongNumArgs(interp
, 2, argv
, "?levelNum?");
14701 Jim_WrongNumArgs(interp
, 2, argv
, "procname");
14704 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
) {
14707 if (!cmdPtr
->isproc
) {
14708 Jim_SetResultFormatted(interp
, "command \"%#s\" is not a procedure", argv
[2]);
14713 Jim_SetResult(interp
, cmdPtr
->u
.proc
.bodyObjPtr
);
14716 Jim_SetResult(interp
, cmdPtr
->u
.proc
.argListObjPtr
);
14719 if (cmdPtr
->u
.proc
.staticVars
) {
14720 Jim_SetResult(interp
, JimHashtablePatternMatch(interp
, cmdPtr
->u
.proc
.staticVars
,
14721 NULL
, JimVariablesMatch
, JIM_VARLIST_LOCALS
| JIM_VARLIST_VALUES
));
14729 case INFO_PATCHLEVEL
:{
14730 char buf
[(JIM_INTEGER_SPACE
* 2) + 1];
14732 sprintf(buf
, "%d.%d", JIM_VERSION
/ 100, JIM_VERSION
% 100);
14733 Jim_SetResultString(interp
, buf
, -1);
14737 case INFO_COMPLETE
:
14738 if (argc
!= 3 && argc
!= 4) {
14739 Jim_WrongNumArgs(interp
, 2, argv
, "script ?missing?");
14745 Jim_SetResultBool(interp
, Jim_ScriptIsComplete(interp
, argv
[2], &missing
));
14746 if (missing
!= ' ' && argc
== 4) {
14747 Jim_SetVariable(interp
, argv
[3], Jim_NewStringObj(interp
, &missing
, 1));
14752 case INFO_HOSTNAME
:
14753 /* Redirect to os.gethostname if it exists */
14754 return Jim_Eval(interp
, "os.gethostname");
14756 case INFO_NAMEOFEXECUTABLE
:
14757 /* Redirect to Tcl proc */
14758 return Jim_Eval(interp
, "{info nameofexecutable}");
14760 case INFO_RETURNCODES
:
14763 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14765 for (i
= 0; jimReturnCodes
[i
]; i
++) {
14766 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewIntObj(interp
, i
));
14767 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
,
14768 jimReturnCodes
[i
], -1));
14771 Jim_SetResult(interp
, listObjPtr
);
14773 else if (argc
== 3) {
14777 if (Jim_GetLong(interp
, argv
[2], &code
) != JIM_OK
) {
14780 name
= Jim_ReturnCode(code
);
14781 if (*name
== '?') {
14782 Jim_SetResultInt(interp
, code
);
14785 Jim_SetResultString(interp
, name
, -1);
14789 Jim_WrongNumArgs(interp
, 2, argv
, "?code?");
14793 case INFO_REFERENCES
:
14794 #ifdef JIM_REFERENCES
14795 return JimInfoReferences(interp
, argc
, argv
);
14797 Jim_SetResultString(interp
, "not supported", -1);
14805 static int Jim_ExistsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14810 static const char * const options
[] = {
14811 "-command", "-proc", "-alias", "-var", NULL
14815 OPT_COMMAND
, OPT_PROC
, OPT_ALIAS
, OPT_VAR
14823 else if (argc
== 3) {
14824 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
14830 Jim_WrongNumArgs(interp
, 1, argv
, "?option? name");
14834 if (option
== OPT_VAR
) {
14835 result
= Jim_GetVariable(interp
, objPtr
, 0) != NULL
;
14838 /* Now different kinds of commands */
14839 Jim_Cmd
*cmd
= Jim_GetCommand(interp
, objPtr
, JIM_NONE
);
14848 result
= cmd
->isproc
== 0 && cmd
->u
.native
.cmdProc
== JimAliasCmd
;
14852 result
= cmd
->isproc
;
14857 Jim_SetResultBool(interp
, result
);
14862 static int Jim_SplitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14864 const char *str
, *splitChars
, *noMatchStart
;
14865 int splitLen
, strLen
;
14866 Jim_Obj
*resObjPtr
;
14870 if (argc
!= 2 && argc
!= 3) {
14871 Jim_WrongNumArgs(interp
, 1, argv
, "string ?splitChars?");
14875 str
= Jim_GetString(argv
[1], &len
);
14879 strLen
= Jim_Utf8Length(interp
, argv
[1]);
14883 splitChars
= " \n\t\r";
14887 splitChars
= Jim_String(argv
[2]);
14888 splitLen
= Jim_Utf8Length(interp
, argv
[2]);
14891 noMatchStart
= str
;
14892 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14898 const char *sc
= splitChars
;
14899 int scLen
= splitLen
;
14900 int sl
= utf8_tounicode(str
, &c
);
14903 sc
+= utf8_tounicode(sc
, &pc
);
14905 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
14906 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
14907 noMatchStart
= str
+ sl
;
14913 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
14914 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
14917 /* This handles the special case of splitchars eq {}
14918 * Optimise by sharing common (ASCII) characters
14920 Jim_Obj
**commonObj
= NULL
;
14921 #define NUM_COMMON (128 - 9)
14923 int n
= utf8_tounicode(str
, &c
);
14924 #ifdef JIM_OPTIMIZATION
14925 if (c
>= 9 && c
< 128) {
14926 /* Common ASCII char. Note that 9 is the tab character */
14929 commonObj
= Jim_Alloc(sizeof(*commonObj
) * NUM_COMMON
);
14930 memset(commonObj
, 0, sizeof(*commonObj
) * NUM_COMMON
);
14932 if (!commonObj
[c
]) {
14933 commonObj
[c
] = Jim_NewStringObj(interp
, str
, 1);
14935 Jim_ListAppendElement(interp
, resObjPtr
, commonObj
[c
]);
14940 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewStringObjUtf8(interp
, str
, 1));
14943 Jim_Free(commonObj
);
14946 Jim_SetResult(interp
, resObjPtr
);
14951 static int Jim_JoinCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14953 const char *joinStr
;
14956 if (argc
!= 2 && argc
!= 3) {
14957 Jim_WrongNumArgs(interp
, 1, argv
, "list ?joinString?");
14966 joinStr
= Jim_GetString(argv
[2], &joinStrLen
);
14968 Jim_SetResult(interp
, Jim_ListJoin(interp
, argv
[1], joinStr
, joinStrLen
));
14973 static int Jim_FormatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14978 Jim_WrongNumArgs(interp
, 1, argv
, "formatString ?arg arg ...?");
14981 objPtr
= Jim_FormatString(interp
, argv
[1], argc
- 2, argv
+ 2);
14982 if (objPtr
== NULL
)
14984 Jim_SetResult(interp
, objPtr
);
14989 static int Jim_ScanCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14991 Jim_Obj
*listPtr
, **outVec
;
14995 Jim_WrongNumArgs(interp
, 1, argv
, "string format ?varName varName ...?");
14998 if (argv
[2]->typePtr
!= &scanFmtStringObjType
)
14999 SetScanFmtFromAny(interp
, argv
[2]);
15000 if (FormatGetError(argv
[2]) != 0) {
15001 Jim_SetResultString(interp
, FormatGetError(argv
[2]), -1);
15005 int maxPos
= FormatGetMaxPos(argv
[2]);
15006 int count
= FormatGetCnvCount(argv
[2]);
15008 if (maxPos
> argc
- 3) {
15009 Jim_SetResultString(interp
, "\"%n$\" argument index out of range", -1);
15012 else if (count
> argc
- 3) {
15013 Jim_SetResultString(interp
, "different numbers of variable names and "
15014 "field specifiers", -1);
15017 else if (count
< argc
- 3) {
15018 Jim_SetResultString(interp
, "variable is not assigned by any "
15019 "conversion specifiers", -1);
15023 listPtr
= Jim_ScanString(interp
, argv
[1], argv
[2], JIM_ERRMSG
);
15030 if (listPtr
!= 0 && listPtr
!= (Jim_Obj
*)EOF
) {
15031 int len
= Jim_ListLength(interp
, listPtr
);
15034 JimListGetElements(interp
, listPtr
, &outc
, &outVec
);
15035 for (i
= 0; i
< outc
; ++i
) {
15036 if (Jim_Length(outVec
[i
]) > 0) {
15038 if (Jim_SetVariable(interp
, argv
[3 + i
], outVec
[i
]) != JIM_OK
) {
15044 Jim_FreeNewObj(interp
, listPtr
);
15049 if (rc
== JIM_OK
) {
15050 Jim_SetResultInt(interp
, count
);
15055 if (listPtr
== (Jim_Obj
*)EOF
) {
15056 Jim_SetResult(interp
, Jim_NewListObj(interp
, 0, 0));
15059 Jim_SetResult(interp
, listPtr
);
15065 static int Jim_ErrorCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15067 if (argc
!= 2 && argc
!= 3) {
15068 Jim_WrongNumArgs(interp
, 1, argv
, "message ?stacktrace?");
15071 Jim_SetResult(interp
, argv
[1]);
15073 JimSetStackTrace(interp
, argv
[2]);
15076 interp
->addStackTrace
++;
15081 static int Jim_LrangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15086 Jim_WrongNumArgs(interp
, 1, argv
, "list first last");
15089 if ((objPtr
= Jim_ListRange(interp
, argv
[1], argv
[2], argv
[3])) == NULL
)
15091 Jim_SetResult(interp
, objPtr
);
15096 static int Jim_LrepeatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15101 if (argc
< 2 || Jim_GetLong(interp
, argv
[1], &count
) != JIM_OK
|| count
< 0) {
15102 Jim_WrongNumArgs(interp
, 1, argv
, "count ?value ...?");
15106 if (count
== 0 || argc
== 2) {
15113 objPtr
= Jim_NewListObj(interp
, argv
, argc
);
15115 ListInsertElements(objPtr
, -1, argc
, argv
);
15118 Jim_SetResult(interp
, objPtr
);
15122 char **Jim_GetEnviron(void)
15124 #if defined(HAVE__NSGETENVIRON)
15125 return *_NSGetEnviron();
15127 #if !defined(NO_ENVIRON_EXTERN)
15128 extern char **environ
;
15135 void Jim_SetEnviron(char **env
)
15137 #if defined(HAVE__NSGETENVIRON)
15138 *_NSGetEnviron() = env
;
15140 #if !defined(NO_ENVIRON_EXTERN)
15141 extern char **environ
;
15149 static int Jim_EnvCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15155 char **e
= Jim_GetEnviron();
15158 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
15160 for (i
= 0; e
[i
]; i
++) {
15161 const char *equals
= strchr(e
[i
], '=');
15164 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, e
[i
],
15166 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, equals
+ 1, -1));
15170 Jim_SetResult(interp
, listObjPtr
);
15175 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?default?");
15178 key
= Jim_String(argv
[1]);
15182 Jim_SetResultFormatted(interp
, "environment variable \"%#s\" does not exist", argv
[1]);
15185 val
= Jim_String(argv
[2]);
15187 Jim_SetResult(interp
, Jim_NewStringObj(interp
, val
, -1));
15192 static int Jim_SourceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15197 Jim_WrongNumArgs(interp
, 1, argv
, "fileName");
15200 retval
= Jim_EvalFile(interp
, Jim_String(argv
[1]));
15201 if (retval
== JIM_RETURN
)
15207 static int Jim_LreverseCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15209 Jim_Obj
*revObjPtr
, **ele
;
15213 Jim_WrongNumArgs(interp
, 1, argv
, "list");
15216 JimListGetElements(interp
, argv
[1], &len
, &ele
);
15218 revObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
15220 ListAppendElement(revObjPtr
, ele
[len
--]);
15221 Jim_SetResult(interp
, revObjPtr
);
15225 static int JimRangeLen(jim_wide start
, jim_wide end
, jim_wide step
)
15233 else if (step
> 0 && start
> end
)
15235 else if (step
< 0 && end
> start
)
15239 len
= -len
; /* abs(len) */
15241 step
= -step
; /* abs(step) */
15242 len
= 1 + ((len
- 1) / step
);
15243 /* We can truncate safely to INT_MAX, the range command
15244 * will always return an error for a such long range
15245 * because Tcl lists can't be so long. */
15248 return (int)((len
< 0) ? -1 : len
);
15252 static int Jim_RangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15254 jim_wide start
= 0, end
, step
= 1;
15258 if (argc
< 2 || argc
> 4) {
15259 Jim_WrongNumArgs(interp
, 1, argv
, "?start? end ?step?");
15263 if (Jim_GetWide(interp
, argv
[1], &end
) != JIM_OK
)
15267 if (Jim_GetWide(interp
, argv
[1], &start
) != JIM_OK
||
15268 Jim_GetWide(interp
, argv
[2], &end
) != JIM_OK
)
15270 if (argc
== 4 && Jim_GetWide(interp
, argv
[3], &step
) != JIM_OK
)
15273 if ((len
= JimRangeLen(start
, end
, step
)) == -1) {
15274 Jim_SetResultString(interp
, "Invalid (infinite?) range specified", -1);
15277 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
15278 for (i
= 0; i
< len
; i
++)
15279 ListAppendElement(objPtr
, Jim_NewIntObj(interp
, start
+ i
* step
));
15280 Jim_SetResult(interp
, objPtr
);
15285 static int Jim_RandCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
15287 jim_wide min
= 0, max
= 0, len
, maxMul
;
15289 if (argc
< 1 || argc
> 3) {
15290 Jim_WrongNumArgs(interp
, 1, argv
, "?min? max");
15294 max
= JIM_WIDE_MAX
;
15295 } else if (argc
== 2) {
15296 if (Jim_GetWide(interp
, argv
[1], &max
) != JIM_OK
)
15298 } else if (argc
== 3) {
15299 if (Jim_GetWide(interp
, argv
[1], &min
) != JIM_OK
||
15300 Jim_GetWide(interp
, argv
[2], &max
) != JIM_OK
)
15305 Jim_SetResultString(interp
, "Invalid arguments (max < min)", -1);
15308 maxMul
= JIM_WIDE_MAX
- (len
? (JIM_WIDE_MAX
%len
) : 0);
15312 JimRandomBytes(interp
, &r
, sizeof(jim_wide
));
15313 if (r
< 0 || r
>= maxMul
) continue;
15314 r
= (len
== 0) ? 0 : r
%len
;
15315 Jim_SetResultInt(interp
, min
+r
);
15320 static const struct {
15322 Jim_CmdProc
*cmdProc
;
15323 } Jim_CoreCommandsTable
[] = {
15324 {"alias", Jim_AliasCoreCommand
},
15325 {"set", Jim_SetCoreCommand
},
15326 {"unset", Jim_UnsetCoreCommand
},
15327 {"puts", Jim_PutsCoreCommand
},
15328 {"+", Jim_AddCoreCommand
},
15329 {"*", Jim_MulCoreCommand
},
15330 {"-", Jim_SubCoreCommand
},
15331 {"/", Jim_DivCoreCommand
},
15332 {"incr", Jim_IncrCoreCommand
},
15333 {"while", Jim_WhileCoreCommand
},
15334 {"loop", Jim_LoopCoreCommand
},
15335 {"for", Jim_ForCoreCommand
},
15336 {"foreach", Jim_ForeachCoreCommand
},
15337 {"lmap", Jim_LmapCoreCommand
},
15338 {"lassign", Jim_LassignCoreCommand
},
15339 {"if", Jim_IfCoreCommand
},
15340 {"switch", Jim_SwitchCoreCommand
},
15341 {"list", Jim_ListCoreCommand
},
15342 {"lindex", Jim_LindexCoreCommand
},
15343 {"lset", Jim_LsetCoreCommand
},
15344 {"lsearch", Jim_LsearchCoreCommand
},
15345 {"llength", Jim_LlengthCoreCommand
},
15346 {"lappend", Jim_LappendCoreCommand
},
15347 {"linsert", Jim_LinsertCoreCommand
},
15348 {"lreplace", Jim_LreplaceCoreCommand
},
15349 {"lsort", Jim_LsortCoreCommand
},
15350 {"append", Jim_AppendCoreCommand
},
15351 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
15352 {"debug", Jim_DebugCoreCommand
},
15354 {"eval", Jim_EvalCoreCommand
},
15355 {"uplevel", Jim_UplevelCoreCommand
},
15356 {"expr", Jim_ExprCoreCommand
},
15357 {"break", Jim_BreakCoreCommand
},
15358 {"continue", Jim_ContinueCoreCommand
},
15359 {"proc", Jim_ProcCoreCommand
},
15360 {"concat", Jim_ConcatCoreCommand
},
15361 {"return", Jim_ReturnCoreCommand
},
15362 {"upvar", Jim_UpvarCoreCommand
},
15363 {"global", Jim_GlobalCoreCommand
},
15364 {"string", Jim_StringCoreCommand
},
15365 {"time", Jim_TimeCoreCommand
},
15366 {"exit", Jim_ExitCoreCommand
},
15367 {"catch", Jim_CatchCoreCommand
},
15368 #ifdef JIM_REFERENCES
15369 {"ref", Jim_RefCoreCommand
},
15370 {"getref", Jim_GetrefCoreCommand
},
15371 {"setref", Jim_SetrefCoreCommand
},
15372 {"finalize", Jim_FinalizeCoreCommand
},
15373 {"collect", Jim_CollectCoreCommand
},
15375 {"rename", Jim_RenameCoreCommand
},
15376 {"dict", Jim_DictCoreCommand
},
15377 {"subst", Jim_SubstCoreCommand
},
15378 {"info", Jim_InfoCoreCommand
},
15379 {"exists", Jim_ExistsCoreCommand
},
15380 {"split", Jim_SplitCoreCommand
},
15381 {"join", Jim_JoinCoreCommand
},
15382 {"format", Jim_FormatCoreCommand
},
15383 {"scan", Jim_ScanCoreCommand
},
15384 {"error", Jim_ErrorCoreCommand
},
15385 {"lrange", Jim_LrangeCoreCommand
},
15386 {"lrepeat", Jim_LrepeatCoreCommand
},
15387 {"env", Jim_EnvCoreCommand
},
15388 {"source", Jim_SourceCoreCommand
},
15389 {"lreverse", Jim_LreverseCoreCommand
},
15390 {"range", Jim_RangeCoreCommand
},
15391 {"rand", Jim_RandCoreCommand
},
15392 {"tailcall", Jim_TailcallCoreCommand
},
15393 {"local", Jim_LocalCoreCommand
},
15394 {"upcall", Jim_UpcallCoreCommand
},
15395 {"apply", Jim_ApplyCoreCommand
},
15399 void Jim_RegisterCoreCommands(Jim_Interp
*interp
)
15403 while (Jim_CoreCommandsTable
[i
].name
!= NULL
) {
15404 Jim_CreateCommand(interp
,
15405 Jim_CoreCommandsTable
[i
].name
, Jim_CoreCommandsTable
[i
].cmdProc
, NULL
, NULL
);
15410 /* -----------------------------------------------------------------------------
15411 * Interactive prompt
15412 * ---------------------------------------------------------------------------*/
15413 void Jim_MakeErrorMessage(Jim_Interp
*interp
)
15417 argv
[0] = Jim_NewStringObj(interp
, "errorInfo", -1);
15418 argv
[1] = interp
->result
;
15420 Jim_EvalObjVector(interp
, 2, argv
);
15424 * Given a null terminated array of strings, returns an allocated, sorted
15425 * copy of the array.
15427 static char **JimSortStringTable(const char *const *tablePtr
)
15430 char **tablePtrSorted
;
15432 /* Find the size of the table */
15433 for (count
= 0; tablePtr
[count
]; count
++) {
15436 /* Allocate one extra for the terminating NULL pointer */
15437 tablePtrSorted
= Jim_Alloc(sizeof(char *) * (count
+ 1));
15438 memcpy(tablePtrSorted
, tablePtr
, sizeof(char *) * count
);
15439 qsort(tablePtrSorted
, count
, sizeof(char *), qsortCompareStringPointers
);
15440 tablePtrSorted
[count
] = NULL
;
15442 return tablePtrSorted
;
15445 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
15446 const char *prefix
, const char *const *tablePtr
, const char *name
)
15448 char **tablePtrSorted
;
15451 if (name
== NULL
) {
15455 Jim_SetResultFormatted(interp
, "%s%s \"%s\": must be ", badtype
, name
, arg
);
15456 tablePtrSorted
= JimSortStringTable(tablePtr
);
15457 for (i
= 0; tablePtrSorted
[i
]; i
++) {
15458 if (tablePtrSorted
[i
+ 1] == NULL
&& i
> 0) {
15459 Jim_AppendString(interp
, Jim_GetResult(interp
), "or ", -1);
15461 Jim_AppendStrings(interp
, Jim_GetResult(interp
), prefix
, tablePtrSorted
[i
], NULL
);
15462 if (tablePtrSorted
[i
+ 1]) {
15463 Jim_AppendString(interp
, Jim_GetResult(interp
), ", ", -1);
15466 Jim_Free(tablePtrSorted
);
15471 * If objPtr is "-commands" sets the Jim result as a sorted list of options in the table
15472 * and returns JIM_OK.
15474 * Otherwise returns JIM_ERR.
15476 int Jim_CheckShowCommands(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *const *tablePtr
)
15478 if (Jim_CompareStringImmediate(interp
, objPtr
, "-commands")) {
15480 char **tablePtrSorted
= JimSortStringTable(tablePtr
);
15481 Jim_SetResult(interp
, Jim_NewListObj(interp
, NULL
, 0));
15482 for (i
= 0; tablePtrSorted
[i
]; i
++) {
15483 Jim_ListAppendElement(interp
, Jim_GetResult(interp
), Jim_NewStringObj(interp
, tablePtrSorted
[i
], -1));
15485 Jim_Free(tablePtrSorted
);
15491 /* internal rep is stored in ptrIntvalue
15496 static const Jim_ObjType getEnumObjType
= {
15501 JIM_TYPE_REFERENCES
15504 int Jim_GetEnum(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
15505 const char *const *tablePtr
, int *indexPtr
, const char *name
, int flags
)
15507 const char *bad
= "bad ";
15508 const char *const *entryPtr
= NULL
;
15514 if (objPtr
->typePtr
== &getEnumObjType
) {
15515 if (objPtr
->internalRep
.ptrIntValue
.ptr
== tablePtr
&& objPtr
->internalRep
.ptrIntValue
.int1
== flags
) {
15516 *indexPtr
= objPtr
->internalRep
.ptrIntValue
.int2
;
15521 arg
= Jim_GetString(objPtr
, &arglen
);
15525 for (entryPtr
= tablePtr
, i
= 0; *entryPtr
!= NULL
; entryPtr
++, i
++) {
15526 if (Jim_CompareStringImmediate(interp
, objPtr
, *entryPtr
)) {
15527 /* Found an exact match */
15531 if (flags
& JIM_ENUM_ABBREV
) {
15532 /* Accept an unambiguous abbreviation.
15533 * Note that '-' doesnt' consitute a valid abbreviation
15535 if (strncmp(arg
, *entryPtr
, arglen
) == 0) {
15536 if (*arg
== '-' && arglen
== 1) {
15540 bad
= "ambiguous ";
15548 /* If we had an unambiguous partial match */
15551 /* Record the match in the object */
15552 Jim_FreeIntRep(interp
, objPtr
);
15553 objPtr
->typePtr
= &getEnumObjType
;
15554 objPtr
->internalRep
.ptrIntValue
.ptr
= (void *)tablePtr
;
15555 objPtr
->internalRep
.ptrIntValue
.int1
= flags
;
15556 objPtr
->internalRep
.ptrIntValue
.int2
= match
;
15557 /* Return the result */
15563 if (flags
& JIM_ERRMSG
) {
15564 JimSetFailedEnumResult(interp
, arg
, bad
, "", tablePtr
, name
);
15569 int Jim_FindByName(const char *name
, const char * const array
[], size_t len
)
15573 for (i
= 0; i
< (int)len
; i
++) {
15574 if (array
[i
] && strcmp(array
[i
], name
) == 0) {
15581 int Jim_IsDict(Jim_Obj
*objPtr
)
15583 return objPtr
->typePtr
== &dictObjType
;
15586 int Jim_IsList(Jim_Obj
*objPtr
)
15588 return objPtr
->typePtr
== &listObjType
;
15592 * Very simple printf-like formatting, designed for error messages.
15594 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
15595 * The resulting string is created and set as the result.
15597 * Each '%s' should correspond to a regular string parameter.
15598 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
15599 * Any other printf specifier is not allowed (but %% is allowed for the % character).
15601 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
15603 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
15605 * Note that any Jim_Obj parameters with zero ref count will be freed as a result of this call.
15607 void Jim_SetResultFormatted(Jim_Interp
*interp
, const char *format
, ...)
15609 /* Initial space needed */
15610 int len
= strlen(format
);
15613 const char *params
[5];
15615 Jim_Obj
*objparam
[5];
15620 va_start(args
, format
);
15622 for (i
= 0; i
< len
&& n
< 5; i
++) {
15625 if (strncmp(format
+ i
, "%s", 2) == 0) {
15626 params
[n
] = va_arg(args
, char *);
15628 l
= strlen(params
[n
]);
15630 else if (strncmp(format
+ i
, "%#s", 3) == 0) {
15631 Jim_Obj
*objPtr
= va_arg(args
, Jim_Obj
*);
15633 params
[n
] = Jim_GetString(objPtr
, &l
);
15634 objparam
[nobjparam
++] = objPtr
;
15635 Jim_IncrRefCount(objPtr
);
15638 if (format
[i
] == '%') {
15648 buf
= Jim_Alloc(len
+ 1);
15649 len
= snprintf(buf
, len
+ 1, format
, params
[0], params
[1], params
[2], params
[3], params
[4]);
15653 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
15655 for (i
= 0; i
< nobjparam
; i
++) {
15656 Jim_DecrRefCount(interp
, objparam
[i
]);
15661 #ifndef jim_ext_package
15662 int Jim_PackageProvide(Jim_Interp
*interp
, const char *name
, const char *ver
, int flags
)
15667 #ifndef jim_ext_aio
15668 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*fhObj
)
15670 Jim_SetResultString(interp
, "aio not enabled", -1);
15677 * Local Variables: ***
15678 * c-basic-offset: 4 ***