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 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>
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials
22 * provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
25 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
27 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
29 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
33 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 * The views and conclusions contained in the software and documentation
38 * are those of the authors and should not be interpreted as representing
39 * official policies, either expressed or implied, of the Jim Tcl Project.
42 #define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
45 #include <pkgconf/jimtcl.h>
48 #define JIM_DYNLIB /* Dynamic library support for UNIX and WIN32 */
49 #endif /* JIM_ANSIC */
61 #include "replacements.h"
63 /* Include the platform dependent libraries for
64 * dynamic loading of libraries. */
66 #if defined(_WIN32) || defined(WIN32)
73 #define WIN32_LEAN_AND_MEAN
76 #pragma warning(disable:4146)
81 #endif /* JIM_DYNLIB */
84 #include <cyg/jimtcl/jim.h>
93 /* -----------------------------------------------------------------------------
95 * ---------------------------------------------------------------------------*/
97 /* A shared empty string for the objects string representation.
98 * Jim_InvalidateStringRep knows about it and don't try to free. */
99 static char *JimEmptyStringRep
= (char*) "";
101 /* -----------------------------------------------------------------------------
102 * Required prototypes of not exported functions
103 * ---------------------------------------------------------------------------*/
104 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
);
105 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
);
106 static void JimRegisterCoreApi(Jim_Interp
*interp
);
108 static Jim_HashTableType JimVariablesHashTableType
;
110 /* -----------------------------------------------------------------------------
112 * ---------------------------------------------------------------------------*/
115 jim_vasprintf( const char *fmt
, va_list ap
)
117 #ifndef HAVE_VASPRINTF
119 static char buf
[2048];
120 vsnprintf( buf
, sizeof(buf
), fmt
, ap
);
121 /* garentee termination */
122 buf
[sizeof(buf
)-1] = 0;
125 vasprintf( &buf
, fmt
, ap
);
131 jim_vasprintf_done( void *buf
)
133 #ifndef HAVE_VASPRINTF
142 * Convert a string to a jim_wide INTEGER.
143 * This function originates from BSD.
145 * Ignores `locale' stuff. Assumes that the upper and lower case
146 * alphabets and digits are each contiguous.
148 #ifdef HAVE_LONG_LONG
149 #define JimIsAscii(c) (((c) & ~0x7f) == 0)
150 static jim_wide
JimStrtoll(const char *nptr
, char **endptr
, register int base
)
152 register const char *s
;
153 register unsigned jim_wide acc
;
154 register unsigned char c
;
155 register unsigned jim_wide qbase
, cutoff
;
156 register int neg
, any
, cutlim
;
159 * Skip white space and pick up leading +/- sign if any.
160 * If base is 0, allow 0x for hex and 0 for octal, else
161 * assume decimal; if base is already 16, allow 0x.
166 } while (isspace(c
));
175 if ((base
== 0 || base
== 16) &&
176 c
== '0' && (*s
== 'x' || *s
== 'X')) {
182 base
= c
== '0' ? 8 : 10;
185 * Compute the cutoff value between legal numbers and illegal
186 * numbers. That is the largest legal value, divided by the
187 * base. An input number that is greater than this value, if
188 * followed by a legal input character, is too big. One that
189 * is equal to this value may be valid or not; the limit
190 * between valid and invalid numbers is then based on the last
191 * digit. For instance, if the range for quads is
192 * [-9223372036854775808..9223372036854775807] and the input base
193 * is 10, cutoff will be set to 922337203685477580 and cutlim to
194 * either 7 (neg==0) or 8 (neg==1), meaning that if we have
195 * accumulated a value > 922337203685477580, or equal but the
196 * next digit is > 7 (or 8), the number is too big, and we will
197 * return a range error.
199 * Set any if any `digits' consumed; make it negative to indicate
202 qbase
= (unsigned)base
;
203 cutoff
= neg
? (unsigned jim_wide
)-(LLONG_MIN
+ LLONG_MAX
) + LLONG_MAX
205 cutlim
= (int)(cutoff
% qbase
);
207 for (acc
= 0, any
= 0;; c
= *s
++) {
213 c
-= isupper(c
) ? 'A' - 10 : 'a' - 10;
218 if (any
< 0 || acc
> cutoff
|| (acc
== cutoff
&& c
> cutlim
))
227 acc
= neg
? LLONG_MIN
: LLONG_MAX
;
232 *endptr
= (char *)(any
? s
- 1 : nptr
);
237 /* Glob-style pattern matching. */
238 static int JimStringMatch(const char *pattern
, int patternLen
,
239 const char *string
, int stringLen
, int nocase
)
244 while (pattern
[1] == '*') {
249 return 1; /* match */
251 if (JimStringMatch(pattern
+1, patternLen
-1,
252 string
, stringLen
, nocase
))
253 return 1; /* match */
257 return 0; /* no match */
261 return 0; /* no match */
271 not = pattern
[0] == '^';
278 if (pattern
[0] == '\\') {
281 if (pattern
[0] == string
[0])
283 } else if (pattern
[0] == ']') {
285 } else if (patternLen
== 0) {
289 } else if (pattern
[1] == '-' && patternLen
>= 3) {
290 int start
= pattern
[0];
291 int end
= pattern
[2];
299 start
= tolower(start
);
305 if (c
>= start
&& c
<= end
)
309 if (pattern
[0] == string
[0])
312 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
322 return 0; /* no match */
328 if (patternLen
>= 2) {
335 if (pattern
[0] != string
[0])
336 return 0; /* no match */
338 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
339 return 0; /* no match */
347 if (stringLen
== 0) {
348 while(*pattern
== '*') {
355 if (patternLen
== 0 && stringLen
== 0)
360 int JimStringCompare(const char *s1
, int l1
, const char *s2
, int l2
,
363 unsigned char *u1
= (unsigned char*) s1
, *u2
= (unsigned char*) s2
;
369 u1
++; u2
++; l1
--; l2
--;
371 if (!l1
&& !l2
) return 0;
375 if (tolower((int)*u1
) != tolower((int)*u2
))
376 return tolower((int)*u1
)-tolower((int)*u2
);
377 u1
++; u2
++; l1
--; l2
--;
379 if (!l1
&& !l2
) return 0;
384 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
385 * The index of the first occurrence of s1 in s2 is returned.
386 * If s1 is not found inside s2, -1 is returned. */
387 int JimStringFirst(const char *s1
, int l1
, const char *s2
, int l2
, int index
)
391 if (!l1
|| !l2
|| l1
> l2
) return -1;
392 if (index
< 0) index
= 0;
394 for (i
= index
; i
<= l2
-l1
; i
++) {
395 if (memcmp(s2
, s1
, l1
) == 0)
402 int Jim_WideToString(char *buf
, jim_wide wideValue
)
404 const char *fmt
= "%" JIM_WIDE_MODIFIER
;
405 return sprintf(buf
, fmt
, wideValue
);
408 int Jim_StringToWide(const char *str
, jim_wide
*widePtr
, int base
)
412 #ifdef HAVE_LONG_LONG
413 *widePtr
= JimStrtoll(str
, &endptr
, base
);
415 *widePtr
= strtol(str
, &endptr
, base
);
417 if ((str
[0] == '\0') || (str
== endptr
) )
419 if (endptr
[0] != '\0') {
421 if (!isspace((int)*endptr
))
429 int Jim_StringToIndex(const char *str
, int *intPtr
)
433 *intPtr
= strtol(str
, &endptr
, 10);
434 if ( (str
[0] == '\0') || (str
== endptr
) )
436 if (endptr
[0] != '\0') {
438 if (!isspace((int)*endptr
))
446 /* The string representation of references has two features in order
447 * to make the GC faster. The first is that every reference starts
448 * with a non common character '~', in order to make the string matching
449 * fater. The second is that the reference string rep his 32 characters
450 * in length, this allows to avoid to check every object with a string
451 * repr < 32, and usually there are many of this objects. */
453 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
455 static int JimFormatReference(char *buf
, Jim_Reference
*refPtr
, jim_wide id
)
457 const char *fmt
= "<reference.<%s>.%020" JIM_WIDE_MODIFIER
">";
458 sprintf(buf
, fmt
, refPtr
->tag
, id
);
459 return JIM_REFERENCE_SPACE
;
462 int Jim_DoubleToString(char *buf
, double doubleValue
)
467 len
= sprintf(buf
, "%.17g", doubleValue
);
470 if (*s
== '.') return len
;
473 /* Add a final ".0" if it's a number. But not
475 if (isdigit((int)buf
[0])
476 || ((buf
[0] == '-' || buf
[0] == '+')
477 && isdigit((int)buf
[1]))) {
486 int Jim_StringToDouble(const char *str
, double *doublePtr
)
490 *doublePtr
= strtod(str
, &endptr
);
491 if (str
[0] == '\0' || endptr
[0] != '\0' || (str
== endptr
) )
496 static jim_wide
JimPowWide(jim_wide b
, jim_wide e
)
499 if ((b
==0 && e
!=0) || (e
<0)) return 0;
500 for(i
=0; i
<e
; i
++) {res
*= b
;}
504 /* -----------------------------------------------------------------------------
506 * ---------------------------------------------------------------------------*/
508 /* Note that 'interp' may be NULL if not available in the
509 * context of the panic. It's only useful to get the error
510 * file descriptor, it will default to stderr otherwise. */
511 void Jim_Panic(Jim_Interp
*interp
, const char *fmt
, ...)
517 * Send it here first.. Assuming STDIO still works
519 fprintf(stderr
, JIM_NL
"JIM INTERPRETER PANIC: ");
520 vfprintf(stderr
, fmt
, ap
);
521 fprintf(stderr
, JIM_NL JIM_NL
);
524 #ifdef HAVE_BACKTRACE
530 size
= backtrace(array
, 40);
531 strings
= backtrace_symbols(array
, size
);
532 for (i
= 0; i
< size
; i
++)
533 fprintf(fp
,"[backtrace] %s" JIM_NL
, strings
[i
]);
534 fprintf(fp
,"[backtrace] Include the above lines and the output" JIM_NL
);
535 fprintf(fp
,"[backtrace] of 'nm <executable>' in the bug report." JIM_NL
);
539 /* This may actually crash... we do it last */
540 if( interp
&& interp
->cookie_stderr
){
541 Jim_fprintf( interp
, interp
->cookie_stderr
, JIM_NL
"JIM INTERPRETER PANIC: ");
542 Jim_vfprintf( interp
, interp
->cookie_stderr
, fmt
, ap
);
543 Jim_fprintf( interp
, interp
->cookie_stderr
, JIM_NL JIM_NL
);
548 /* -----------------------------------------------------------------------------
550 * ---------------------------------------------------------------------------*/
552 /* Macro used for memory debugging.
553 * In order for they to work you have to rename Jim_Alloc into _Jim_Alloc
554 * and similary for Jim_Realloc and Jim_Free */
556 #define Jim_Alloc(s) (printf("%s %d: Jim_Alloc(%d)\n",__FILE__,__LINE__,s),_Jim_Alloc(s))
557 #define Jim_Free(p) (printf("%s %d: Jim_Free(%p)\n",__FILE__,__LINE__,p),_Jim_Free(p))
558 #define Jim_Realloc(p,s) (printf("%s %d: Jim_Realloc(%p,%d)\n",__FILE__,__LINE__,p,s),_Jim_Realloc(p,s))
561 void *Jim_Alloc(int size
)
563 /* We allocate zero length arrayes, etc. to use a single orthogonal codepath */
566 void *p
= malloc(size
);
568 Jim_Panic(NULL
,"malloc: Out of memory");
572 void Jim_Free(void *ptr
) {
576 void *Jim_Realloc(void *ptr
, int size
)
578 /* We allocate zero length arrayes, etc. to use a single orthogonal codepath */
581 void *p
= realloc(ptr
, size
);
583 Jim_Panic(NULL
,"realloc: Out of memory");
587 char *Jim_StrDup(const char *s
)
590 char *copy
= Jim_Alloc(l
+1);
592 memcpy(copy
, s
, l
+1);
596 char *Jim_StrDupLen(const char *s
, int l
)
598 char *copy
= Jim_Alloc(l
+1);
600 memcpy(copy
, s
, l
+1);
601 copy
[l
] = 0; /* Just to be sure, original could be substring */
605 /* -----------------------------------------------------------------------------
606 * Time related functions
607 * ---------------------------------------------------------------------------*/
608 /* Returns microseconds of CPU used since start. */
609 static jim_wide
JimClock(void)
611 #if (defined WIN32) && !(defined JIM_ANSIC)
613 QueryPerformanceFrequency(&f
);
614 QueryPerformanceCounter(&t
);
615 return (long)((t
.QuadPart
* 1000000) / f
.QuadPart
);
617 clock_t clocks
= clock();
619 return (long)(clocks
*(1000000/CLOCKS_PER_SEC
));
623 /* -----------------------------------------------------------------------------
625 * ---------------------------------------------------------------------------*/
627 /* -------------------------- private prototypes ---------------------------- */
628 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
);
629 static unsigned int JimHashTableNextPower(unsigned int size
);
630 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
);
632 /* -------------------------- hash functions -------------------------------- */
634 /* Thomas Wang's 32 bit Mix Function */
635 unsigned int Jim_IntHashFunction(unsigned int key
)
646 /* Identity hash function for integer keys */
647 unsigned int Jim_IdentityHashFunction(unsigned int key
)
652 /* Generic hash function (we are using to multiply by 9 and add the byte
654 unsigned int Jim_GenHashFunction(const unsigned char *buf
, int len
)
662 /* ----------------------------- API implementation ------------------------- */
663 /* reset an hashtable already initialized with ht_init().
664 * NOTE: This function should only called by ht_destroy(). */
665 static void JimResetHashTable(Jim_HashTable
*ht
)
674 /* Initialize the hash table */
675 int Jim_InitHashTable(Jim_HashTable
*ht
, Jim_HashTableType
*type
,
678 JimResetHashTable(ht
);
680 ht
->privdata
= privDataPtr
;
684 /* Resize the table to the minimal size that contains all the elements,
685 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
686 int Jim_ResizeHashTable(Jim_HashTable
*ht
)
688 int minimal
= ht
->used
;
690 if (minimal
< JIM_HT_INITIAL_SIZE
)
691 minimal
= JIM_HT_INITIAL_SIZE
;
692 return Jim_ExpandHashTable(ht
, minimal
);
695 /* Expand or create the hashtable */
696 int Jim_ExpandHashTable(Jim_HashTable
*ht
, unsigned int size
)
698 Jim_HashTable n
; /* the new hashtable */
699 unsigned int realsize
= JimHashTableNextPower(size
), i
;
701 /* the size is invalid if it is smaller than the number of
702 * elements already inside the hashtable */
703 if (ht
->used
>= size
)
706 Jim_InitHashTable(&n
, ht
->type
, ht
->privdata
);
708 n
.sizemask
= realsize
-1;
709 n
.table
= Jim_Alloc(realsize
*sizeof(Jim_HashEntry
*));
711 /* Initialize all the pointers to NULL */
712 memset(n
.table
, 0, realsize
*sizeof(Jim_HashEntry
*));
714 /* Copy all the elements from the old to the new table:
715 * note that if the old hash table is empty ht->size is zero,
716 * so Jim_ExpandHashTable just creates an hash table. */
718 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
719 Jim_HashEntry
*he
, *nextHe
;
721 if (ht
->table
[i
] == NULL
) continue;
723 /* For each hash entry on this slot... */
729 /* Get the new element index */
730 h
= Jim_HashKey(ht
, he
->key
) & n
.sizemask
;
731 he
->next
= n
.table
[h
];
734 /* Pass to the next element */
738 assert(ht
->used
== 0);
741 /* Remap the new hashtable in the old */
746 /* Add an element to the target hash table */
747 int Jim_AddHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
750 Jim_HashEntry
*entry
;
752 /* Get the index of the new element, or -1 if
753 * the element already exists. */
754 if ((index
= JimInsertHashEntry(ht
, key
)) == -1)
757 /* Allocates the memory and stores key */
758 entry
= Jim_Alloc(sizeof(*entry
));
759 entry
->next
= ht
->table
[index
];
760 ht
->table
[index
] = entry
;
762 /* Set the hash entry fields. */
763 Jim_SetHashKey(ht
, entry
, key
);
764 Jim_SetHashVal(ht
, entry
, val
);
769 /* Add an element, discarding the old if the key already exists */
770 int Jim_ReplaceHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
772 Jim_HashEntry
*entry
;
774 /* Try to add the element. If the key
775 * does not exists Jim_AddHashEntry will suceed. */
776 if (Jim_AddHashEntry(ht
, key
, val
) == JIM_OK
)
778 /* It already exists, get the entry */
779 entry
= Jim_FindHashEntry(ht
, key
);
780 /* Free the old value and set the new one */
781 Jim_FreeEntryVal(ht
, entry
);
782 Jim_SetHashVal(ht
, entry
, val
);
786 /* Search and remove an element */
787 int Jim_DeleteHashEntry(Jim_HashTable
*ht
, const void *key
)
790 Jim_HashEntry
*he
, *prevHe
;
794 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
799 if (Jim_CompareHashKeys(ht
, key
, he
->key
)) {
800 /* Unlink the element from the list */
802 prevHe
->next
= he
->next
;
804 ht
->table
[h
] = he
->next
;
805 Jim_FreeEntryKey(ht
, he
);
806 Jim_FreeEntryVal(ht
, he
);
814 return JIM_ERR
; /* not found */
817 /* Destroy an entire hash table */
818 int Jim_FreeHashTable(Jim_HashTable
*ht
)
822 /* Free all the elements */
823 for (i
= 0; i
< ht
->size
&& ht
->used
> 0; i
++) {
824 Jim_HashEntry
*he
, *nextHe
;
826 if ((he
= ht
->table
[i
]) == NULL
) continue;
829 Jim_FreeEntryKey(ht
, he
);
830 Jim_FreeEntryVal(ht
, he
);
836 /* Free the table and the allocated cache structure */
838 /* Re-initialize the table */
839 JimResetHashTable(ht
);
840 return JIM_OK
; /* never fails */
843 Jim_HashEntry
*Jim_FindHashEntry(Jim_HashTable
*ht
, const void *key
)
848 if (ht
->size
== 0) return NULL
;
849 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
852 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
859 Jim_HashTableIterator
*Jim_GetHashTableIterator(Jim_HashTable
*ht
)
861 Jim_HashTableIterator
*iter
= Jim_Alloc(sizeof(*iter
));
866 iter
->nextEntry
= NULL
;
870 Jim_HashEntry
*Jim_NextHashEntry(Jim_HashTableIterator
*iter
)
873 if (iter
->entry
== NULL
) {
876 (signed)iter
->ht
->size
) break;
877 iter
->entry
= iter
->ht
->table
[iter
->index
];
879 iter
->entry
= iter
->nextEntry
;
882 /* We need to save the 'next' here, the iterator user
883 * may delete the entry we are returning. */
884 iter
->nextEntry
= iter
->entry
->next
;
891 /* ------------------------- private functions ------------------------------ */
893 /* Expand the hash table if needed */
894 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
)
896 /* If the hash table is empty expand it to the intial size,
897 * if the table is "full" dobule its size. */
899 return Jim_ExpandHashTable(ht
, JIM_HT_INITIAL_SIZE
);
900 if (ht
->size
== ht
->used
)
901 return Jim_ExpandHashTable(ht
, ht
->size
*2);
905 /* Our hash table capability is a power of two */
906 static unsigned int JimHashTableNextPower(unsigned int size
)
908 unsigned int i
= JIM_HT_INITIAL_SIZE
;
910 if (size
>= 2147483648U)
919 /* Returns the index of a free slot that can be populated with
920 * an hash entry for the given 'key'.
921 * If the key already exists, -1 is returned. */
922 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
)
927 /* Expand the hashtable if needed */
928 if (JimExpandHashTableIfNeeded(ht
) == JIM_ERR
)
930 /* Compute the key hash value */
931 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
932 /* Search if this slot does not already contain the given key */
935 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
942 /* ----------------------- StringCopy Hash Table Type ------------------------*/
944 static unsigned int JimStringCopyHTHashFunction(const void *key
)
946 return Jim_GenHashFunction(key
, strlen(key
));
949 static const void *JimStringCopyHTKeyDup(void *privdata
, const void *key
)
951 int len
= strlen(key
);
952 char *copy
= Jim_Alloc(len
+1);
953 JIM_NOTUSED(privdata
);
955 memcpy(copy
, key
, len
);
960 static void *JimStringKeyValCopyHTValDup(void *privdata
, const void *val
)
962 int len
= strlen(val
);
963 char *copy
= Jim_Alloc(len
+1);
964 JIM_NOTUSED(privdata
);
966 memcpy(copy
, val
, len
);
971 static int JimStringCopyHTKeyCompare(void *privdata
, const void *key1
,
974 JIM_NOTUSED(privdata
);
976 return strcmp(key1
, key2
) == 0;
979 static void JimStringCopyHTKeyDestructor(void *privdata
, const void *key
)
981 JIM_NOTUSED(privdata
);
983 Jim_Free((void*)key
); /* ATTENTION: const cast */
986 static void JimStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
988 JIM_NOTUSED(privdata
);
990 Jim_Free((void*)val
); /* ATTENTION: const cast */
993 static Jim_HashTableType JimStringCopyHashTableType
= {
994 JimStringCopyHTHashFunction
, /* hash function */
995 JimStringCopyHTKeyDup
, /* key dup */
997 JimStringCopyHTKeyCompare
, /* key compare */
998 JimStringCopyHTKeyDestructor
, /* key destructor */
999 NULL
/* val destructor */
1002 /* This is like StringCopy but does not auto-duplicate the key.
1003 * It's used for intepreter's shared strings. */
1004 static Jim_HashTableType JimSharedStringsHashTableType
= {
1005 JimStringCopyHTHashFunction
, /* hash function */
1008 JimStringCopyHTKeyCompare
, /* key compare */
1009 JimStringCopyHTKeyDestructor
, /* key destructor */
1010 NULL
/* val destructor */
1013 /* This is like StringCopy but also automatically handle dynamic
1014 * allocated C strings as values. */
1015 static Jim_HashTableType JimStringKeyValCopyHashTableType
= {
1016 JimStringCopyHTHashFunction
, /* hash function */
1017 JimStringCopyHTKeyDup
, /* key dup */
1018 JimStringKeyValCopyHTValDup
, /* val dup */
1019 JimStringCopyHTKeyCompare
, /* key compare */
1020 JimStringCopyHTKeyDestructor
, /* key destructor */
1021 JimStringKeyValCopyHTValDestructor
, /* val destructor */
1024 typedef struct AssocDataValue
{
1025 Jim_InterpDeleteProc
*delProc
;
1029 static void JimAssocDataHashTableValueDestructor(void *privdata
, void *data
)
1031 AssocDataValue
*assocPtr
= (AssocDataValue
*)data
;
1032 if (assocPtr
->delProc
!= NULL
)
1033 assocPtr
->delProc((Jim_Interp
*)privdata
, assocPtr
->data
);
1037 static Jim_HashTableType JimAssocDataHashTableType
= {
1038 JimStringCopyHTHashFunction
, /* hash function */
1039 JimStringCopyHTKeyDup
, /* key dup */
1041 JimStringCopyHTKeyCompare
, /* key compare */
1042 JimStringCopyHTKeyDestructor
, /* key destructor */
1043 JimAssocDataHashTableValueDestructor
/* val destructor */
1046 /* -----------------------------------------------------------------------------
1047 * Stack - This is a simple generic stack implementation. It is used for
1048 * example in the 'expr' expression compiler.
1049 * ---------------------------------------------------------------------------*/
1050 void Jim_InitStack(Jim_Stack
*stack
)
1054 stack
->vector
= NULL
;
1057 void Jim_FreeStack(Jim_Stack
*stack
)
1059 Jim_Free(stack
->vector
);
1062 int Jim_StackLen(Jim_Stack
*stack
)
1067 void Jim_StackPush(Jim_Stack
*stack
, void *element
) {
1068 int neededLen
= stack
->len
+1;
1069 if (neededLen
> stack
->maxlen
) {
1070 stack
->maxlen
= neededLen
*2;
1071 stack
->vector
= Jim_Realloc(stack
->vector
, sizeof(void*)*stack
->maxlen
);
1073 stack
->vector
[stack
->len
] = element
;
1077 void *Jim_StackPop(Jim_Stack
*stack
)
1079 if (stack
->len
== 0) return NULL
;
1081 return stack
->vector
[stack
->len
];
1084 void *Jim_StackPeek(Jim_Stack
*stack
)
1086 if (stack
->len
== 0) return NULL
;
1087 return stack
->vector
[stack
->len
-1];
1090 void Jim_FreeStackElements(Jim_Stack
*stack
, void (*freeFunc
)(void *ptr
))
1094 for (i
= 0; i
< stack
->len
; i
++)
1095 freeFunc(stack
->vector
[i
]);
1098 /* -----------------------------------------------------------------------------
1100 * ---------------------------------------------------------------------------*/
1103 #define JIM_TT_NONE -1 /* No token returned */
1104 #define JIM_TT_STR 0 /* simple string */
1105 #define JIM_TT_ESC 1 /* string that needs escape chars conversion */
1106 #define JIM_TT_VAR 2 /* var substitution */
1107 #define JIM_TT_DICTSUGAR 3 /* Syntax sugar for [dict get], $foo(bar) */
1108 #define JIM_TT_CMD 4 /* command substitution */
1109 #define JIM_TT_SEP 5 /* word separator */
1110 #define JIM_TT_EOL 6 /* line separator */
1112 /* Additional token types needed for expressions */
1113 #define JIM_TT_SUBEXPR_START 7
1114 #define JIM_TT_SUBEXPR_END 8
1115 #define JIM_TT_EXPR_NUMBER 9
1116 #define JIM_TT_EXPR_OPERATOR 10
1119 #define JIM_PS_DEF 0 /* Default state */
1120 #define JIM_PS_QUOTE 1 /* Inside "" */
1122 /* Parser context structure. The same context is used both to parse
1123 * Tcl scripts and lists. */
1124 struct JimParserCtx
{
1125 const char *prg
; /* Program text */
1126 const char *p
; /* Pointer to the point of the program we are parsing */
1127 int len
; /* Left length of 'prg' */
1128 int linenr
; /* Current line number */
1130 const char *tend
; /* Returned token is at tstart-tend in 'prg'. */
1131 int tline
; /* Line number of the returned token */
1132 int tt
; /* Token type */
1133 int eof
; /* Non zero if EOF condition is true. */
1134 int state
; /* Parser state */
1135 int comment
; /* Non zero if the next chars may be a comment. */
1138 #define JimParserEof(c) ((c)->eof)
1139 #define JimParserTstart(c) ((c)->tstart)
1140 #define JimParserTend(c) ((c)->tend)
1141 #define JimParserTtype(c) ((c)->tt)
1142 #define JimParserTline(c) ((c)->tline)
1144 static int JimParseScript(struct JimParserCtx
*pc
);
1145 static int JimParseSep(struct JimParserCtx
*pc
);
1146 static int JimParseEol(struct JimParserCtx
*pc
);
1147 static int JimParseCmd(struct JimParserCtx
*pc
);
1148 static int JimParseVar(struct JimParserCtx
*pc
);
1149 static int JimParseBrace(struct JimParserCtx
*pc
);
1150 static int JimParseStr(struct JimParserCtx
*pc
);
1151 static int JimParseComment(struct JimParserCtx
*pc
);
1152 static char *JimParserGetToken(struct JimParserCtx
*pc
,
1153 int *lenPtr
, int *typePtr
, int *linePtr
);
1155 /* Initialize a parser context.
1156 * 'prg' is a pointer to the program text, linenr is the line
1157 * number of the first line contained in the program. */
1158 void JimParserInit(struct JimParserCtx
*pc
, const char *prg
,
1159 int len
, int linenr
)
1167 pc
->tt
= JIM_TT_NONE
;
1169 pc
->state
= JIM_PS_DEF
;
1170 pc
->linenr
= linenr
;
1174 int JimParseScript(struct JimParserCtx
*pc
)
1176 while(1) { /* the while is used to reiterate with continue if needed */
1180 pc
->tline
= pc
->linenr
;
1181 pc
->tt
= JIM_TT_EOL
;
1187 if (*(pc
->p
+1) == '\n')
1188 return JimParseSep(pc
);
1191 return JimParseStr(pc
);
1197 if (pc
->state
== JIM_PS_DEF
)
1198 return JimParseSep(pc
);
1201 return JimParseStr(pc
);
1207 if (pc
->state
== JIM_PS_DEF
)
1208 return JimParseEol(pc
);
1210 return JimParseStr(pc
);
1214 return JimParseCmd(pc
);
1218 if (JimParseVar(pc
) == JIM_ERR
) {
1219 pc
->tstart
= pc
->tend
= pc
->p
++; pc
->len
--;
1220 pc
->tline
= pc
->linenr
;
1221 pc
->tt
= JIM_TT_STR
;
1228 JimParseComment(pc
);
1231 return JimParseStr(pc
);
1235 return JimParseStr(pc
);
1242 int JimParseSep(struct JimParserCtx
*pc
)
1245 pc
->tline
= pc
->linenr
;
1246 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' ||
1247 (*pc
->p
== '\\' && *(pc
->p
+1) == '\n')) {
1248 if (*pc
->p
== '\\') {
1255 pc
->tt
= JIM_TT_SEP
;
1259 int JimParseEol(struct JimParserCtx
*pc
)
1262 pc
->tline
= pc
->linenr
;
1263 while (*pc
->p
== ' ' || *pc
->p
== '\n' ||
1264 *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== ';') {
1270 pc
->tt
= JIM_TT_EOL
;
1274 /* Todo. Don't stop if ']' appears inside {} or quoted.
1275 * Also should handle the case of puts [string length "]"] */
1276 int JimParseCmd(struct JimParserCtx
*pc
)
1281 pc
->tstart
= ++pc
->p
; pc
->len
--;
1282 pc
->tline
= pc
->linenr
;
1286 } else if (*pc
->p
== '[' && blevel
== 0) {
1288 } else if (*pc
->p
== ']' && blevel
== 0) {
1291 } else if (*pc
->p
== '\\') {
1293 } else if (*pc
->p
== '{') {
1295 } else if (*pc
->p
== '}') {
1298 } else if (*pc
->p
== '\n')
1303 pc
->tt
= JIM_TT_CMD
;
1304 if (*pc
->p
== ']') {
1310 int JimParseVar(struct JimParserCtx
*pc
)
1312 int brace
= 0, stop
= 0, ttype
= JIM_TT_VAR
;
1314 pc
->tstart
= ++pc
->p
; pc
->len
--; /* skip the $ */
1315 pc
->tline
= pc
->linenr
;
1316 if (*pc
->p
== '{') {
1317 pc
->tstart
= ++pc
->p
; pc
->len
--;
1322 if (*pc
->p
== '}' || pc
->len
== 0) {
1327 else if (*pc
->p
== '\n')
1337 if (!((*pc
->p
>= 'a' && *pc
->p
<= 'z') ||
1338 (*pc
->p
>= 'A' && *pc
->p
<= 'Z') ||
1339 (*pc
->p
>= '0' && *pc
->p
<= '9') || *pc
->p
== '_'))
1345 /* Parse [dict get] syntax sugar. */
1346 if (*pc
->p
== '(') {
1347 while (*pc
->p
!= ')' && pc
->len
) {
1349 if (*pc
->p
== '\\' && pc
->len
>= 2) {
1350 pc
->p
+= 2; pc
->len
-= 2;
1353 if (*pc
->p
!= '\0') {
1356 ttype
= JIM_TT_DICTSUGAR
;
1360 /* Check if we parsed just the '$' character.
1361 * That's not a variable so an error is returned
1362 * to tell the state machine to consider this '$' just
1364 if (pc
->tstart
== pc
->p
) {
1372 int JimParseBrace(struct JimParserCtx
*pc
)
1376 pc
->tstart
= ++pc
->p
; pc
->len
--;
1377 pc
->tline
= pc
->linenr
;
1379 if (*pc
->p
== '\\' && pc
->len
>= 2) {
1383 } else if (*pc
->p
== '{') {
1385 } else if (pc
->len
== 0 || *pc
->p
== '}') {
1387 if (pc
->len
== 0 || level
== 0) {
1392 pc
->tt
= JIM_TT_STR
;
1395 } else if (*pc
->p
== '\n') {
1400 return JIM_OK
; /* unreached */
1403 int JimParseStr(struct JimParserCtx
*pc
)
1405 int newword
= (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1406 pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_STR
);
1407 if (newword
&& *pc
->p
== '{') {
1408 return JimParseBrace(pc
);
1409 } else if (newword
&& *pc
->p
== '"') {
1410 pc
->state
= JIM_PS_QUOTE
;
1414 pc
->tline
= pc
->linenr
;
1418 pc
->tt
= JIM_TT_ESC
;
1423 if (pc
->state
== JIM_PS_DEF
&&
1424 *(pc
->p
+1) == '\n') {
1426 pc
->tt
= JIM_TT_ESC
;
1436 pc
->tt
= JIM_TT_ESC
;
1443 if (pc
->state
== JIM_PS_DEF
) {
1445 pc
->tt
= JIM_TT_ESC
;
1447 } else if (*pc
->p
== '\n') {
1452 if (pc
->state
== JIM_PS_QUOTE
) {
1454 pc
->tt
= JIM_TT_ESC
;
1456 pc
->state
= JIM_PS_DEF
;
1463 return JIM_OK
; /* unreached */
1466 int JimParseComment(struct JimParserCtx
*pc
)
1469 if (*pc
->p
== '\n') {
1471 if (*(pc
->p
-1) != '\\') {
1481 /* xdigitval and odigitval are helper functions for JimParserGetToken() */
1482 static int xdigitval(int c
)
1484 if (c
>= '0' && c
<= '9') return c
-'0';
1485 if (c
>= 'a' && c
<= 'f') return c
-'a'+10;
1486 if (c
>= 'A' && c
<= 'F') return c
-'A'+10;
1490 static int odigitval(int c
)
1492 if (c
>= '0' && c
<= '7') return c
-'0';
1496 /* Perform Tcl escape substitution of 's', storing the result
1497 * string into 'dest'. The escaped string is guaranteed to
1498 * be the same length or shorted than the source string.
1499 * Slen is the length of the string at 's', if it's -1 the string
1500 * length will be calculated by the function.
1502 * The function returns the length of the resulting string. */
1503 static int JimEscape(char *dest
, const char *s
, int slen
)
1511 for (i
= 0; i
< slen
; i
++) {
1515 case 'a': *p
++ = 0x7; i
++; break;
1516 case 'b': *p
++ = 0x8; i
++; break;
1517 case 'f': *p
++ = 0xc; i
++; break;
1518 case 'n': *p
++ = 0xa; i
++; break;
1519 case 'r': *p
++ = 0xd; i
++; break;
1520 case 't': *p
++ = 0x9; i
++; break;
1521 case 'v': *p
++ = 0xb; i
++; break;
1522 case '\0': *p
++ = '\\'; i
++; break;
1523 case '\n': *p
++ = ' '; i
++; break;
1525 if (s
[i
+1] == 'x') {
1527 int c
= xdigitval(s
[i
+2]);
1534 c
= xdigitval(s
[i
+3]);
1544 } else if (s
[i
+1] >= '0' && s
[i
+1] <= '7')
1547 int c
= odigitval(s
[i
+1]);
1549 c
= odigitval(s
[i
+2]);
1556 c
= odigitval(s
[i
+3]);
1582 /* Returns a dynamically allocated copy of the current token in the
1583 * parser context. The function perform conversion of escapes if
1584 * the token is of type JIM_TT_ESC.
1586 * Note that after the conversion, tokens that are grouped with
1587 * braces in the source code, are always recognizable from the
1588 * identical string obtained in a different way from the type.
1590 * For exmple the string:
1594 * will return as first token "expand", of type JIM_TT_STR
1600 * will return as first token "expand", of type JIM_TT_ESC
1602 char *JimParserGetToken(struct JimParserCtx
*pc
,
1603 int *lenPtr
, int *typePtr
, int *linePtr
)
1605 const char *start
, *end
;
1609 start
= JimParserTstart(pc
);
1610 end
= JimParserTend(pc
);
1612 if (lenPtr
) *lenPtr
= 0;
1613 if (typePtr
) *typePtr
= JimParserTtype(pc
);
1614 if (linePtr
) *linePtr
= JimParserTline(pc
);
1615 token
= Jim_Alloc(1);
1619 len
= (end
-start
)+1;
1620 token
= Jim_Alloc(len
+1);
1621 if (JimParserTtype(pc
) != JIM_TT_ESC
) {
1622 /* No escape conversion needed? Just copy it. */
1623 memcpy(token
, start
, len
);
1626 /* Else convert the escape chars. */
1627 len
= JimEscape(token
, start
, len
);
1629 if (lenPtr
) *lenPtr
= len
;
1630 if (typePtr
) *typePtr
= JimParserTtype(pc
);
1631 if (linePtr
) *linePtr
= JimParserTline(pc
);
1635 /* The following functin is not really part of the parsing engine of Jim,
1636 * but it somewhat related. Given an string and its length, it tries
1637 * to guess if the script is complete or there are instead " " or { }
1638 * open and not completed. This is useful for interactive shells
1639 * implementation and for [info complete].
1641 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1642 * '{' on scripts incomplete missing one or more '}' to be balanced.
1643 * '"' on scripts incomplete missing a '"' char.
1645 * If the script is complete, 1 is returned, otherwise 0. */
1646 int Jim_ScriptIsComplete(const char *s
, int len
, char *stateCharPtr
)
1660 } else if (state
== '"') {
1667 } else if (state
== ' ') {
1684 *stateCharPtr
= state
;
1685 return state
== ' ';
1688 /* -----------------------------------------------------------------------------
1690 * ---------------------------------------------------------------------------*/
1691 static int JimParseListSep(struct JimParserCtx
*pc
);
1692 static int JimParseListStr(struct JimParserCtx
*pc
);
1694 int JimParseList(struct JimParserCtx
*pc
)
1697 pc
->tstart
= pc
->tend
= pc
->p
;
1698 pc
->tline
= pc
->linenr
;
1699 pc
->tt
= JIM_TT_EOL
;
1708 if (pc
->state
== JIM_PS_DEF
)
1709 return JimParseListSep(pc
);
1711 return JimParseListStr(pc
);
1714 return JimParseListStr(pc
);
1720 int JimParseListSep(struct JimParserCtx
*pc
)
1723 pc
->tline
= pc
->linenr
;
1724 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== '\n')
1729 pc
->tt
= JIM_TT_SEP
;
1733 int JimParseListStr(struct JimParserCtx
*pc
)
1735 int newword
= (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1736 pc
->tt
== JIM_TT_NONE
);
1737 if (newword
&& *pc
->p
== '{') {
1738 return JimParseBrace(pc
);
1739 } else if (newword
&& *pc
->p
== '"') {
1740 pc
->state
= JIM_PS_QUOTE
;
1744 pc
->tline
= pc
->linenr
;
1748 pc
->tt
= JIM_TT_ESC
;
1759 if (pc
->state
== JIM_PS_DEF
) {
1761 pc
->tt
= JIM_TT_ESC
;
1763 } else if (*pc
->p
== '\n') {
1768 if (pc
->state
== JIM_PS_QUOTE
) {
1770 pc
->tt
= JIM_TT_ESC
;
1772 pc
->state
= JIM_PS_DEF
;
1779 return JIM_OK
; /* unreached */
1782 /* -----------------------------------------------------------------------------
1783 * Jim_Obj related functions
1784 * ---------------------------------------------------------------------------*/
1786 /* Return a new initialized object. */
1787 Jim_Obj
*Jim_NewObj(Jim_Interp
*interp
)
1791 /* -- Check if there are objects in the free list -- */
1792 if (interp
->freeList
!= NULL
) {
1793 /* -- Unlink the object from the free list -- */
1794 objPtr
= interp
->freeList
;
1795 interp
->freeList
= objPtr
->nextObjPtr
;
1797 /* -- No ready to use objects: allocate a new one -- */
1798 objPtr
= Jim_Alloc(sizeof(*objPtr
));
1801 /* Object is returned with refCount of 0. Every
1802 * kind of GC implemented should take care to don't try
1803 * to scan objects with refCount == 0. */
1804 objPtr
->refCount
= 0;
1805 /* All the other fields are left not initialized to save time.
1806 * The caller will probably want set they to the right
1809 /* -- Put the object into the live list -- */
1810 objPtr
->prevObjPtr
= NULL
;
1811 objPtr
->nextObjPtr
= interp
->liveList
;
1812 if (interp
->liveList
)
1813 interp
->liveList
->prevObjPtr
= objPtr
;
1814 interp
->liveList
= objPtr
;
1819 /* Free an object. Actually objects are never freed, but
1820 * just moved to the free objects list, where they will be
1821 * reused by Jim_NewObj(). */
1822 void Jim_FreeObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
1824 /* Check if the object was already freed, panic. */
1825 if (objPtr
->refCount
!= 0) {
1826 Jim_Panic(interp
,"!!!Object %p freed with bad refcount %d", objPtr
,
1829 /* Free the internal representation */
1830 Jim_FreeIntRep(interp
, objPtr
);
1831 /* Free the string representation */
1832 if (objPtr
->bytes
!= NULL
) {
1833 if (objPtr
->bytes
!= JimEmptyStringRep
)
1834 Jim_Free(objPtr
->bytes
);
1836 /* Unlink the object from the live objects list */
1837 if (objPtr
->prevObjPtr
)
1838 objPtr
->prevObjPtr
->nextObjPtr
= objPtr
->nextObjPtr
;
1839 if (objPtr
->nextObjPtr
)
1840 objPtr
->nextObjPtr
->prevObjPtr
= objPtr
->prevObjPtr
;
1841 if (interp
->liveList
== objPtr
)
1842 interp
->liveList
= objPtr
->nextObjPtr
;
1843 /* Link the object into the free objects list */
1844 objPtr
->prevObjPtr
= NULL
;
1845 objPtr
->nextObjPtr
= interp
->freeList
;
1846 if (interp
->freeList
)
1847 interp
->freeList
->prevObjPtr
= objPtr
;
1848 interp
->freeList
= objPtr
;
1849 objPtr
->refCount
= -1;
1852 /* Invalidate the string representation of an object. */
1853 void Jim_InvalidateStringRep(Jim_Obj
*objPtr
)
1855 if (objPtr
->bytes
!= NULL
) {
1856 if (objPtr
->bytes
!= JimEmptyStringRep
)
1857 Jim_Free(objPtr
->bytes
);
1859 objPtr
->bytes
= NULL
;
1862 #define Jim_SetStringRep(o, b, l) \
1863 do { (o)->bytes = b; (o)->length = l; } while (0)
1865 /* Set the initial string representation for an object.
1866 * Does not try to free an old one. */
1867 void Jim_InitStringRep(Jim_Obj
*objPtr
, const char *bytes
, int length
)
1870 objPtr
->bytes
= JimEmptyStringRep
;
1873 objPtr
->bytes
= Jim_Alloc(length
+1);
1874 objPtr
->length
= length
;
1875 memcpy(objPtr
->bytes
, bytes
, length
);
1876 objPtr
->bytes
[length
] = '\0';
1880 /* Duplicate an object. The returned object has refcount = 0. */
1881 Jim_Obj
*Jim_DuplicateObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
1885 dupPtr
= Jim_NewObj(interp
);
1886 if (objPtr
->bytes
== NULL
) {
1887 /* Object does not have a valid string representation. */
1888 dupPtr
->bytes
= NULL
;
1890 Jim_InitStringRep(dupPtr
, objPtr
->bytes
, objPtr
->length
);
1892 if (objPtr
->typePtr
!= NULL
) {
1893 if (objPtr
->typePtr
->dupIntRepProc
== NULL
) {
1894 dupPtr
->internalRep
= objPtr
->internalRep
;
1896 objPtr
->typePtr
->dupIntRepProc(interp
, objPtr
, dupPtr
);
1898 dupPtr
->typePtr
= objPtr
->typePtr
;
1900 dupPtr
->typePtr
= NULL
;
1905 /* Return the string representation for objPtr. If the object
1906 * string representation is invalid, calls the method to create
1907 * a new one starting from the internal representation of the object. */
1908 const char *Jim_GetString(Jim_Obj
*objPtr
, int *lenPtr
)
1910 if (objPtr
->bytes
== NULL
) {
1911 /* Invalid string repr. Generate it. */
1912 if (objPtr
->typePtr
->updateStringProc
== NULL
) {
1913 Jim_Panic(NULL
,"UpdataStringProc called against '%s' type.",
1914 objPtr
->typePtr
->name
);
1916 objPtr
->typePtr
->updateStringProc(objPtr
);
1919 *lenPtr
= objPtr
->length
;
1920 return objPtr
->bytes
;
1923 /* Just returns the length of the object's string rep */
1924 int Jim_Length(Jim_Obj
*objPtr
)
1928 Jim_GetString(objPtr
, &len
);
1932 /* -----------------------------------------------------------------------------
1934 * ---------------------------------------------------------------------------*/
1935 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
1936 static int SetStringFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
1938 static Jim_ObjType stringObjType
= {
1941 DupStringInternalRep
,
1943 JIM_TYPE_REFERENCES
,
1946 void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
1948 JIM_NOTUSED(interp
);
1950 /* This is a bit subtle: the only caller of this function
1951 * should be Jim_DuplicateObj(), that will copy the
1952 * string representaion. After the copy, the duplicated
1953 * object will not have more room in teh buffer than
1954 * srcPtr->length bytes. So we just set it to length. */
1955 dupPtr
->internalRep
.strValue
.maxLength
= srcPtr
->length
;
1958 int SetStringFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
1960 /* Get a fresh string representation. */
1961 (void) Jim_GetString(objPtr
, NULL
);
1962 /* Free any other internal representation. */
1963 Jim_FreeIntRep(interp
, objPtr
);
1964 /* Set it as string, i.e. just set the maxLength field. */
1965 objPtr
->typePtr
= &stringObjType
;
1966 objPtr
->internalRep
.strValue
.maxLength
= objPtr
->length
;
1970 Jim_Obj
*Jim_NewStringObj(Jim_Interp
*interp
, const char *s
, int len
)
1972 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
1976 /* Alloc/Set the string rep. */
1978 objPtr
->bytes
= JimEmptyStringRep
;
1981 objPtr
->bytes
= Jim_Alloc(len
+1);
1982 objPtr
->length
= len
;
1983 memcpy(objPtr
->bytes
, s
, len
);
1984 objPtr
->bytes
[len
] = '\0';
1987 /* No typePtr field for the vanilla string object. */
1988 objPtr
->typePtr
= NULL
;
1992 /* This version does not try to duplicate the 's' pointer, but
1993 * use it directly. */
1994 Jim_Obj
*Jim_NewStringObjNoAlloc(Jim_Interp
*interp
, char *s
, int len
)
1996 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2000 Jim_SetStringRep(objPtr
, s
, len
);
2001 objPtr
->typePtr
= NULL
;
2005 /* Low-level string append. Use it only against objects
2006 * of type "string". */
2007 void StringAppendString(Jim_Obj
*objPtr
, const char *str
, int len
)
2013 needlen
= objPtr
->length
+ len
;
2014 if (objPtr
->internalRep
.strValue
.maxLength
< needlen
||
2015 objPtr
->internalRep
.strValue
.maxLength
== 0) {
2016 if (objPtr
->bytes
== JimEmptyStringRep
) {
2017 objPtr
->bytes
= Jim_Alloc((needlen
*2)+1);
2019 objPtr
->bytes
= Jim_Realloc(objPtr
->bytes
, (needlen
*2)+1);
2021 objPtr
->internalRep
.strValue
.maxLength
= needlen
*2;
2023 memcpy(objPtr
->bytes
+ objPtr
->length
, str
, len
);
2024 objPtr
->bytes
[objPtr
->length
+len
] = '\0';
2025 objPtr
->length
+= len
;
2028 /* Low-level wrapper to append an object. */
2029 void StringAppendObj(Jim_Obj
*objPtr
, Jim_Obj
*appendObjPtr
)
2034 str
= Jim_GetString(appendObjPtr
, &len
);
2035 StringAppendString(objPtr
, str
, len
);
2038 /* Higher level API to append strings to objects. */
2039 void Jim_AppendString(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
,
2042 if (Jim_IsShared(objPtr
))
2043 Jim_Panic(interp
,"Jim_AppendString called with shared object");
2044 if (objPtr
->typePtr
!= &stringObjType
)
2045 SetStringFromAny(interp
, objPtr
);
2046 StringAppendString(objPtr
, str
, len
);
2049 void Jim_AppendString_sprintf( Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *fmt
, ... )
2054 va_start( ap
, fmt
);
2055 buf
= jim_vasprintf( fmt
, ap
);
2059 Jim_AppendString( interp
, objPtr
, buf
, -1 );
2060 jim_vasprintf_done(buf
);
2065 void Jim_AppendObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2066 Jim_Obj
*appendObjPtr
)
2071 str
= Jim_GetString(appendObjPtr
, &len
);
2072 Jim_AppendString(interp
, objPtr
, str
, len
);
2075 void Jim_AppendStrings(Jim_Interp
*interp
, Jim_Obj
*objPtr
, ...)
2079 if (objPtr
->typePtr
!= &stringObjType
)
2080 SetStringFromAny(interp
, objPtr
);
2081 va_start(ap
, objPtr
);
2083 char *s
= va_arg(ap
, char*);
2085 if (s
== NULL
) break;
2086 Jim_AppendString(interp
, objPtr
, s
, -1);
2091 int Jim_StringEqObj(Jim_Obj
*aObjPtr
, Jim_Obj
*bObjPtr
, int nocase
)
2093 const char *aStr
, *bStr
;
2096 if (aObjPtr
== bObjPtr
) return 1;
2097 aStr
= Jim_GetString(aObjPtr
, &aLen
);
2098 bStr
= Jim_GetString(bObjPtr
, &bLen
);
2099 if (aLen
!= bLen
) return 0;
2101 return memcmp(aStr
, bStr
, aLen
) == 0;
2102 for (i
= 0; i
< aLen
; i
++) {
2103 if (tolower((int)aStr
[i
]) != tolower((int)bStr
[i
]))
2109 int Jim_StringMatchObj(Jim_Obj
*patternObjPtr
, Jim_Obj
*objPtr
,
2112 const char *pattern
, *string
;
2113 int patternLen
, stringLen
;
2115 pattern
= Jim_GetString(patternObjPtr
, &patternLen
);
2116 string
= Jim_GetString(objPtr
, &stringLen
);
2117 return JimStringMatch(pattern
, patternLen
, string
, stringLen
, nocase
);
2120 int Jim_StringCompareObj(Jim_Obj
*firstObjPtr
,
2121 Jim_Obj
*secondObjPtr
, int nocase
)
2123 const char *s1
, *s2
;
2126 s1
= Jim_GetString(firstObjPtr
, &l1
);
2127 s2
= Jim_GetString(secondObjPtr
, &l2
);
2128 return JimStringCompare(s1
, l1
, s2
, l2
, nocase
);
2131 /* Convert a range, as returned by Jim_GetRange(), into
2132 * an absolute index into an object of the specified length.
2133 * This function may return negative values, or values
2134 * bigger or equal to the length of the list if the index
2135 * is out of range. */
2136 static int JimRelToAbsIndex(int len
, int index
)
2143 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2144 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2145 * for implementation of commands like [string range] and [lrange].
2147 * The resulting range is guaranteed to address valid elements of
2149 static void JimRelToAbsRange(int len
, int first
, int last
,
2150 int *firstPtr
, int *lastPtr
, int *rangeLenPtr
)
2157 rangeLen
= last
-first
+1;
2164 rangeLen
-= (last
-(len
-1));
2169 if (rangeLen
< 0) rangeLen
= 0;
2173 *rangeLenPtr
= rangeLen
;
2176 Jim_Obj
*Jim_StringRangeObj(Jim_Interp
*interp
,
2177 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2183 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2184 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2186 str
= Jim_GetString(strObjPtr
, &len
);
2187 first
= JimRelToAbsIndex(len
, first
);
2188 last
= JimRelToAbsIndex(len
, last
);
2189 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
2190 return Jim_NewStringObj(interp
, str
+first
, rangeLen
);
2193 static Jim_Obj
*JimStringToLower(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2195 char *buf
= Jim_Alloc(strObjPtr
->length
+1);
2198 memcpy(buf
, strObjPtr
->bytes
, strObjPtr
->length
+1);
2199 for (i
= 0; i
< strObjPtr
->length
; i
++)
2200 buf
[i
] = tolower(buf
[i
]);
2201 return Jim_NewStringObjNoAlloc(interp
, buf
, strObjPtr
->length
);
2204 static Jim_Obj
*JimStringToUpper(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2206 char *buf
= Jim_Alloc(strObjPtr
->length
+1);
2209 memcpy(buf
, strObjPtr
->bytes
, strObjPtr
->length
+1);
2210 for (i
= 0; i
< strObjPtr
->length
; i
++)
2211 buf
[i
] = toupper(buf
[i
]);
2212 return Jim_NewStringObjNoAlloc(interp
, buf
, strObjPtr
->length
);
2215 /* This is the core of the [format] command.
2216 * TODO: Lots of things work - via a hack
2217 * However, no format item can be >= JIM_MAX_FMT
2219 #define JIM_MAX_FMT 2048
2220 static Jim_Obj
*Jim_FormatString_Inner(Jim_Interp
*interp
, Jim_Obj
*fmtObjPtr
,
2221 int objc
, Jim_Obj
*const *objv
, char *sprintf_buf
)
2223 const char *fmt
, *_fmt
;
2228 fmt
= Jim_GetString(fmtObjPtr
, &fmtLen
);
2230 resObjPtr
= Jim_NewStringObj(interp
, "", 0);
2232 const char *p
= fmt
;
2236 /* we cheat and use Sprintf()! */
2250 while (*fmt
!= '%' && fmtLen
) {
2253 Jim_AppendString(interp
, resObjPtr
, p
, fmt
-p
);
2256 fmt
++; fmtLen
--; /* skip '%' */
2265 prec
= -1; /* not found yet */
2272 case 'b': /* binary - not all printfs() do this */
2273 case 's': /* string */
2274 case 'i': /* integer */
2275 case 'd': /* decimal */
2277 case 'X': /* CAP hex */
2278 case 'c': /* char */
2279 case 'o': /* octal */
2280 case 'u': /* unsigned */
2281 case 'f': /* float */
2285 case '0': /* zero pad */
2295 case ' ': /* sign space */
2325 while( isdigit(*fmt
) && (fmtLen
> 0) ){
2326 accum
= (accum
* 10) + (*fmt
- '0');
2337 /* suck up the next item as an integer */
2341 goto not_enough_args
;
2343 if( Jim_GetWide(interp
,objv
[0],&wideValue
)== JIM_ERR
){
2344 Jim_FreeNewObj(interp
, resObjPtr
);
2351 /* man 3 printf says */
2352 /* if prec is negative, it is zero */
2371 Jim_FreeNewObj(interp
, resObjPtr
);
2372 Jim_SetResultString(interp
,
2373 "not enough arguments for all format specifiers", -1);
2381 * Create the formatter
2382 * cause we cheat and use sprintf()
2392 /* PLUS overrides */
2402 sprintf( cp
, "%d", width
);
2406 /* did we find a period? */
2410 /* did something occur after the period? */
2412 sprintf( cp
, "%d", prec
);
2418 /* here we do the work */
2419 /* actually - we make sprintf() do it for us */
2424 /* BUG: we do not handled embeded NULLs */
2425 snprintf( sprintf_buf
, JIM_MAX_FMT
, fmt_str
, Jim_GetString( objv
[0], NULL
));
2430 if (Jim_GetWide(interp
, objv
[0], &wideValue
) == JIM_ERR
) {
2431 Jim_FreeNewObj(interp
, resObjPtr
);
2434 c
= (char) wideValue
;
2435 snprintf( sprintf_buf
, JIM_MAX_FMT
, fmt_str
, c
);
2445 if( Jim_GetDouble( interp
, objv
[0], &doubleValue
) == JIM_ERR
){
2446 Jim_FreeNewObj( interp
, resObjPtr
);
2449 snprintf( sprintf_buf
, JIM_MAX_FMT
, fmt_str
, doubleValue
);
2457 /* jim widevaluse are 64bit */
2458 if( sizeof(jim_wide
) == sizeof(long long) ){
2466 if (Jim_GetWide(interp
, objv
[0], &wideValue
) == JIM_ERR
) {
2467 Jim_FreeNewObj(interp
, resObjPtr
);
2470 snprintf(sprintf_buf
, JIM_MAX_FMT
, fmt_str
, wideValue
);
2473 sprintf_buf
[0] = '%';
2475 objv
--; /* undo the objv++ below */
2478 spec
[0] = *fmt
; spec
[1] = '\0';
2479 Jim_FreeNewObj(interp
, resObjPtr
);
2480 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
2481 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
2482 "bad field specifier \"", spec
, "\"", NULL
);
2485 /* force terminate */
2487 printf("FMT was: %s\n", fmt_str
);
2488 printf("RES was: |%s|\n", sprintf_buf
);
2491 sprintf_buf
[ JIM_MAX_FMT
- 1] = 0;
2492 Jim_AppendString( interp
, resObjPtr
, sprintf_buf
, strlen(sprintf_buf
) );
2501 Jim_Obj
*Jim_FormatString(Jim_Interp
*interp
, Jim_Obj
*fmtObjPtr
,
2502 int objc
, Jim_Obj
*const *objv
)
2504 char *sprintf_buf
=malloc(JIM_MAX_FMT
);
2505 Jim_Obj
*t
=Jim_FormatString_Inner(interp
, fmtObjPtr
, objc
, objv
, sprintf_buf
);
2510 /* -----------------------------------------------------------------------------
2511 * Compared String Object
2512 * ---------------------------------------------------------------------------*/
2514 /* This is strange object that allows to compare a C literal string
2515 * with a Jim object in very short time if the same comparison is done
2516 * multiple times. For example every time the [if] command is executed,
2517 * Jim has to check if a given argument is "else". This comparions if
2518 * the code has no errors are true most of the times, so we can cache
2519 * inside the object the pointer of the string of the last matching
2520 * comparison. Because most C compilers perform literal sharing,
2521 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2522 * this works pretty well even if comparisons are at different places
2523 * inside the C code. */
2525 static Jim_ObjType comparedStringObjType
= {
2530 JIM_TYPE_REFERENCES
,
2533 /* The only way this object is exposed to the API is via the following
2534 * function. Returns true if the string and the object string repr.
2535 * are the same, otherwise zero is returned.
2537 * Note: this isn't binary safe, but it hardly needs to be.*/
2538 int Jim_CompareStringImmediate(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2541 if (objPtr
->typePtr
== &comparedStringObjType
&&
2542 objPtr
->internalRep
.ptr
== str
)
2545 const char *objStr
= Jim_GetString(objPtr
, NULL
);
2546 if (strcmp(str
, objStr
) != 0) return 0;
2547 if (objPtr
->typePtr
!= &comparedStringObjType
) {
2548 Jim_FreeIntRep(interp
, objPtr
);
2549 objPtr
->typePtr
= &comparedStringObjType
;
2551 objPtr
->internalRep
.ptr
= (char*)str
; /*ATTENTION: const cast */
2556 int qsortCompareStringPointers(const void *a
, const void *b
)
2558 char * const *sa
= (char * const *)a
;
2559 char * const *sb
= (char * const *)b
;
2560 return strcmp(*sa
, *sb
);
2563 int Jim_GetEnum(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2564 const char * const *tablePtr
, int *indexPtr
, const char *name
, int flags
)
2566 const char * const *entryPtr
= NULL
;
2567 char **tablePtrSorted
;
2571 for (entryPtr
= tablePtr
, i
= 0; *entryPtr
!= NULL
; entryPtr
++, i
++) {
2572 if (Jim_CompareStringImmediate(interp
, objPtr
, *entryPtr
)) {
2576 count
++; /* If nothing matches, this will reach the len of tablePtr */
2578 if (flags
& JIM_ERRMSG
) {
2581 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
2582 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
2583 "bad ", name
, " \"", Jim_GetString(objPtr
, NULL
), "\": must be one of ",
2585 tablePtrSorted
= Jim_Alloc(sizeof(char*)*count
);
2586 memcpy(tablePtrSorted
, tablePtr
, sizeof(char*)*count
);
2587 qsort(tablePtrSorted
, count
, sizeof(char*), qsortCompareStringPointers
);
2588 for (i
= 0; i
< count
; i
++) {
2589 if (i
+1 == count
&& count
> 1)
2590 Jim_AppendString(interp
, Jim_GetResult(interp
), "or ", -1);
2591 Jim_AppendString(interp
, Jim_GetResult(interp
),
2592 tablePtrSorted
[i
], -1);
2594 Jim_AppendString(interp
, Jim_GetResult(interp
), ", ", -1);
2596 Jim_Free(tablePtrSorted
);
2601 int Jim_GetNvp(Jim_Interp
*interp
,
2603 const Jim_Nvp
*nvp_table
,
2604 const Jim_Nvp
** result
)
2609 e
= Jim_Nvp_name2value_obj( interp
, nvp_table
, objPtr
, &n
);
2614 /* Success? found? */
2617 *result
= (Jim_Nvp
*)n
;
2624 /* -----------------------------------------------------------------------------
2627 * This object is just a string from the language point of view, but
2628 * in the internal representation it contains the filename and line number
2629 * where this given token was read. This information is used by
2630 * Jim_EvalObj() if the object passed happens to be of type "source".
2632 * This allows to propagate the information about line numbers and file
2633 * names and give error messages with absolute line numbers.
2635 * Note that this object uses shared strings for filenames, and the
2636 * pointer to the filename together with the line number is taken into
2637 * the space for the "inline" internal represenation of the Jim_Object,
2638 * so there is almost memory zero-overhead.
2640 * Also the object will be converted to something else if the given
2641 * token it represents in the source file is not something to be
2642 * evaluated (not a script), and will be specialized in some other way,
2643 * so the time overhead is alzo null.
2644 * ---------------------------------------------------------------------------*/
2646 static void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2647 static void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2649 static Jim_ObjType sourceObjType
= {
2651 FreeSourceInternalRep
,
2652 DupSourceInternalRep
,
2654 JIM_TYPE_REFERENCES
,
2657 void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2659 Jim_ReleaseSharedString(interp
,
2660 objPtr
->internalRep
.sourceValue
.fileName
);
2663 void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2665 dupPtr
->internalRep
.sourceValue
.fileName
=
2666 Jim_GetSharedString(interp
,
2667 srcPtr
->internalRep
.sourceValue
.fileName
);
2668 dupPtr
->internalRep
.sourceValue
.lineNumber
=
2669 dupPtr
->internalRep
.sourceValue
.lineNumber
;
2670 dupPtr
->typePtr
= &sourceObjType
;
2673 static void JimSetSourceInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2674 const char *fileName
, int lineNumber
)
2676 if (Jim_IsShared(objPtr
))
2677 Jim_Panic(interp
,"JimSetSourceInfo called with shared object");
2678 if (objPtr
->typePtr
!= NULL
)
2679 Jim_Panic(interp
,"JimSetSourceInfo called with typePtr != NULL");
2680 objPtr
->internalRep
.sourceValue
.fileName
=
2681 Jim_GetSharedString(interp
, fileName
);
2682 objPtr
->internalRep
.sourceValue
.lineNumber
= lineNumber
;
2683 objPtr
->typePtr
= &sourceObjType
;
2686 /* -----------------------------------------------------------------------------
2688 * ---------------------------------------------------------------------------*/
2690 #define JIM_CMDSTRUCT_EXPAND -1
2692 static void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2693 static void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2694 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2696 static Jim_ObjType scriptObjType
= {
2698 FreeScriptInternalRep
,
2699 DupScriptInternalRep
,
2701 JIM_TYPE_REFERENCES
,
2704 /* The ScriptToken structure represents every token into a scriptObj.
2705 * Every token contains an associated Jim_Obj that can be specialized
2706 * by commands operating on it. */
2707 typedef struct ScriptToken
{
2713 /* This is the script object internal representation. An array of
2714 * ScriptToken structures, with an associated command structure array.
2715 * The command structure is a pre-computed representation of the
2716 * command length and arguments structure as a simple liner array
2719 * For example the script:
2722 * set $i $x$y [foo]BAR
2724 * will produce a ScriptObj with the following Tokens:
2741 * This is a description of the tokens, separators, and of lines.
2742 * The command structure instead represents the number of arguments
2743 * of every command, followed by the tokens of which every argument
2744 * is composed. So for the example script, the cmdstruct array will
2749 * Because "puts hello" has two args (2), composed of single tokens (1 1)
2750 * While "set $i $x$y [foo]BAR" has four (4) args, the first two
2751 * composed of single tokens (1 1) and the last two of double tokens
2754 * The precomputation of the command structure makes Jim_Eval() faster,
2755 * and simpler because there aren't dynamic lengths / allocations.
2757 * -- {expand} handling --
2759 * Expand is handled in a special way. When a command
2760 * contains at least an argument with the {expand} prefix,
2761 * the command structure presents a -1 before the integer
2762 * describing the number of arguments. This is used in order
2763 * to send the command exection to a different path in case
2764 * of {expand} and guarantee a fast path for the more common
2765 * case. Also, the integers describing the number of tokens
2766 * are expressed with negative sign, to allow for fast check
2767 * of what's an {expand}-prefixed argument and what not.
2769 * For example the command:
2771 * list {expand}{1 2}
2773 * Will produce the following cmdstruct array:
2777 * -- the substFlags field of the structure --
2779 * The scriptObj structure is used to represent both "script" objects
2780 * and "subst" objects. In the second case, the cmdStruct related
2781 * fields are not used at all, but there is an additional field used
2782 * that is 'substFlags': this represents the flags used to turn
2783 * the string into the intenral representation used to perform the
2784 * substitution. If this flags are not what the application requires
2785 * the scriptObj is created again. For example the script:
2787 * subst -nocommands $string
2788 * subst -novariables $string
2790 * Will recreate the internal representation of the $string object
2793 typedef struct ScriptObj
{
2794 int len
; /* Length as number of tokens. */
2795 int commands
; /* number of top-level commands in script. */
2796 ScriptToken
*token
; /* Tokens array. */
2797 int *cmdStruct
; /* commands structure */
2798 int csLen
; /* length of the cmdStruct array. */
2799 int substFlags
; /* flags used for the compilation of "subst" objects */
2800 int inUse
; /* Used to share a ScriptObj. Currently
2801 only used by Jim_EvalObj() as protection against
2802 shimmering of the currently evaluated object. */
2806 void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2809 struct ScriptObj
*script
= (void*) objPtr
->internalRep
.ptr
;
2812 if (script
->inUse
!= 0) return;
2813 for (i
= 0; i
< script
->len
; i
++) {
2814 if (script
->token
[i
].objPtr
!= NULL
)
2815 Jim_DecrRefCount(interp
, script
->token
[i
].objPtr
);
2817 Jim_Free(script
->token
);
2818 Jim_Free(script
->cmdStruct
);
2819 Jim_Free(script
->fileName
);
2823 void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2825 JIM_NOTUSED(interp
);
2826 JIM_NOTUSED(srcPtr
);
2828 /* Just returns an simple string. */
2829 dupPtr
->typePtr
= NULL
;
2832 /* Add a new token to the internal repr of a script object */
2833 static void ScriptObjAddToken(Jim_Interp
*interp
, struct ScriptObj
*script
,
2834 char *strtoken
, int len
, int type
, char *filename
, int linenr
)
2837 struct ScriptToken
*token
;
2839 prevtype
= (script
->len
== 0) ? JIM_TT_EOL
: \
2840 script
->token
[script
->len
-1].type
;
2841 /* Skip tokens without meaning, like words separators
2842 * following a word separator or an end of command and
2844 if (prevtype
== JIM_TT_EOL
) {
2845 if (type
== JIM_TT_EOL
|| type
== JIM_TT_SEP
) {
2849 } else if (prevtype
== JIM_TT_SEP
) {
2850 if (type
== JIM_TT_SEP
) {
2853 } else if (type
== JIM_TT_EOL
) {
2854 /* If an EOL is following by a SEP, drop the previous
2857 Jim_DecrRefCount(interp
, script
->token
[script
->len
].objPtr
);
2859 } else if (prevtype
!= JIM_TT_EOL
&& prevtype
!= JIM_TT_SEP
&&
2860 type
== JIM_TT_ESC
&& len
== 0)
2862 /* Don't add empty tokens used in interpolation */
2866 /* Make space for a new istruction */
2868 script
->token
= Jim_Realloc(script
->token
,
2869 sizeof(ScriptToken
)*script
->len
);
2870 /* Initialize the new token */
2871 token
= script
->token
+(script
->len
-1);
2873 /* Every object is intially as a string, but the
2874 * internal type may be specialized during execution of the
2876 token
->objPtr
= Jim_NewStringObjNoAlloc(interp
, strtoken
, len
);
2877 /* To add source info to SEP and EOL tokens is useless because
2878 * they will never by called as arguments of Jim_EvalObj(). */
2879 if (filename
&& type
!= JIM_TT_SEP
&& type
!= JIM_TT_EOL
)
2880 JimSetSourceInfo(interp
, token
->objPtr
, filename
, linenr
);
2881 Jim_IncrRefCount(token
->objPtr
);
2882 token
->linenr
= linenr
;
2885 /* Add an integer into the command structure field of the script object. */
2886 static void ScriptObjAddInt(struct ScriptObj
*script
, int val
)
2889 script
->cmdStruct
= Jim_Realloc(script
->cmdStruct
,
2890 sizeof(int)*script
->csLen
);
2891 script
->cmdStruct
[script
->csLen
-1] = val
;
2894 /* Search a Jim_Obj contained in 'script' with the same stinrg repr.
2895 * of objPtr. Search nested script objects recursively. */
2896 static Jim_Obj
*ScriptSearchLiteral(Jim_Interp
*interp
, ScriptObj
*script
,
2897 ScriptObj
*scriptBarrier
, Jim_Obj
*objPtr
)
2901 for (i
= 0; i
< script
->len
; i
++) {
2902 if (script
->token
[i
].objPtr
!= objPtr
&&
2903 Jim_StringEqObj(script
->token
[i
].objPtr
, objPtr
, 0)) {
2904 return script
->token
[i
].objPtr
;
2906 /* Enter recursively on scripts only if the object
2907 * is not the same as the one we are searching for
2908 * shared occurrences. */
2909 if (script
->token
[i
].objPtr
->typePtr
== &scriptObjType
&&
2910 script
->token
[i
].objPtr
!= objPtr
) {
2911 Jim_Obj
*foundObjPtr
;
2913 ScriptObj
*subScript
=
2914 script
->token
[i
].objPtr
->internalRep
.ptr
;
2915 /* Don't recursively enter the script we are trying
2916 * to make shared to avoid circular references. */
2917 if (subScript
== scriptBarrier
) continue;
2918 if (subScript
!= script
) {
2920 ScriptSearchLiteral(interp
, subScript
,
2921 scriptBarrier
, objPtr
);
2922 if (foundObjPtr
!= NULL
)
2930 /* Share literals of a script recursively sharing sub-scripts literals. */
2931 static void ScriptShareLiterals(Jim_Interp
*interp
, ScriptObj
*script
,
2932 ScriptObj
*topLevelScript
)
2937 /* Try to share with toplevel object. */
2938 if (topLevelScript
!= NULL
) {
2939 for (i
= 0; i
< script
->len
; i
++) {
2940 Jim_Obj
*foundObjPtr
;
2941 char *str
= script
->token
[i
].objPtr
->bytes
;
2943 if (script
->token
[i
].objPtr
->refCount
!= 1) continue;
2944 if (script
->token
[i
].objPtr
->typePtr
== &scriptObjType
) continue;
2945 if (strchr(str
, ' ') || strchr(str
, '\n')) continue;
2946 foundObjPtr
= ScriptSearchLiteral(interp
,
2948 script
, /* barrier */
2949 script
->token
[i
].objPtr
);
2950 if (foundObjPtr
!= NULL
) {
2951 Jim_IncrRefCount(foundObjPtr
);
2952 Jim_DecrRefCount(interp
,
2953 script
->token
[i
].objPtr
);
2954 script
->token
[i
].objPtr
= foundObjPtr
;
2958 /* Try to share locally */
2959 for (i
= 0; i
< script
->len
; i
++) {
2960 char *str
= script
->token
[i
].objPtr
->bytes
;
2962 if (script
->token
[i
].objPtr
->refCount
!= 1) continue;
2963 if (strchr(str
, ' ') || strchr(str
, '\n')) continue;
2964 for (j
= 0; j
< script
->len
; j
++) {
2965 if (script
->token
[i
].objPtr
!=
2966 script
->token
[j
].objPtr
&&
2967 Jim_StringEqObj(script
->token
[i
].objPtr
,
2968 script
->token
[j
].objPtr
, 0))
2970 Jim_IncrRefCount(script
->token
[j
].objPtr
);
2971 Jim_DecrRefCount(interp
,
2972 script
->token
[i
].objPtr
);
2973 script
->token
[i
].objPtr
=
2974 script
->token
[j
].objPtr
;
2980 /* This method takes the string representation of an object
2981 * as a Tcl script, and generates the pre-parsed internal representation
2983 int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
2986 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
2987 struct JimParserCtx parser
;
2988 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
2990 int args
, tokens
, start
, end
, i
;
2991 int initialLineNumber
;
2992 int propagateSourceInfo
= 0;
2996 script
->commands
= 0;
2997 script
->token
= NULL
;
2998 script
->cmdStruct
= NULL
;
3000 /* Try to get information about filename / line number */
3001 if (objPtr
->typePtr
== &sourceObjType
) {
3003 Jim_StrDup(objPtr
->internalRep
.sourceValue
.fileName
);
3004 initialLineNumber
= objPtr
->internalRep
.sourceValue
.lineNumber
;
3005 propagateSourceInfo
= 1;
3007 script
->fileName
= Jim_StrDup("?");
3008 initialLineNumber
= 1;
3011 JimParserInit(&parser
, scriptText
, scriptTextLen
, initialLineNumber
);
3012 while(!JimParserEof(&parser
)) {
3014 int len
, type
, linenr
;
3016 JimParseScript(&parser
);
3017 token
= JimParserGetToken(&parser
, &len
, &type
, &linenr
);
3018 ScriptObjAddToken(interp
, script
, token
, len
, type
,
3019 propagateSourceInfo
? script
->fileName
: NULL
,
3022 token
= script
->token
;
3024 /* Compute the command structure array
3025 * (see the ScriptObj struct definition for more info) */
3026 start
= 0; /* Current command start token index */
3027 end
= -1; /* Current command end token index */
3029 int expand
= 0; /* expand flag. set to 1 on {expand} form. */
3030 int interpolation
= 0; /* set to 1 if there is at least one
3031 argument of the command obtained via
3032 interpolation of more tokens. */
3033 /* Search for the end of command, while
3034 * count the number of args. */
3036 if (start
>= script
->len
) break;
3037 args
= 1; /* Number of args in current command */
3038 while (token
[end
].type
!= JIM_TT_EOL
) {
3039 if (end
== 0 || token
[end
-1].type
== JIM_TT_SEP
||
3040 token
[end
-1].type
== JIM_TT_EOL
)
3042 if (token
[end
].type
== JIM_TT_STR
&&
3043 token
[end
+1].type
!= JIM_TT_SEP
&&
3044 token
[end
+1].type
!= JIM_TT_EOL
&&
3045 (!strcmp(token
[end
].objPtr
->bytes
, "expand") ||
3046 !strcmp(token
[end
].objPtr
->bytes
, "*")))
3049 if (token
[end
].type
== JIM_TT_SEP
)
3053 interpolation
= !((end
-start
+1) == args
*2);
3054 /* Add the 'number of arguments' info into cmdstruct.
3055 * Negative value if there is list expansion involved. */
3057 ScriptObjAddInt(script
, -1);
3058 ScriptObjAddInt(script
, args
);
3059 /* Now add info about the number of tokens. */
3060 tokens
= 0; /* Number of tokens in current argument. */
3062 for (i
= start
; i
<= end
; i
++) {
3063 if (token
[i
].type
== JIM_TT_SEP
||
3064 token
[i
].type
== JIM_TT_EOL
)
3066 if (tokens
== 1 && expand
)
3068 ScriptObjAddInt(script
,
3069 expand
? -tokens
: tokens
);
3074 } else if (tokens
== 0 && token
[i
].type
== JIM_TT_STR
&&
3075 (!strcmp(token
[i
].objPtr
->bytes
, "expand") ||
3076 !strcmp(token
[i
].objPtr
->bytes
, "*")))
3083 /* Perform literal sharing, but only for objects that appear
3084 * to be scripts written as literals inside the source code,
3085 * and not computed at runtime. Literal sharing is a costly
3086 * operation that should be done only against objects that
3087 * are likely to require compilation only the first time, and
3088 * then are executed multiple times. */
3089 if (propagateSourceInfo
&& interp
->framePtr
->procBodyObjPtr
) {
3090 Jim_Obj
*bodyObjPtr
= interp
->framePtr
->procBodyObjPtr
;
3091 if (bodyObjPtr
->typePtr
== &scriptObjType
) {
3092 ScriptObj
*bodyScript
=
3093 bodyObjPtr
->internalRep
.ptr
;
3094 ScriptShareLiterals(interp
, script
, bodyScript
);
3096 } else if (propagateSourceInfo
) {
3097 ScriptShareLiterals(interp
, script
, NULL
);
3099 /* Free the old internal rep and set the new one. */
3100 Jim_FreeIntRep(interp
, objPtr
);
3101 Jim_SetIntRepPtr(objPtr
, script
);
3102 objPtr
->typePtr
= &scriptObjType
;
3106 ScriptObj
*Jim_GetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3108 if (objPtr
->typePtr
!= &scriptObjType
) {
3109 SetScriptFromAny(interp
, objPtr
);
3111 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
3114 /* -----------------------------------------------------------------------------
3116 * ---------------------------------------------------------------------------*/
3118 /* Commands HashTable Type.
3120 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3121 static void Jim_CommandsHT_ValDestructor(void *interp
, void *val
)
3123 Jim_Cmd
*cmdPtr
= (void*) val
;
3125 if (cmdPtr
->cmdProc
== NULL
) {
3126 Jim_DecrRefCount(interp
, cmdPtr
->argListObjPtr
);
3127 Jim_DecrRefCount(interp
, cmdPtr
->bodyObjPtr
);
3128 if (cmdPtr
->staticVars
) {
3129 Jim_FreeHashTable(cmdPtr
->staticVars
);
3130 Jim_Free(cmdPtr
->staticVars
);
3132 } else if (cmdPtr
->delProc
!= NULL
) {
3133 /* If it was a C coded command, call the delProc if any */
3134 cmdPtr
->delProc(interp
, cmdPtr
->privData
);
3139 static Jim_HashTableType JimCommandsHashTableType
= {
3140 JimStringCopyHTHashFunction
, /* hash function */
3141 JimStringCopyHTKeyDup
, /* key dup */
3143 JimStringCopyHTKeyCompare
, /* key compare */
3144 JimStringCopyHTKeyDestructor
, /* key destructor */
3145 Jim_CommandsHT_ValDestructor
/* val destructor */
3148 /* ------------------------- Commands related functions --------------------- */
3150 int Jim_CreateCommand(Jim_Interp
*interp
, const char *cmdName
,
3151 Jim_CmdProc cmdProc
, void *privData
, Jim_DelCmdProc delProc
)
3156 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3157 if (he
== NULL
) { /* New command to create */
3158 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3159 cmdPtr
->cmdProc
= cmdProc
;
3160 cmdPtr
->privData
= privData
;
3161 cmdPtr
->delProc
= delProc
;
3162 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3164 Jim_InterpIncrProcEpoch(interp
);
3165 /* Free the arglist/body objects if it was a Tcl procedure */
3167 if (cmdPtr
->cmdProc
== NULL
) {
3168 Jim_DecrRefCount(interp
, cmdPtr
->argListObjPtr
);
3169 Jim_DecrRefCount(interp
, cmdPtr
->bodyObjPtr
);
3170 if (cmdPtr
->staticVars
) {
3171 Jim_FreeHashTable(cmdPtr
->staticVars
);
3172 Jim_Free(cmdPtr
->staticVars
);
3174 cmdPtr
->staticVars
= NULL
;
3175 } else if (cmdPtr
->delProc
!= NULL
) {
3176 /* If it was a C coded command, call the delProc if any */
3177 cmdPtr
->delProc(interp
, cmdPtr
->privData
);
3179 cmdPtr
->cmdProc
= cmdProc
;
3180 cmdPtr
->privData
= privData
;
3182 /* There is no need to increment the 'proc epoch' because
3183 * creation of a new procedure can never affect existing
3184 * cached commands. We don't do negative caching. */
3188 int Jim_CreateProcedure(Jim_Interp
*interp
, const char *cmdName
,
3189 Jim_Obj
*argListObjPtr
, Jim_Obj
*staticsListObjPtr
, Jim_Obj
*bodyObjPtr
,
3190 int arityMin
, int arityMax
)
3194 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3195 cmdPtr
->cmdProc
= NULL
; /* Not a C coded command */
3196 cmdPtr
->argListObjPtr
= argListObjPtr
;
3197 cmdPtr
->bodyObjPtr
= bodyObjPtr
;
3198 Jim_IncrRefCount(argListObjPtr
);
3199 Jim_IncrRefCount(bodyObjPtr
);
3200 cmdPtr
->arityMin
= arityMin
;
3201 cmdPtr
->arityMax
= arityMax
;
3202 cmdPtr
->staticVars
= NULL
;
3204 /* Create the statics hash table. */
3205 if (staticsListObjPtr
) {
3208 Jim_ListLength(interp
, staticsListObjPtr
, &len
);
3210 cmdPtr
->staticVars
= Jim_Alloc(sizeof(Jim_HashTable
));
3211 Jim_InitHashTable(cmdPtr
->staticVars
, &JimVariablesHashTableType
,
3213 for (i
= 0; i
< len
; i
++) {
3214 Jim_Obj
*objPtr
, *initObjPtr
, *nameObjPtr
;
3218 Jim_ListIndex(interp
, staticsListObjPtr
, i
, &objPtr
, JIM_NONE
);
3219 /* Check if it's composed of two elements. */
3220 Jim_ListLength(interp
, objPtr
, &subLen
);
3221 if (subLen
== 1 || subLen
== 2) {
3222 /* Try to get the variable value from the current
3224 Jim_ListIndex(interp
, objPtr
, 0, &nameObjPtr
, JIM_NONE
);
3226 initObjPtr
= Jim_GetVariable(interp
, nameObjPtr
,
3228 if (initObjPtr
== NULL
) {
3229 Jim_SetResult(interp
,
3230 Jim_NewEmptyStringObj(interp
));
3231 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3232 "variable for initialization of static \"",
3233 Jim_GetString(nameObjPtr
, NULL
),
3234 "\" not found in the local context",
3239 Jim_ListIndex(interp
, objPtr
, 1, &initObjPtr
, JIM_NONE
);
3241 varPtr
= Jim_Alloc(sizeof(*varPtr
));
3242 varPtr
->objPtr
= initObjPtr
;
3243 Jim_IncrRefCount(initObjPtr
);
3244 varPtr
->linkFramePtr
= NULL
;
3245 if (Jim_AddHashEntry(cmdPtr
->staticVars
,
3246 Jim_GetString(nameObjPtr
, NULL
),
3249 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
3250 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3251 "static variable name \"",
3252 Jim_GetString(objPtr
, NULL
), "\"",
3253 " duplicated in statics list", NULL
);
3254 Jim_DecrRefCount(interp
, initObjPtr
);
3259 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
3260 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3261 "too many fields in static specifier \"",
3262 objPtr
, "\"", NULL
);
3269 /* Add the new command */
3271 /* it may already exist, so we try to delete the old one */
3272 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) != JIM_ERR
) {
3273 /* There was an old procedure with the same name, this requires
3274 * a 'proc epoch' update. */
3275 Jim_InterpIncrProcEpoch(interp
);
3277 /* If a procedure with the same name didn't existed there is no need
3278 * to increment the 'proc epoch' because creation of a new procedure
3279 * can never affect existing cached commands. We don't do
3280 * negative caching. */
3281 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3285 Jim_FreeHashTable(cmdPtr
->staticVars
);
3286 Jim_Free(cmdPtr
->staticVars
);
3287 Jim_DecrRefCount(interp
, argListObjPtr
);
3288 Jim_DecrRefCount(interp
, bodyObjPtr
);
3293 int Jim_DeleteCommand(Jim_Interp
*interp
, const char *cmdName
)
3295 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) == JIM_ERR
)
3297 Jim_InterpIncrProcEpoch(interp
);
3301 int Jim_RenameCommand(Jim_Interp
*interp
, const char *oldName
,
3302 const char *newName
)
3306 Jim_Cmd
*copyCmdPtr
;
3308 if (newName
[0] == '\0') /* Delete! */
3309 return Jim_DeleteCommand(interp
, oldName
);
3311 he
= Jim_FindHashEntry(&interp
->commands
, oldName
);
3313 return JIM_ERR
; /* Invalid command name */
3315 copyCmdPtr
= Jim_Alloc(sizeof(Jim_Cmd
));
3316 *copyCmdPtr
= *cmdPtr
;
3317 /* In order to avoid that a procedure will get arglist/body/statics
3318 * freed by the hash table methods, fake a C-coded command
3319 * setting cmdPtr->cmdProc as not NULL */
3320 cmdPtr
->cmdProc
= (void*)1;
3321 /* Also make sure delProc is NULL. */
3322 cmdPtr
->delProc
= NULL
;
3323 /* Destroy the old command, and make sure the new is freed
3325 Jim_DeleteHashEntry(&interp
->commands
, oldName
);
3326 Jim_DeleteHashEntry(&interp
->commands
, newName
);
3327 /* Now the new command. We are sure it can't fail because
3328 * the target name was already freed. */
3329 Jim_AddHashEntry(&interp
->commands
, newName
, copyCmdPtr
);
3330 /* Increment the epoch */
3331 Jim_InterpIncrProcEpoch(interp
);
3335 /* -----------------------------------------------------------------------------
3337 * ---------------------------------------------------------------------------*/
3339 static int SetCommandFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3341 static Jim_ObjType commandObjType
= {
3346 JIM_TYPE_REFERENCES
,
3349 int SetCommandFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3352 const char *cmdName
;
3354 /* Get the string representation */
3355 cmdName
= Jim_GetString(objPtr
, NULL
);
3356 /* Lookup this name into the commands hash table */
3357 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3361 /* Free the old internal repr and set the new one. */
3362 Jim_FreeIntRep(interp
, objPtr
);
3363 objPtr
->typePtr
= &commandObjType
;
3364 objPtr
->internalRep
.cmdValue
.procEpoch
= interp
->procEpoch
;
3365 objPtr
->internalRep
.cmdValue
.cmdPtr
= (void*)he
->val
;
3369 /* This function returns the command structure for the command name
3370 * stored in objPtr. It tries to specialize the objPtr to contain
3371 * a cached info instead to perform the lookup into the hash table
3372 * every time. The information cached may not be uptodate, in such
3373 * a case the lookup is performed and the cache updated. */
3374 Jim_Cmd
*Jim_GetCommand(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
3376 if ((objPtr
->typePtr
!= &commandObjType
||
3377 objPtr
->internalRep
.cmdValue
.procEpoch
!= interp
->procEpoch
) &&
3378 SetCommandFromAny(interp
, objPtr
) == JIM_ERR
) {
3379 if (flags
& JIM_ERRMSG
) {
3380 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
3381 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3382 "invalid command name \"", objPtr
->bytes
, "\"",
3387 return objPtr
->internalRep
.cmdValue
.cmdPtr
;
3390 /* -----------------------------------------------------------------------------
3392 * ---------------------------------------------------------------------------*/
3394 /* Variables HashTable Type.
3396 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3397 static void JimVariablesHTValDestructor(void *interp
, void *val
)
3399 Jim_Var
*varPtr
= (void*) val
;
3401 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
3405 static Jim_HashTableType JimVariablesHashTableType
= {
3406 JimStringCopyHTHashFunction
, /* hash function */
3407 JimStringCopyHTKeyDup
, /* key dup */
3409 JimStringCopyHTKeyCompare
, /* key compare */
3410 JimStringCopyHTKeyDestructor
, /* key destructor */
3411 JimVariablesHTValDestructor
/* val destructor */
3414 /* -----------------------------------------------------------------------------
3416 * ---------------------------------------------------------------------------*/
3418 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3420 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3422 static Jim_ObjType variableObjType
= {
3427 JIM_TYPE_REFERENCES
,
3430 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3431 * is in the form "varname(key)". */
3432 static int Jim_NameIsDictSugar(const char *str
, int len
)
3436 if (len
&& str
[len
-1] == ')' && strchr(str
, '(') != NULL
)
3441 /* This method should be called only by the variable API.
3442 * It returns JIM_OK on success (variable already exists),
3443 * JIM_ERR if it does not exists, JIM_DICT_GLUE if it's not
3444 * a variable name, but syntax glue for [dict] i.e. the last
3445 * character is ')' */
3446 int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3449 const char *varName
;
3452 /* Check if the object is already an uptodate variable */
3453 if (objPtr
->typePtr
== &variableObjType
&&
3454 objPtr
->internalRep
.varValue
.callFrameId
== interp
->framePtr
->id
)
3455 return JIM_OK
; /* nothing to do */
3456 /* Get the string representation */
3457 varName
= Jim_GetString(objPtr
, &len
);
3458 /* Make sure it's not syntax glue to get/set dict. */
3459 if (Jim_NameIsDictSugar(varName
, len
))
3460 return JIM_DICT_SUGAR
;
3461 /* Lookup this name into the variables hash table */
3462 he
= Jim_FindHashEntry(&interp
->framePtr
->vars
, varName
);
3464 /* Try with static vars. */
3465 if (interp
->framePtr
->staticVars
== NULL
)
3467 if (!(he
= Jim_FindHashEntry(interp
->framePtr
->staticVars
, varName
)))
3470 /* Free the old internal repr and set the new one. */
3471 Jim_FreeIntRep(interp
, objPtr
);
3472 objPtr
->typePtr
= &variableObjType
;
3473 objPtr
->internalRep
.varValue
.callFrameId
= interp
->framePtr
->id
;
3474 objPtr
->internalRep
.varValue
.varPtr
= (void*)he
->val
;
3478 /* -------------------- Variables related functions ------------------------- */
3479 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
,
3480 Jim_Obj
*valObjPtr
);
3481 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
);
3483 /* For now that's dummy. Variables lookup should be optimized
3484 * in many ways, with caching of lookups, and possibly with
3485 * a table of pre-allocated vars in every CallFrame for local vars.
3486 * All the caching should also have an 'epoch' mechanism similar
3487 * to the one used by Tcl for procedures lookup caching. */
3489 int Jim_SetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
3495 if ((err
= SetVariableFromAny(interp
, nameObjPtr
)) != JIM_OK
) {
3496 /* Check for [dict] syntax sugar. */
3497 if (err
== JIM_DICT_SUGAR
)
3498 return JimDictSugarSet(interp
, nameObjPtr
, valObjPtr
);
3499 /* New variable to create */
3500 name
= Jim_GetString(nameObjPtr
, NULL
);
3502 var
= Jim_Alloc(sizeof(*var
));
3503 var
->objPtr
= valObjPtr
;
3504 Jim_IncrRefCount(valObjPtr
);
3505 var
->linkFramePtr
= NULL
;
3506 /* Insert the new variable */
3507 Jim_AddHashEntry(&interp
->framePtr
->vars
, name
, var
);
3508 /* Make the object int rep a variable */
3509 Jim_FreeIntRep(interp
, nameObjPtr
);
3510 nameObjPtr
->typePtr
= &variableObjType
;
3511 nameObjPtr
->internalRep
.varValue
.callFrameId
=
3512 interp
->framePtr
->id
;
3513 nameObjPtr
->internalRep
.varValue
.varPtr
= var
;
3515 var
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3516 if (var
->linkFramePtr
== NULL
) {
3517 Jim_IncrRefCount(valObjPtr
);
3518 Jim_DecrRefCount(interp
, var
->objPtr
);
3519 var
->objPtr
= valObjPtr
;
3520 } else { /* Else handle the link */
3521 Jim_CallFrame
*savedCallFrame
;
3523 savedCallFrame
= interp
->framePtr
;
3524 interp
->framePtr
= var
->linkFramePtr
;
3525 err
= Jim_SetVariable(interp
, var
->objPtr
, valObjPtr
);
3526 interp
->framePtr
= savedCallFrame
;
3534 int Jim_SetVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
3536 Jim_Obj
*nameObjPtr
;
3539 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
3540 Jim_IncrRefCount(nameObjPtr
);
3541 result
= Jim_SetVariable(interp
, nameObjPtr
, objPtr
);
3542 Jim_DecrRefCount(interp
, nameObjPtr
);
3546 int Jim_SetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
3548 Jim_CallFrame
*savedFramePtr
;
3551 savedFramePtr
= interp
->framePtr
;
3552 interp
->framePtr
= interp
->topFramePtr
;
3553 result
= Jim_SetVariableStr(interp
, name
, objPtr
);
3554 interp
->framePtr
= savedFramePtr
;
3558 int Jim_SetVariableStrWithStr(Jim_Interp
*interp
, const char *name
, const char *val
)
3560 Jim_Obj
*nameObjPtr
, *valObjPtr
;
3563 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
3564 valObjPtr
= Jim_NewStringObj(interp
, val
, -1);
3565 Jim_IncrRefCount(nameObjPtr
);
3566 Jim_IncrRefCount(valObjPtr
);
3567 result
= Jim_SetVariable(interp
, nameObjPtr
, valObjPtr
);
3568 Jim_DecrRefCount(interp
, nameObjPtr
);
3569 Jim_DecrRefCount(interp
, valObjPtr
);
3573 int Jim_SetVariableLink(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
3574 Jim_Obj
*targetNameObjPtr
, Jim_CallFrame
*targetCallFrame
)
3576 const char *varName
;
3579 /* Check for cycles. */
3580 if (interp
->framePtr
== targetCallFrame
) {
3581 Jim_Obj
*objPtr
= targetNameObjPtr
;
3583 /* Cycles are only possible with 'uplevel 0' */
3585 if (Jim_StringEqObj(objPtr
, nameObjPtr
, 0)) {
3586 Jim_SetResultString(interp
,
3587 "can't upvar from variable to itself", -1);
3590 if (SetVariableFromAny(interp
, objPtr
) != JIM_OK
)
3592 varPtr
= objPtr
->internalRep
.varValue
.varPtr
;
3593 if (varPtr
->linkFramePtr
!= targetCallFrame
) break;
3594 objPtr
= varPtr
->objPtr
;
3597 varName
= Jim_GetString(nameObjPtr
, &len
);
3598 if (Jim_NameIsDictSugar(varName
, len
)) {
3599 Jim_SetResultString(interp
,
3600 "Dict key syntax invalid as link source", -1);
3603 /* Perform the binding */
3604 Jim_SetVariable(interp
, nameObjPtr
, targetNameObjPtr
);
3605 /* We are now sure 'nameObjPtr' type is variableObjType */
3606 nameObjPtr
->internalRep
.varValue
.varPtr
->linkFramePtr
= targetCallFrame
;
3610 /* Return the Jim_Obj pointer associated with a variable name,
3611 * or NULL if the variable was not found in the current context.
3612 * The same optimization discussed in the comment to the
3613 * 'SetVariable' function should apply here. */
3614 Jim_Obj
*Jim_GetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
3618 /* All the rest is handled here */
3619 if ((err
= SetVariableFromAny(interp
, nameObjPtr
)) != JIM_OK
) {
3620 /* Check for [dict] syntax sugar. */
3621 if (err
== JIM_DICT_SUGAR
)
3622 return JimDictSugarGet(interp
, nameObjPtr
);
3623 if (flags
& JIM_ERRMSG
) {
3624 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
3625 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3626 "can't read \"", nameObjPtr
->bytes
,
3627 "\": no such variable", NULL
);
3633 Jim_CallFrame
*savedCallFrame
;
3635 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3636 if (varPtr
->linkFramePtr
== NULL
)
3637 return varPtr
->objPtr
;
3638 /* The variable is a link? Resolve it. */
3639 savedCallFrame
= interp
->framePtr
;
3640 interp
->framePtr
= varPtr
->linkFramePtr
;
3641 objPtr
= Jim_GetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
3642 if (objPtr
== NULL
&& flags
& JIM_ERRMSG
) {
3643 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
3644 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3645 "can't read \"", nameObjPtr
->bytes
,
3646 "\": no such variable", NULL
);
3648 interp
->framePtr
= savedCallFrame
;
3653 Jim_Obj
*Jim_GetGlobalVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
3656 Jim_CallFrame
*savedFramePtr
;
3659 savedFramePtr
= interp
->framePtr
;
3660 interp
->framePtr
= interp
->topFramePtr
;
3661 objPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
3662 interp
->framePtr
= savedFramePtr
;
3667 Jim_Obj
*Jim_GetVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
3669 Jim_Obj
*nameObjPtr
, *varObjPtr
;
3671 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
3672 Jim_IncrRefCount(nameObjPtr
);
3673 varObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
3674 Jim_DecrRefCount(interp
, nameObjPtr
);
3678 Jim_Obj
*Jim_GetGlobalVariableStr(Jim_Interp
*interp
, const char *name
,
3681 Jim_CallFrame
*savedFramePtr
;
3684 savedFramePtr
= interp
->framePtr
;
3685 interp
->framePtr
= interp
->topFramePtr
;
3686 objPtr
= Jim_GetVariableStr(interp
, name
, flags
);
3687 interp
->framePtr
= savedFramePtr
;
3692 /* Unset a variable.
3693 * Note: On success unset invalidates all the variable objects created
3694 * in the current call frame incrementing. */
3695 int Jim_UnsetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
3701 if ((err
= SetVariableFromAny(interp
, nameObjPtr
)) != JIM_OK
) {
3702 /* Check for [dict] syntax sugar. */
3703 if (err
== JIM_DICT_SUGAR
)
3704 return JimDictSugarSet(interp
, nameObjPtr
, NULL
);
3705 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
3706 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3707 "can't unset \"", nameObjPtr
->bytes
,
3708 "\": no such variable", NULL
);
3709 return JIM_ERR
; /* var not found */
3711 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3712 /* If it's a link call UnsetVariable recursively */
3713 if (varPtr
->linkFramePtr
) {
3716 Jim_CallFrame
*savedCallFrame
;
3718 savedCallFrame
= interp
->framePtr
;
3719 interp
->framePtr
= varPtr
->linkFramePtr
;
3720 retval
= Jim_UnsetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
3721 interp
->framePtr
= savedCallFrame
;
3722 if (retval
!= JIM_OK
&& flags
& JIM_ERRMSG
) {
3723 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
3724 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
3725 "can't unset \"", nameObjPtr
->bytes
,
3726 "\": no such variable", NULL
);
3730 name
= Jim_GetString(nameObjPtr
, NULL
);
3731 if (Jim_DeleteHashEntry(&interp
->framePtr
->vars
, name
)
3732 != JIM_OK
) return JIM_ERR
;
3733 /* Change the callframe id, invalidating var lookup caching */
3734 JimChangeCallFrameId(interp
, interp
->framePtr
);
3739 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
3741 /* Given a variable name for [dict] operation syntax sugar,
3742 * this function returns two objects, the first with the name
3743 * of the variable to set, and the second with the rispective key.
3744 * For example "foo(bar)" will return objects with string repr. of
3747 * The returned objects have refcount = 1. The function can't fail. */
3748 static void JimDictSugarParseVarKey(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
3749 Jim_Obj
**varPtrPtr
, Jim_Obj
**keyPtrPtr
)
3751 const char *str
, *p
;
3753 int len
, keyLen
, nameLen
;
3754 Jim_Obj
*varObjPtr
, *keyObjPtr
;
3756 str
= Jim_GetString(objPtr
, &len
);
3757 p
= strchr(str
, '(');
3759 keyLen
= len
-((p
-str
)+1);
3760 nameLen
= (p
-str
)-1;
3761 /* Create the objects with the variable name and key. */
3762 t
= Jim_Alloc(nameLen
+1);
3763 memcpy(t
, str
, nameLen
);
3765 varObjPtr
= Jim_NewStringObjNoAlloc(interp
, t
, nameLen
);
3767 t
= Jim_Alloc(keyLen
+1);
3768 memcpy(t
, p
, keyLen
);
3770 keyObjPtr
= Jim_NewStringObjNoAlloc(interp
, t
, keyLen
);
3772 Jim_IncrRefCount(varObjPtr
);
3773 Jim_IncrRefCount(keyObjPtr
);
3774 *varPtrPtr
= varObjPtr
;
3775 *keyPtrPtr
= keyObjPtr
;
3778 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
3779 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
3780 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
3783 Jim_Obj
*varObjPtr
, *keyObjPtr
;
3786 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
3787 err
= Jim_SetDictKeysVector(interp
, varObjPtr
, &keyObjPtr
, 1,
3789 Jim_DecrRefCount(interp
, varObjPtr
);
3790 Jim_DecrRefCount(interp
, keyObjPtr
);
3794 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
3795 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3797 Jim_Obj
*varObjPtr
, *keyObjPtr
, *dictObjPtr
, *resObjPtr
;
3799 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
3800 dictObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
3805 if (Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_ERRMSG
)
3810 Jim_DecrRefCount(interp
, varObjPtr
);
3811 Jim_DecrRefCount(interp
, keyObjPtr
);
3815 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
3817 static void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
3818 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
,
3821 static Jim_ObjType dictSubstObjType
= {
3822 "dict-substitution",
3823 FreeDictSubstInternalRep
,
3824 DupDictSubstInternalRep
,
3829 void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3831 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
3832 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
3835 void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
,
3838 JIM_NOTUSED(interp
);
3840 dupPtr
->internalRep
.dictSubstValue
.varNameObjPtr
=
3841 srcPtr
->internalRep
.dictSubstValue
.varNameObjPtr
;
3842 dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
=
3843 srcPtr
->internalRep
.dictSubstValue
.indexObjPtr
;
3844 dupPtr
->typePtr
= &dictSubstObjType
;
3847 /* This function is used to expand [dict get] sugar in the form
3848 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
3849 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
3850 * object that is *guaranteed* to be in the form VARNAME(INDEX).
3851 * The 'index' part is [subst]ituted, and is used to lookup a key inside
3852 * the [dict]ionary contained in variable VARNAME. */
3853 Jim_Obj
*Jim_ExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3855 Jim_Obj
*varObjPtr
, *keyObjPtr
, *dictObjPtr
, *resObjPtr
;
3856 Jim_Obj
*substKeyObjPtr
= NULL
;
3858 if (objPtr
->typePtr
!= &dictSubstObjType
) {
3859 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
3860 Jim_FreeIntRep(interp
, objPtr
);
3861 objPtr
->typePtr
= &dictSubstObjType
;
3862 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= varObjPtr
;
3863 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= keyObjPtr
;
3865 if (Jim_SubstObj(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
,
3866 &substKeyObjPtr
, JIM_NONE
)
3868 substKeyObjPtr
= NULL
;
3871 Jim_IncrRefCount(substKeyObjPtr
);
3872 dictObjPtr
= Jim_GetVariable(interp
,
3873 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
, JIM_ERRMSG
);
3878 if (Jim_DictKey(interp
, dictObjPtr
, substKeyObjPtr
, &resObjPtr
, JIM_ERRMSG
)
3884 if (substKeyObjPtr
) Jim_DecrRefCount(interp
, substKeyObjPtr
);
3888 /* -----------------------------------------------------------------------------
3890 * ---------------------------------------------------------------------------*/
3892 static Jim_CallFrame
*JimCreateCallFrame(Jim_Interp
*interp
)
3895 if (interp
->freeFramesList
) {
3896 cf
= interp
->freeFramesList
;
3897 interp
->freeFramesList
= cf
->nextFramePtr
;
3899 cf
= Jim_Alloc(sizeof(*cf
));
3900 cf
->vars
.table
= NULL
;
3903 cf
->id
= interp
->callFrameEpoch
++;
3904 cf
->parentCallFrame
= NULL
;
3907 cf
->procArgsObjPtr
= NULL
;
3908 cf
->procBodyObjPtr
= NULL
;
3909 cf
->nextFramePtr
= NULL
;
3910 cf
->staticVars
= NULL
;
3911 if (cf
->vars
.table
== NULL
)
3912 Jim_InitHashTable(&cf
->vars
, &JimVariablesHashTableType
, interp
);
3916 /* Used to invalidate every caching related to callframe stability. */
3917 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
)
3919 cf
->id
= interp
->callFrameEpoch
++;
3922 #define JIM_FCF_NONE 0 /* no flags */
3923 #define JIM_FCF_NOHT 1 /* don't free the hash table */
3924 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
,
3927 if (cf
->procArgsObjPtr
) Jim_DecrRefCount(interp
, cf
->procArgsObjPtr
);
3928 if (cf
->procBodyObjPtr
) Jim_DecrRefCount(interp
, cf
->procBodyObjPtr
);
3929 if (!(flags
& JIM_FCF_NOHT
))
3930 Jim_FreeHashTable(&cf
->vars
);
3933 Jim_HashEntry
**table
= cf
->vars
.table
, *he
;
3935 for (i
= 0; i
< JIM_HT_INITIAL_SIZE
; i
++) {
3937 while (he
!= NULL
) {
3938 Jim_HashEntry
*nextEntry
= he
->next
;
3939 Jim_Var
*varPtr
= (void*) he
->val
;
3941 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
3943 Jim_Free((void*)he
->key
); /* ATTENTION: const cast */
3951 cf
->nextFramePtr
= interp
->freeFramesList
;
3952 interp
->freeFramesList
= cf
;
3955 /* -----------------------------------------------------------------------------
3957 * ---------------------------------------------------------------------------*/
3959 /* References HashTable Type.
3961 * Keys are jim_wide integers, dynamically allocated for now but in the
3962 * future it's worth to cache this 8 bytes objects. Values are poitners
3963 * to Jim_References. */
3964 static void JimReferencesHTValDestructor(void *interp
, void *val
)
3966 Jim_Reference
*refPtr
= (void*) val
;
3968 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
3969 if (refPtr
->finalizerCmdNamePtr
!= NULL
) {
3970 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
3975 unsigned int JimReferencesHTHashFunction(const void *key
)
3977 /* Only the least significant bits are used. */
3978 const jim_wide
*widePtr
= key
;
3979 unsigned int intValue
= (unsigned int) *widePtr
;
3980 return Jim_IntHashFunction(intValue
);
3983 unsigned int JimReferencesHTDoubleHashFunction(const void *key
)
3985 /* Only the least significant bits are used. */
3986 const jim_wide
*widePtr
= key
;
3987 unsigned int intValue
= (unsigned int) *widePtr
;
3988 return intValue
; /* identity function. */
3991 const void *JimReferencesHTKeyDup(void *privdata
, const void *key
)
3993 void *copy
= Jim_Alloc(sizeof(jim_wide
));
3994 JIM_NOTUSED(privdata
);
3996 memcpy(copy
, key
, sizeof(jim_wide
));
4000 int JimReferencesHTKeyCompare(void *privdata
, const void *key1
,
4003 JIM_NOTUSED(privdata
);
4005 return memcmp(key1
, key2
, sizeof(jim_wide
)) == 0;
4008 void JimReferencesHTKeyDestructor(void *privdata
, const void *key
)
4010 JIM_NOTUSED(privdata
);
4012 Jim_Free((void*)key
);
4015 static Jim_HashTableType JimReferencesHashTableType
= {
4016 JimReferencesHTHashFunction
, /* hash function */
4017 JimReferencesHTKeyDup
, /* key dup */
4019 JimReferencesHTKeyCompare
, /* key compare */
4020 JimReferencesHTKeyDestructor
, /* key destructor */
4021 JimReferencesHTValDestructor
/* val destructor */
4024 /* -----------------------------------------------------------------------------
4025 * Reference object type and References API
4026 * ---------------------------------------------------------------------------*/
4028 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
);
4030 static Jim_ObjType referenceObjType
= {
4034 UpdateStringOfReference
,
4035 JIM_TYPE_REFERENCES
,
4038 void UpdateStringOfReference(struct Jim_Obj
*objPtr
)
4041 char buf
[JIM_REFERENCE_SPACE
+1];
4042 Jim_Reference
*refPtr
;
4044 refPtr
= objPtr
->internalRep
.refValue
.refPtr
;
4045 len
= JimFormatReference(buf
, refPtr
, objPtr
->internalRep
.refValue
.id
);
4046 objPtr
->bytes
= Jim_Alloc(len
+1);
4047 memcpy(objPtr
->bytes
, buf
, len
+1);
4048 objPtr
->length
= len
;
4051 /* returns true if 'c' is a valid reference tag character.
4052 * i.e. inside the range [_a-zA-Z0-9] */
4053 static int isrefchar(int c
)
4055 if (c
== '_' || (c
>= 'a' && c
<= 'z') || (c
>= 'A' && c
<= 'Z') ||
4056 (c
>= '0' && c
<= '9')) return 1;
4060 int SetReferenceFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4064 const char *str
, *start
, *end
;
4066 Jim_Reference
*refPtr
;
4069 /* Get the string representation */
4070 str
= Jim_GetString(objPtr
, &len
);
4071 /* Check if it looks like a reference */
4072 if (len
< JIM_REFERENCE_SPACE
) goto badformat
;
4076 while (*start
== ' ') start
++;
4077 while (*end
== ' ' && end
> start
) end
--;
4078 if (end
-start
+1 != JIM_REFERENCE_SPACE
) goto badformat
;
4079 /* <reference.<1234567>.%020> */
4080 if (memcmp(start
, "<reference.<", 12) != 0) goto badformat
;
4081 if (start
[12+JIM_REFERENCE_TAGLEN
] != '>' || end
[0] != '>') goto badformat
;
4082 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4083 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4084 if (!isrefchar(start
[12+i
])) goto badformat
;
4086 /* Extract info from the refernece. */
4087 memcpy(refId
, start
+14+JIM_REFERENCE_TAGLEN
, 20);
4089 /* Try to convert the ID into a jim_wide */
4090 if (Jim_StringToWide(refId
, &wideValue
, 10) != JIM_OK
) goto badformat
;
4091 /* Check if the reference really exists! */
4092 he
= Jim_FindHashEntry(&interp
->references
, &wideValue
);
4094 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
4095 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
4096 "Invalid reference ID \"", str
, "\"", NULL
);
4100 /* Free the old internal repr and set the new one. */
4101 Jim_FreeIntRep(interp
, objPtr
);
4102 objPtr
->typePtr
= &referenceObjType
;
4103 objPtr
->internalRep
.refValue
.id
= wideValue
;
4104 objPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4108 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
4109 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
4110 "expected reference but got \"", str
, "\"", NULL
);
4114 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4115 * as finalizer command (or NULL if there is no finalizer).
4116 * The returned reference object has refcount = 0. */
4117 Jim_Obj
*Jim_NewReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*tagPtr
,
4118 Jim_Obj
*cmdNamePtr
)
4120 struct Jim_Reference
*refPtr
;
4121 jim_wide wideValue
= interp
->referenceNextId
;
4126 /* Perform the Garbage Collection if needed. */
4127 Jim_CollectIfNeeded(interp
);
4129 refPtr
= Jim_Alloc(sizeof(*refPtr
));
4130 refPtr
->objPtr
= objPtr
;
4131 Jim_IncrRefCount(objPtr
);
4132 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4134 Jim_IncrRefCount(cmdNamePtr
);
4135 Jim_AddHashEntry(&interp
->references
, &wideValue
, refPtr
);
4136 refObjPtr
= Jim_NewObj(interp
);
4137 refObjPtr
->typePtr
= &referenceObjType
;
4138 refObjPtr
->bytes
= NULL
;
4139 refObjPtr
->internalRep
.refValue
.id
= interp
->referenceNextId
;
4140 refObjPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4141 interp
->referenceNextId
++;
4142 /* Set the tag. Trimmered at JIM_REFERENCE_TAGLEN. Everything
4143 * that does not pass the 'isrefchar' test is replaced with '_' */
4144 tag
= Jim_GetString(tagPtr
, &tagLen
);
4145 if (tagLen
> JIM_REFERENCE_TAGLEN
)
4146 tagLen
= JIM_REFERENCE_TAGLEN
;
4147 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4149 refPtr
->tag
[i
] = tag
[i
];
4151 refPtr
->tag
[i
] = '_';
4153 refPtr
->tag
[JIM_REFERENCE_TAGLEN
] = '\0';
4157 Jim_Reference
*Jim_GetReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4159 if (objPtr
->typePtr
!= &referenceObjType
&&
4160 SetReferenceFromAny(interp
, objPtr
) == JIM_ERR
)
4162 return objPtr
->internalRep
.refValue
.refPtr
;
4165 int Jim_SetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*cmdNamePtr
)
4167 Jim_Reference
*refPtr
;
4169 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4171 Jim_IncrRefCount(cmdNamePtr
);
4172 if (refPtr
->finalizerCmdNamePtr
)
4173 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4174 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4178 int Jim_GetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
**cmdNamePtrPtr
)
4180 Jim_Reference
*refPtr
;
4182 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4184 *cmdNamePtrPtr
= refPtr
->finalizerCmdNamePtr
;
4188 /* -----------------------------------------------------------------------------
4189 * References Garbage Collection
4190 * ---------------------------------------------------------------------------*/
4192 /* This the hash table type for the "MARK" phase of the GC */
4193 static Jim_HashTableType JimRefMarkHashTableType
= {
4194 JimReferencesHTHashFunction
, /* hash function */
4195 JimReferencesHTKeyDup
, /* key dup */
4197 JimReferencesHTKeyCompare
, /* key compare */
4198 JimReferencesHTKeyDestructor
, /* key destructor */
4199 NULL
/* val destructor */
4202 /* #define JIM_DEBUG_GC 1 */
4204 /* Performs the garbage collection. */
4205 int Jim_Collect(Jim_Interp
*interp
)
4207 Jim_HashTable marks
;
4208 Jim_HashTableIterator
*htiter
;
4213 /* Avoid recursive calls */
4214 if (interp
->lastCollectId
== -1) {
4215 /* Jim_Collect() already running. Return just now. */
4218 interp
->lastCollectId
= -1;
4220 /* Mark all the references found into the 'mark' hash table.
4221 * The references are searched in every live object that
4222 * is of a type that can contain references. */
4223 Jim_InitHashTable(&marks
, &JimRefMarkHashTableType
, NULL
);
4224 objPtr
= interp
->liveList
;
4226 if (objPtr
->typePtr
== NULL
||
4227 objPtr
->typePtr
->flags
& JIM_TYPE_REFERENCES
) {
4228 const char *str
, *p
;
4231 /* If the object is of type reference, to get the
4232 * Id is simple... */
4233 if (objPtr
->typePtr
== &referenceObjType
) {
4234 Jim_AddHashEntry(&marks
,
4235 &objPtr
->internalRep
.refValue
.id
, NULL
);
4237 Jim_fprintf(interp
,interp
->cookie_stdout
,
4238 "MARK (reference): %d refcount: %d" JIM_NL
,
4239 (int) objPtr
->internalRep
.refValue
.id
,
4242 objPtr
= objPtr
->nextObjPtr
;
4245 /* Get the string repr of the object we want
4246 * to scan for references. */
4247 p
= str
= Jim_GetString(objPtr
, &len
);
4248 /* Skip objects too little to contain references. */
4249 if (len
< JIM_REFERENCE_SPACE
) {
4250 objPtr
= objPtr
->nextObjPtr
;
4253 /* Extract references from the object string repr. */
4259 if ((p
= strstr(p
, "<reference.<")) == NULL
)
4261 /* Check if it's a valid reference. */
4262 if (len
-(p
-str
) < JIM_REFERENCE_SPACE
) break;
4263 if (p
[41] != '>' || p
[19] != '>' || p
[20] != '.') break;
4264 for (i
= 21; i
<= 40; i
++)
4265 if (!isdigit((int)p
[i
]))
4268 memcpy(buf
, p
+21, 20);
4270 Jim_StringToWide(buf
, &id
, 10);
4272 /* Ok, a reference for the given ID
4273 * was found. Mark it. */
4274 Jim_AddHashEntry(&marks
, &id
, NULL
);
4276 Jim_fprintf(interp
,interp
->cookie_stdout
,"MARK: %d" JIM_NL
, (int)id
);
4278 p
+= JIM_REFERENCE_SPACE
;
4281 objPtr
= objPtr
->nextObjPtr
;
4284 /* Run the references hash table to destroy every reference that
4285 * is not referenced outside (not present in the mark HT). */
4286 htiter
= Jim_GetHashTableIterator(&interp
->references
);
4287 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
4288 const jim_wide
*refId
;
4289 Jim_Reference
*refPtr
;
4292 /* Check if in the mark phase we encountered
4293 * this reference. */
4294 if (Jim_FindHashEntry(&marks
, refId
) == NULL
) {
4296 Jim_fprintf(interp
,interp
->cookie_stdout
,"COLLECTING %d" JIM_NL
, (int)*refId
);
4299 /* Drop the reference, but call the
4300 * finalizer first if registered. */
4302 if (refPtr
->finalizerCmdNamePtr
) {
4303 char *refstr
= Jim_Alloc(JIM_REFERENCE_SPACE
+1);
4304 Jim_Obj
*objv
[3], *oldResult
;
4306 JimFormatReference(refstr
, refPtr
, *refId
);
4308 objv
[0] = refPtr
->finalizerCmdNamePtr
;
4309 objv
[1] = Jim_NewStringObjNoAlloc(interp
,
4311 objv
[2] = refPtr
->objPtr
;
4312 Jim_IncrRefCount(objv
[0]);
4313 Jim_IncrRefCount(objv
[1]);
4314 Jim_IncrRefCount(objv
[2]);
4316 /* Drop the reference itself */
4317 Jim_DeleteHashEntry(&interp
->references
, refId
);
4319 /* Call the finalizer. Errors ignored. */
4320 oldResult
= interp
->result
;
4321 Jim_IncrRefCount(oldResult
);
4322 Jim_EvalObjVector(interp
, 3, objv
);
4323 Jim_SetResult(interp
, oldResult
);
4324 Jim_DecrRefCount(interp
, oldResult
);
4326 Jim_DecrRefCount(interp
, objv
[0]);
4327 Jim_DecrRefCount(interp
, objv
[1]);
4328 Jim_DecrRefCount(interp
, objv
[2]);
4330 Jim_DeleteHashEntry(&interp
->references
, refId
);
4334 Jim_FreeHashTableIterator(htiter
);
4335 Jim_FreeHashTable(&marks
);
4336 interp
->lastCollectId
= interp
->referenceNextId
;
4337 interp
->lastCollectTime
= time(NULL
);
4341 #define JIM_COLLECT_ID_PERIOD 5000
4342 #define JIM_COLLECT_TIME_PERIOD 300
4344 void Jim_CollectIfNeeded(Jim_Interp
*interp
)
4349 elapsedId
= interp
->referenceNextId
- interp
->lastCollectId
;
4350 elapsedTime
= time(NULL
) - interp
->lastCollectTime
;
4353 if (elapsedId
> JIM_COLLECT_ID_PERIOD
||
4354 elapsedTime
> JIM_COLLECT_TIME_PERIOD
) {
4355 Jim_Collect(interp
);
4359 /* -----------------------------------------------------------------------------
4360 * Interpreter related functions
4361 * ---------------------------------------------------------------------------*/
4363 Jim_Interp
*Jim_CreateInterp(void)
4365 Jim_Interp
*i
= Jim_Alloc(sizeof(*i
));
4369 i
->errorFileName
= Jim_StrDup("");
4371 i
->maxNestingDepth
= JIM_MAX_NESTING_DEPTH
;
4372 i
->returnCode
= JIM_OK
;
4375 i
->callFrameEpoch
= 0;
4376 i
->liveList
= i
->freeList
= NULL
;
4377 i
->scriptFileName
= Jim_StrDup("");
4378 i
->referenceNextId
= 0;
4379 i
->lastCollectId
= 0;
4380 i
->lastCollectTime
= time(NULL
);
4381 i
->freeFramesList
= NULL
;
4382 i
->prngState
= NULL
;
4383 i
->evalRetcodeLevel
= -1;
4384 i
->cookie_stdin
= stdin
;
4385 i
->cookie_stdout
= stdout
;
4386 i
->cookie_stderr
= stderr
;
4387 i
->cb_fwrite
= ((size_t (*)( const void *, size_t, size_t, void *))(fwrite
));
4388 i
->cb_fread
= ((size_t (*)( void *, size_t, size_t, void *))(fread
));
4389 i
->cb_vfprintf
= ((int (*)( void *, const char *fmt
, va_list ))(vfprintf
));
4390 i
->cb_fflush
= ((int (*)( void *))(fflush
));
4391 i
->cb_fgets
= ((char * (*)( char *, int, void *))(fgets
));
4393 /* Note that we can create objects only after the
4394 * interpreter liveList and freeList pointers are
4395 * initialized to NULL. */
4396 Jim_InitHashTable(&i
->commands
, &JimCommandsHashTableType
, i
);
4397 Jim_InitHashTable(&i
->references
, &JimReferencesHashTableType
, i
);
4398 Jim_InitHashTable(&i
->sharedStrings
, &JimSharedStringsHashTableType
,
4400 Jim_InitHashTable(&i
->stub
, &JimStringCopyHashTableType
, NULL
);
4401 Jim_InitHashTable(&i
->assocData
, &JimAssocDataHashTableType
, i
);
4402 Jim_InitHashTable(&i
->packages
, &JimStringKeyValCopyHashTableType
, NULL
);
4403 i
->framePtr
= i
->topFramePtr
= JimCreateCallFrame(i
);
4404 i
->emptyObj
= Jim_NewEmptyStringObj(i
);
4405 i
->result
= i
->emptyObj
;
4406 i
->stackTrace
= Jim_NewListObj(i
, NULL
, 0);
4407 i
->unknown
= Jim_NewStringObj(i
, "unknown", -1);
4408 Jim_IncrRefCount(i
->emptyObj
);
4409 Jim_IncrRefCount(i
->result
);
4410 Jim_IncrRefCount(i
->stackTrace
);
4411 Jim_IncrRefCount(i
->unknown
);
4413 /* Initialize key variables every interpreter should contain */
4414 pathPtr
= Jim_NewStringObj(i
, "./", -1);
4415 Jim_SetVariableStr(i
, "jim_libpath", pathPtr
);
4416 Jim_SetVariableStrWithStr(i
, "jim_interactive", "0");
4418 /* Export the core API to extensions */
4419 JimRegisterCoreApi(i
);
4423 /* This is the only function Jim exports directly without
4424 * to use the STUB system. It is only used by embedders
4425 * in order to get an interpreter with the Jim API pointers
4427 Jim_Interp
*ExportedJimCreateInterp(void)
4429 return Jim_CreateInterp();
4432 void Jim_FreeInterp(Jim_Interp
*i
)
4434 Jim_CallFrame
*cf
= i
->framePtr
, *prevcf
, *nextcf
;
4435 Jim_Obj
*objPtr
, *nextObjPtr
;
4437 Jim_DecrRefCount(i
, i
->emptyObj
);
4438 Jim_DecrRefCount(i
, i
->result
);
4439 Jim_DecrRefCount(i
, i
->stackTrace
);
4440 Jim_DecrRefCount(i
, i
->unknown
);
4441 Jim_Free((void*)i
->errorFileName
);
4442 Jim_Free((void*)i
->scriptFileName
);
4443 Jim_FreeHashTable(&i
->commands
);
4444 Jim_FreeHashTable(&i
->references
);
4445 Jim_FreeHashTable(&i
->stub
);
4446 Jim_FreeHashTable(&i
->assocData
);
4447 Jim_FreeHashTable(&i
->packages
);
4448 Jim_Free(i
->prngState
);
4449 /* Free the call frames list */
4451 prevcf
= cf
->parentCallFrame
;
4452 JimFreeCallFrame(i
, cf
, JIM_FCF_NONE
);
4455 /* Check that the live object list is empty, otherwise
4456 * there is a memory leak. */
4457 if (i
->liveList
!= NULL
) {
4458 Jim_Obj
*objPtr
= i
->liveList
;
4460 Jim_fprintf( i
, i
->cookie_stdout
,JIM_NL
"-------------------------------------" JIM_NL
);
4461 Jim_fprintf( i
, i
->cookie_stdout
,"Objects still in the free list:" JIM_NL
);
4463 const char *type
= objPtr
->typePtr
?
4464 objPtr
->typePtr
->name
: "";
4465 Jim_fprintf( i
, i
->cookie_stdout
,"%p \"%-10s\": '%.20s' (refCount: %d)" JIM_NL
,
4467 objPtr
->bytes
? objPtr
->bytes
4468 : "(null)", objPtr
->refCount
);
4469 if (objPtr
->typePtr
== &sourceObjType
) {
4470 Jim_fprintf( i
, i
->cookie_stdout
, "FILE %s LINE %d" JIM_NL
,
4471 objPtr
->internalRep
.sourceValue
.fileName
,
4472 objPtr
->internalRep
.sourceValue
.lineNumber
);
4474 objPtr
= objPtr
->nextObjPtr
;
4476 Jim_fprintf( i
, i
->cookie_stdout
, "-------------------------------------" JIM_NL JIM_NL
);
4477 Jim_Panic(i
,"Live list non empty freeing the interpreter! Leak?");
4479 /* Free all the freed objects. */
4480 objPtr
= i
->freeList
;
4482 nextObjPtr
= objPtr
->nextObjPtr
;
4484 objPtr
= nextObjPtr
;
4486 /* Free cached CallFrame structures */
4487 cf
= i
->freeFramesList
;
4489 nextcf
= cf
->nextFramePtr
;
4490 if (cf
->vars
.table
!= NULL
)
4491 Jim_Free(cf
->vars
.table
);
4495 /* Free the sharedString hash table. Make sure to free it
4496 * after every other Jim_Object was freed. */
4497 Jim_FreeHashTable(&i
->sharedStrings
);
4498 /* Free the interpreter structure. */
4502 /* Store the call frame relative to the level represented by
4503 * levelObjPtr into *framePtrPtr. If levelObjPtr == NULL, the
4504 * level is assumed to be '1'.
4506 * If a newLevelptr int pointer is specified, the function stores
4507 * the absolute level integer value of the new target callframe into
4508 * *newLevelPtr. (this is used to adjust interp->numLevels
4509 * in the implementation of [uplevel], so that [info level] will
4510 * return a correct information).
4512 * This function accepts the 'level' argument in the form
4513 * of the commands [uplevel] and [upvar].
4515 * For a function accepting a relative integer as level suitable
4516 * for implementation of [info level ?level?] check the
4517 * GetCallFrameByInteger() function. */
4518 int Jim_GetCallFrameByLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
4519 Jim_CallFrame
**framePtrPtr
, int *newLevelPtr
)
4523 Jim_CallFrame
*framePtr
;
4525 if (newLevelPtr
) *newLevelPtr
= interp
->numLevels
;
4527 str
= Jim_GetString(levelObjPtr
, NULL
);
4528 if (str
[0] == '#') {
4530 /* speedup for the toplevel (level #0) */
4531 if (str
[1] == '0' && str
[2] == '\0') {
4532 if (newLevelPtr
) *newLevelPtr
= 0;
4533 *framePtrPtr
= interp
->topFramePtr
;
4537 level
= strtol(str
+1, &endptr
, 0);
4538 if (str
[1] == '\0' || endptr
[0] != '\0' || level
< 0)
4540 /* An 'absolute' level is converted into the
4541 * 'number of levels to go back' format. */
4542 level
= interp
->numLevels
- level
;
4543 if (level
< 0) goto badlevel
;
4545 if (Jim_GetLong(interp
, levelObjPtr
, &level
) != JIM_OK
|| level
< 0)
4549 str
= "1"; /* Needed to format the error message. */
4553 framePtr
= interp
->framePtr
;
4554 if (newLevelPtr
) *newLevelPtr
= (*newLevelPtr
)-level
;
4556 framePtr
= framePtr
->parentCallFrame
;
4557 if (framePtr
== NULL
) goto badlevel
;
4559 *framePtrPtr
= framePtr
;
4562 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
4563 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
4564 "bad level \"", str
, "\"", NULL
);
4568 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
4569 * as a relative integer like in the [info level ?level?] command. */
4570 static int JimGetCallFrameByInteger(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
4571 Jim_CallFrame
**framePtrPtr
)
4574 jim_wide relLevel
; /* level relative to the current one. */
4575 Jim_CallFrame
*framePtr
;
4577 if (Jim_GetWide(interp
, levelObjPtr
, &level
) != JIM_OK
)
4580 /* An 'absolute' level is converted into the
4581 * 'number of levels to go back' format. */
4582 relLevel
= interp
->numLevels
- level
;
4587 framePtr
= interp
->framePtr
;
4588 while (relLevel
--) {
4589 framePtr
= framePtr
->parentCallFrame
;
4590 if (framePtr
== NULL
) goto badlevel
;
4592 *framePtrPtr
= framePtr
;
4595 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
4596 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
4597 "bad level \"", Jim_GetString(levelObjPtr
, NULL
), "\"", NULL
);
4601 static void JimSetErrorFileName(Jim_Interp
*interp
, char *filename
)
4603 Jim_Free((void*)interp
->errorFileName
);
4604 interp
->errorFileName
= Jim_StrDup(filename
);
4607 static void JimSetErrorLineNumber(Jim_Interp
*interp
, int linenr
)
4609 interp
->errorLine
= linenr
;
4612 static void JimResetStackTrace(Jim_Interp
*interp
)
4614 Jim_DecrRefCount(interp
, interp
->stackTrace
);
4615 interp
->stackTrace
= Jim_NewListObj(interp
, NULL
, 0);
4616 Jim_IncrRefCount(interp
->stackTrace
);
4619 static void JimAppendStackTrace(Jim_Interp
*interp
, const char *procname
,
4620 const char *filename
, int linenr
)
4622 if (Jim_IsShared(interp
->stackTrace
)) {
4623 interp
->stackTrace
=
4624 Jim_DuplicateObj(interp
, interp
->stackTrace
);
4625 Jim_IncrRefCount(interp
->stackTrace
);
4627 Jim_ListAppendElement(interp
, interp
->stackTrace
,
4628 Jim_NewStringObj(interp
, procname
, -1));
4629 Jim_ListAppendElement(interp
, interp
->stackTrace
,
4630 Jim_NewStringObj(interp
, filename
, -1));
4631 Jim_ListAppendElement(interp
, interp
->stackTrace
,
4632 Jim_NewIntObj(interp
, linenr
));
4635 int Jim_SetAssocData(Jim_Interp
*interp
, const char *key
, Jim_InterpDeleteProc
*delProc
, void *data
)
4637 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*)Jim_Alloc(sizeof(AssocDataValue
));
4638 assocEntryPtr
->delProc
= delProc
;
4639 assocEntryPtr
->data
= data
;
4640 return Jim_AddHashEntry(&interp
->assocData
, key
, assocEntryPtr
);
4643 void *Jim_GetAssocData(Jim_Interp
*interp
, const char *key
)
4645 Jim_HashEntry
*entryPtr
= Jim_FindHashEntry(&interp
->assocData
, key
);
4646 if (entryPtr
!= NULL
) {
4647 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*)entryPtr
->val
;
4648 return assocEntryPtr
->data
;
4653 int Jim_DeleteAssocData(Jim_Interp
*interp
, const char *key
)
4655 return Jim_DeleteHashEntry(&interp
->assocData
, key
);
4658 int Jim_GetExitCode(Jim_Interp
*interp
) {
4659 return interp
->exitCode
;
4662 void *Jim_SetStdin(Jim_Interp
*interp
, void *fp
)
4664 if (fp
!= NULL
) interp
->cookie_stdin
= fp
;
4665 return interp
->cookie_stdin
;
4668 void *Jim_SetStdout(Jim_Interp
*interp
, void *fp
)
4670 if (fp
!= NULL
) interp
->cookie_stdout
= fp
;
4671 return interp
->cookie_stdout
;
4674 void *Jim_SetStderr(Jim_Interp
*interp
, void *fp
)
4676 if (fp
!= NULL
) interp
->cookie_stderr
= fp
;
4677 return interp
->cookie_stderr
;
4680 /* -----------------------------------------------------------------------------
4682 * Every interpreter has an hash table where to put shared dynamically
4683 * allocate strings that are likely to be used a lot of times.
4684 * For example, in the 'source' object type, there is a pointer to
4685 * the filename associated with that object. Every script has a lot
4686 * of this objects with the identical file name, so it is wise to share
4689 * The API is trivial: Jim_GetSharedString(interp, "foobar")
4690 * returns the pointer to the shared string. Every time a reference
4691 * to the string is no longer used, the user should call
4692 * Jim_ReleaseSharedString(interp, stringPointer). Once no one is using
4693 * a given string, it is removed from the hash table.
4694 * ---------------------------------------------------------------------------*/
4695 const char *Jim_GetSharedString(Jim_Interp
*interp
, const char *str
)
4697 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->sharedStrings
, str
);
4700 char *strCopy
= Jim_StrDup(str
);
4702 Jim_AddHashEntry(&interp
->sharedStrings
, strCopy
, (void*)1);
4705 long refCount
= (long) he
->val
;
4708 he
->val
= (void*) refCount
;
4713 void Jim_ReleaseSharedString(Jim_Interp
*interp
, const char *str
)
4716 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->sharedStrings
, str
);
4719 Jim_Panic(interp
,"Jim_ReleaseSharedString called with "
4720 "unknown shared string '%s'", str
);
4721 refCount
= (long) he
->val
;
4723 if (refCount
== 0) {
4724 Jim_DeleteHashEntry(&interp
->sharedStrings
, str
);
4726 he
->val
= (void*) refCount
;
4730 /* -----------------------------------------------------------------------------
4732 * ---------------------------------------------------------------------------*/
4733 #define JIM_INTEGER_SPACE 24
4735 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
);
4736 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
4738 static Jim_ObjType intObjType
= {
4746 void UpdateStringOfInt(struct Jim_Obj
*objPtr
)
4749 char buf
[JIM_INTEGER_SPACE
+1];
4751 len
= Jim_WideToString(buf
, objPtr
->internalRep
.wideValue
);
4752 objPtr
->bytes
= Jim_Alloc(len
+1);
4753 memcpy(objPtr
->bytes
, buf
, len
+1);
4754 objPtr
->length
= len
;
4757 int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4762 /* Get the string representation */
4763 str
= Jim_GetString(objPtr
, NULL
);
4764 /* Try to convert into a jim_wide */
4765 if (Jim_StringToWide(str
, &wideValue
, 0) != JIM_OK
) {
4766 if (flags
& JIM_ERRMSG
) {
4767 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
4768 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
4769 "expected integer but got \"", str
, "\"", NULL
);
4773 if ((wideValue
== JIM_WIDE_MIN
|| wideValue
== JIM_WIDE_MAX
) &&
4775 Jim_SetResultString(interp
,
4776 "Integer value too big to be represented", -1);
4779 /* Free the old internal repr and set the new one. */
4780 Jim_FreeIntRep(interp
, objPtr
);
4781 objPtr
->typePtr
= &intObjType
;
4782 objPtr
->internalRep
.wideValue
= wideValue
;
4786 int Jim_GetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
*widePtr
)
4788 if (objPtr
->typePtr
!= &intObjType
&&
4789 SetIntFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
4791 *widePtr
= objPtr
->internalRep
.wideValue
;
4795 /* Get a wide but does not set an error if the format is bad. */
4796 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
4799 if (objPtr
->typePtr
!= &intObjType
&&
4800 SetIntFromAny(interp
, objPtr
, JIM_NONE
) == JIM_ERR
)
4802 *widePtr
= objPtr
->internalRep
.wideValue
;
4806 int Jim_GetLong(Jim_Interp
*interp
, Jim_Obj
*objPtr
, long *longPtr
)
4811 retval
= Jim_GetWide(interp
, objPtr
, &wideValue
);
4812 if (retval
== JIM_OK
) {
4813 *longPtr
= (long) wideValue
;
4819 void Jim_SetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide wideValue
)
4821 if (Jim_IsShared(objPtr
))
4822 Jim_Panic(interp
,"Jim_SetWide called with shared object");
4823 if (objPtr
->typePtr
!= &intObjType
) {
4824 Jim_FreeIntRep(interp
, objPtr
);
4825 objPtr
->typePtr
= &intObjType
;
4827 Jim_InvalidateStringRep(objPtr
);
4828 objPtr
->internalRep
.wideValue
= wideValue
;
4831 Jim_Obj
*Jim_NewIntObj(Jim_Interp
*interp
, jim_wide wideValue
)
4835 objPtr
= Jim_NewObj(interp
);
4836 objPtr
->typePtr
= &intObjType
;
4837 objPtr
->bytes
= NULL
;
4838 objPtr
->internalRep
.wideValue
= wideValue
;
4842 /* -----------------------------------------------------------------------------
4844 * ---------------------------------------------------------------------------*/
4845 #define JIM_DOUBLE_SPACE 30
4847 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
);
4848 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
4850 static Jim_ObjType doubleObjType
= {
4854 UpdateStringOfDouble
,
4858 void UpdateStringOfDouble(struct Jim_Obj
*objPtr
)
4861 char buf
[JIM_DOUBLE_SPACE
+1];
4863 len
= Jim_DoubleToString(buf
, objPtr
->internalRep
.doubleValue
);
4864 objPtr
->bytes
= Jim_Alloc(len
+1);
4865 memcpy(objPtr
->bytes
, buf
, len
+1);
4866 objPtr
->length
= len
;
4869 int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4874 /* Get the string representation */
4875 str
= Jim_GetString(objPtr
, NULL
);
4876 /* Try to convert into a double */
4877 if (Jim_StringToDouble(str
, &doubleValue
) != JIM_OK
) {
4878 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
4879 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
4880 "expected number but got '", str
, "'", NULL
);
4883 /* Free the old internal repr and set the new one. */
4884 Jim_FreeIntRep(interp
, objPtr
);
4885 objPtr
->typePtr
= &doubleObjType
;
4886 objPtr
->internalRep
.doubleValue
= doubleValue
;
4890 int Jim_GetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double *doublePtr
)
4892 if (objPtr
->typePtr
!= &doubleObjType
&&
4893 SetDoubleFromAny(interp
, objPtr
) == JIM_ERR
)
4895 *doublePtr
= objPtr
->internalRep
.doubleValue
;
4899 void Jim_SetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double doubleValue
)
4901 if (Jim_IsShared(objPtr
))
4902 Jim_Panic(interp
,"Jim_SetDouble called with shared object");
4903 if (objPtr
->typePtr
!= &doubleObjType
) {
4904 Jim_FreeIntRep(interp
, objPtr
);
4905 objPtr
->typePtr
= &doubleObjType
;
4907 Jim_InvalidateStringRep(objPtr
);
4908 objPtr
->internalRep
.doubleValue
= doubleValue
;
4911 Jim_Obj
*Jim_NewDoubleObj(Jim_Interp
*interp
, double doubleValue
)
4915 objPtr
= Jim_NewObj(interp
);
4916 objPtr
->typePtr
= &doubleObjType
;
4917 objPtr
->bytes
= NULL
;
4918 objPtr
->internalRep
.doubleValue
= doubleValue
;
4922 /* -----------------------------------------------------------------------------
4924 * ---------------------------------------------------------------------------*/
4925 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
);
4926 static void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
4927 static void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
4928 static void UpdateStringOfList(struct Jim_Obj
*objPtr
);
4929 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
4931 /* Note that while the elements of the list may contain references,
4932 * the list object itself can't. This basically means that the
4933 * list object string representation as a whole can't contain references
4934 * that are not presents in the single elements. */
4935 static Jim_ObjType listObjType
= {
4937 FreeListInternalRep
,
4943 void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4947 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
4948 Jim_DecrRefCount(interp
, objPtr
->internalRep
.listValue
.ele
[i
]);
4950 Jim_Free(objPtr
->internalRep
.listValue
.ele
);
4953 void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4956 JIM_NOTUSED(interp
);
4958 dupPtr
->internalRep
.listValue
.len
= srcPtr
->internalRep
.listValue
.len
;
4959 dupPtr
->internalRep
.listValue
.maxLen
= srcPtr
->internalRep
.listValue
.maxLen
;
4960 dupPtr
->internalRep
.listValue
.ele
=
4961 Jim_Alloc(sizeof(Jim_Obj
*)*srcPtr
->internalRep
.listValue
.maxLen
);
4962 memcpy(dupPtr
->internalRep
.listValue
.ele
, srcPtr
->internalRep
.listValue
.ele
,
4963 sizeof(Jim_Obj
*)*srcPtr
->internalRep
.listValue
.len
);
4964 for (i
= 0; i
< dupPtr
->internalRep
.listValue
.len
; i
++) {
4965 Jim_IncrRefCount(dupPtr
->internalRep
.listValue
.ele
[i
]);
4967 dupPtr
->typePtr
= &listObjType
;
4970 /* The following function checks if a given string can be encoded
4971 * into a list element without any kind of quoting, surrounded by braces,
4972 * or using escapes to quote. */
4973 #define JIM_ELESTR_SIMPLE 0
4974 #define JIM_ELESTR_BRACE 1
4975 #define JIM_ELESTR_QUOTE 2
4976 static int ListElementQuotingType(const char *s
, int len
)
4978 int i
, level
, trySimple
= 1;
4980 /* Try with the SIMPLE case */
4981 if (len
== 0) return JIM_ELESTR_BRACE
;
4982 if (s
[0] == '"' || s
[0] == '{') {
4986 for (i
= 0; i
< len
; i
++) {
5006 return JIM_ELESTR_SIMPLE
;
5009 /* Test if it's possible to do with braces */
5010 if (s
[len
-1] == '\\' ||
5011 s
[len
-1] == ']') return JIM_ELESTR_QUOTE
;
5013 for (i
= 0; i
< len
; i
++) {
5015 case '{': level
++; break;
5017 if (level
< 0) return JIM_ELESTR_QUOTE
;
5021 return JIM_ELESTR_QUOTE
;
5023 if (s
[i
+1] != '\0') i
++;
5028 if (!trySimple
) return JIM_ELESTR_BRACE
;
5029 for (i
= 0; i
< len
; i
++) {
5043 return JIM_ELESTR_BRACE
;
5047 return JIM_ELESTR_SIMPLE
;
5049 return JIM_ELESTR_QUOTE
;
5052 /* Returns the malloc-ed representation of a string
5053 * using backslash to quote special chars. */
5054 char *BackslashQuoteString(const char *s
, int len
, int *qlenPtr
)
5056 char *q
= Jim_Alloc(len
*2+1), *p
;
5073 case '\n': *p
++ = '\\'; *p
++ = 'n'; s
++; break;
5074 case '\r': *p
++ = '\\'; *p
++ = 'r'; s
++; break;
5075 case '\t': *p
++ = '\\'; *p
++ = 't'; s
++; break;
5076 case '\f': *p
++ = '\\'; *p
++ = 'f'; s
++; break;
5077 case '\v': *p
++ = '\\'; *p
++ = 'v'; s
++; break;
5088 void UpdateStringOfList(struct Jim_Obj
*objPtr
)
5090 int i
, bufLen
, realLength
;
5094 Jim_Obj
**ele
= objPtr
->internalRep
.listValue
.ele
;
5096 /* (Over) Estimate the space needed. */
5097 quotingType
= Jim_Alloc(sizeof(int)*objPtr
->internalRep
.listValue
.len
+1);
5099 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5102 strRep
= Jim_GetString(ele
[i
], &len
);
5103 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
5104 switch (quotingType
[i
]) {
5105 case JIM_ELESTR_SIMPLE
: bufLen
+= len
; break;
5106 case JIM_ELESTR_BRACE
: bufLen
+= len
+2; break;
5107 case JIM_ELESTR_QUOTE
: bufLen
+= len
*2; break;
5109 bufLen
++; /* elements separator. */
5113 /* Generate the string rep. */
5114 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+1);
5116 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5118 const char *strRep
= Jim_GetString(ele
[i
], &len
);
5121 switch(quotingType
[i
]) {
5122 case JIM_ELESTR_SIMPLE
:
5123 memcpy(p
, strRep
, len
);
5127 case JIM_ELESTR_BRACE
:
5129 memcpy(p
, strRep
, len
);
5132 realLength
+= len
+2;
5134 case JIM_ELESTR_QUOTE
:
5135 q
= BackslashQuoteString(strRep
, len
, &qlen
);
5142 /* Add a separating space */
5143 if (i
+1 != objPtr
->internalRep
.listValue
.len
) {
5148 *p
= '\0'; /* nul term. */
5149 objPtr
->length
= realLength
;
5150 Jim_Free(quotingType
);
5153 int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
5155 struct JimParserCtx parser
;
5159 /* Get the string representation */
5160 str
= Jim_GetString(objPtr
, &strLen
);
5162 /* Free the old internal repr just now and initialize the
5163 * new one just now. The string->list conversion can't fail. */
5164 Jim_FreeIntRep(interp
, objPtr
);
5165 objPtr
->typePtr
= &listObjType
;
5166 objPtr
->internalRep
.listValue
.len
= 0;
5167 objPtr
->internalRep
.listValue
.maxLen
= 0;
5168 objPtr
->internalRep
.listValue
.ele
= NULL
;
5170 /* Convert into a list */
5171 JimParserInit(&parser
, str
, strLen
, 1);
5172 while(!JimParserEof(&parser
)) {
5175 Jim_Obj
*elementPtr
;
5177 JimParseList(&parser
);
5178 if (JimParserTtype(&parser
) != JIM_TT_STR
&&
5179 JimParserTtype(&parser
) != JIM_TT_ESC
)
5181 token
= JimParserGetToken(&parser
, &tokenLen
, &type
, NULL
);
5182 elementPtr
= Jim_NewStringObjNoAlloc(interp
, token
, tokenLen
);
5183 ListAppendElement(objPtr
, elementPtr
);
5188 Jim_Obj
*Jim_NewListObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
,
5194 objPtr
= Jim_NewObj(interp
);
5195 objPtr
->typePtr
= &listObjType
;
5196 objPtr
->bytes
= NULL
;
5197 objPtr
->internalRep
.listValue
.ele
= NULL
;
5198 objPtr
->internalRep
.listValue
.len
= 0;
5199 objPtr
->internalRep
.listValue
.maxLen
= 0;
5200 for (i
= 0; i
< len
; i
++) {
5201 ListAppendElement(objPtr
, elements
[i
]);
5206 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5207 * length of the vector. Note that the user of this function should make
5208 * sure that the list object can't shimmer while the vector returned
5209 * is in use, this vector is the one stored inside the internal representation
5210 * of the list object. This function is not exported, extensions should
5211 * always access to the List object elements using Jim_ListIndex(). */
5212 static void JimListGetElements(Jim_Interp
*interp
, Jim_Obj
*listObj
, int *argc
,
5215 Jim_ListLength(interp
, listObj
, argc
);
5216 assert(listObj
->typePtr
== &listObjType
);
5217 *listVec
= listObj
->internalRep
.listValue
.ele
;
5220 /* ListSortElements type values */
5221 enum {JIM_LSORT_ASCII
, JIM_LSORT_NOCASE
, JIM_LSORT_ASCII_DECR
,
5222 JIM_LSORT_NOCASE_DECR
};
5224 /* Sort the internal rep of a list. */
5225 static int ListSortString(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5227 return Jim_StringCompareObj(*lhsObj
, *rhsObj
, 0);
5230 static int ListSortStringDecr(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5232 return Jim_StringCompareObj(*lhsObj
, *rhsObj
, 0) * -1;
5235 static int ListSortStringNoCase(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5237 return Jim_StringCompareObj(*lhsObj
, *rhsObj
, 1);
5240 static int ListSortStringNoCaseDecr(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5242 return Jim_StringCompareObj(*lhsObj
, *rhsObj
, 1) * -1;
5245 /* Sort a list *in place*. MUST be called with non-shared objects. */
5246 static void ListSortElements(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, int type
)
5248 typedef int (qsort_comparator
)(const void *, const void *);
5249 int (*fn
)(Jim_Obj
**, Jim_Obj
**);
5253 if (Jim_IsShared(listObjPtr
))
5254 Jim_Panic(interp
,"Jim_ListSortElements called with shared object");
5255 if (listObjPtr
->typePtr
!= &listObjType
)
5256 SetListFromAny(interp
, listObjPtr
);
5258 vector
= listObjPtr
->internalRep
.listValue
.ele
;
5259 len
= listObjPtr
->internalRep
.listValue
.len
;
5261 case JIM_LSORT_ASCII
: fn
= ListSortString
; break;
5262 case JIM_LSORT_NOCASE
: fn
= ListSortStringNoCase
; break;
5263 case JIM_LSORT_ASCII_DECR
: fn
= ListSortStringDecr
; break;
5264 case JIM_LSORT_NOCASE_DECR
: fn
= ListSortStringNoCaseDecr
; break;
5266 fn
= NULL
; /* avoid warning */
5267 Jim_Panic(interp
,"ListSort called with invalid sort type");
5269 qsort(vector
, len
, sizeof(Jim_Obj
*), (qsort_comparator
*)fn
);
5270 Jim_InvalidateStringRep(listObjPtr
);
5273 /* This is the low-level function to append an element to a list.
5274 * The higher-level Jim_ListAppendElement() performs shared object
5275 * check and invalidate the string repr. This version is used
5276 * in the internals of the List Object and is not exported.
5278 * NOTE: this function can be called only against objects
5279 * with internal type of List. */
5280 void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
5282 int requiredLen
= listPtr
->internalRep
.listValue
.len
+ 1;
5284 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
5285 int maxLen
= requiredLen
* 2;
5287 listPtr
->internalRep
.listValue
.ele
=
5288 Jim_Realloc(listPtr
->internalRep
.listValue
.ele
,
5289 sizeof(Jim_Obj
*)*maxLen
);
5290 listPtr
->internalRep
.listValue
.maxLen
= maxLen
;
5292 listPtr
->internalRep
.listValue
.ele
[listPtr
->internalRep
.listValue
.len
] =
5294 listPtr
->internalRep
.listValue
.len
++;
5295 Jim_IncrRefCount(objPtr
);
5298 /* This is the low-level function to insert elements into a list.
5299 * The higher-level Jim_ListInsertElements() performs shared object
5300 * check and invalidate the string repr. This version is used
5301 * in the internals of the List Object and is not exported.
5303 * NOTE: this function can be called only against objects
5304 * with internal type of List. */
5305 void ListInsertElements(Jim_Obj
*listPtr
, int index
, int elemc
,
5306 Jim_Obj
*const *elemVec
)
5308 int currentLen
= listPtr
->internalRep
.listValue
.len
;
5309 int requiredLen
= currentLen
+ elemc
;
5313 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
5314 int maxLen
= requiredLen
* 2;
5316 listPtr
->internalRep
.listValue
.ele
=
5317 Jim_Realloc(listPtr
->internalRep
.listValue
.ele
,
5318 sizeof(Jim_Obj
*)*maxLen
);
5319 listPtr
->internalRep
.listValue
.maxLen
= maxLen
;
5321 point
= listPtr
->internalRep
.listValue
.ele
+ index
;
5322 memmove(point
+elemc
, point
, (currentLen
-index
) * sizeof(Jim_Obj
*));
5323 for (i
=0; i
< elemc
; ++i
) {
5324 point
[i
] = elemVec
[i
];
5325 Jim_IncrRefCount(point
[i
]);
5327 listPtr
->internalRep
.listValue
.len
+= elemc
;
5330 /* Appends every element of appendListPtr into listPtr.
5331 * Both have to be of the list type. */
5332 void ListAppendList(Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
5334 int i
, oldLen
= listPtr
->internalRep
.listValue
.len
;
5335 int appendLen
= appendListPtr
->internalRep
.listValue
.len
;
5336 int requiredLen
= oldLen
+ appendLen
;
5338 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
5339 int maxLen
= requiredLen
* 2;
5341 listPtr
->internalRep
.listValue
.ele
=
5342 Jim_Realloc(listPtr
->internalRep
.listValue
.ele
,
5343 sizeof(Jim_Obj
*)*maxLen
);
5344 listPtr
->internalRep
.listValue
.maxLen
= maxLen
;
5346 for (i
= 0; i
< appendLen
; i
++) {
5347 Jim_Obj
*objPtr
= appendListPtr
->internalRep
.listValue
.ele
[i
];
5348 listPtr
->internalRep
.listValue
.ele
[oldLen
+i
] = objPtr
;
5349 Jim_IncrRefCount(objPtr
);
5351 listPtr
->internalRep
.listValue
.len
+= appendLen
;
5354 void Jim_ListAppendElement(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
5356 if (Jim_IsShared(listPtr
))
5357 Jim_Panic(interp
,"Jim_ListAppendElement called with shared object");
5358 if (listPtr
->typePtr
!= &listObjType
)
5359 SetListFromAny(interp
, listPtr
);
5360 Jim_InvalidateStringRep(listPtr
);
5361 ListAppendElement(listPtr
, objPtr
);
5364 void Jim_ListAppendList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
5366 if (Jim_IsShared(listPtr
))
5367 Jim_Panic(interp
,"Jim_ListAppendList called with shared object");
5368 if (listPtr
->typePtr
!= &listObjType
)
5369 SetListFromAny(interp
, listPtr
);
5370 Jim_InvalidateStringRep(listPtr
);
5371 ListAppendList(listPtr
, appendListPtr
);
5374 void Jim_ListLength(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int *intPtr
)
5376 if (listPtr
->typePtr
!= &listObjType
)
5377 SetListFromAny(interp
, listPtr
);
5378 *intPtr
= listPtr
->internalRep
.listValue
.len
;
5381 void Jim_ListInsertElements(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int index
,
5382 int objc
, Jim_Obj
*const *objVec
)
5384 if (Jim_IsShared(listPtr
))
5385 Jim_Panic(interp
,"Jim_ListInsertElement called with shared object");
5386 if (listPtr
->typePtr
!= &listObjType
)
5387 SetListFromAny(interp
, listPtr
);
5388 if (index
>= 0 && index
> listPtr
->internalRep
.listValue
.len
)
5389 index
= listPtr
->internalRep
.listValue
.len
;
5390 else if (index
< 0 )
5392 Jim_InvalidateStringRep(listPtr
);
5393 ListInsertElements(listPtr
, index
, objc
, objVec
);
5396 int Jim_ListIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int index
,
5397 Jim_Obj
**objPtrPtr
, int flags
)
5399 if (listPtr
->typePtr
!= &listObjType
)
5400 SetListFromAny(interp
, listPtr
);
5401 if ((index
>= 0 && index
>= listPtr
->internalRep
.listValue
.len
) ||
5402 (index
< 0 && (-index
-1) >= listPtr
->internalRep
.listValue
.len
)) {
5403 if (flags
& JIM_ERRMSG
) {
5404 Jim_SetResultString(interp
,
5405 "list index out of range", -1);
5410 index
= listPtr
->internalRep
.listValue
.len
+index
;
5411 *objPtrPtr
= listPtr
->internalRep
.listValue
.ele
[index
];
5415 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int index
,
5416 Jim_Obj
*newObjPtr
, int flags
)
5418 if (listPtr
->typePtr
!= &listObjType
)
5419 SetListFromAny(interp
, listPtr
);
5420 if ((index
>= 0 && index
>= listPtr
->internalRep
.listValue
.len
) ||
5421 (index
< 0 && (-index
-1) >= listPtr
->internalRep
.listValue
.len
)) {
5422 if (flags
& JIM_ERRMSG
) {
5423 Jim_SetResultString(interp
,
5424 "list index out of range", -1);
5429 index
= listPtr
->internalRep
.listValue
.len
+index
;
5430 Jim_DecrRefCount(interp
, listPtr
->internalRep
.listValue
.ele
[index
]);
5431 listPtr
->internalRep
.listValue
.ele
[index
] = newObjPtr
;
5432 Jim_IncrRefCount(newObjPtr
);
5436 /* Modify the list stored into the variable named 'varNamePtr'
5437 * setting the element specified by the 'indexc' indexes objects in 'indexv',
5438 * with the new element 'newObjptr'. */
5439 int Jim_SetListIndex(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
5440 Jim_Obj
*const *indexv
, int indexc
, Jim_Obj
*newObjPtr
)
5442 Jim_Obj
*varObjPtr
, *objPtr
, *listObjPtr
;
5443 int shared
, i
, index
;
5445 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
5448 if ((shared
= Jim_IsShared(objPtr
)))
5449 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
5450 for (i
= 0; i
< indexc
-1; i
++) {
5451 listObjPtr
= objPtr
;
5452 if (Jim_GetIndex(interp
, indexv
[i
], &index
) != JIM_OK
)
5454 if (Jim_ListIndex(interp
, listObjPtr
, index
, &objPtr
,
5455 JIM_ERRMSG
) != JIM_OK
) {
5458 if (Jim_IsShared(objPtr
)) {
5459 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
5460 ListSetIndex(interp
, listObjPtr
, index
, objPtr
, JIM_NONE
);
5462 Jim_InvalidateStringRep(listObjPtr
);
5464 if (Jim_GetIndex(interp
, indexv
[indexc
-1], &index
) != JIM_OK
)
5466 if (ListSetIndex(interp
, objPtr
, index
, newObjPtr
, JIM_ERRMSG
) == JIM_ERR
)
5468 Jim_InvalidateStringRep(objPtr
);
5469 Jim_InvalidateStringRep(varObjPtr
);
5470 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
5472 Jim_SetResult(interp
, varObjPtr
);
5476 Jim_FreeNewObj(interp
, varObjPtr
);
5481 Jim_Obj
*Jim_ConcatObj(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
5485 /* If all the objects in objv are lists without string rep.
5486 * it's possible to return a list as result, that's the
5487 * concatenation of all the lists. */
5488 for (i
= 0; i
< objc
; i
++) {
5489 if (objv
[i
]->typePtr
!= &listObjType
|| objv
[i
]->bytes
)
5493 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
5494 for (i
= 0; i
< objc
; i
++)
5495 Jim_ListAppendList(interp
, objPtr
, objv
[i
]);
5498 /* Else... we have to glue strings together */
5499 int len
= 0, objLen
;
5502 /* Compute the length */
5503 for (i
= 0; i
< objc
; i
++) {
5504 Jim_GetString(objv
[i
], &objLen
);
5507 if (objc
) len
+= objc
-1;
5508 /* Create the string rep, and a stinrg object holding it. */
5509 p
= bytes
= Jim_Alloc(len
+1);
5510 for (i
= 0; i
< objc
; i
++) {
5511 const char *s
= Jim_GetString(objv
[i
], &objLen
);
5512 while (objLen
&& (*s
== ' ' || *s
== '\t' || *s
== '\n'))
5514 s
++; objLen
--; len
--;
5516 while (objLen
&& (s
[objLen
-1] == ' ' ||
5517 s
[objLen
-1] == '\n' || s
[objLen
-1] == '\t')) {
5520 memcpy(p
, s
, objLen
);
5522 if (objLen
&& i
+1 != objc
) {
5524 } else if (i
+1 != objc
) {
5525 /* Drop the space calcuated for this
5526 * element that is instead null. */
5531 return Jim_NewStringObjNoAlloc(interp
, bytes
, len
);
5535 /* Returns a list composed of the elements in the specified range.
5536 * first and start are directly accepted as Jim_Objects and
5537 * processed for the end?-index? case. */
5538 Jim_Obj
*Jim_ListRange(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
5543 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
5544 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
5546 Jim_ListLength(interp
, listObjPtr
, &len
); /* will convert into list */
5547 first
= JimRelToAbsIndex(len
, first
);
5548 last
= JimRelToAbsIndex(len
, last
);
5549 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
5550 return Jim_NewListObj(interp
,
5551 listObjPtr
->internalRep
.listValue
.ele
+first
, rangeLen
);
5554 /* -----------------------------------------------------------------------------
5556 * ---------------------------------------------------------------------------*/
5557 static void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5558 static void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
5559 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
);
5560 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
5562 /* Dict HashTable Type.
5564 * Keys and Values are Jim objects. */
5566 unsigned int JimObjectHTHashFunction(const void *key
)
5569 Jim_Obj
*objPtr
= (Jim_Obj
*) key
;
5572 str
= Jim_GetString(objPtr
, &len
);
5573 h
= Jim_GenHashFunction((unsigned char*)str
, len
);
5577 int JimObjectHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
5579 JIM_NOTUSED(privdata
);
5581 return Jim_StringEqObj((Jim_Obj
*)key1
, (Jim_Obj
*)key2
, 0);
5584 static void JimObjectHTKeyValDestructor(void *interp
, void *val
)
5586 Jim_Obj
*objPtr
= val
;
5588 Jim_DecrRefCount(interp
, objPtr
);
5591 static Jim_HashTableType JimDictHashTableType
= {
5592 JimObjectHTHashFunction
, /* hash function */
5595 JimObjectHTKeyCompare
, /* key compare */
5596 (void(*)(void*, const void*)) /* ATTENTION: const cast */
5597 JimObjectHTKeyValDestructor
, /* key destructor */
5598 JimObjectHTKeyValDestructor
/* val destructor */
5601 /* Note that while the elements of the dict may contain references,
5602 * the list object itself can't. This basically means that the
5603 * dict object string representation as a whole can't contain references
5604 * that are not presents in the single elements. */
5605 static Jim_ObjType dictObjType
= {
5607 FreeDictInternalRep
,
5613 void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5615 JIM_NOTUSED(interp
);
5617 Jim_FreeHashTable(objPtr
->internalRep
.ptr
);
5618 Jim_Free(objPtr
->internalRep
.ptr
);
5621 void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
5623 Jim_HashTable
*ht
, *dupHt
;
5624 Jim_HashTableIterator
*htiter
;
5627 /* Create a new hash table */
5628 ht
= srcPtr
->internalRep
.ptr
;
5629 dupHt
= Jim_Alloc(sizeof(*dupHt
));
5630 Jim_InitHashTable(dupHt
, &JimDictHashTableType
, interp
);
5632 Jim_ExpandHashTable(dupHt
, ht
->size
);
5633 /* Copy every element from the source to the dup hash table */
5634 htiter
= Jim_GetHashTableIterator(ht
);
5635 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
5636 const Jim_Obj
*keyObjPtr
= he
->key
;
5637 Jim_Obj
*valObjPtr
= he
->val
;
5639 Jim_IncrRefCount((Jim_Obj
*)keyObjPtr
); /* ATTENTION: const cast */
5640 Jim_IncrRefCount(valObjPtr
);
5641 Jim_AddHashEntry(dupHt
, keyObjPtr
, valObjPtr
);
5643 Jim_FreeHashTableIterator(htiter
);
5645 dupPtr
->internalRep
.ptr
= dupHt
;
5646 dupPtr
->typePtr
= &dictObjType
;
5649 void UpdateStringOfDict(struct Jim_Obj
*objPtr
)
5651 int i
, bufLen
, realLength
;
5654 int *quotingType
, objc
;
5656 Jim_HashTableIterator
*htiter
;
5660 /* Trun the hash table into a flat vector of Jim_Objects. */
5661 ht
= objPtr
->internalRep
.ptr
;
5663 objv
= Jim_Alloc(objc
*sizeof(Jim_Obj
*));
5664 htiter
= Jim_GetHashTableIterator(ht
);
5666 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
5667 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
5668 objv
[i
++] = he
->val
;
5670 Jim_FreeHashTableIterator(htiter
);
5671 /* (Over) Estimate the space needed. */
5672 quotingType
= Jim_Alloc(sizeof(int)*objc
);
5674 for (i
= 0; i
< objc
; i
++) {
5677 strRep
= Jim_GetString(objv
[i
], &len
);
5678 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
5679 switch (quotingType
[i
]) {
5680 case JIM_ELESTR_SIMPLE
: bufLen
+= len
; break;
5681 case JIM_ELESTR_BRACE
: bufLen
+= len
+2; break;
5682 case JIM_ELESTR_QUOTE
: bufLen
+= len
*2; break;
5684 bufLen
++; /* elements separator. */
5688 /* Generate the string rep. */
5689 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+1);
5691 for (i
= 0; i
< objc
; i
++) {
5693 const char *strRep
= Jim_GetString(objv
[i
], &len
);
5696 switch(quotingType
[i
]) {
5697 case JIM_ELESTR_SIMPLE
:
5698 memcpy(p
, strRep
, len
);
5702 case JIM_ELESTR_BRACE
:
5704 memcpy(p
, strRep
, len
);
5707 realLength
+= len
+2;
5709 case JIM_ELESTR_QUOTE
:
5710 q
= BackslashQuoteString(strRep
, len
, &qlen
);
5717 /* Add a separating space */
5723 *p
= '\0'; /* nul term. */
5724 objPtr
->length
= realLength
;
5725 Jim_Free(quotingType
);
5729 int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
5731 struct JimParserCtx parser
;
5737 /* Get the string representation */
5738 str
= Jim_GetString(objPtr
, &strLen
);
5740 /* Free the old internal repr just now and initialize the
5741 * new one just now. The string->list conversion can't fail. */
5742 Jim_FreeIntRep(interp
, objPtr
);
5743 ht
= Jim_Alloc(sizeof(*ht
));
5744 Jim_InitHashTable(ht
, &JimDictHashTableType
, interp
);
5745 objPtr
->typePtr
= &dictObjType
;
5746 objPtr
->internalRep
.ptr
= ht
;
5748 /* Convert into a dict */
5749 JimParserInit(&parser
, str
, strLen
, 1);
5751 while(!JimParserEof(&parser
)) {
5755 JimParseList(&parser
);
5756 if (JimParserTtype(&parser
) != JIM_TT_STR
&&
5757 JimParserTtype(&parser
) != JIM_TT_ESC
)
5759 token
= JimParserGetToken(&parser
, &tokenLen
, &type
, NULL
);
5760 objv
[i
++] = Jim_NewStringObjNoAlloc(interp
, token
, tokenLen
);
5763 Jim_IncrRefCount(objv
[0]);
5764 Jim_IncrRefCount(objv
[1]);
5765 if (Jim_AddHashEntry(ht
, objv
[0], objv
[1]) != JIM_OK
) {
5767 he
= Jim_FindHashEntry(ht
, objv
[0]);
5768 Jim_DecrRefCount(interp
, objv
[0]);
5769 /* ATTENTION: const cast */
5770 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->val
);
5776 Jim_FreeNewObj(interp
, objv
[0]);
5777 objPtr
->typePtr
= NULL
;
5778 Jim_FreeHashTable(ht
);
5779 Jim_SetResultString(interp
, "invalid dictionary value: must be a list with an even number of elements", -1);
5785 /* Dict object API */
5787 /* Add an element to a dict. objPtr must be of the "dict" type.
5788 * The higer-level exported function is Jim_DictAddElement().
5789 * If an element with the specified key already exists, the value
5790 * associated is replaced with the new one.
5792 * if valueObjPtr == NULL, the key is instead removed if it exists. */
5793 static void DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
5794 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
5796 Jim_HashTable
*ht
= objPtr
->internalRep
.ptr
;
5798 if (valueObjPtr
== NULL
) { /* unset */
5799 Jim_DeleteHashEntry(ht
, keyObjPtr
);
5802 Jim_IncrRefCount(keyObjPtr
);
5803 Jim_IncrRefCount(valueObjPtr
);
5804 if (Jim_AddHashEntry(ht
, keyObjPtr
, valueObjPtr
) != JIM_OK
) {
5805 Jim_HashEntry
*he
= Jim_FindHashEntry(ht
, keyObjPtr
);
5806 Jim_DecrRefCount(interp
, keyObjPtr
);
5807 /* ATTENTION: const cast */
5808 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->val
);
5809 he
->val
= valueObjPtr
;
5813 /* Add an element, higher-level interface for DictAddElement().
5814 * If valueObjPtr == NULL, the key is removed if it exists. */
5815 int Jim_DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
5816 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
5818 if (Jim_IsShared(objPtr
))
5819 Jim_Panic(interp
,"Jim_DictAddElement called with shared object");
5820 if (objPtr
->typePtr
!= &dictObjType
) {
5821 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
)
5824 DictAddElement(interp
, objPtr
, keyObjPtr
, valueObjPtr
);
5825 Jim_InvalidateStringRep(objPtr
);
5829 Jim_Obj
*Jim_NewDictObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
5835 Jim_Panic(interp
,"Jim_NewDicObj() 'len' argument must be even");
5837 objPtr
= Jim_NewObj(interp
);
5838 objPtr
->typePtr
= &dictObjType
;
5839 objPtr
->bytes
= NULL
;
5840 objPtr
->internalRep
.ptr
= Jim_Alloc(sizeof(Jim_HashTable
));
5841 Jim_InitHashTable(objPtr
->internalRep
.ptr
, &JimDictHashTableType
, interp
);
5842 for (i
= 0; i
< len
; i
+= 2)
5843 DictAddElement(interp
, objPtr
, elements
[i
], elements
[i
+1]);
5847 /* Return the value associated to the specified dict key */
5848 int Jim_DictKey(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
*keyPtr
,
5849 Jim_Obj
**objPtrPtr
, int flags
)
5854 if (dictPtr
->typePtr
!= &dictObjType
) {
5855 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
5858 ht
= dictPtr
->internalRep
.ptr
;
5859 if ((he
= Jim_FindHashEntry(ht
, keyPtr
)) == NULL
) {
5860 if (flags
& JIM_ERRMSG
) {
5861 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
5862 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
5863 "key \"", Jim_GetString(keyPtr
, NULL
),
5864 "\" not found in dictionary", NULL
);
5868 *objPtrPtr
= he
->val
;
5872 /* Return the value associated to the specified dict keys */
5873 int Jim_DictKeysVector(Jim_Interp
*interp
, Jim_Obj
*dictPtr
,
5874 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
**objPtrPtr
, int flags
)
5880 *objPtrPtr
= dictPtr
;
5884 for (i
= 0; i
< keyc
; i
++) {
5885 if (Jim_DictKey(interp
, dictPtr
, keyv
[i
], &objPtr
, flags
)
5890 *objPtrPtr
= objPtr
;
5894 /* Modify the dict stored into the variable named 'varNamePtr'
5895 * setting the element specified by the 'keyc' keys objects in 'keyv',
5896 * with the new value of the element 'newObjPtr'.
5898 * If newObjPtr == NULL the operation is to remove the given key
5899 * from the dictionary. */
5900 int Jim_SetDictKeysVector(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
5901 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*newObjPtr
)
5903 Jim_Obj
*varObjPtr
, *objPtr
, *dictObjPtr
;
5906 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
5907 if (objPtr
== NULL
) {
5908 if (newObjPtr
== NULL
) /* Cannot remove a key from non existing var */
5910 varObjPtr
= objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
5911 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
5912 Jim_FreeNewObj(interp
, varObjPtr
);
5916 if ((shared
= Jim_IsShared(objPtr
)))
5917 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
5918 for (i
= 0; i
< keyc
-1; i
++) {
5919 dictObjPtr
= objPtr
;
5921 /* Check if it's a valid dictionary */
5922 if (dictObjPtr
->typePtr
!= &dictObjType
) {
5923 if (SetDictFromAny(interp
, dictObjPtr
) != JIM_OK
)
5926 /* Check if the given key exists. */
5927 Jim_InvalidateStringRep(dictObjPtr
);
5928 if (Jim_DictKey(interp
, dictObjPtr
, keyv
[i
], &objPtr
,
5929 newObjPtr
? JIM_NONE
: JIM_ERRMSG
) == JIM_OK
)
5931 /* This key exists at the current level.
5932 * Make sure it's not shared!. */
5933 if (Jim_IsShared(objPtr
)) {
5934 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
5935 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
5938 /* Key not found. If it's an [unset] operation
5939 * this is an error. Only the last key may not
5941 if (newObjPtr
== NULL
)
5943 /* Otherwise set an empty dictionary
5944 * as key's value. */
5945 objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
5946 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
5949 if (Jim_DictAddElement(interp
, objPtr
, keyv
[keyc
-1], newObjPtr
)
5952 Jim_InvalidateStringRep(objPtr
);
5953 Jim_InvalidateStringRep(varObjPtr
);
5954 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
5956 Jim_SetResult(interp
, varObjPtr
);
5960 Jim_FreeNewObj(interp
, varObjPtr
);
5965 /* -----------------------------------------------------------------------------
5967 * ---------------------------------------------------------------------------*/
5968 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
);
5969 static int SetIndexFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
5971 static Jim_ObjType indexObjType
= {
5975 UpdateStringOfIndex
,
5979 void UpdateStringOfIndex(struct Jim_Obj
*objPtr
)
5982 char buf
[JIM_INTEGER_SPACE
+1];
5984 if (objPtr
->internalRep
.indexValue
>= 0)
5985 len
= sprintf(buf
, "%d", objPtr
->internalRep
.indexValue
);
5986 else if (objPtr
->internalRep
.indexValue
== -1)
5987 len
= sprintf(buf
, "end");
5989 len
= sprintf(buf
, "end%d", objPtr
->internalRep
.indexValue
+1);
5991 objPtr
->bytes
= Jim_Alloc(len
+1);
5992 memcpy(objPtr
->bytes
, buf
, len
+1);
5993 objPtr
->length
= len
;
5996 int SetIndexFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6001 /* Get the string representation */
6002 str
= Jim_GetString(objPtr
, NULL
);
6003 /* Try to convert into an index */
6004 if (!strcmp(str
, "end")) {
6008 if (!strncmp(str
, "end-", 4)) {
6012 if (Jim_StringToIndex(str
, &index
) != JIM_OK
) {
6013 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
6014 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
6015 "bad index \"", Jim_GetString(objPtr
, NULL
), "\": "
6016 "must be integer or end?-integer?", NULL
);
6025 } else if (!end
&& index
< 0)
6027 /* Free the old internal repr and set the new one. */
6028 Jim_FreeIntRep(interp
, objPtr
);
6029 objPtr
->typePtr
= &indexObjType
;
6030 objPtr
->internalRep
.indexValue
= index
;
6034 int Jim_GetIndex(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *indexPtr
)
6036 /* Avoid shimmering if the object is an integer. */
6037 if (objPtr
->typePtr
== &intObjType
) {
6038 jim_wide val
= objPtr
->internalRep
.wideValue
;
6039 if (!(val
< LONG_MIN
) && !(val
> LONG_MAX
)) {
6040 *indexPtr
= (val
< 0) ? -INT_MAX
: (long)val
;;
6044 if (objPtr
->typePtr
!= &indexObjType
&&
6045 SetIndexFromAny(interp
, objPtr
) == JIM_ERR
)
6047 *indexPtr
= objPtr
->internalRep
.indexValue
;
6051 /* -----------------------------------------------------------------------------
6052 * Return Code Object.
6053 * ---------------------------------------------------------------------------*/
6055 static int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6057 static Jim_ObjType returnCodeObjType
= {
6065 int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6068 int strLen
, returnCode
;
6071 /* Get the string representation */
6072 str
= Jim_GetString(objPtr
, &strLen
);
6073 /* Try to convert into an integer */
6074 if (JimGetWideNoErr(interp
, objPtr
, &wideValue
) != JIM_ERR
)
6075 returnCode
= (int) wideValue
;
6076 else if (!JimStringCompare(str
, strLen
, "ok", 2, JIM_NOCASE
))
6077 returnCode
= JIM_OK
;
6078 else if (!JimStringCompare(str
, strLen
, "error", 5, JIM_NOCASE
))
6079 returnCode
= JIM_ERR
;
6080 else if (!JimStringCompare(str
, strLen
, "return", 6, JIM_NOCASE
))
6081 returnCode
= JIM_RETURN
;
6082 else if (!JimStringCompare(str
, strLen
, "break", 5, JIM_NOCASE
))
6083 returnCode
= JIM_BREAK
;
6084 else if (!JimStringCompare(str
, strLen
, "continue", 8, JIM_NOCASE
))
6085 returnCode
= JIM_CONTINUE
;
6086 else if (!JimStringCompare(str
, strLen
, "eval", 4, JIM_NOCASE
))
6087 returnCode
= JIM_EVAL
;
6088 else if (!JimStringCompare(str
, strLen
, "exit", 4, JIM_NOCASE
))
6089 returnCode
= JIM_EXIT
;
6091 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
6092 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
6093 "expected return code but got '", str
, "'",
6097 /* Free the old internal repr and set the new one. */
6098 Jim_FreeIntRep(interp
, objPtr
);
6099 objPtr
->typePtr
= &returnCodeObjType
;
6100 objPtr
->internalRep
.returnCode
= returnCode
;
6104 int Jim_GetReturnCode(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *intPtr
)
6106 if (objPtr
->typePtr
!= &returnCodeObjType
&&
6107 SetReturnCodeFromAny(interp
, objPtr
) == JIM_ERR
)
6109 *intPtr
= objPtr
->internalRep
.returnCode
;
6113 /* -----------------------------------------------------------------------------
6114 * Expression Parsing
6115 * ---------------------------------------------------------------------------*/
6116 static int JimParseExprOperator(struct JimParserCtx
*pc
);
6117 static int JimParseExprNumber(struct JimParserCtx
*pc
);
6118 static int JimParseExprIrrational(struct JimParserCtx
*pc
);
6120 /* Exrp's Stack machine operators opcodes. */
6122 /* Binary operators (numbers) */
6123 #define JIM_EXPROP_BINARY_NUM_FIRST 0 /* first */
6124 #define JIM_EXPROP_MUL 0
6125 #define JIM_EXPROP_DIV 1
6126 #define JIM_EXPROP_MOD 2
6127 #define JIM_EXPROP_SUB 3
6128 #define JIM_EXPROP_ADD 4
6129 #define JIM_EXPROP_LSHIFT 5
6130 #define JIM_EXPROP_RSHIFT 6
6131 #define JIM_EXPROP_ROTL 7
6132 #define JIM_EXPROP_ROTR 8
6133 #define JIM_EXPROP_LT 9
6134 #define JIM_EXPROP_GT 10
6135 #define JIM_EXPROP_LTE 11
6136 #define JIM_EXPROP_GTE 12
6137 #define JIM_EXPROP_NUMEQ 13
6138 #define JIM_EXPROP_NUMNE 14
6139 #define JIM_EXPROP_BITAND 15
6140 #define JIM_EXPROP_BITXOR 16
6141 #define JIM_EXPROP_BITOR 17
6142 #define JIM_EXPROP_LOGICAND 18
6143 #define JIM_EXPROP_LOGICOR 19
6144 #define JIM_EXPROP_LOGICAND_LEFT 20
6145 #define JIM_EXPROP_LOGICOR_LEFT 21
6146 #define JIM_EXPROP_POW 22
6147 #define JIM_EXPROP_BINARY_NUM_LAST 22 /* last */
6149 /* Binary operators (strings) */
6150 #define JIM_EXPROP_STREQ 23
6151 #define JIM_EXPROP_STRNE 24
6153 /* Unary operators (numbers) */
6154 #define JIM_EXPROP_NOT 25
6155 #define JIM_EXPROP_BITNOT 26
6156 #define JIM_EXPROP_UNARYMINUS 27
6157 #define JIM_EXPROP_UNARYPLUS 28
6158 #define JIM_EXPROP_LOGICAND_RIGHT 29
6159 #define JIM_EXPROP_LOGICOR_RIGHT 30
6161 /* Ternary operators */
6162 #define JIM_EXPROP_TERNARY 31
6165 #define JIM_EXPROP_NUMBER 32
6166 #define JIM_EXPROP_COMMAND 33
6167 #define JIM_EXPROP_VARIABLE 34
6168 #define JIM_EXPROP_DICTSUGAR 35
6169 #define JIM_EXPROP_SUBST 36
6170 #define JIM_EXPROP_STRING 37
6172 /* Operators table */
6173 typedef struct Jim_ExprOperator
{
6180 /* name - precedence - arity - opcode */
6181 static struct Jim_ExprOperator Jim_ExprOperators
[] = {
6182 {"!", 300, 1, JIM_EXPROP_NOT
},
6183 {"~", 300, 1, JIM_EXPROP_BITNOT
},
6184 {"unarymin", 300, 1, JIM_EXPROP_UNARYMINUS
},
6185 {"unaryplus", 300, 1, JIM_EXPROP_UNARYPLUS
},
6187 {"**", 250, 2, JIM_EXPROP_POW
},
6189 {"*", 200, 2, JIM_EXPROP_MUL
},
6190 {"/", 200, 2, JIM_EXPROP_DIV
},
6191 {"%", 200, 2, JIM_EXPROP_MOD
},
6193 {"-", 100, 2, JIM_EXPROP_SUB
},
6194 {"+", 100, 2, JIM_EXPROP_ADD
},
6196 {"<<<", 90, 3, JIM_EXPROP_ROTL
},
6197 {">>>", 90, 3, JIM_EXPROP_ROTR
},
6198 {"<<", 90, 2, JIM_EXPROP_LSHIFT
},
6199 {">>", 90, 2, JIM_EXPROP_RSHIFT
},
6201 {"<", 80, 2, JIM_EXPROP_LT
},
6202 {">", 80, 2, JIM_EXPROP_GT
},
6203 {"<=", 80, 2, JIM_EXPROP_LTE
},
6204 {">=", 80, 2, JIM_EXPROP_GTE
},
6206 {"==", 70, 2, JIM_EXPROP_NUMEQ
},
6207 {"!=", 70, 2, JIM_EXPROP_NUMNE
},
6209 {"eq", 60, 2, JIM_EXPROP_STREQ
},
6210 {"ne", 60, 2, JIM_EXPROP_STRNE
},
6212 {"&", 50, 2, JIM_EXPROP_BITAND
},
6213 {"^", 49, 2, JIM_EXPROP_BITXOR
},
6214 {"|", 48, 2, JIM_EXPROP_BITOR
},
6216 {"&&", 10, 2, JIM_EXPROP_LOGICAND
},
6217 {"||", 10, 2, JIM_EXPROP_LOGICOR
},
6219 {"?", 5, 3, JIM_EXPROP_TERNARY
},
6220 /* private operators */
6221 {NULL
, 10, 2, JIM_EXPROP_LOGICAND_LEFT
},
6222 {NULL
, 10, 1, JIM_EXPROP_LOGICAND_RIGHT
},
6223 {NULL
, 10, 2, JIM_EXPROP_LOGICOR_LEFT
},
6224 {NULL
, 10, 1, JIM_EXPROP_LOGICOR_RIGHT
},
6227 #define JIM_EXPR_OPERATORS_NUM \
6228 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
6230 int JimParseExpression(struct JimParserCtx
*pc
)
6232 /* Discard spaces and quoted newline */
6233 while(*(pc
->p
) == ' ' ||
6237 (*(pc
->p
) == '\\' && *(pc
->p
+1) == '\n')) {
6242 pc
->tstart
= pc
->tend
= pc
->p
;
6243 pc
->tline
= pc
->linenr
;
6244 pc
->tt
= JIM_TT_EOL
;
6250 pc
->tstart
= pc
->tend
= pc
->p
;
6251 pc
->tline
= pc
->linenr
;
6252 pc
->tt
= JIM_TT_SUBEXPR_START
;
6256 pc
->tstart
= pc
->tend
= pc
->p
;
6257 pc
->tline
= pc
->linenr
;
6258 pc
->tt
= JIM_TT_SUBEXPR_END
;
6262 return JimParseCmd(pc
);
6265 if (JimParseVar(pc
) == JIM_ERR
)
6266 return JimParseExprOperator(pc
);
6271 if ((pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_EXPR_OPERATOR
) &&
6272 isdigit((int)*(pc
->p
+1)))
6273 return JimParseExprNumber(pc
);
6275 return JimParseExprOperator(pc
);
6277 case '0': case '1': case '2': case '3': case '4':
6278 case '5': case '6': case '7': case '8': case '9': case '.':
6279 return JimParseExprNumber(pc
);
6283 /* Here it's possible to reuse the List String parsing. */
6284 pc
->tt
= JIM_TT_NONE
; /* Make sure it's sensed as a new word. */
6285 return JimParseListStr(pc
);
6289 if (JimParseExprIrrational(pc
) == JIM_ERR
)
6290 return JimParseExprOperator(pc
);
6293 return JimParseExprOperator(pc
);
6299 int JimParseExprNumber(struct JimParserCtx
*pc
)
6305 pc
->tline
= pc
->linenr
;
6306 if (*pc
->p
== '-') {
6309 while ( isdigit((int)*pc
->p
)
6310 || (allowhex
&& isxdigit((int)*pc
->p
) )
6311 || (allowdot
&& *pc
->p
== '.')
6312 || (pc
->p
-pc
->tstart
== 1 && *pc
->tstart
== '0' &&
6313 (*pc
->p
== 'x' || *pc
->p
== 'X'))
6316 if ((*pc
->p
== 'x') || (*pc
->p
== 'X')) {
6323 if (!allowdot
&& *pc
->p
== 'e' && *(pc
->p
+1) == '-') {
6324 pc
->p
+= 2; pc
->len
-= 2;
6328 pc
->tt
= JIM_TT_EXPR_NUMBER
;
6332 int JimParseExprIrrational(struct JimParserCtx
*pc
)
6334 const char *Tokens
[] = {"NaN", "nan", "NAN", "Inf", "inf", "INF", NULL
};
6336 for (token
= Tokens
; *token
!= NULL
; token
++) {
6337 int len
= strlen(*token
);
6338 if (strncmp(*token
, pc
->p
, len
) == 0) {
6340 pc
->tend
= pc
->p
+ len
- 1;
6341 pc
->p
+= len
; pc
->len
-= len
;
6342 pc
->tline
= pc
->linenr
;
6343 pc
->tt
= JIM_TT_EXPR_NUMBER
;
6350 int JimParseExprOperator(struct JimParserCtx
*pc
)
6353 int bestIdx
= -1, bestLen
= 0;
6355 /* Try to get the longest match. */
6356 for (i
= 0; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++) {
6360 opname
= Jim_ExprOperators
[i
].name
;
6361 if (opname
== NULL
) continue;
6362 oplen
= strlen(opname
);
6364 if (strncmp(opname
, pc
->p
, oplen
) == 0 && oplen
> bestLen
) {
6369 if (bestIdx
== -1) return JIM_ERR
;
6371 pc
->tend
= pc
->p
+ bestLen
- 1;
6372 pc
->p
+= bestLen
; pc
->len
-= bestLen
;
6373 pc
->tline
= pc
->linenr
;
6374 pc
->tt
= JIM_TT_EXPR_OPERATOR
;
6378 struct Jim_ExprOperator
*JimExprOperatorInfo(const char *opname
)
6381 for (i
= 0; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++)
6382 if (Jim_ExprOperators
[i
].name
&&
6383 strcmp(opname
, Jim_ExprOperators
[i
].name
) == 0)
6384 return &Jim_ExprOperators
[i
];
6388 struct Jim_ExprOperator
*JimExprOperatorInfoByOpcode(int opcode
)
6391 for (i
= 0; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++)
6392 if (Jim_ExprOperators
[i
].opcode
== opcode
)
6393 return &Jim_ExprOperators
[i
];
6397 /* -----------------------------------------------------------------------------
6399 * ---------------------------------------------------------------------------*/
6400 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6401 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
6402 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6404 static Jim_ObjType exprObjType
= {
6406 FreeExprInternalRep
,
6409 JIM_TYPE_REFERENCES
,
6412 /* Expr bytecode structure */
6413 typedef struct ExprByteCode
{
6414 int *opcode
; /* Integer array of opcodes. */
6415 Jim_Obj
**obj
; /* Array of associated Jim Objects. */
6416 int len
; /* Bytecode length */
6417 int inUse
; /* Used for sharing. */
6420 void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6423 ExprByteCode
*expr
= (void*) objPtr
->internalRep
.ptr
;
6426 if (expr
->inUse
!= 0) return;
6427 for (i
= 0; i
< expr
->len
; i
++)
6428 Jim_DecrRefCount(interp
, expr
->obj
[i
]);
6429 Jim_Free(expr
->opcode
);
6430 Jim_Free(expr
->obj
);
6434 void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
6436 JIM_NOTUSED(interp
);
6437 JIM_NOTUSED(srcPtr
);
6439 /* Just returns an simple string. */
6440 dupPtr
->typePtr
= NULL
;
6443 /* Add a new instruction to an expression bytecode structure. */
6444 static void ExprObjAddInstr(Jim_Interp
*interp
, ExprByteCode
*expr
,
6445 int opcode
, char *str
, int len
)
6447 expr
->opcode
= Jim_Realloc(expr
->opcode
, sizeof(int)*(expr
->len
+1));
6448 expr
->obj
= Jim_Realloc(expr
->obj
, sizeof(Jim_Obj
*)*(expr
->len
+1));
6449 expr
->opcode
[expr
->len
] = opcode
;
6450 expr
->obj
[expr
->len
] = Jim_NewStringObjNoAlloc(interp
, str
, len
);
6451 Jim_IncrRefCount(expr
->obj
[expr
->len
]);
6455 /* Check if an expr program looks correct. */
6456 static int ExprCheckCorrectness(ExprByteCode
*expr
)
6461 /* Try to check if there are stack underflows,
6462 * and make sure at the end of the program there is
6463 * a single result on the stack. */
6464 for (i
= 0; i
< expr
->len
; i
++) {
6465 switch(expr
->opcode
[i
]) {
6466 case JIM_EXPROP_NUMBER
:
6467 case JIM_EXPROP_STRING
:
6468 case JIM_EXPROP_SUBST
:
6469 case JIM_EXPROP_VARIABLE
:
6470 case JIM_EXPROP_DICTSUGAR
:
6471 case JIM_EXPROP_COMMAND
:
6474 case JIM_EXPROP_NOT
:
6475 case JIM_EXPROP_BITNOT
:
6476 case JIM_EXPROP_UNARYMINUS
:
6477 case JIM_EXPROP_UNARYPLUS
:
6478 /* Unary operations */
6479 if (stacklen
< 1) return JIM_ERR
;
6481 case JIM_EXPROP_ADD
:
6482 case JIM_EXPROP_SUB
:
6483 case JIM_EXPROP_MUL
:
6484 case JIM_EXPROP_DIV
:
6485 case JIM_EXPROP_MOD
:
6488 case JIM_EXPROP_LTE
:
6489 case JIM_EXPROP_GTE
:
6490 case JIM_EXPROP_ROTL
:
6491 case JIM_EXPROP_ROTR
:
6492 case JIM_EXPROP_LSHIFT
:
6493 case JIM_EXPROP_RSHIFT
:
6494 case JIM_EXPROP_NUMEQ
:
6495 case JIM_EXPROP_NUMNE
:
6496 case JIM_EXPROP_STREQ
:
6497 case JIM_EXPROP_STRNE
:
6498 case JIM_EXPROP_BITAND
:
6499 case JIM_EXPROP_BITXOR
:
6500 case JIM_EXPROP_BITOR
:
6501 case JIM_EXPROP_LOGICAND
:
6502 case JIM_EXPROP_LOGICOR
:
6503 case JIM_EXPROP_POW
:
6504 /* binary operations */
6505 if (stacklen
< 2) return JIM_ERR
;
6509 Jim_Panic(NULL
,"Default opcode reached ExprCheckCorrectness");
6513 if (stacklen
!= 1) return JIM_ERR
;
6517 static void ExprShareLiterals(Jim_Interp
*interp
, ExprByteCode
*expr
,
6518 ScriptObj
*topLevelScript
)
6523 for (i
= 0; i
< expr
->len
; i
++) {
6524 Jim_Obj
*foundObjPtr
;
6526 if (expr
->obj
[i
] == NULL
) continue;
6527 foundObjPtr
= ScriptSearchLiteral(interp
, topLevelScript
,
6528 NULL
, expr
->obj
[i
]);
6529 if (foundObjPtr
!= NULL
) {
6530 Jim_IncrRefCount(foundObjPtr
);
6531 Jim_DecrRefCount(interp
, expr
->obj
[i
]);
6532 expr
->obj
[i
] = foundObjPtr
;
6537 /* This procedure converts every occurrence of || and && opereators
6538 * in lazy unary versions.
6540 * a b || is converted into:
6542 * a <offset> |L b |R
6544 * a b && is converted into:
6546 * a <offset> &L b &R
6548 * "|L" checks if 'a' is true:
6549 * 1) if it is true pushes 1 and skips <offset> istructions to reach
6550 * the opcode just after |R.
6551 * 2) if it is false does nothing.
6552 * "|R" checks if 'b' is true:
6553 * 1) if it is true pushes 1, otherwise pushes 0.
6555 * "&L" checks if 'a' is true:
6556 * 1) if it is true does nothing.
6557 * 2) If it is false pushes 0 and skips <offset> istructions to reach
6558 * the opcode just after &R
6559 * "&R" checks if 'a' is true:
6560 * if it is true pushes 1, otherwise pushes 0.
6562 static void ExprMakeLazy(Jim_Interp
*interp
, ExprByteCode
*expr
)
6565 int index
= -1, leftindex
, arity
, i
, offset
;
6566 Jim_ExprOperator
*op
;
6568 /* Search for || or && */
6569 for (i
= 0; i
< expr
->len
; i
++) {
6570 if (expr
->opcode
[i
] == JIM_EXPROP_LOGICAND
||
6571 expr
->opcode
[i
] == JIM_EXPROP_LOGICOR
) {
6576 if (index
== -1) return;
6577 /* Search for the end of the first operator */
6578 leftindex
= index
-1;
6581 switch(expr
->opcode
[leftindex
]) {
6582 case JIM_EXPROP_NUMBER
:
6583 case JIM_EXPROP_COMMAND
:
6584 case JIM_EXPROP_VARIABLE
:
6585 case JIM_EXPROP_DICTSUGAR
:
6586 case JIM_EXPROP_SUBST
:
6587 case JIM_EXPROP_STRING
:
6590 op
= JimExprOperatorInfoByOpcode(expr
->opcode
[i
]);
6592 Jim_Panic(interp
,"Default reached in ExprMakeLazy()");
6601 expr
->opcode
= Jim_Realloc(expr
->opcode
, sizeof(int)*(expr
->len
+2));
6602 expr
->obj
= Jim_Realloc(expr
->obj
, sizeof(Jim_Obj
*)*(expr
->len
+2));
6603 memmove(&expr
->opcode
[leftindex
+2], &expr
->opcode
[leftindex
],
6604 sizeof(int)*(expr
->len
-leftindex
));
6605 memmove(&expr
->obj
[leftindex
+2], &expr
->obj
[leftindex
],
6606 sizeof(Jim_Obj
*)*(expr
->len
-leftindex
));
6609 offset
= (index
-leftindex
)-1;
6610 Jim_DecrRefCount(interp
, expr
->obj
[index
]);
6611 if (expr
->opcode
[index
] == JIM_EXPROP_LOGICAND
) {
6612 expr
->opcode
[leftindex
+1] = JIM_EXPROP_LOGICAND_LEFT
;
6613 expr
->opcode
[index
] = JIM_EXPROP_LOGICAND_RIGHT
;
6614 expr
->obj
[leftindex
+1] = Jim_NewStringObj(interp
, "&L", -1);
6615 expr
->obj
[index
] = Jim_NewStringObj(interp
, "&R", -1);
6617 expr
->opcode
[leftindex
+1] = JIM_EXPROP_LOGICOR_LEFT
;
6618 expr
->opcode
[index
] = JIM_EXPROP_LOGICOR_RIGHT
;
6619 expr
->obj
[leftindex
+1] = Jim_NewStringObj(interp
, "|L", -1);
6620 expr
->obj
[index
] = Jim_NewStringObj(interp
, "|R", -1);
6622 expr
->opcode
[leftindex
] = JIM_EXPROP_NUMBER
;
6623 expr
->obj
[leftindex
] = Jim_NewIntObj(interp
, offset
);
6624 Jim_IncrRefCount(expr
->obj
[index
]);
6625 Jim_IncrRefCount(expr
->obj
[leftindex
]);
6626 Jim_IncrRefCount(expr
->obj
[leftindex
+1]);
6630 /* This method takes the string representation of an expression
6631 * and generates a program for the Expr's stack-based VM. */
6632 int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
6635 const char *exprText
= Jim_GetString(objPtr
, &exprTextLen
);
6636 struct JimParserCtx parser
;
6637 int i
, shareLiterals
;
6638 ExprByteCode
*expr
= Jim_Alloc(sizeof(*expr
));
6640 Jim_ExprOperator
*op
;
6642 /* Perform literal sharing with the current procedure
6643 * running only if this expression appears to be not generated
6645 shareLiterals
= objPtr
->typePtr
== &sourceObjType
;
6647 expr
->opcode
= NULL
;
6652 Jim_InitStack(&stack
);
6653 JimParserInit(&parser
, exprText
, exprTextLen
, 1);
6654 while(!JimParserEof(&parser
)) {
6658 if (JimParseExpression(&parser
) != JIM_OK
) {
6659 Jim_SetResultString(interp
, "Syntax error in expression", -1);
6662 token
= JimParserGetToken(&parser
, &len
, &type
, NULL
);
6663 if (type
== JIM_TT_EOL
) {
6669 ExprObjAddInstr(interp
, expr
, JIM_EXPROP_STRING
, token
, len
);
6672 ExprObjAddInstr(interp
, expr
, JIM_EXPROP_SUBST
, token
, len
);
6675 ExprObjAddInstr(interp
, expr
, JIM_EXPROP_VARIABLE
, token
, len
);
6677 case JIM_TT_DICTSUGAR
:
6678 ExprObjAddInstr(interp
, expr
, JIM_EXPROP_DICTSUGAR
, token
, len
);
6681 ExprObjAddInstr(interp
, expr
, JIM_EXPROP_COMMAND
, token
, len
);
6683 case JIM_TT_EXPR_NUMBER
:
6684 ExprObjAddInstr(interp
, expr
, JIM_EXPROP_NUMBER
, token
, len
);
6686 case JIM_TT_EXPR_OPERATOR
:
6687 op
= JimExprOperatorInfo(token
);
6689 Jim_ExprOperator
*stackTopOp
;
6691 if (Jim_StackPeek(&stack
) != NULL
) {
6692 stackTopOp
= JimExprOperatorInfo(Jim_StackPeek(&stack
));
6696 if (Jim_StackLen(&stack
) && op
->arity
!= 1 &&
6697 stackTopOp
&& stackTopOp
->precedence
>= op
->precedence
)
6699 ExprObjAddInstr(interp
, expr
, stackTopOp
->opcode
,
6700 Jim_StackPeek(&stack
), -1);
6701 Jim_StackPop(&stack
);
6706 Jim_StackPush(&stack
, token
);
6708 case JIM_TT_SUBEXPR_START
:
6709 Jim_StackPush(&stack
, Jim_StrDup("("));
6712 case JIM_TT_SUBEXPR_END
:
6715 while(Jim_StackLen(&stack
)) {
6716 char *opstr
= Jim_StackPop(&stack
);
6717 if (!strcmp(opstr
, "(")) {
6722 op
= JimExprOperatorInfo(opstr
);
6723 ExprObjAddInstr(interp
, expr
, op
->opcode
, opstr
, -1);
6726 Jim_SetResultString(interp
,
6727 "Unexpected close parenthesis", -1);
6734 Jim_Panic(interp
,"Default reached in SetExprFromAny()");
6738 while (Jim_StackLen(&stack
)) {
6739 char *opstr
= Jim_StackPop(&stack
);
6740 op
= JimExprOperatorInfo(opstr
);
6741 if (op
== NULL
&& !strcmp(opstr
, "(")) {
6743 Jim_SetResultString(interp
, "Missing close parenthesis", -1);
6746 ExprObjAddInstr(interp
, expr
, op
->opcode
, opstr
, -1);
6748 /* Check program correctness. */
6749 if (ExprCheckCorrectness(expr
) != JIM_OK
) {
6750 Jim_SetResultString(interp
, "Invalid expression", -1);
6754 /* Free the stack used for the compilation. */
6755 Jim_FreeStackElements(&stack
, Jim_Free
);
6756 Jim_FreeStack(&stack
);
6758 /* Convert || and && operators in unary |L |R and &L &R for lazyness */
6759 ExprMakeLazy(interp
, expr
);
6761 /* Perform literal sharing */
6762 if (shareLiterals
&& interp
->framePtr
->procBodyObjPtr
) {
6763 Jim_Obj
*bodyObjPtr
= interp
->framePtr
->procBodyObjPtr
;
6764 if (bodyObjPtr
->typePtr
== &scriptObjType
) {
6765 ScriptObj
*bodyScript
= bodyObjPtr
->internalRep
.ptr
;
6766 ExprShareLiterals(interp
, expr
, bodyScript
);
6770 /* Free the old internal rep and set the new one. */
6771 Jim_FreeIntRep(interp
, objPtr
);
6772 Jim_SetIntRepPtr(objPtr
, expr
);
6773 objPtr
->typePtr
= &exprObjType
;
6776 err
: /* we jump here on syntax/compile errors. */
6777 Jim_FreeStackElements(&stack
, Jim_Free
);
6778 Jim_FreeStack(&stack
);
6779 Jim_Free(expr
->opcode
);
6780 for (i
= 0; i
< expr
->len
; i
++) {
6781 Jim_DecrRefCount(interp
,expr
->obj
[i
]);
6783 Jim_Free(expr
->obj
);
6788 ExprByteCode
*Jim_GetExpression(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6790 if (objPtr
->typePtr
!= &exprObjType
) {
6791 if (SetExprFromAny(interp
, objPtr
) != JIM_OK
)
6794 return (ExprByteCode
*) Jim_GetIntRepPtr(objPtr
);
6797 /* -----------------------------------------------------------------------------
6798 * Expressions evaluation.
6799 * Jim uses a specialized stack-based virtual machine for expressions,
6800 * that takes advantage of the fact that expr's operators
6801 * can't be redefined.
6803 * Jim_EvalExpression() uses the bytecode compiled by
6804 * SetExprFromAny() method of the "expression" object.
6806 * On success a Tcl Object containing the result of the evaluation
6807 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
6809 * On error the function returns a retcode != to JIM_OK and set a suitable
6810 * error on the interp.
6811 * ---------------------------------------------------------------------------*/
6812 #define JIM_EE_STATICSTACK_LEN 10
6814 int Jim_EvalExpression(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
,
6815 Jim_Obj
**exprResultPtrPtr
)
6818 Jim_Obj
**stack
, *staticStack
[JIM_EE_STATICSTACK_LEN
];
6819 int stacklen
= 0, i
, error
= 0, errRetCode
= JIM_ERR
;
6821 Jim_IncrRefCount(exprObjPtr
);
6822 expr
= Jim_GetExpression(interp
, exprObjPtr
);
6824 Jim_DecrRefCount(interp
, exprObjPtr
);
6825 return JIM_ERR
; /* error in expression. */
6827 /* In order to avoid that the internal repr gets freed due to
6828 * shimmering of the exprObjPtr's object, we make the internal rep
6832 /* The stack-based expr VM itself */
6834 /* Stack allocation. Expr programs have the feature that
6835 * a program of length N can't require a stack longer than
6837 if (expr
->len
> JIM_EE_STATICSTACK_LEN
)
6838 stack
= Jim_Alloc(sizeof(Jim_Obj
*)*expr
->len
);
6840 stack
= staticStack
;
6842 /* Execute every istruction */
6843 for (i
= 0; i
< expr
->len
; i
++) {
6844 Jim_Obj
*A
, *B
, *objPtr
;
6845 jim_wide wA
, wB
, wC
;
6847 const char *sA
, *sB
;
6848 int Alen
, Blen
, retcode
;
6849 int opcode
= expr
->opcode
[i
];
6851 if (opcode
== JIM_EXPROP_NUMBER
|| opcode
== JIM_EXPROP_STRING
) {
6852 stack
[stacklen
++] = expr
->obj
[i
];
6853 Jim_IncrRefCount(expr
->obj
[i
]);
6854 } else if (opcode
== JIM_EXPROP_VARIABLE
) {
6855 objPtr
= Jim_GetVariable(interp
, expr
->obj
[i
], JIM_ERRMSG
);
6856 if (objPtr
== NULL
) {
6860 stack
[stacklen
++] = objPtr
;
6861 Jim_IncrRefCount(objPtr
);
6862 } else if (opcode
== JIM_EXPROP_SUBST
) {
6863 if ((retcode
= Jim_SubstObj(interp
, expr
->obj
[i
],
6864 &objPtr
, JIM_NONE
)) != JIM_OK
)
6867 errRetCode
= retcode
;
6870 stack
[stacklen
++] = objPtr
;
6871 Jim_IncrRefCount(objPtr
);
6872 } else if (opcode
== JIM_EXPROP_DICTSUGAR
) {
6873 objPtr
= Jim_ExpandDictSugar(interp
, expr
->obj
[i
]);
6874 if (objPtr
== NULL
) {
6878 stack
[stacklen
++] = objPtr
;
6879 Jim_IncrRefCount(objPtr
);
6880 } else if (opcode
== JIM_EXPROP_COMMAND
) {
6881 if ((retcode
= Jim_EvalObj(interp
, expr
->obj
[i
])) != JIM_OK
) {
6883 errRetCode
= retcode
;
6886 stack
[stacklen
++] = interp
->result
;
6887 Jim_IncrRefCount(interp
->result
);
6888 } else if (opcode
>= JIM_EXPROP_BINARY_NUM_FIRST
&&
6889 opcode
<= JIM_EXPROP_BINARY_NUM_LAST
)
6891 /* Note that there isn't to increment the
6892 * refcount of objects. the references are moved
6893 * from stack to A and B. */
6894 B
= stack
[--stacklen
];
6895 A
= stack
[--stacklen
];
6897 /* --- Integer --- */
6898 if ((A
->typePtr
== &doubleObjType
&& !A
->bytes
) ||
6899 (B
->typePtr
== &doubleObjType
&& !B
->bytes
) ||
6900 JimGetWideNoErr(interp
, A
, &wA
) != JIM_OK
||
6901 JimGetWideNoErr(interp
, B
, &wB
) != JIM_OK
) {
6904 Jim_DecrRefCount(interp
, A
);
6905 Jim_DecrRefCount(interp
, B
);
6906 switch(expr
->opcode
[i
]) {
6907 case JIM_EXPROP_ADD
: wC
= wA
+wB
; break;
6908 case JIM_EXPROP_SUB
: wC
= wA
-wB
; break;
6909 case JIM_EXPROP_MUL
: wC
= wA
*wB
; break;
6910 case JIM_EXPROP_LT
: wC
= wA
<wB
; break;
6911 case JIM_EXPROP_GT
: wC
= wA
>wB
; break;
6912 case JIM_EXPROP_LTE
: wC
= wA
<=wB
; break;
6913 case JIM_EXPROP_GTE
: wC
= wA
>=wB
; break;
6914 case JIM_EXPROP_LSHIFT
: wC
= wA
<<wB
; break;
6915 case JIM_EXPROP_RSHIFT
: wC
= wA
>>wB
; break;
6916 case JIM_EXPROP_NUMEQ
: wC
= wA
==wB
; break;
6917 case JIM_EXPROP_NUMNE
: wC
= wA
!=wB
; break;
6918 case JIM_EXPROP_BITAND
: wC
= wA
&wB
; break;
6919 case JIM_EXPROP_BITXOR
: wC
= wA
^wB
; break;
6920 case JIM_EXPROP_BITOR
: wC
= wA
|wB
; break;
6921 case JIM_EXPROP_POW
: wC
= JimPowWide(wA
,wB
); break;
6922 case JIM_EXPROP_LOGICAND_LEFT
:
6930 case JIM_EXPROP_LOGICOR_LEFT
:
6938 case JIM_EXPROP_DIV
:
6939 if (wB
== 0) goto divbyzero
;
6942 case JIM_EXPROP_MOD
:
6943 if (wB
== 0) goto divbyzero
;
6946 case JIM_EXPROP_ROTL
: {
6947 /* uint32_t would be better. But not everyone has inttypes.h?*/
6948 unsigned long uA
= (unsigned long)wA
;
6950 wC
= _rotl(uA
,(unsigned long)wB
);
6952 const unsigned int S
= sizeof(unsigned long) * 8;
6953 wC
= (unsigned long)((uA
<<wB
)|(uA
>>(S
-wB
)));
6957 case JIM_EXPROP_ROTR
: {
6958 unsigned long uA
= (unsigned long)wA
;
6960 wC
= _rotr(uA
,(unsigned long)wB
);
6962 const unsigned int S
= sizeof(unsigned long) * 8;
6963 wC
= (unsigned long)((uA
>>wB
)|(uA
<<(S
-wB
)));
6969 wC
= 0; /* avoid gcc warning */
6972 stack
[stacklen
] = Jim_NewIntObj(interp
, wC
);
6973 Jim_IncrRefCount(stack
[stacklen
]);
6977 /* --- Double --- */
6978 if (Jim_GetDouble(interp
, A
, &dA
) != JIM_OK
||
6979 Jim_GetDouble(interp
, B
, &dB
) != JIM_OK
) {
6980 Jim_DecrRefCount(interp
, A
);
6981 Jim_DecrRefCount(interp
, B
);
6985 Jim_DecrRefCount(interp
, A
);
6986 Jim_DecrRefCount(interp
, B
);
6987 switch(expr
->opcode
[i
]) {
6988 case JIM_EXPROP_ROTL
:
6989 case JIM_EXPROP_ROTR
:
6990 case JIM_EXPROP_LSHIFT
:
6991 case JIM_EXPROP_RSHIFT
:
6992 case JIM_EXPROP_BITAND
:
6993 case JIM_EXPROP_BITXOR
:
6994 case JIM_EXPROP_BITOR
:
6995 case JIM_EXPROP_MOD
:
6996 case JIM_EXPROP_POW
:
6997 Jim_SetResultString(interp
,
6998 "Got floating-point value where integer was expected", -1);
7002 case JIM_EXPROP_ADD
: dC
= dA
+dB
; break;
7003 case JIM_EXPROP_SUB
: dC
= dA
-dB
; break;
7004 case JIM_EXPROP_MUL
: dC
= dA
*dB
; break;
7005 case JIM_EXPROP_LT
: dC
= dA
<dB
; break;
7006 case JIM_EXPROP_GT
: dC
= dA
>dB
; break;
7007 case JIM_EXPROP_LTE
: dC
= dA
<=dB
; break;
7008 case JIM_EXPROP_GTE
: dC
= dA
>=dB
; break;
7009 case JIM_EXPROP_NUMEQ
: dC
= dA
==dB
; break;
7010 case JIM_EXPROP_NUMNE
: dC
= dA
!=dB
; break;
7011 case JIM_EXPROP_LOGICAND_LEFT
:
7019 case JIM_EXPROP_LOGICOR_LEFT
:
7027 case JIM_EXPROP_DIV
:
7028 if (dB
== 0) goto divbyzero
;
7032 dC
= 0; /* avoid gcc warning */
7035 stack
[stacklen
] = Jim_NewDoubleObj(interp
, dC
);
7036 Jim_IncrRefCount(stack
[stacklen
]);
7038 } else if (opcode
== JIM_EXPROP_STREQ
|| opcode
== JIM_EXPROP_STRNE
) {
7039 B
= stack
[--stacklen
];
7040 A
= stack
[--stacklen
];
7041 sA
= Jim_GetString(A
, &Alen
);
7042 sB
= Jim_GetString(B
, &Blen
);
7043 switch(expr
->opcode
[i
]) {
7044 case JIM_EXPROP_STREQ
:
7045 if (Alen
== Blen
&& memcmp(sA
, sB
, Alen
) ==0)
7050 case JIM_EXPROP_STRNE
:
7051 if (Alen
!= Blen
|| memcmp(sA
, sB
, Alen
) != 0)
7057 wC
= 0; /* avoid gcc warning */
7060 Jim_DecrRefCount(interp
, A
);
7061 Jim_DecrRefCount(interp
, B
);
7062 stack
[stacklen
] = Jim_NewIntObj(interp
, wC
);
7063 Jim_IncrRefCount(stack
[stacklen
]);
7065 } else if (opcode
== JIM_EXPROP_NOT
||
7066 opcode
== JIM_EXPROP_BITNOT
||
7067 opcode
== JIM_EXPROP_LOGICAND_RIGHT
||
7068 opcode
== JIM_EXPROP_LOGICOR_RIGHT
) {
7069 /* Note that there isn't to increment the
7070 * refcount of objects. the references are moved
7071 * from stack to A and B. */
7072 A
= stack
[--stacklen
];
7074 /* --- Integer --- */
7075 if ((A
->typePtr
== &doubleObjType
&& !A
->bytes
) ||
7076 JimGetWideNoErr(interp
, A
, &wA
) != JIM_OK
) {
7077 goto trydouble_unary
;
7079 Jim_DecrRefCount(interp
, A
);
7080 switch(expr
->opcode
[i
]) {
7081 case JIM_EXPROP_NOT
: wC
= !wA
; break;
7082 case JIM_EXPROP_BITNOT
: wC
= ~wA
; break;
7083 case JIM_EXPROP_LOGICAND_RIGHT
:
7084 case JIM_EXPROP_LOGICOR_RIGHT
: wC
= (wA
!= 0); break;
7086 wC
= 0; /* avoid gcc warning */
7089 stack
[stacklen
] = Jim_NewIntObj(interp
, wC
);
7090 Jim_IncrRefCount(stack
[stacklen
]);
7094 /* --- Double --- */
7095 if (Jim_GetDouble(interp
, A
, &dA
) != JIM_OK
) {
7096 Jim_DecrRefCount(interp
, A
);
7100 Jim_DecrRefCount(interp
, A
);
7101 switch(expr
->opcode
[i
]) {
7102 case JIM_EXPROP_NOT
: dC
= !dA
; break;
7103 case JIM_EXPROP_LOGICAND_RIGHT
:
7104 case JIM_EXPROP_LOGICOR_RIGHT
: dC
= (dA
!= 0); break;
7105 case JIM_EXPROP_BITNOT
:
7106 Jim_SetResultString(interp
,
7107 "Got floating-point value where integer was expected", -1);
7112 dC
= 0; /* avoid gcc warning */
7115 stack
[stacklen
] = Jim_NewDoubleObj(interp
, dC
);
7116 Jim_IncrRefCount(stack
[stacklen
]);
7119 Jim_Panic(interp
,"Unknown opcode in Jim_EvalExpression");
7123 /* There is no need to decerement the inUse field because
7124 * this reference is transfered back into the exprObjPtr. */
7125 Jim_FreeIntRep(interp
, exprObjPtr
);
7126 exprObjPtr
->typePtr
= &exprObjType
;
7127 Jim_SetIntRepPtr(exprObjPtr
, expr
);
7128 Jim_DecrRefCount(interp
, exprObjPtr
);
7130 *exprResultPtrPtr
= stack
[0];
7131 Jim_IncrRefCount(stack
[0]);
7132 errRetCode
= JIM_OK
;
7134 for (i
= 0; i
< stacklen
; i
++) {
7135 Jim_DecrRefCount(interp
, stack
[i
]);
7137 if (stack
!= staticStack
)
7142 Jim_SetResultString(interp
, "Division by zero", -1);
7146 int Jim_GetBoolFromExpr(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, int *boolPtr
)
7151 Jim_Obj
*exprResultPtr
;
7153 retcode
= Jim_EvalExpression(interp
, exprObjPtr
, &exprResultPtr
);
7154 if (retcode
!= JIM_OK
)
7156 if (JimGetWideNoErr(interp
, exprResultPtr
, &wideValue
) != JIM_OK
) {
7157 if (Jim_GetDouble(interp
, exprResultPtr
, &doubleValue
) != JIM_OK
)
7159 Jim_DecrRefCount(interp
, exprResultPtr
);
7162 Jim_DecrRefCount(interp
, exprResultPtr
);
7163 *boolPtr
= doubleValue
!= 0;
7167 Jim_DecrRefCount(interp
, exprResultPtr
);
7168 *boolPtr
= wideValue
!= 0;
7172 /* -----------------------------------------------------------------------------
7173 * ScanFormat String Object
7174 * ---------------------------------------------------------------------------*/
7176 /* This Jim_Obj will held a parsed representation of a format string passed to
7177 * the Jim_ScanString command. For error diagnostics, the scanformat string has
7178 * to be parsed in its entirely first and then, if correct, can be used for
7179 * scanning. To avoid endless re-parsing, the parsed representation will be
7180 * stored in an internal representation and re-used for performance reason. */
7182 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
7183 * scanformat string. This part will later be used to extract information
7184 * out from the string to be parsed by Jim_ScanString */
7186 typedef struct ScanFmtPartDescr
{
7187 char type
; /* Type of conversion (e.g. c, d, f) */
7188 char modifier
; /* Modify type (e.g. l - long, h - short */
7189 size_t width
; /* Maximal width of input to be converted */
7190 int pos
; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
7191 char *arg
; /* Specification of a CHARSET conversion */
7192 char *prefix
; /* Prefix to be scanned literally before conversion */
7195 /* The ScanFmtStringObj will held the internal representation of a scanformat
7196 * string parsed and separated in part descriptions. Furthermore it contains
7197 * the original string representation of the scanformat string to allow for
7198 * fast update of the Jim_Obj's string representation part.
7200 * As add-on the internal object representation add some scratch pad area
7201 * for usage by Jim_ScanString to avoid endless allocating and freeing of
7202 * memory for purpose of string scanning.
7204 * The error member points to a static allocated string in case of a mal-
7205 * formed scanformat string or it contains '0' (NULL) in case of a valid
7206 * parse representation.
7208 * The whole memory of the internal representation is allocated as a single
7209 * area of memory that will be internally separated. So freeing and duplicating
7210 * of such an object is cheap */
7212 typedef struct ScanFmtStringObj
{
7213 jim_wide size
; /* Size of internal repr in bytes */
7214 char *stringRep
; /* Original string representation */
7215 size_t count
; /* Number of ScanFmtPartDescr contained */
7216 size_t convCount
; /* Number of conversions that will assign */
7217 size_t maxPos
; /* Max position index if XPG3 is used */
7218 const char *error
; /* Ptr to error text (NULL if no error */
7219 char *scratch
; /* Some scratch pad used by Jim_ScanString */
7220 ScanFmtPartDescr descr
[1]; /* The vector of partial descriptions */
7224 static void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
7225 static void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
7226 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
);
7228 static Jim_ObjType scanFmtStringObjType
= {
7230 FreeScanFmtInternalRep
,
7231 DupScanFmtInternalRep
,
7232 UpdateStringOfScanFmt
,
7236 void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
7238 JIM_NOTUSED(interp
);
7239 Jim_Free((char*)objPtr
->internalRep
.ptr
);
7240 objPtr
->internalRep
.ptr
= 0;
7243 void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
7245 size_t size
= (size_t)((ScanFmtStringObj
*)srcPtr
->internalRep
.ptr
)->size
;
7246 ScanFmtStringObj
*newVec
= (ScanFmtStringObj
*)Jim_Alloc(size
);
7248 JIM_NOTUSED(interp
);
7249 memcpy(newVec
, srcPtr
->internalRep
.ptr
, size
);
7250 dupPtr
->internalRep
.ptr
= newVec
;
7251 dupPtr
->typePtr
= &scanFmtStringObjType
;
7254 void UpdateStringOfScanFmt(Jim_Obj
*objPtr
)
7256 char *bytes
= ((ScanFmtStringObj
*)objPtr
->internalRep
.ptr
)->stringRep
;
7258 objPtr
->bytes
= Jim_StrDup(bytes
);
7259 objPtr
->length
= strlen(bytes
);
7262 /* SetScanFmtFromAny will parse a given string and create the internal
7263 * representation of the format specification. In case of an error
7264 * the error data member of the internal representation will be set
7265 * to an descriptive error text and the function will be left with
7266 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
7269 static int SetScanFmtFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
7271 ScanFmtStringObj
*fmtObj
;
7273 int maxCount
, i
, approxSize
, lastPos
= -1;
7274 const char *fmt
= objPtr
->bytes
;
7275 int maxFmtLen
= objPtr
->length
;
7276 const char *fmtEnd
= fmt
+ maxFmtLen
;
7279 Jim_FreeIntRep(interp
, objPtr
);
7280 /* Count how many conversions could take place maximally */
7281 for (i
=0, maxCount
=0; i
< maxFmtLen
; ++i
)
7284 /* Calculate an approximation of the memory necessary */
7285 approxSize
= sizeof(ScanFmtStringObj
) /* Size of the container */
7286 + (maxCount
+ 1) * sizeof(ScanFmtPartDescr
) /* Size of all partials */
7287 + maxFmtLen
* sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
7288 + maxFmtLen
* sizeof(char) + 1 /* Original stringrep */
7289 + maxFmtLen
* sizeof(char) /* Arg for CHARSETs */
7290 + (maxCount
+1) * sizeof(char) /* '\0' for every partial */
7291 + 1; /* safety byte */
7292 fmtObj
= (ScanFmtStringObj
*)Jim_Alloc(approxSize
);
7293 memset(fmtObj
, 0, approxSize
);
7294 fmtObj
->size
= approxSize
;
7296 fmtObj
->scratch
= (char*)&fmtObj
->descr
[maxCount
+1];
7297 fmtObj
->stringRep
= fmtObj
->scratch
+ maxFmtLen
+ 3 + 1;
7298 memcpy(fmtObj
->stringRep
, fmt
, maxFmtLen
);
7299 buffer
= fmtObj
->stringRep
+ maxFmtLen
+ 1;
7300 objPtr
->internalRep
.ptr
= fmtObj
;
7301 objPtr
->typePtr
= &scanFmtStringObjType
;
7302 for (i
=0, curr
=0; fmt
< fmtEnd
; ++fmt
) {
7304 ScanFmtPartDescr
*descr
= &fmtObj
->descr
[curr
];
7306 descr
->width
= 0; /* Assume width unspecified */
7307 /* Overread and store any "literal" prefix */
7308 if (*fmt
!= '%' || fmt
[1] == '%') {
7310 descr
->prefix
= &buffer
[i
];
7311 for (; fmt
< fmtEnd
; ++fmt
) {
7313 if (fmt
[1] != '%') break;
7320 /* Skip the conversion introducing '%' sign */
7322 /* End reached due to non-conversion literal only? */
7325 descr
->pos
= 0; /* Assume "natural" positioning */
7327 descr
->pos
= -1; /* Okay, conversion will not be assigned */
7330 fmtObj
->convCount
++; /* Otherwise count as assign-conversion */
7331 /* Check if next token is a number (could be width or pos */
7332 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
7334 /* Was the number a XPG3 position specifier? */
7335 if (descr
->pos
!= -1 && *fmt
== '$') {
7340 /* Look if "natural" postioning and XPG3 one was mixed */
7341 if ((lastPos
== 0 && descr
->pos
> 0)
7342 || (lastPos
> 0 && descr
->pos
== 0)) {
7343 fmtObj
->error
= "cannot mix \"%\" and \"%n$\" conversion specifiers";
7346 /* Look if this position was already used */
7347 for (prev
=0; prev
< curr
; ++prev
) {
7348 if (fmtObj
->descr
[prev
].pos
== -1) continue;
7349 if (fmtObj
->descr
[prev
].pos
== descr
->pos
) {
7350 fmtObj
->error
= "same \"%n$\" conversion specifier "
7351 "used more than once";
7355 /* Try to find a width after the XPG3 specifier */
7356 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
7357 descr
->width
= width
;
7360 if (descr
->pos
> 0 && (size_t)descr
->pos
> fmtObj
->maxPos
)
7361 fmtObj
->maxPos
= descr
->pos
;
7363 /* Number was not a XPG3, so it has to be a width */
7364 descr
->width
= width
;
7367 /* If positioning mode was undetermined yet, fix this */
7369 lastPos
= descr
->pos
;
7370 /* Handle CHARSET conversion type ... */
7372 int swapped
= 1, beg
= i
, end
, j
;
7374 descr
->arg
= &buffer
[i
];
7376 if (*fmt
== '^') buffer
[i
++] = *fmt
++;
7377 if (*fmt
== ']') buffer
[i
++] = *fmt
++;
7378 while (*fmt
&& *fmt
!= ']') buffer
[i
++] = *fmt
++;
7380 fmtObj
->error
= "unmatched [ in format string";
7385 /* In case a range fence was given "backwards", swap it */
7388 for (j
=beg
+1; j
< end
-1; ++j
) {
7389 if (buffer
[j
] == '-' && buffer
[j
-1] > buffer
[j
+1]) {
7390 char tmp
= buffer
[j
-1];
7391 buffer
[j
-1] = buffer
[j
+1];
7398 /* Remember any valid modifier if given */
7399 if (strchr("hlL", *fmt
) != 0)
7400 descr
->modifier
= tolower((int)*fmt
++);
7403 if (strchr("efgcsndoxui", *fmt
) == 0) {
7404 fmtObj
->error
= "bad scan conversion character";
7406 } else if (*fmt
== 'c' && descr
->width
!= 0) {
7407 fmtObj
->error
= "field width may not be specified in %c "
7410 } else if (*fmt
== 'u' && descr
->modifier
== 'l') {
7411 fmtObj
->error
= "unsigned wide not supported";
7418 if (fmtObj
->convCount
== 0) {
7419 fmtObj
->error
= "no any conversion specifier given";
7425 /* Some accessor macros to allow lowlevel access to fields of internal repr */
7427 #define FormatGetCnvCount(_fo_) \
7428 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
7429 #define FormatGetMaxPos(_fo_) \
7430 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
7431 #define FormatGetError(_fo_) \
7432 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
7434 /* Some Bit testing/setting/cleaning routines. For now only used in handling
7435 * charsets ([a-z123]) within scanning. Later on perhaps a base for a
7436 * bitvector implementation in Jim? */
7438 static int JimTestBit(const char *bitvec
, char ch
)
7440 div_t pos
= div(ch
-1, 8);
7441 return bitvec
[pos
.quot
] & (1 << pos
.rem
);
7444 static void JimSetBit(char *bitvec
, char ch
)
7446 div_t pos
= div(ch
-1, 8);
7447 bitvec
[pos
.quot
] |= (1 << pos
.rem
);
7450 #if 0 /* currently not used */
7451 static void JimClearBit(char *bitvec
, char ch
)
7453 div_t pos
= div(ch
-1, 8);
7454 bitvec
[pos
.quot
] &= ~(1 << pos
.rem
);
7458 /* JimScanAString is used to scan an unspecified string that ends with
7459 * next WS, or a string that is specified via a charset. The charset
7460 * is currently implemented in a way to only allow for usage with
7461 * ASCII. Whenever we will switch to UNICODE, another idea has to
7464 * FIXME: Works only with ASCII */
7467 JimScanAString(Jim_Interp
*interp
, const char *sdescr
, const char *str
)
7471 char charset
[256/8+1]; /* A Charset may contain max 256 chars */
7472 char *buffer
= Jim_Alloc(strlen(str
)+1), *anchor
= buffer
;
7474 /* First init charset to nothing or all, depending if a specified
7475 * or an unspecified string has to be parsed */
7476 memset(charset
, (sdescr
? 0 : 255), sizeof(charset
));
7478 /* There was a set description given, that means we are parsing
7479 * a specified string. So we have to build a corresponding
7480 * charset reflecting the description */
7482 /* Should the set be negated at the end? */
7483 if (*sdescr
== '^') {
7487 /* Here '-' is meant literally and not to define a range */
7488 if (*sdescr
== '-') {
7489 JimSetBit(charset
, '-');
7493 if (sdescr
[1] == '-' && sdescr
[2] != 0) {
7494 /* Handle range definitions */
7496 for (i
=sdescr
[0]; i
<= sdescr
[2]; ++i
)
7497 JimSetBit(charset
, (char)i
);
7500 /* Handle verbatim character definitions */
7501 JimSetBit(charset
, *sdescr
++);
7504 /* Negate the charset if there was a NOT given */
7505 for (i
=0; notFlag
&& i
< sizeof(charset
); ++i
)
7506 charset
[i
] = ~charset
[i
];
7508 /* And after all the mess above, the real work begin ... */
7509 while (str
&& *str
) {
7510 if (!sdescr
&& isspace((int)*str
))
7511 break; /* EOS via WS if unspecified */
7512 if (JimTestBit(charset
, *str
)) *buffer
++ = *str
++;
7513 else break; /* EOS via mismatch if specified scanning */
7515 *buffer
= 0; /* Close the string properly ... */
7516 result
= Jim_NewStringObj(interp
, anchor
, -1);
7517 Jim_Free(anchor
); /* ... and free it afer usage */
7521 /* ScanOneEntry will scan one entry out of the string passed as argument.
7522 * It use the sscanf() function for this task. After extracting and
7523 * converting of the value, the count of scanned characters will be
7524 * returned of -1 in case of no conversion tool place and string was
7525 * already scanned thru */
7527 static int ScanOneEntry(Jim_Interp
*interp
, const char *str
, long pos
,
7528 ScanFmtStringObj
*fmtObj
, long index
, Jim_Obj
**valObjPtr
)
7530 # define MAX_SIZE (sizeof(jim_wide) > sizeof(double) \
7531 ? sizeof(jim_wide) \
7533 char buffer
[MAX_SIZE
];
7534 char *value
= buffer
;
7536 const ScanFmtPartDescr
*descr
= &fmtObj
->descr
[index
];
7537 size_t sLen
= strlen(&str
[pos
]), scanned
= 0;
7538 size_t anchor
= pos
;
7541 /* First pessimiticly assume, we will not scan anything :-) */
7543 if (descr
->prefix
) {
7544 /* There was a prefix given before the conversion, skip it and adjust
7545 * the string-to-be-parsed accordingly */
7546 for (i
=0; str
[pos
] && descr
->prefix
[i
]; ++i
) {
7547 /* If prefix require, skip WS */
7548 if (isspace((int)descr
->prefix
[i
]))
7549 while (str
[pos
] && isspace((int)str
[pos
])) ++pos
;
7550 else if (descr
->prefix
[i
] != str
[pos
])
7551 break; /* Prefix do not match here, leave the loop */
7553 ++pos
; /* Prefix matched so far, next round */
7556 return -1; /* All of str consumed: EOF condition */
7557 else if (descr
->prefix
[i
] != 0)
7558 return 0; /* Not whole prefix consumed, no conversion possible */
7560 /* For all but following conversion, skip leading WS */
7561 if (descr
->type
!= 'c' && descr
->type
!= '[' && descr
->type
!= 'n')
7562 while (isspace((int)str
[pos
])) ++pos
;
7563 /* Determine how much skipped/scanned so far */
7564 scanned
= pos
- anchor
;
7565 if (descr
->type
== 'n') {
7566 /* Return pseudo conversion means: how much scanned so far? */
7567 *valObjPtr
= Jim_NewIntObj(interp
, anchor
+ scanned
);
7568 } else if (str
[pos
] == 0) {
7569 /* Cannot scan anything, as str is totally consumed */
7572 /* Processing of conversions follows ... */
7573 if (descr
->width
> 0) {
7574 /* Do not try to scan as fas as possible but only the given width.
7575 * To ensure this, we copy the part that should be scanned. */
7576 size_t tLen
= descr
->width
> sLen
? sLen
: descr
->width
;
7577 tok
= Jim_StrDupLen(&str
[pos
], tLen
);
7579 /* As no width was given, simply refer to the original string */
7582 switch (descr
->type
) {
7584 *valObjPtr
= Jim_NewIntObj(interp
, *tok
);
7587 case 'd': case 'o': case 'x': case 'u': case 'i': {
7588 char *endp
; /* Position where the number finished */
7589 int base
= descr
->type
== 'o' ? 8
7590 : descr
->type
== 'x' ? 16
7591 : descr
->type
== 'i' ? 0
7595 /* Try to scan a number with the given base */
7596 if (descr
->modifier
== 'l')
7597 #ifdef HAVE_LONG_LONG
7598 *(jim_wide
*)value
= JimStrtoll(tok
, &endp
, base
);
7600 *(jim_wide
*)value
= strtol(tok
, &endp
, base
);
7603 if (descr
->type
== 'u')
7604 *(long*)value
= strtoul(tok
, &endp
, base
);
7606 *(long*)value
= strtol(tok
, &endp
, base
);
7607 /* If scanning failed, and base was undetermined, simply
7608 * put it to 10 and try once more. This should catch the
7609 * case where %i begin to parse a number prefix (e.g.
7610 * '0x' but no further digits follows. This will be
7611 * handled as a ZERO followed by a char 'x' by Tcl */
7612 if (endp
== tok
&& base
== 0) base
= 10;
7616 /* There was some number sucessfully scanned! */
7617 if (descr
->modifier
== 'l')
7618 *valObjPtr
= Jim_NewIntObj(interp
, *(jim_wide
*)value
);
7620 *valObjPtr
= Jim_NewIntObj(interp
, *(long*)value
);
7621 /* Adjust the number-of-chars scanned so far */
7622 scanned
+= endp
- tok
;
7624 /* Nothing was scanned. We have to determine if this
7625 * happened due to e.g. prefix mismatch or input str
7627 scanned
= *tok
? 0 : -1;
7631 case 's': case '[': {
7632 *valObjPtr
= JimScanAString(interp
, descr
->arg
, tok
);
7633 scanned
+= Jim_Length(*valObjPtr
);
7636 case 'e': case 'f': case 'g': {
7639 *(double*)value
= strtod(tok
, &endp
);
7641 /* There was some number sucessfully scanned! */
7642 *valObjPtr
= Jim_NewDoubleObj(interp
, *(double*)value
);
7643 /* Adjust the number-of-chars scanned so far */
7644 scanned
+= endp
- tok
;
7646 /* Nothing was scanned. We have to determine if this
7647 * happened due to e.g. prefix mismatch or input str
7649 scanned
= *tok
? 0 : -1;
7654 /* If a substring was allocated (due to pre-defined width) do not
7655 * forget to free it */
7656 if (tok
!= &str
[pos
])
7657 Jim_Free((char*)tok
);
7662 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
7663 * string and returns all converted (and not ignored) values in a list back
7664 * to the caller. If an error occured, a NULL pointer will be returned */
7666 Jim_Obj
*Jim_ScanString(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
,
7667 Jim_Obj
*fmtObjPtr
, int flags
)
7671 const char *str
= Jim_GetString(strObjPtr
, 0);
7672 Jim_Obj
*resultList
= 0;
7673 Jim_Obj
**resultVec
;
7675 Jim_Obj
*emptyStr
= 0;
7676 ScanFmtStringObj
*fmtObj
;
7678 /* If format specification is not an object, convert it! */
7679 if (fmtObjPtr
->typePtr
!= &scanFmtStringObjType
)
7680 SetScanFmtFromAny(interp
, fmtObjPtr
);
7681 fmtObj
= (ScanFmtStringObj
*)fmtObjPtr
->internalRep
.ptr
;
7682 /* Check if format specification was valid */
7683 if (fmtObj
->error
!= 0) {
7684 if (flags
& JIM_ERRMSG
)
7685 Jim_SetResultString(interp
, fmtObj
->error
, -1);
7688 /* Allocate a new "shared" empty string for all unassigned conversions */
7689 emptyStr
= Jim_NewEmptyStringObj(interp
);
7690 Jim_IncrRefCount(emptyStr
);
7691 /* Create a list and fill it with empty strings up to max specified XPG3 */
7692 resultList
= Jim_NewListObj(interp
, 0, 0);
7693 if (fmtObj
->maxPos
> 0) {
7694 for (i
=0; i
< fmtObj
->maxPos
; ++i
)
7695 Jim_ListAppendElement(interp
, resultList
, emptyStr
);
7696 JimListGetElements(interp
, resultList
, &resultc
, &resultVec
);
7698 /* Now handle every partial format description */
7699 for (i
=0, pos
=0; i
< fmtObj
->count
; ++i
) {
7700 ScanFmtPartDescr
*descr
= &(fmtObj
->descr
[i
]);
7702 /* Only last type may be "literal" w/o conversion - skip it! */
7703 if (descr
->type
== 0) continue;
7704 /* As long as any conversion could be done, we will proceed */
7706 scanned
= ScanOneEntry(interp
, str
, pos
, fmtObj
, i
, &value
);
7707 /* In case our first try results in EOF, we will leave */
7708 if (scanned
== -1 && i
== 0)
7710 /* Advance next pos-to-be-scanned for the amount scanned already */
7712 /* value == 0 means no conversion took place so take empty string */
7714 value
= Jim_NewEmptyStringObj(interp
);
7715 /* If value is a non-assignable one, skip it */
7716 if (descr
->pos
== -1) {
7717 Jim_FreeNewObj(interp
, value
);
7718 } else if (descr
->pos
== 0)
7719 /* Otherwise append it to the result list if no XPG3 was given */
7720 Jim_ListAppendElement(interp
, resultList
, value
);
7721 else if (resultVec
[descr
->pos
-1] == emptyStr
) {
7722 /* But due to given XPG3, put the value into the corr. slot */
7723 Jim_DecrRefCount(interp
, resultVec
[descr
->pos
-1]);
7724 Jim_IncrRefCount(value
);
7725 resultVec
[descr
->pos
-1] = value
;
7727 /* Otherwise, the slot was already used - free obj and ERROR */
7728 Jim_FreeNewObj(interp
, value
);
7732 Jim_DecrRefCount(interp
, emptyStr
);
7735 Jim_DecrRefCount(interp
, emptyStr
);
7736 Jim_FreeNewObj(interp
, resultList
);
7737 return (Jim_Obj
*)EOF
;
7739 Jim_DecrRefCount(interp
, emptyStr
);
7740 Jim_FreeNewObj(interp
, resultList
);
7744 /* -----------------------------------------------------------------------------
7745 * Pseudo Random Number Generation
7746 * ---------------------------------------------------------------------------*/
7747 static void JimPrngSeed(Jim_Interp
*interp
, const unsigned char *seed
,
7750 /* Initialize the sbox with the numbers from 0 to 255 */
7751 static void JimPrngInit(Jim_Interp
*interp
)
7754 unsigned int seed
[256];
7756 interp
->prngState
= Jim_Alloc(sizeof(Jim_PrngState
));
7757 for (i
= 0; i
< 256; i
++)
7758 seed
[i
] = (rand() ^ time(NULL
) ^ clock());
7759 JimPrngSeed(interp
, (unsigned char*) seed
, sizeof(int)*256);
7762 /* Generates N bytes of random data */
7763 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
)
7765 Jim_PrngState
*prng
;
7766 unsigned char *destByte
= (unsigned char*) dest
;
7767 unsigned int si
, sj
, x
;
7769 /* initialization, only needed the first time */
7770 if (interp
->prngState
== NULL
)
7771 JimPrngInit(interp
);
7772 prng
= interp
->prngState
;
7773 /* generates 'len' bytes of pseudo-random numbers */
7774 for (x
= 0; x
< len
; x
++) {
7775 prng
->i
= (prng
->i
+1) & 0xff;
7776 si
= prng
->sbox
[prng
->i
];
7777 prng
->j
= (prng
->j
+ si
) & 0xff;
7778 sj
= prng
->sbox
[prng
->j
];
7779 prng
->sbox
[prng
->i
] = sj
;
7780 prng
->sbox
[prng
->j
] = si
;
7781 *destByte
++ = prng
->sbox
[(si
+sj
)&0xff];
7785 /* Re-seed the generator with user-provided bytes */
7786 static void JimPrngSeed(Jim_Interp
*interp
, const unsigned char *seed
,
7790 unsigned char buf
[256];
7791 Jim_PrngState
*prng
;
7793 /* initialization, only needed the first time */
7794 if (interp
->prngState
== NULL
)
7795 JimPrngInit(interp
);
7796 prng
= interp
->prngState
;
7798 /* Set the sbox[i] with i */
7799 for (i
= 0; i
< 256; i
++)
7801 /* Now use the seed to perform a random permutation of the sbox */
7802 for (i
= 0; i
< seedLen
; i
++) {
7805 t
= prng
->sbox
[i
&0xFF];
7806 prng
->sbox
[i
&0xFF] = prng
->sbox
[seed
[i
]];
7807 prng
->sbox
[seed
[i
]] = t
;
7809 prng
->i
= prng
->j
= 0;
7810 /* discard the first 256 bytes of stream. */
7811 JimRandomBytes(interp
, buf
, 256);
7814 /* -----------------------------------------------------------------------------
7815 * Dynamic libraries support (WIN32 not supported)
7816 * ---------------------------------------------------------------------------*/
7821 void * dlopen(const char *path
, int mode
)
7825 return (void *)LoadLibraryA(path
);
7827 int dlclose(void *handle
)
7829 FreeLibrary((HANDLE
)handle
);
7832 void *dlsym(void *handle
, const char *symbol
)
7834 return GetProcAddress((HMODULE
)handle
, symbol
);
7836 static char win32_dlerror_string
[121];
7837 const char *dlerror(void)
7839 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, GetLastError(),
7840 LANG_NEUTRAL
, win32_dlerror_string
, 120, NULL
);
7841 return win32_dlerror_string
;
7845 int Jim_LoadLibrary(Jim_Interp
*interp
, const char *pathName
)
7847 Jim_Obj
*libPathObjPtr
;
7850 int (*onload
)(Jim_Interp
*interp
);
7852 libPathObjPtr
= Jim_GetGlobalVariableStr(interp
, "jim_libpath", JIM_NONE
);
7853 if (libPathObjPtr
== NULL
) {
7855 libPathObjPtr
= NULL
;
7857 Jim_IncrRefCount(libPathObjPtr
);
7858 Jim_ListLength(interp
, libPathObjPtr
, &prefixc
);
7861 for (i
= -1; i
< prefixc
; i
++) {
7863 handle
= dlopen(pathName
, RTLD_LAZY
);
7866 char buf
[JIM_PATH_LEN
];
7869 Jim_Obj
*prefixObjPtr
;
7872 if (Jim_ListIndex(interp
, libPathObjPtr
, i
,
7873 &prefixObjPtr
, JIM_NONE
) != JIM_OK
)
7875 prefix
= Jim_GetString(prefixObjPtr
, NULL
);
7876 prefixlen
= strlen(prefix
);
7877 if (prefixlen
+strlen(pathName
)+1 >= JIM_PATH_LEN
)
7879 if (prefixlen
&& prefix
[prefixlen
-1] == '/')
7880 sprintf(buf
, "%s%s", prefix
, pathName
);
7882 sprintf(buf
, "%s/%s", prefix
, pathName
);
7883 printf("opening '%s'\n", buf
);
7884 fp
= fopen(buf
, "r");
7888 handle
= dlopen(buf
, RTLD_LAZY
);
7889 printf("got handle %p\n", handle
);
7891 if (handle
== NULL
) {
7892 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
7893 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
7894 "error loading extension \"", pathName
,
7895 "\": ", dlerror(), NULL
);
7900 if ((onload
= dlsym(handle
, "Jim_OnLoad")) == NULL
) {
7901 Jim_SetResultString(interp
,
7902 "No Jim_OnLoad symbol found on extension", -1);
7905 if (onload(interp
) == JIM_ERR
) {
7909 Jim_SetEmptyResult(interp
);
7910 if (libPathObjPtr
!= NULL
)
7911 Jim_DecrRefCount(interp
, libPathObjPtr
);
7915 if (libPathObjPtr
!= NULL
)
7916 Jim_DecrRefCount(interp
, libPathObjPtr
);
7919 #else /* JIM_DYNLIB */
7920 int Jim_LoadLibrary(Jim_Interp
*interp
, const char *pathName
)
7922 JIM_NOTUSED(interp
);
7923 JIM_NOTUSED(pathName
);
7925 Jim_SetResultString(interp
, "the Jim binary has no support for [load]", -1);
7928 #endif/* JIM_DYNLIB */
7930 /* -----------------------------------------------------------------------------
7932 * ---------------------------------------------------------------------------*/
7934 #define JIM_PKG_ANY_VERSION -1
7936 /* Convert a string of the type "1.2" into an integer.
7937 * MAJOR.MINOR is converted as MAJOR*100+MINOR, so "1.2" is converted
7938 * to the integer with value 102 */
7939 static int JimPackageVersionToInt(Jim_Interp
*interp
, const char *v
,
7940 int *intPtr
, int flags
)
7943 jim_wide major
, minor
;
7944 char *majorStr
, *minorStr
, *p
;
7947 *intPtr
= JIM_PKG_ANY_VERSION
;
7951 copy
= Jim_StrDup(v
);
7952 p
= strchr(copy
, '.');
7953 if (p
== NULL
) goto badfmt
;
7958 if (Jim_StringToWide(majorStr
, &major
, 10) != JIM_OK
||
7959 Jim_StringToWide(minorStr
, &minor
, 10) != JIM_OK
)
7961 *intPtr
= (int)(major
*100+minor
);
7967 if (flags
& JIM_ERRMSG
) {
7968 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
7969 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
7970 "invalid package version '", v
, "'", NULL
);
7975 #define JIM_MATCHVER_EXACT (1<<JIM_PRIV_FLAG_SHIFT)
7976 static int JimPackageMatchVersion(int needed
, int actual
, int flags
)
7978 if (needed
== JIM_PKG_ANY_VERSION
) return 1;
7979 if (flags
& JIM_MATCHVER_EXACT
) {
7980 return needed
== actual
;
7982 return needed
/100 == actual
/100 && (needed
<= actual
);
7986 int Jim_PackageProvide(Jim_Interp
*interp
, const char *name
, const char *ver
,
7990 /* Check if the version format is ok */
7991 if (JimPackageVersionToInt(interp
, ver
, &intVersion
, JIM_ERRMSG
) != JIM_OK
)
7993 /* If the package was already provided returns an error. */
7994 if (Jim_FindHashEntry(&interp
->packages
, name
) != NULL
) {
7995 if (flags
& JIM_ERRMSG
) {
7996 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
7997 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
7998 "package '", name
, "' was already provided", NULL
);
8002 Jim_AddHashEntry(&interp
->packages
, name
, (char*) ver
);
8009 # include <sys/types.h>
8010 # include <dirent.h>
8013 /* Posix dirent.h compatiblity layer for WIN32.
8014 * Copyright Kevlin Henney, 1997, 2003. All rights reserved.
8015 * Copyright Salvatore Sanfilippo ,2005.
8017 * Permission to use, copy, modify, and distribute this software and its
8018 * documentation for any purpose is hereby granted without fee, provided
8019 * that this copyright and permissions notice appear in all copies and
8022 * This software is supplied "as is" without express or implied warranty.
8023 * This software was modified by Salvatore Sanfilippo for the Jim Interpreter.
8030 typedef struct DIR {
8031 long handle
; /* -1 for failed rewind */
8032 struct _finddata_t info
;
8033 struct dirent result
; /* d_name null iff first time */
8034 char *name
; /* null-terminated char string */
8037 DIR *opendir(const char *name
)
8041 if(name
&& name
[0]) {
8042 size_t base_length
= strlen(name
);
8043 const char *all
= /* search pattern must end with suitable wildcard */
8044 strchr("/\\", name
[base_length
- 1]) ? "*" : "/*";
8046 if((dir
= (DIR *) Jim_Alloc(sizeof *dir
)) != 0 &&
8047 (dir
->name
= (char *) Jim_Alloc(base_length
+ strlen(all
) + 1)) != 0)
8049 strcat(strcpy(dir
->name
, name
), all
);
8051 if((dir
->handle
= (long) _findfirst(dir
->name
, &dir
->info
)) != -1)
8052 dir
->result
.d_name
= 0;
8053 else { /* rollback */
8054 Jim_Free(dir
->name
);
8058 } else { /* rollback */
8069 int closedir(DIR *dir
)
8074 if(dir
->handle
!= -1)
8075 result
= _findclose(dir
->handle
);
8076 Jim_Free(dir
->name
);
8079 if(result
== -1) /* map all errors to EBADF */
8084 struct dirent
*readdir(DIR *dir
)
8086 struct dirent
*result
= 0;
8088 if(dir
&& dir
->handle
!= -1) {
8089 if(!dir
->result
.d_name
|| _findnext(dir
->handle
, &dir
->info
) != -1) {
8090 result
= &dir
->result
;
8091 result
->d_name
= dir
->info
.name
;
8101 static char *JimFindBestPackage(Jim_Interp
*interp
, char **prefixes
,
8102 int prefixc
, const char *pkgName
, int pkgVer
, int flags
)
8104 int bestVer
= -1, i
;
8105 int pkgNameLen
= strlen(pkgName
);
8106 char *bestPackage
= NULL
;
8109 for (i
= 0; i
< prefixc
; i
++) {
8111 char buf
[JIM_PATH_LEN
];
8114 if (prefixes
[i
] == NULL
) continue;
8115 strncpy(buf
, prefixes
[i
], JIM_PATH_LEN
);
8116 buf
[JIM_PATH_LEN
-1] = '\0';
8117 prefixLen
= strlen(buf
);
8118 if (prefixLen
&& buf
[prefixLen
-1] == '/')
8119 buf
[prefixLen
-1] = '\0';
8121 if ((dir
= opendir(buf
)) == NULL
) continue;
8122 while ((de
= readdir(dir
)) != NULL
) {
8123 char *fileName
= de
->d_name
;
8124 int fileNameLen
= strlen(fileName
);
8126 if (strncmp(fileName
, "jim-", 4) == 0 &&
8127 strncmp(fileName
+4, pkgName
, pkgNameLen
) == 0 &&
8128 *(fileName
+4+pkgNameLen
) == '-' &&
8129 fileNameLen
> 4 && /* note that this is not really useful */
8130 (strncmp(fileName
+fileNameLen
-4, ".tcl", 4) == 0 ||
8131 strncmp(fileName
+fileNameLen
-4, ".dll", 4) == 0 ||
8132 strncmp(fileName
+fileNameLen
-3, ".so", 3) == 0))
8134 char ver
[6]; /* xx.yy<nulterm> */
8135 char *p
= strrchr(fileName
, '.');
8136 int verLen
, fileVer
;
8138 verLen
= p
- (fileName
+4+pkgNameLen
+1);
8139 if (verLen
< 3 || verLen
> 5) continue;
8140 memcpy(ver
, fileName
+4+pkgNameLen
+1, verLen
);
8142 if (JimPackageVersionToInt(interp
, ver
, &fileVer
, JIM_NONE
)
8143 != JIM_OK
) continue;
8144 if (JimPackageMatchVersion(pkgVer
, fileVer
, flags
) &&
8145 (bestVer
== -1 || bestVer
< fileVer
))
8148 Jim_Free(bestPackage
);
8149 bestPackage
= Jim_Alloc(strlen(buf
)+strlen(fileName
)+2);
8150 sprintf(bestPackage
, "%s/%s", buf
, fileName
);
8159 #else /* JIM_ANSIC */
8161 static char *JimFindBestPackage(Jim_Interp
*interp
, char **prefixes
,
8162 int prefixc
, const char *pkgName
, int pkgVer
, int flags
)
8164 JIM_NOTUSED(interp
);
8165 JIM_NOTUSED(prefixes
);
8166 JIM_NOTUSED(prefixc
);
8167 JIM_NOTUSED(pkgName
);
8168 JIM_NOTUSED(pkgVer
);
8173 #endif /* JIM_ANSIC */
8175 /* Search for a suitable package under every dir specified by jim_libpath
8176 * and load it if possible. If a suitable package was loaded with success
8177 * JIM_OK is returned, otherwise JIM_ERR is returned. */
8178 static int JimLoadPackage(Jim_Interp
*interp
, const char *name
, int ver
,
8181 Jim_Obj
*libPathObjPtr
;
8182 char **prefixes
, *best
;
8183 int prefixc
, i
, retCode
= JIM_OK
;
8185 libPathObjPtr
= Jim_GetGlobalVariableStr(interp
, "jim_libpath", JIM_NONE
);
8186 if (libPathObjPtr
== NULL
) {
8188 libPathObjPtr
= NULL
;
8190 Jim_IncrRefCount(libPathObjPtr
);
8191 Jim_ListLength(interp
, libPathObjPtr
, &prefixc
);
8194 prefixes
= Jim_Alloc(sizeof(char*)*prefixc
);
8195 for (i
= 0; i
< prefixc
; i
++) {
8196 Jim_Obj
*prefixObjPtr
;
8197 if (Jim_ListIndex(interp
, libPathObjPtr
, i
,
8198 &prefixObjPtr
, JIM_NONE
) != JIM_OK
)
8203 prefixes
[i
] = Jim_StrDup(Jim_GetString(prefixObjPtr
, NULL
));
8205 /* Scan every directory to find the "best" package. */
8206 best
= JimFindBestPackage(interp
, prefixes
, prefixc
, name
, ver
, flags
);
8208 char *p
= strrchr(best
, '.');
8209 /* Try to load/source it */
8210 if (p
&& strcmp(p
, ".tcl") == 0) {
8211 retCode
= Jim_EvalFile(interp
, best
);
8213 retCode
= Jim_LoadLibrary(interp
, best
);
8219 for (i
= 0; i
< prefixc
; i
++)
8220 Jim_Free(prefixes
[i
]);
8223 Jim_DecrRefCount(interp
, libPathObjPtr
);
8227 const char *Jim_PackageRequire(Jim_Interp
*interp
, const char *name
,
8228 const char *ver
, int flags
)
8233 if (JimPackageVersionToInt(interp
, ver
, &requiredVer
, JIM_ERRMSG
) != JIM_OK
)
8235 he
= Jim_FindHashEntry(&interp
->packages
, name
);
8237 /* Try to load the package. */
8238 if (JimLoadPackage(interp
, name
, requiredVer
, flags
) == JIM_OK
) {
8239 he
= Jim_FindHashEntry(&interp
->packages
, name
);
8245 /* No way... return an error. */
8246 if (flags
& JIM_ERRMSG
) {
8247 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
8248 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
8249 "Can't find package '", name
, "'", NULL
);
8254 if (JimPackageVersionToInt(interp
, he
->val
, &actualVer
, JIM_ERRMSG
)
8259 /* Check if version matches. */
8260 if (JimPackageMatchVersion(requiredVer
, actualVer
, flags
) == 0) {
8261 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
8262 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
8263 "Package '", name
, "' already loaded, but with version ",
8271 /* -----------------------------------------------------------------------------
8273 * ---------------------------------------------------------------------------*/
8274 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
8275 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
8277 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, int argc
,
8278 Jim_Obj
*const *argv
);
8280 /* Handle calls to the [unknown] command */
8281 static int JimUnknown(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
8283 Jim_Obj
**v
, *sv
[JIM_EVAL_SARGV_LEN
];
8286 /* If the [unknown] command does not exists returns
8288 if (Jim_GetCommand(interp
, interp
->unknown
, JIM_NONE
) == NULL
)
8291 /* The object interp->unknown just contains
8292 * the "unknown" string, it is used in order to
8293 * avoid to lookup the unknown command every time
8294 * but instread to cache the result. */
8295 if (argc
+1 <= JIM_EVAL_SARGV_LEN
)
8298 v
= Jim_Alloc(sizeof(Jim_Obj
*)*(argc
+1));
8299 /* Make a copy of the arguments vector, but shifted on
8300 * the right of one position. The command name of the
8301 * command will be instead the first argument of the
8302 * [unknonw] call. */
8303 memcpy(v
+1, argv
, sizeof(Jim_Obj
*)*argc
);
8304 v
[0] = interp
->unknown
;
8306 retCode
= Jim_EvalObjVector(interp
, argc
+1, v
);
8313 /* Eval the object vector 'objv' composed of 'objc' elements.
8314 * Every element is used as single argument.
8315 * Jim_EvalObj() will call this function every time its object
8316 * argument is of "list" type, with no string representation.
8318 * This is possible because the string representation of a
8319 * list object generated by the UpdateStringOfList is made
8320 * in a way that ensures that every list element is a different
8321 * command argument. */
8322 int Jim_EvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
8327 /* Incr refcount of arguments. */
8328 for (i
= 0; i
< objc
; i
++)
8329 Jim_IncrRefCount(objv
[i
]);
8330 /* Command lookup */
8331 cmdPtr
= Jim_GetCommand(interp
, objv
[0], JIM_ERRMSG
);
8332 if (cmdPtr
== NULL
) {
8333 retcode
= JimUnknown(interp
, objc
, objv
);
8335 /* Call it -- Make sure result is an empty object. */
8336 Jim_SetEmptyResult(interp
);
8337 if (cmdPtr
->cmdProc
) {
8338 interp
->cmdPrivData
= cmdPtr
->privData
;
8339 retcode
= cmdPtr
->cmdProc(interp
, objc
, objv
);
8341 retcode
= JimCallProcedure(interp
, cmdPtr
, objc
, objv
);
8342 if (retcode
== JIM_ERR
) {
8343 JimAppendStackTrace(interp
,
8344 Jim_GetString(objv
[0], NULL
), "?", 1);
8348 /* Decr refcount of arguments and return the retcode */
8349 for (i
= 0; i
< objc
; i
++)
8350 Jim_DecrRefCount(interp
, objv
[i
]);
8354 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
8355 * via *objPtrPtr. This function is only called by Jim_EvalObj().
8356 * The returned object has refcount = 0. */
8357 int Jim_InterpolateTokens(Jim_Interp
*interp
, ScriptToken
*token
,
8358 int tokens
, Jim_Obj
**objPtrPtr
)
8360 int totlen
= 0, i
, retcode
;
8362 Jim_Obj
*sintv
[JIM_EVAL_SINTV_LEN
];
8366 if (tokens
<= JIM_EVAL_SINTV_LEN
)
8369 intv
= Jim_Alloc(sizeof(Jim_Obj
*)*
8371 /* Compute every token forming the argument
8372 * in the intv objects vector. */
8373 for (i
= 0; i
< tokens
; i
++) {
8374 switch(token
[i
].type
) {
8377 intv
[i
] = token
[i
].objPtr
;
8380 intv
[i
] = Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
8386 case JIM_TT_DICTSUGAR
:
8387 intv
[i
] = Jim_ExpandDictSugar(interp
, token
[i
].objPtr
);
8394 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
8395 if (retcode
!= JIM_OK
)
8397 intv
[i
] = Jim_GetResult(interp
);
8401 "default token type reached "
8402 "in Jim_InterpolateTokens().");
8405 Jim_IncrRefCount(intv
[i
]);
8406 /* Make sure there is a valid
8407 * string rep, and add the string
8408 * length to the total legnth. */
8409 Jim_GetString(intv
[i
], NULL
);
8410 totlen
+= intv
[i
]->length
;
8412 /* Concatenate every token in an unique
8414 objPtr
= Jim_NewStringObjNoAlloc(interp
,
8416 s
= objPtr
->bytes
= Jim_Alloc(totlen
+1);
8417 objPtr
->length
= totlen
;
8418 for (i
= 0; i
< tokens
; i
++) {
8419 memcpy(s
, intv
[i
]->bytes
, intv
[i
]->length
);
8420 s
+= intv
[i
]->length
;
8421 Jim_DecrRefCount(interp
, intv
[i
]);
8423 objPtr
->bytes
[totlen
] = '\0';
8424 /* Free the intv vector if not static. */
8425 if (tokens
> JIM_EVAL_SINTV_LEN
)
8427 *objPtrPtr
= objPtr
;
8432 Jim_DecrRefCount(interp
, intv
[i
]);
8433 if (tokens
> JIM_EVAL_SINTV_LEN
)
8438 /* Helper of Jim_EvalObj() to perform argument expansion.
8439 * Basically this function append an argument to 'argv'
8440 * (and increments argc by reference accordingly), performing
8441 * expansion of the list object if 'expand' is non-zero, or
8442 * just adding objPtr to argv if 'expand' is zero. */
8443 void Jim_ExpandArgument(Jim_Interp
*interp
, Jim_Obj
***argv
,
8444 int *argcPtr
, int expand
, Jim_Obj
*objPtr
)
8447 (*argv
) = Jim_Realloc(*argv
, sizeof(Jim_Obj
*)*((*argcPtr
)+1));
8448 /* refcount of objPtr not incremented because
8449 * we are actually transfering a reference from
8450 * the old 'argv' to the expanded one. */
8451 (*argv
)[*argcPtr
] = objPtr
;
8456 Jim_ListLength(interp
, objPtr
, &len
);
8457 (*argv
) = Jim_Realloc(*argv
, sizeof(Jim_Obj
*)*((*argcPtr
)+len
));
8458 for (i
= 0; i
< len
; i
++) {
8459 (*argv
)[*argcPtr
] = objPtr
->internalRep
.listValue
.ele
[i
];
8460 Jim_IncrRefCount(objPtr
->internalRep
.listValue
.ele
[i
]);
8463 /* The original object reference is no longer needed,
8464 * after the expansion it is no longer present on
8465 * the argument vector, but the single elements are
8467 Jim_DecrRefCount(interp
, objPtr
);
8471 int Jim_EvalObj(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
8476 int *cs
; /* command structure array */
8477 int retcode
= JIM_OK
;
8478 Jim_Obj
*sargv
[JIM_EVAL_SARGV_LEN
], **argv
= NULL
, *tmpObjPtr
;
8480 interp
->errorFlag
= 0;
8482 /* If the object is of type "list" and there is no
8483 * string representation for this object, we can call
8484 * a specialized version of Jim_EvalObj() */
8485 if (scriptObjPtr
->typePtr
== &listObjType
&&
8486 scriptObjPtr
->internalRep
.listValue
.len
&&
8487 scriptObjPtr
->bytes
== NULL
) {
8488 Jim_IncrRefCount(scriptObjPtr
);
8489 retcode
= Jim_EvalObjVector(interp
,
8490 scriptObjPtr
->internalRep
.listValue
.len
,
8491 scriptObjPtr
->internalRep
.listValue
.ele
);
8492 Jim_DecrRefCount(interp
, scriptObjPtr
);
8496 Jim_IncrRefCount(scriptObjPtr
); /* Make sure it's shared. */
8497 script
= Jim_GetScript(interp
, scriptObjPtr
);
8498 /* Now we have to make sure the internal repr will not be
8499 * freed on shimmering.
8501 * Think for example to this:
8503 * set x {llength $x; ... some more code ...}; eval $x
8505 * In order to preserve the internal rep, we increment the
8506 * inUse field of the script internal rep structure. */
8509 token
= script
->token
;
8511 cs
= script
->cmdStruct
;
8512 i
= 0; /* 'i' is the current token index. */
8514 /* Reset the interpreter result. This is useful to
8515 * return the emtpy result in the case of empty program. */
8516 Jim_SetEmptyResult(interp
);
8518 /* Execute every command sequentially, returns on
8519 * error (i.e. if a command does not return JIM_OK) */
8522 int argc
= *cs
++; /* Get the number of arguments */
8525 /* Set the expand flag if needed. */
8530 /* Allocate the arguments vector */
8531 if (argc
<= JIM_EVAL_SARGV_LEN
)
8534 argv
= Jim_Alloc(sizeof(Jim_Obj
*)*argc
);
8535 /* Populate the arguments objects. */
8536 for (j
= 0; j
< argc
; j
++) {
8539 /* tokens is negative if expansion is needed.
8540 * for this argument. */
8542 tokens
= (-tokens
)-1;
8546 /* Fast path if the token does not
8547 * need interpolation */
8548 switch(token
[i
].type
) {
8551 argv
[j
] = token
[i
].objPtr
;
8554 tmpObjPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
,
8560 argv
[j
] = tmpObjPtr
;
8562 case JIM_TT_DICTSUGAR
:
8563 tmpObjPtr
= Jim_ExpandDictSugar(interp
, token
[i
].objPtr
);
8568 argv
[j
] = tmpObjPtr
;
8571 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
8572 if (retcode
!= JIM_OK
)
8574 argv
[j
] = Jim_GetResult(interp
);
8578 "default token type reached "
8579 "in Jim_EvalObj().");
8582 Jim_IncrRefCount(argv
[j
]);
8585 /* For interpolation we call an helper
8586 * function doing the work for us. */
8587 if ((retcode
= Jim_InterpolateTokens(interp
,
8588 token
+i
, tokens
, &tmpObjPtr
)) != JIM_OK
)
8592 argv
[j
] = tmpObjPtr
;
8593 Jim_IncrRefCount(argv
[j
]);
8597 /* Handle {expand} expansion */
8599 int *ecs
= cs
- argc
;
8601 Jim_Obj
**eargv
= NULL
;
8603 for (j
= 0; j
< argc
; j
++) {
8604 Jim_ExpandArgument( interp
, &eargv
, &eargc
,
8605 ecs
[j
] < 0, argv
[j
]);
8613 /* Nothing to do with zero args. */
8618 /* Lookup the command to call */
8619 cmd
= Jim_GetCommand(interp
, argv
[0], JIM_ERRMSG
);
8621 /* Call it -- Make sure result is an empty object. */
8622 Jim_SetEmptyResult(interp
);
8624 interp
->cmdPrivData
= cmd
->privData
;
8625 retcode
= cmd
->cmdProc(interp
, argc
, argv
);
8627 retcode
= JimCallProcedure(interp
, cmd
, argc
, argv
);
8628 if (retcode
== JIM_ERR
) {
8629 JimAppendStackTrace(interp
,
8630 Jim_GetString(argv
[0], NULL
), script
->fileName
,
8631 token
[i
-argc
*2].linenr
);
8635 /* Call [unknown] */
8636 retcode
= JimUnknown(interp
, argc
, argv
);
8637 if (retcode
== JIM_ERR
) {
8638 JimAppendStackTrace(interp
,
8639 Jim_GetString(argv
[0], NULL
), script
->fileName
,
8640 token
[i
-argc
*2].linenr
);
8643 if (retcode
!= JIM_OK
) {
8644 i
-= argc
*2; /* point to the command name. */
8647 /* Decrement the arguments count */
8648 for (j
= 0; j
< argc
; j
++) {
8649 Jim_DecrRefCount(interp
, argv
[j
]);
8652 if (argv
!= sargv
) {
8657 /* Note that we don't have to decrement inUse, because the
8658 * following code transfers our use of the reference again to
8659 * the script object. */
8660 j
= 0; /* on normal termination, the argv array is already
8661 Jim_DecrRefCount-ed. */
8663 /* Handle errors. */
8664 if (retcode
== JIM_ERR
&& !interp
->errorFlag
) {
8665 interp
->errorFlag
= 1;
8666 JimSetErrorFileName(interp
, script
->fileName
);
8667 JimSetErrorLineNumber(interp
, token
[i
].linenr
);
8668 JimResetStackTrace(interp
);
8670 Jim_FreeIntRep(interp
, scriptObjPtr
);
8671 scriptObjPtr
->typePtr
= &scriptObjType
;
8672 Jim_SetIntRepPtr(scriptObjPtr
, script
);
8673 Jim_DecrRefCount(interp
, scriptObjPtr
);
8674 for (i
= 0; i
< j
; i
++) {
8675 Jim_DecrRefCount(interp
, argv
[i
]);
8682 /* Call a procedure implemented in Tcl.
8683 * It's possible to speed-up a lot this function, currently
8684 * the callframes are not cached, but allocated and
8685 * destroied every time. What is expecially costly is
8686 * to create/destroy the local vars hash table every time.
8688 * This can be fixed just implementing callframes caching
8689 * in JimCreateCallFrame() and JimFreeCallFrame(). */
8690 int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, int argc
,
8691 Jim_Obj
*const *argv
)
8694 Jim_CallFrame
*callFramePtr
;
8697 if (argc
< cmd
->arityMin
|| (cmd
->arityMax
!= -1 &&
8698 argc
> cmd
->arityMax
)) {
8699 Jim_Obj
*objPtr
= Jim_NewEmptyStringObj(interp
);
8700 Jim_AppendStrings(interp
, objPtr
,
8701 "wrong # args: should be \"", Jim_GetString(argv
[0], NULL
),
8702 (cmd
->arityMin
> 1) ? " " : "",
8703 Jim_GetString(cmd
->argListObjPtr
, NULL
), "\"", NULL
);
8704 Jim_SetResult(interp
, objPtr
);
8707 /* Check if there are too nested calls */
8708 if (interp
->numLevels
== interp
->maxNestingDepth
) {
8709 Jim_SetResultString(interp
,
8710 "Too many nested calls. Infinite recursion?", -1);
8713 /* Create a new callframe */
8714 callFramePtr
= JimCreateCallFrame(interp
);
8715 callFramePtr
->parentCallFrame
= interp
->framePtr
;
8716 callFramePtr
->argv
= argv
;
8717 callFramePtr
->argc
= argc
;
8718 callFramePtr
->procArgsObjPtr
= cmd
->argListObjPtr
;
8719 callFramePtr
->procBodyObjPtr
= cmd
->bodyObjPtr
;
8720 callFramePtr
->staticVars
= cmd
->staticVars
;
8721 Jim_IncrRefCount(cmd
->argListObjPtr
);
8722 Jim_IncrRefCount(cmd
->bodyObjPtr
);
8723 interp
->framePtr
= callFramePtr
;
8724 interp
->numLevels
++;
8726 for (i
= 0; i
< cmd
->arityMin
-1; i
++) {
8729 Jim_ListIndex(interp
, cmd
->argListObjPtr
, i
, &objPtr
, JIM_NONE
);
8730 Jim_SetVariable(interp
, objPtr
, argv
[i
+1]);
8732 if (cmd
->arityMax
== -1) {
8733 Jim_Obj
*listObjPtr
, *objPtr
;
8735 listObjPtr
= Jim_NewListObj(interp
, argv
+cmd
->arityMin
,
8736 argc
-cmd
->arityMin
);
8737 Jim_ListIndex(interp
, cmd
->argListObjPtr
, i
, &objPtr
, JIM_NONE
);
8738 Jim_SetVariable(interp
, objPtr
, listObjPtr
);
8741 retcode
= Jim_EvalObj(interp
, cmd
->bodyObjPtr
);
8743 /* Destroy the callframe */
8744 interp
->numLevels
--;
8745 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
8746 if (callFramePtr
->vars
.size
!= JIM_HT_INITIAL_SIZE
) {
8747 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NONE
);
8749 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NOHT
);
8751 /* Handle the JIM_EVAL return code */
8752 if (retcode
== JIM_EVAL
&& interp
->evalRetcodeLevel
!= interp
->numLevels
) {
8753 int savedLevel
= interp
->evalRetcodeLevel
;
8755 interp
->evalRetcodeLevel
= interp
->numLevels
;
8756 while (retcode
== JIM_EVAL
) {
8757 Jim_Obj
*resultScriptObjPtr
= Jim_GetResult(interp
);
8758 Jim_IncrRefCount(resultScriptObjPtr
);
8759 retcode
= Jim_EvalObj(interp
, resultScriptObjPtr
);
8760 Jim_DecrRefCount(interp
, resultScriptObjPtr
);
8762 interp
->evalRetcodeLevel
= savedLevel
;
8764 /* Handle the JIM_RETURN return code */
8765 if (retcode
== JIM_RETURN
) {
8766 retcode
= interp
->returnCode
;
8767 interp
->returnCode
= JIM_OK
;
8772 int Jim_Eval_Named(Jim_Interp
*interp
, const char *script
, const char *filename
, int lineno
)
8775 Jim_Obj
*scriptObjPtr
;
8777 scriptObjPtr
= Jim_NewStringObj(interp
, script
, -1);
8778 Jim_IncrRefCount(scriptObjPtr
);
8782 JimSetSourceInfo( interp
, scriptObjPtr
, filename
, lineno
);
8785 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
8786 Jim_DecrRefCount(interp
, scriptObjPtr
);
8790 int Jim_Eval(Jim_Interp
*interp
, const char *script
)
8792 return Jim_Eval_Named( interp
, script
, NULL
, 0 );
8797 /* Execute script in the scope of the global level */
8798 int Jim_EvalGlobal(Jim_Interp
*interp
, const char *script
)
8800 Jim_CallFrame
*savedFramePtr
;
8803 savedFramePtr
= interp
->framePtr
;
8804 interp
->framePtr
= interp
->topFramePtr
;
8805 retval
= Jim_Eval(interp
, script
);
8806 interp
->framePtr
= savedFramePtr
;
8810 int Jim_EvalObjBackground(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
8812 Jim_CallFrame
*savedFramePtr
;
8815 savedFramePtr
= interp
->framePtr
;
8816 interp
->framePtr
= interp
->topFramePtr
;
8817 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
8818 interp
->framePtr
= savedFramePtr
;
8819 /* Try to report the error (if any) via the bgerror proc */
8820 if (retval
!= JIM_OK
) {
8823 objv
[0] = Jim_NewStringObj(interp
, "bgerror", -1);
8824 objv
[1] = Jim_GetResult(interp
);
8825 Jim_IncrRefCount(objv
[0]);
8826 Jim_IncrRefCount(objv
[1]);
8827 if (Jim_EvalObjVector(interp
, 2, objv
) != JIM_OK
) {
8828 /* Report the error to stderr. */
8829 Jim_fprintf( interp
, interp
->cookie_stderr
, "Background error:" JIM_NL
);
8830 Jim_PrintErrorMessage(interp
);
8832 Jim_DecrRefCount(interp
, objv
[0]);
8833 Jim_DecrRefCount(interp
, objv
[1]);
8838 int Jim_EvalFile(Jim_Interp
*interp
, const char *filename
)
8842 int nread
, totread
, maxlen
, buflen
;
8844 Jim_Obj
*scriptObjPtr
;
8846 if ((fp
= fopen(filename
, "r")) == NULL
) {
8847 const int cwd_len
=2048;
8848 char *cwd
=malloc(cwd_len
);
8849 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
8850 getcwd( cwd
, cwd_len
);
8851 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
8852 "Error loading script \"", filename
, "\"",
8854 " err: ", strerror(errno
), NULL
);
8859 maxlen
= totread
= 0;
8861 if (maxlen
< totread
+buflen
+1) {
8862 maxlen
= totread
+buflen
+1;
8863 prg
= Jim_Realloc(prg
, maxlen
);
8865 /* do not use Jim_fread() - this is really a file */
8866 if ((nread
= fread(prg
+totread
, 1, buflen
, fp
)) == 0) break;
8869 prg
[totread
] = '\0';
8870 /* do not use Jim_fclose() - this is really a file */
8873 scriptObjPtr
= Jim_NewStringObjNoAlloc(interp
, prg
, totread
);
8874 JimSetSourceInfo(interp
, scriptObjPtr
, filename
, 1);
8875 Jim_IncrRefCount(scriptObjPtr
);
8876 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
8877 Jim_DecrRefCount(interp
, scriptObjPtr
);
8881 /* -----------------------------------------------------------------------------
8883 * ---------------------------------------------------------------------------*/
8884 static int JimParseSubstStr(struct JimParserCtx
*pc
)
8887 pc
->tline
= pc
->linenr
;
8888 while (*pc
->p
&& *pc
->p
!= '$' && *pc
->p
!= '[') {
8892 pc
->tt
= JIM_TT_ESC
;
8896 static int JimParseSubst(struct JimParserCtx
*pc
, int flags
)
8901 pc
->tstart
= pc
->tend
= pc
->p
;
8902 pc
->tline
= pc
->linenr
;
8903 pc
->tt
= JIM_TT_EOL
;
8909 retval
= JimParseCmd(pc
);
8910 if (flags
& JIM_SUBST_NOCMD
) {
8913 pc
->tt
= (flags
& JIM_SUBST_NOESC
) ?
8914 JIM_TT_STR
: JIM_TT_ESC
;
8919 if (JimParseVar(pc
) == JIM_ERR
) {
8920 pc
->tstart
= pc
->tend
= pc
->p
++; pc
->len
--;
8921 pc
->tline
= pc
->linenr
;
8922 pc
->tt
= JIM_TT_STR
;
8924 if (flags
& JIM_SUBST_NOVAR
) {
8926 if (flags
& JIM_SUBST_NOESC
)
8927 pc
->tt
= JIM_TT_STR
;
8929 pc
->tt
= JIM_TT_ESC
;
8930 if (*pc
->tstart
== '{') {
8939 retval
= JimParseSubstStr(pc
);
8940 if (flags
& JIM_SUBST_NOESC
)
8941 pc
->tt
= JIM_TT_STR
;
8948 /* The subst object type reuses most of the data structures and functions
8949 * of the script object. Script's data structures are a bit more complex
8950 * for what is needed for [subst]itution tasks, but the reuse helps to
8951 * deal with a single data structure at the cost of some more memory
8952 * usage for substitutions. */
8953 static Jim_ObjType substObjType
= {
8955 FreeScriptInternalRep
,
8956 DupScriptInternalRep
,
8958 JIM_TYPE_REFERENCES
,
8961 /* This method takes the string representation of an object
8962 * as a Tcl string where to perform [subst]itution, and generates
8963 * the pre-parsed internal representation. */
8964 int SetSubstFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, int flags
)
8967 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
8968 struct JimParserCtx parser
;
8969 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
8973 script
->commands
= 0;
8974 script
->token
= NULL
;
8975 script
->cmdStruct
= NULL
;
8977 script
->substFlags
= flags
;
8978 script
->fileName
= NULL
;
8980 JimParserInit(&parser
, scriptText
, scriptTextLen
, 1);
8983 int len
, type
, linenr
;
8985 JimParseSubst(&parser
, flags
);
8986 if (JimParserEof(&parser
)) break;
8987 token
= JimParserGetToken(&parser
, &len
, &type
, &linenr
);
8988 ScriptObjAddToken(interp
, script
, token
, len
, type
,
8991 /* Free the old internal rep and set the new one. */
8992 Jim_FreeIntRep(interp
, objPtr
);
8993 Jim_SetIntRepPtr(objPtr
, script
);
8994 objPtr
->typePtr
= &scriptObjType
;
8998 ScriptObj
*Jim_GetSubst(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
9000 struct ScriptObj
*script
= Jim_GetIntRepPtr(objPtr
);
9002 if (objPtr
->typePtr
!= &substObjType
|| script
->substFlags
!= flags
)
9003 SetSubstFromAny(interp
, objPtr
, flags
);
9004 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
9007 /* Performs commands,variables,blackslashes substitution,
9008 * storing the result object (with refcount 0) into
9010 int Jim_SubstObj(Jim_Interp
*interp
, Jim_Obj
*substObjPtr
,
9011 Jim_Obj
**resObjPtrPtr
, int flags
)
9015 int i
, len
, retcode
= JIM_OK
;
9016 Jim_Obj
*resObjPtr
, *savedResultObjPtr
;
9018 script
= Jim_GetSubst(interp
, substObjPtr
, flags
);
9019 #ifdef JIM_OPTIMIZATION
9020 /* Fast path for a very common case with array-alike syntax,
9021 * that's: $foo($bar) */
9022 if (script
->len
== 1 && script
->token
[0].type
== JIM_TT_VAR
) {
9023 Jim_Obj
*varObjPtr
= script
->token
[0].objPtr
;
9025 Jim_IncrRefCount(varObjPtr
);
9026 resObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
9027 if (resObjPtr
== NULL
) {
9028 Jim_DecrRefCount(interp
, varObjPtr
);
9031 Jim_DecrRefCount(interp
, varObjPtr
);
9032 *resObjPtrPtr
= resObjPtr
;
9037 Jim_IncrRefCount(substObjPtr
); /* Make sure it's shared. */
9038 /* In order to preserve the internal rep, we increment the
9039 * inUse field of the script internal rep structure. */
9042 token
= script
->token
;
9045 /* Save the interp old result, to set it again before
9047 savedResultObjPtr
= interp
->result
;
9048 Jim_IncrRefCount(savedResultObjPtr
);
9050 /* Perform the substitution. Starts with an empty object
9051 * and adds every token (performing the appropriate
9052 * var/command/escape substitution). */
9053 resObjPtr
= Jim_NewStringObj(interp
, "", 0);
9054 for (i
= 0; i
< len
; i
++) {
9057 switch(token
[i
].type
) {
9060 Jim_AppendObj(interp
, resObjPtr
, token
[i
].objPtr
);
9063 objPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
9064 if (objPtr
== NULL
) goto err
;
9065 Jim_IncrRefCount(objPtr
);
9066 Jim_AppendObj(interp
, resObjPtr
, objPtr
);
9067 Jim_DecrRefCount(interp
, objPtr
);
9069 case JIM_TT_DICTSUGAR
:
9070 objPtr
= Jim_ExpandDictSugar(interp
, token
[i
].objPtr
);
9077 if (Jim_EvalObj(interp
, token
[i
].objPtr
) != JIM_OK
)
9079 Jim_AppendObj(interp
, resObjPtr
, interp
->result
);
9083 "default token type (%d) reached "
9084 "in Jim_SubstObj().", token
[i
].type
);
9089 if (retcode
== JIM_OK
)
9090 Jim_SetResult(interp
, savedResultObjPtr
);
9091 Jim_DecrRefCount(interp
, savedResultObjPtr
);
9092 /* Note that we don't have to decrement inUse, because the
9093 * following code transfers our use of the reference again to
9094 * the script object. */
9095 Jim_FreeIntRep(interp
, substObjPtr
);
9096 substObjPtr
->typePtr
= &scriptObjType
;
9097 Jim_SetIntRepPtr(substObjPtr
, script
);
9098 Jim_DecrRefCount(interp
, substObjPtr
);
9099 *resObjPtrPtr
= resObjPtr
;
9102 Jim_FreeNewObj(interp
, resObjPtr
);
9107 /* -----------------------------------------------------------------------------
9108 * API Input/Export functions
9109 * ---------------------------------------------------------------------------*/
9111 int Jim_GetApi(Jim_Interp
*interp
, const char *funcname
, void *targetPtrPtr
)
9115 he
= Jim_FindHashEntry(&interp
->stub
, funcname
);
9118 memcpy(targetPtrPtr
, &he
->val
, sizeof(void*));
9122 int Jim_RegisterApi(Jim_Interp
*interp
, const char *funcname
, void *funcptr
)
9124 return Jim_AddHashEntry(&interp
->stub
, funcname
, funcptr
);
9127 #define JIM_REGISTER_API(name) \
9128 Jim_RegisterApi(interp, "Jim_" #name, (void *)Jim_ ## name)
9130 void JimRegisterCoreApi(Jim_Interp
*interp
)
9132 interp
->getApiFuncPtr
= Jim_GetApi
;
9133 JIM_REGISTER_API(Alloc
);
9134 JIM_REGISTER_API(Free
);
9135 JIM_REGISTER_API(Eval
);
9136 JIM_REGISTER_API(Eval_Named
);
9137 JIM_REGISTER_API(EvalGlobal
);
9138 JIM_REGISTER_API(EvalFile
);
9139 JIM_REGISTER_API(EvalObj
);
9140 JIM_REGISTER_API(EvalObjBackground
);
9141 JIM_REGISTER_API(EvalObjVector
);
9142 JIM_REGISTER_API(InitHashTable
);
9143 JIM_REGISTER_API(ExpandHashTable
);
9144 JIM_REGISTER_API(AddHashEntry
);
9145 JIM_REGISTER_API(ReplaceHashEntry
);
9146 JIM_REGISTER_API(DeleteHashEntry
);
9147 JIM_REGISTER_API(FreeHashTable
);
9148 JIM_REGISTER_API(FindHashEntry
);
9149 JIM_REGISTER_API(ResizeHashTable
);
9150 JIM_REGISTER_API(GetHashTableIterator
);
9151 JIM_REGISTER_API(NextHashEntry
);
9152 JIM_REGISTER_API(NewObj
);
9153 JIM_REGISTER_API(FreeObj
);
9154 JIM_REGISTER_API(InvalidateStringRep
);
9155 JIM_REGISTER_API(InitStringRep
);
9156 JIM_REGISTER_API(DuplicateObj
);
9157 JIM_REGISTER_API(GetString
);
9158 JIM_REGISTER_API(Length
);
9159 JIM_REGISTER_API(InvalidateStringRep
);
9160 JIM_REGISTER_API(NewStringObj
);
9161 JIM_REGISTER_API(NewStringObjNoAlloc
);
9162 JIM_REGISTER_API(AppendString
);
9163 JIM_REGISTER_API(AppendString_sprintf
);
9164 JIM_REGISTER_API(AppendObj
);
9165 JIM_REGISTER_API(AppendStrings
);
9166 JIM_REGISTER_API(StringEqObj
);
9167 JIM_REGISTER_API(StringMatchObj
);
9168 JIM_REGISTER_API(StringRangeObj
);
9169 JIM_REGISTER_API(FormatString
);
9170 JIM_REGISTER_API(CompareStringImmediate
);
9171 JIM_REGISTER_API(NewReference
);
9172 JIM_REGISTER_API(GetReference
);
9173 JIM_REGISTER_API(SetFinalizer
);
9174 JIM_REGISTER_API(GetFinalizer
);
9175 JIM_REGISTER_API(CreateInterp
);
9176 JIM_REGISTER_API(FreeInterp
);
9177 JIM_REGISTER_API(GetExitCode
);
9178 JIM_REGISTER_API(SetStdin
);
9179 JIM_REGISTER_API(SetStdout
);
9180 JIM_REGISTER_API(SetStderr
);
9181 JIM_REGISTER_API(CreateCommand
);
9182 JIM_REGISTER_API(CreateProcedure
);
9183 JIM_REGISTER_API(DeleteCommand
);
9184 JIM_REGISTER_API(RenameCommand
);
9185 JIM_REGISTER_API(GetCommand
);
9186 JIM_REGISTER_API(SetVariable
);
9187 JIM_REGISTER_API(SetVariableStr
);
9188 JIM_REGISTER_API(SetGlobalVariableStr
);
9189 JIM_REGISTER_API(SetVariableStrWithStr
);
9190 JIM_REGISTER_API(SetVariableLink
);
9191 JIM_REGISTER_API(GetVariable
);
9192 JIM_REGISTER_API(GetCallFrameByLevel
);
9193 JIM_REGISTER_API(Collect
);
9194 JIM_REGISTER_API(CollectIfNeeded
);
9195 JIM_REGISTER_API(GetIndex
);
9196 JIM_REGISTER_API(NewListObj
);
9197 JIM_REGISTER_API(ListAppendElement
);
9198 JIM_REGISTER_API(ListAppendList
);
9199 JIM_REGISTER_API(ListLength
);
9200 JIM_REGISTER_API(ListIndex
);
9201 JIM_REGISTER_API(SetListIndex
);
9202 JIM_REGISTER_API(ConcatObj
);
9203 JIM_REGISTER_API(NewDictObj
);
9204 JIM_REGISTER_API(DictKey
);
9205 JIM_REGISTER_API(DictKeysVector
);
9206 JIM_REGISTER_API(GetIndex
);
9207 JIM_REGISTER_API(GetReturnCode
);
9208 JIM_REGISTER_API(EvalExpression
);
9209 JIM_REGISTER_API(GetBoolFromExpr
);
9210 JIM_REGISTER_API(GetWide
);
9211 JIM_REGISTER_API(GetLong
);
9212 JIM_REGISTER_API(SetWide
);
9213 JIM_REGISTER_API(NewIntObj
);
9214 JIM_REGISTER_API(GetDouble
);
9215 JIM_REGISTER_API(SetDouble
);
9216 JIM_REGISTER_API(NewDoubleObj
);
9217 JIM_REGISTER_API(WrongNumArgs
);
9218 JIM_REGISTER_API(SetDictKeysVector
);
9219 JIM_REGISTER_API(SubstObj
);
9220 JIM_REGISTER_API(RegisterApi
);
9221 JIM_REGISTER_API(PrintErrorMessage
);
9222 JIM_REGISTER_API(InteractivePrompt
);
9223 JIM_REGISTER_API(RegisterCoreCommands
);
9224 JIM_REGISTER_API(GetSharedString
);
9225 JIM_REGISTER_API(ReleaseSharedString
);
9226 JIM_REGISTER_API(Panic
);
9227 JIM_REGISTER_API(StrDup
);
9228 JIM_REGISTER_API(UnsetVariable
);
9229 JIM_REGISTER_API(GetVariableStr
);
9230 JIM_REGISTER_API(GetGlobalVariable
);
9231 JIM_REGISTER_API(GetGlobalVariableStr
);
9232 JIM_REGISTER_API(GetAssocData
);
9233 JIM_REGISTER_API(SetAssocData
);
9234 JIM_REGISTER_API(DeleteAssocData
);
9235 JIM_REGISTER_API(GetEnum
);
9236 JIM_REGISTER_API(ScriptIsComplete
);
9237 JIM_REGISTER_API(PackageRequire
);
9238 JIM_REGISTER_API(PackageProvide
);
9239 JIM_REGISTER_API(InitStack
);
9240 JIM_REGISTER_API(FreeStack
);
9241 JIM_REGISTER_API(StackLen
);
9242 JIM_REGISTER_API(StackPush
);
9243 JIM_REGISTER_API(StackPop
);
9244 JIM_REGISTER_API(StackPeek
);
9245 JIM_REGISTER_API(FreeStackElements
);
9246 JIM_REGISTER_API(fprintf
);
9247 JIM_REGISTER_API(vfprintf
);
9248 JIM_REGISTER_API(fwrite
);
9249 JIM_REGISTER_API(fread
);
9250 JIM_REGISTER_API(fflush
);
9251 JIM_REGISTER_API(fgets
);
9252 JIM_REGISTER_API(GetNvp
);
9253 JIM_REGISTER_API(Nvp_name2value
);
9254 JIM_REGISTER_API(Nvp_name2value_simple
);
9255 JIM_REGISTER_API(Nvp_name2value_obj
);
9256 JIM_REGISTER_API(Nvp_name2value_nocase
);
9257 JIM_REGISTER_API(Nvp_name2value_obj_nocase
);
9259 JIM_REGISTER_API(Nvp_value2name
);
9260 JIM_REGISTER_API(Nvp_value2name_simple
);
9261 JIM_REGISTER_API(Nvp_value2name_obj
);
9263 JIM_REGISTER_API(GetOpt_Setup
);
9264 JIM_REGISTER_API(GetOpt_Debug
);
9265 JIM_REGISTER_API(GetOpt_Obj
);
9266 JIM_REGISTER_API(GetOpt_String
);
9267 JIM_REGISTER_API(GetOpt_Double
);
9268 JIM_REGISTER_API(GetOpt_Wide
);
9269 JIM_REGISTER_API(GetOpt_Nvp
);
9270 JIM_REGISTER_API(GetOpt_NvpUnknown
);
9271 JIM_REGISTER_API(GetOpt_Enum
);
9273 JIM_REGISTER_API(Debug_ArgvString
);
9274 JIM_REGISTER_API(SetResult_sprintf
);
9275 JIM_REGISTER_API(SetResult_NvpUnknown
);
9279 /* -----------------------------------------------------------------------------
9280 * Core commands utility functions
9281 * ---------------------------------------------------------------------------*/
9282 void Jim_WrongNumArgs(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
,
9286 Jim_Obj
*objPtr
= Jim_NewEmptyStringObj(interp
);
9288 Jim_AppendString(interp
, objPtr
, "wrong # args: should be \"", -1);
9289 for (i
= 0; i
< argc
; i
++) {
9290 Jim_AppendObj(interp
, objPtr
, argv
[i
]);
9291 if (!(i
+1 == argc
&& msg
[0] == '\0'))
9292 Jim_AppendString(interp
, objPtr
, " ", 1);
9294 Jim_AppendString(interp
, objPtr
, msg
, -1);
9295 Jim_AppendString(interp
, objPtr
, "\"", 1);
9296 Jim_SetResult(interp
, objPtr
);
9299 static Jim_Obj
*JimCommandsList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
)
9301 Jim_HashTableIterator
*htiter
;
9303 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
9304 const char *pattern
;
9307 pattern
= patternObjPtr
? Jim_GetString(patternObjPtr
, &patternLen
) : NULL
;
9308 htiter
= Jim_GetHashTableIterator(&interp
->commands
);
9309 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
9310 if (pattern
&& !JimStringMatch(pattern
, patternLen
, he
->key
,
9311 strlen((const char*)he
->key
), 0))
9313 Jim_ListAppendElement(interp
, listObjPtr
,
9314 Jim_NewStringObj(interp
, he
->key
, -1));
9316 Jim_FreeHashTableIterator(htiter
);
9320 #define JIM_VARLIST_GLOBALS 0
9321 #define JIM_VARLIST_LOCALS 1
9322 #define JIM_VARLIST_VARS 2
9324 static Jim_Obj
*JimVariablesList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
,
9327 Jim_HashTableIterator
*htiter
;
9329 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
9330 const char *pattern
;
9333 pattern
= patternObjPtr
? Jim_GetString(patternObjPtr
, &patternLen
) : NULL
;
9334 if (mode
== JIM_VARLIST_GLOBALS
) {
9335 htiter
= Jim_GetHashTableIterator(&interp
->topFramePtr
->vars
);
9337 /* For [info locals], if we are at top level an emtpy list
9338 * is returned. I don't agree, but we aim at compatibility (SS) */
9339 if (mode
== JIM_VARLIST_LOCALS
&&
9340 interp
->framePtr
== interp
->topFramePtr
)
9342 htiter
= Jim_GetHashTableIterator(&interp
->framePtr
->vars
);
9344 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
9345 Jim_Var
*varPtr
= (Jim_Var
*) he
->val
;
9346 if (mode
== JIM_VARLIST_LOCALS
) {
9347 if (varPtr
->linkFramePtr
!= NULL
)
9350 if (pattern
&& !JimStringMatch(pattern
, patternLen
, he
->key
,
9351 strlen((const char*)he
->key
), 0))
9353 Jim_ListAppendElement(interp
, listObjPtr
,
9354 Jim_NewStringObj(interp
, he
->key
, -1));
9356 Jim_FreeHashTableIterator(htiter
);
9360 static int JimInfoLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
9361 Jim_Obj
**objPtrPtr
)
9363 Jim_CallFrame
*targetCallFrame
;
9365 if (JimGetCallFrameByInteger(interp
, levelObjPtr
, &targetCallFrame
)
9368 /* No proc call at toplevel callframe */
9369 if (targetCallFrame
== interp
->topFramePtr
) {
9370 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
9371 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
9373 Jim_GetString(levelObjPtr
, NULL
), "\"", NULL
);
9376 *objPtrPtr
= Jim_NewListObj(interp
,
9377 targetCallFrame
->argv
,
9378 targetCallFrame
->argc
);
9382 /* -----------------------------------------------------------------------------
9384 * ---------------------------------------------------------------------------*/
9386 /* fake [puts] -- not the real puts, just for debugging. */
9387 static int Jim_PutsCoreCommand(Jim_Interp
*interp
, int argc
,
9388 Jim_Obj
*const *argv
)
9391 int len
, nonewline
= 0;
9393 if (argc
!= 2 && argc
!= 3) {
9394 Jim_WrongNumArgs(interp
, 1, argv
, "-nonewline string");
9398 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-nonewline"))
9400 Jim_SetResultString(interp
, "The second argument must "
9401 "be -nonewline", -1);
9408 str
= Jim_GetString(argv
[1], &len
);
9409 Jim_fwrite(interp
, str
, 1, len
, interp
->cookie_stdout
);
9410 if (!nonewline
) Jim_fprintf( interp
, interp
->cookie_stdout
, JIM_NL
);
9414 /* Helper for [+] and [*] */
9415 static int Jim_AddMulHelper(Jim_Interp
*interp
, int argc
,
9416 Jim_Obj
*const *argv
, int op
)
9418 jim_wide wideValue
, res
;
9419 double doubleValue
, doubleRes
;
9422 res
= (op
== JIM_EXPROP_ADD
) ? 0 : 1;
9424 for (i
= 1; i
< argc
; i
++) {
9425 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
)
9427 if (op
== JIM_EXPROP_ADD
)
9432 Jim_SetResult(interp
, Jim_NewIntObj(interp
, res
));
9435 doubleRes
= (double) res
;
9436 for (;i
< argc
; i
++) {
9437 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
9439 if (op
== JIM_EXPROP_ADD
)
9440 doubleRes
+= doubleValue
;
9442 doubleRes
*= doubleValue
;
9444 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
9448 /* Helper for [-] and [/] */
9449 static int Jim_SubDivHelper(Jim_Interp
*interp
, int argc
,
9450 Jim_Obj
*const *argv
, int op
)
9452 jim_wide wideValue
, res
= 0;
9453 double doubleValue
, doubleRes
= 0;
9457 Jim_WrongNumArgs(interp
, 1, argv
, "number ?number ... number?");
9459 } else if (argc
== 2) {
9460 /* The arity = 2 case is different. For [- x] returns -x,
9461 * while [/ x] returns 1/x. */
9462 if (Jim_GetWide(interp
, argv
[1], &wideValue
) != JIM_OK
) {
9463 if (Jim_GetDouble(interp
, argv
[1], &doubleValue
) !=
9468 if (op
== JIM_EXPROP_SUB
)
9469 doubleRes
= -doubleValue
;
9471 doubleRes
= 1.0/doubleValue
;
9472 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
,
9477 if (op
== JIM_EXPROP_SUB
) {
9479 Jim_SetResult(interp
, Jim_NewIntObj(interp
, res
));
9481 doubleRes
= 1.0/wideValue
;
9482 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
,
9487 if (Jim_GetWide(interp
, argv
[1], &res
) != JIM_OK
) {
9488 if (Jim_GetDouble(interp
, argv
[1], &doubleRes
)
9496 for (i
= 2; i
< argc
; i
++) {
9497 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
) {
9498 doubleRes
= (double) res
;
9501 if (op
== JIM_EXPROP_SUB
)
9506 Jim_SetResult(interp
, Jim_NewIntObj(interp
, res
));
9509 for (;i
< argc
; i
++) {
9510 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
9512 if (op
== JIM_EXPROP_SUB
)
9513 doubleRes
-= doubleValue
;
9515 doubleRes
/= doubleValue
;
9517 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
9523 static int Jim_AddCoreCommand(Jim_Interp
*interp
, int argc
,
9524 Jim_Obj
*const *argv
)
9526 return Jim_AddMulHelper(interp
, argc
, argv
, JIM_EXPROP_ADD
);
9530 static int Jim_MulCoreCommand(Jim_Interp
*interp
, int argc
,
9531 Jim_Obj
*const *argv
)
9533 return Jim_AddMulHelper(interp
, argc
, argv
, JIM_EXPROP_MUL
);
9537 static int Jim_SubCoreCommand(Jim_Interp
*interp
, int argc
,
9538 Jim_Obj
*const *argv
)
9540 return Jim_SubDivHelper(interp
, argc
, argv
, JIM_EXPROP_SUB
);
9544 static int Jim_DivCoreCommand(Jim_Interp
*interp
, int argc
,
9545 Jim_Obj
*const *argv
)
9547 return Jim_SubDivHelper(interp
, argc
, argv
, JIM_EXPROP_DIV
);
9551 static int Jim_SetCoreCommand(Jim_Interp
*interp
, int argc
,
9552 Jim_Obj
*const *argv
)
9554 if (argc
!= 2 && argc
!= 3) {
9555 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?newValue?");
9560 objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
9563 Jim_SetResult(interp
, objPtr
);
9566 /* argc == 3 case. */
9567 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
9569 Jim_SetResult(interp
, argv
[2]);
9574 static int Jim_UnsetCoreCommand(Jim_Interp
*interp
, int argc
,
9575 Jim_Obj
*const *argv
)
9580 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
9583 for (i
= 1; i
< argc
; i
++) {
9584 if (Jim_UnsetVariable(interp
, argv
[i
], JIM_ERRMSG
) != JIM_OK
)
9591 static int Jim_IncrCoreCommand(Jim_Interp
*interp
, int argc
,
9592 Jim_Obj
*const *argv
)
9594 jim_wide wideValue
, increment
= 1;
9597 if (argc
!= 2 && argc
!= 3) {
9598 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?increment?");
9602 if (Jim_GetWide(interp
, argv
[2], &increment
) != JIM_OK
)
9605 intObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
9606 if (!intObjPtr
) return JIM_ERR
;
9607 if (Jim_GetWide(interp
, intObjPtr
, &wideValue
) != JIM_OK
)
9609 if (Jim_IsShared(intObjPtr
)) {
9610 intObjPtr
= Jim_NewIntObj(interp
, wideValue
+increment
);
9611 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
9612 Jim_FreeNewObj(interp
, intObjPtr
);
9616 Jim_SetWide(interp
, intObjPtr
, wideValue
+increment
);
9617 /* The following step is required in order to invalidate the
9618 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9619 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
9623 Jim_SetResult(interp
, intObjPtr
);
9628 static int Jim_WhileCoreCommand(Jim_Interp
*interp
, int argc
,
9629 Jim_Obj
*const *argv
)
9632 Jim_WrongNumArgs(interp
, 1, argv
, "condition body");
9635 /* Try to run a specialized version of while if the expression
9636 * is in one of the following forms:
9638 * $a < CONST, $a < $b
9639 * $a <= CONST, $a <= $b
9640 * $a > CONST, $a > $b
9641 * $a >= CONST, $a >= $b
9642 * $a != CONST, $a != $b
9643 * $a == CONST, $a == $b
9649 #ifdef JIM_OPTIMIZATION
9652 Jim_Obj
*varAObjPtr
= NULL
, *varBObjPtr
= NULL
, *objPtr
;
9653 int exprLen
, retval
;
9655 /* STEP 1 -- Check if there are the conditions to run the specialized
9656 * version of while */
9658 if ((expr
= Jim_GetExpression(interp
, argv
[1])) == NULL
) goto noopt
;
9659 if (expr
->len
<= 0 || expr
->len
> 3) goto noopt
;
9662 if (expr
->opcode
[0] != JIM_EXPROP_VARIABLE
&&
9663 expr
->opcode
[0] != JIM_EXPROP_NUMBER
)
9667 if (expr
->opcode
[1] != JIM_EXPROP_NOT
||
9668 expr
->opcode
[0] != JIM_EXPROP_VARIABLE
)
9672 if (expr
->opcode
[0] != JIM_EXPROP_VARIABLE
||
9673 (expr
->opcode
[1] != JIM_EXPROP_NUMBER
&&
9674 expr
->opcode
[1] != JIM_EXPROP_VARIABLE
))
9676 switch(expr
->opcode
[2]) {
9678 case JIM_EXPROP_LTE
:
9680 case JIM_EXPROP_GTE
:
9681 case JIM_EXPROP_NUMEQ
:
9682 case JIM_EXPROP_NUMNE
:
9691 "Unexpected default reached in Jim_WhileCoreCommand()");
9695 /* STEP 2 -- conditions meet. Initialization. Take different
9696 * branches for different expression lengths. */
9697 exprLen
= expr
->len
;
9702 if (expr
->opcode
[0] == JIM_EXPROP_VARIABLE
) {
9703 varAObjPtr
= expr
->obj
[0];
9704 Jim_IncrRefCount(varAObjPtr
);
9706 if (Jim_GetWide(interp
, expr
->obj
[0], &wideValue
) != JIM_OK
)
9712 Jim_GetVariable(interp
, varAObjPtr
, JIM_NONE
)) ||
9713 Jim_GetWide(interp
, objPtr
, &wideValue
) != JIM_OK
)
9715 Jim_DecrRefCount(interp
, varAObjPtr
);
9719 if (!wideValue
) break;
9720 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
9724 Jim_DecrRefCount(interp
, varAObjPtr
);
9732 Jim_DecrRefCount(interp
, varAObjPtr
);
9738 Jim_DecrRefCount(interp
, varAObjPtr
);
9739 } else if (exprLen
== 3) {
9740 jim_wide wideValueA
, wideValueB
, cmpRes
= 0;
9741 int cmpType
= expr
->opcode
[2];
9743 varAObjPtr
= expr
->obj
[0];
9744 Jim_IncrRefCount(varAObjPtr
);
9745 if (expr
->opcode
[1] == JIM_EXPROP_VARIABLE
) {
9746 varBObjPtr
= expr
->obj
[1];
9747 Jim_IncrRefCount(varBObjPtr
);
9749 if (Jim_GetWide(interp
, expr
->obj
[1], &wideValueB
) != JIM_OK
)
9753 if (!(objPtr
= Jim_GetVariable(interp
, varAObjPtr
, JIM_NONE
)) ||
9754 Jim_GetWide(interp
, objPtr
, &wideValueA
) != JIM_OK
)
9756 Jim_DecrRefCount(interp
, varAObjPtr
);
9758 Jim_DecrRefCount(interp
, varBObjPtr
);
9763 Jim_GetVariable(interp
, varBObjPtr
, JIM_NONE
)) ||
9764 Jim_GetWide(interp
, objPtr
, &wideValueB
) != JIM_OK
)
9766 Jim_DecrRefCount(interp
, varAObjPtr
);
9768 Jim_DecrRefCount(interp
, varBObjPtr
);
9774 cmpRes
= wideValueA
< wideValueB
; break;
9775 case JIM_EXPROP_LTE
:
9776 cmpRes
= wideValueA
<= wideValueB
; break;
9778 cmpRes
= wideValueA
> wideValueB
; break;
9779 case JIM_EXPROP_GTE
:
9780 cmpRes
= wideValueA
>= wideValueB
; break;
9781 case JIM_EXPROP_NUMEQ
:
9782 cmpRes
= wideValueA
== wideValueB
; break;
9783 case JIM_EXPROP_NUMNE
:
9784 cmpRes
= wideValueA
!= wideValueB
; break;
9787 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
9790 Jim_DecrRefCount(interp
, varAObjPtr
);
9792 Jim_DecrRefCount(interp
, varBObjPtr
);
9799 Jim_DecrRefCount(interp
, varAObjPtr
);
9801 Jim_DecrRefCount(interp
, varBObjPtr
);
9806 Jim_DecrRefCount(interp
, varAObjPtr
);
9808 Jim_DecrRefCount(interp
, varBObjPtr
);
9810 /* TODO: case for len == 2 */
9813 Jim_SetEmptyResult(interp
);
9819 /* The general purpose implementation of while starts here */
9821 int boolean
, retval
;
9823 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[1],
9824 &boolean
)) != JIM_OK
)
9826 if (!boolean
) break;
9827 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
9841 Jim_SetEmptyResult(interp
);
9846 static int Jim_ForCoreCommand(Jim_Interp
*interp
, int argc
,
9847 Jim_Obj
*const *argv
)
9852 Jim_WrongNumArgs(interp
, 1, argv
, "start test next body");
9855 /* Check if the for is on the form:
9856 * for {set i CONST} {$i < CONST} {incr i}
9857 * for {set i CONST} {$i < $j} {incr i}
9858 * for {set i CONST} {$i <= CONST} {incr i}
9859 * for {set i CONST} {$i <= $j} {incr i}
9860 * XXX: NOTE: if variable traces are implemented, this optimization
9861 * need to be modified to check for the proc epoch at every variable
9863 #ifdef JIM_OPTIMIZATION
9865 ScriptObj
*initScript
, *incrScript
;
9867 jim_wide start
, stop
, currentVal
;
9868 unsigned jim_wide procEpoch
= interp
->procEpoch
;
9869 Jim_Obj
*varNamePtr
, *stopVarNamePtr
= NULL
, *objPtr
;
9871 struct Jim_Cmd
*cmdPtr
;
9873 /* Do it only if there aren't shared arguments */
9874 if (argv
[1] == argv
[2] || argv
[2] == argv
[3] || argv
[1] == argv
[3])
9876 initScript
= Jim_GetScript(interp
, argv
[1]);
9877 expr
= Jim_GetExpression(interp
, argv
[2]);
9878 incrScript
= Jim_GetScript(interp
, argv
[3]);
9880 /* Ensure proper lengths to start */
9881 if (initScript
->len
!= 6) goto evalstart
;
9882 if (incrScript
->len
!= 4) goto evalstart
;
9883 if (expr
->len
!= 3) goto evalstart
;
9884 /* Ensure proper token types. */
9885 if (initScript
->token
[2].type
!= JIM_TT_ESC
||
9886 initScript
->token
[4].type
!= JIM_TT_ESC
||
9887 incrScript
->token
[2].type
!= JIM_TT_ESC
||
9888 expr
->opcode
[0] != JIM_EXPROP_VARIABLE
||
9889 (expr
->opcode
[1] != JIM_EXPROP_NUMBER
&&
9890 expr
->opcode
[1] != JIM_EXPROP_VARIABLE
) ||
9891 (expr
->opcode
[2] != JIM_EXPROP_LT
&&
9892 expr
->opcode
[2] != JIM_EXPROP_LTE
))
9894 cmpType
= expr
->opcode
[2];
9895 /* Initialization command must be [set] */
9896 cmdPtr
= Jim_GetCommand(interp
, initScript
->token
[0].objPtr
, JIM_NONE
);
9897 if (cmdPtr
== NULL
|| cmdPtr
->cmdProc
!= Jim_SetCoreCommand
)
9899 /* Update command must be incr */
9900 cmdPtr
= Jim_GetCommand(interp
, incrScript
->token
[0].objPtr
, JIM_NONE
);
9901 if (cmdPtr
== NULL
|| cmdPtr
->cmdProc
!= Jim_IncrCoreCommand
)
9903 /* set, incr, expression must be about the same variable */
9904 if (!Jim_StringEqObj(initScript
->token
[2].objPtr
,
9905 incrScript
->token
[2].objPtr
, 0))
9907 if (!Jim_StringEqObj(initScript
->token
[2].objPtr
,
9910 /* Check that the initialization and comparison are valid integers */
9911 if (Jim_GetWide(interp
, initScript
->token
[4].objPtr
, &start
) == JIM_ERR
)
9913 if (expr
->opcode
[1] == JIM_EXPROP_NUMBER
&&
9914 Jim_GetWide(interp
, expr
->obj
[1], &stop
) == JIM_ERR
)
9919 /* Initialization */
9920 varNamePtr
= expr
->obj
[0];
9921 if (expr
->opcode
[1] == JIM_EXPROP_VARIABLE
) {
9922 stopVarNamePtr
= expr
->obj
[1];
9923 Jim_IncrRefCount(stopVarNamePtr
);
9925 Jim_IncrRefCount(varNamePtr
);
9927 /* --- OPTIMIZED FOR --- */
9929 objPtr
= Jim_NewIntObj(interp
, start
);
9930 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
9931 Jim_DecrRefCount(interp
, varNamePtr
);
9932 if (stopVarNamePtr
) Jim_DecrRefCount(interp
, stopVarNamePtr
);
9933 Jim_FreeNewObj(interp
, objPtr
);
9937 /* === Check condition === */
9939 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_NONE
);
9940 if (objPtr
== NULL
||
9941 Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
)
9943 Jim_DecrRefCount(interp
, varNamePtr
);
9944 if (stopVarNamePtr
) Jim_DecrRefCount(interp
, stopVarNamePtr
);
9947 /* Immediate or Variable? get the 'stop' value if the latter. */
9948 if (stopVarNamePtr
) {
9949 objPtr
= Jim_GetVariable(interp
, stopVarNamePtr
, JIM_NONE
);
9950 if (objPtr
== NULL
||
9951 Jim_GetWide(interp
, objPtr
, &stop
) != JIM_OK
)
9953 Jim_DecrRefCount(interp
, varNamePtr
);
9954 Jim_DecrRefCount(interp
, stopVarNamePtr
);
9958 if (cmpType
== JIM_EXPROP_LT
) {
9959 if (currentVal
>= stop
) break;
9961 if (currentVal
> stop
) break;
9964 if ((retval
= Jim_EvalObj(interp
, argv
[4])) != JIM_OK
) {
9968 Jim_DecrRefCount(interp
, stopVarNamePtr
);
9969 Jim_DecrRefCount(interp
, varNamePtr
);
9976 Jim_DecrRefCount(interp
, stopVarNamePtr
);
9977 Jim_DecrRefCount(interp
, varNamePtr
);
9981 /* If there was a change in procedures/command continue
9982 * with the usual [for] command implementation */
9983 if (procEpoch
!= interp
->procEpoch
) {
9985 Jim_DecrRefCount(interp
, stopVarNamePtr
);
9986 Jim_DecrRefCount(interp
, varNamePtr
);
9990 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
9991 if (objPtr
->refCount
== 1 && objPtr
->typePtr
== &intObjType
) {
9992 objPtr
->internalRep
.wideValue
++;
9993 Jim_InvalidateStringRep(objPtr
);
9997 if (Jim_GetWide(interp
, objPtr
, ¤tVal
) == JIM_ERR
) {
9999 Jim_DecrRefCount(interp
, stopVarNamePtr
);
10000 Jim_DecrRefCount(interp
, varNamePtr
);
10003 auxObjPtr
= Jim_NewIntObj(interp
, currentVal
+1);
10004 if (Jim_SetVariable(interp
, varNamePtr
, auxObjPtr
) == JIM_ERR
) {
10005 if (stopVarNamePtr
)
10006 Jim_DecrRefCount(interp
, stopVarNamePtr
);
10007 Jim_DecrRefCount(interp
, varNamePtr
);
10008 Jim_FreeNewObj(interp
, auxObjPtr
);
10013 if (stopVarNamePtr
)
10014 Jim_DecrRefCount(interp
, stopVarNamePtr
);
10015 Jim_DecrRefCount(interp
, varNamePtr
);
10016 Jim_SetEmptyResult(interp
);
10022 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
)
10027 /* Test the condition */
10028 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
))
10031 if (!boolean
) break;
10033 if ((retval
= Jim_EvalObj(interp
, argv
[4])) != JIM_OK
) {
10039 /* Nothing to do */
10047 if ((retval
= Jim_EvalObj(interp
, argv
[3])) != JIM_OK
) {
10061 Jim_SetEmptyResult(interp
);
10065 /* foreach + lmap implementation. */
10066 static int JimForeachMapHelper(Jim_Interp
*interp
, int argc
,
10067 Jim_Obj
*const *argv
, int doMap
)
10069 int result
= JIM_ERR
, i
, nbrOfLists
, *listsIdx
, *listsEnd
;
10070 int nbrOfLoops
= 0;
10071 Jim_Obj
*emptyStr
, *script
, *mapRes
= NULL
;
10073 if (argc
< 4 || argc
% 2 != 0) {
10074 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varList list ...? script");
10078 mapRes
= Jim_NewListObj(interp
, NULL
, 0);
10079 Jim_IncrRefCount(mapRes
);
10081 emptyStr
= Jim_NewEmptyStringObj(interp
);
10082 Jim_IncrRefCount(emptyStr
);
10083 script
= argv
[argc
-1]; /* Last argument is a script */
10084 nbrOfLists
= (argc
- 1 - 1) / 2; /* argc - 'foreach' - script */
10085 listsIdx
= (int*)Jim_Alloc(nbrOfLists
* sizeof(int));
10086 listsEnd
= (int*)Jim_Alloc(nbrOfLists
*2 * sizeof(int));
10087 /* Initialize iterators and remember max nbr elements each list */
10088 memset(listsIdx
, 0, nbrOfLists
* sizeof(int));
10089 /* Remember lengths of all lists and calculate how much rounds to loop */
10090 for (i
=0; i
< nbrOfLists
*2; i
+= 2) {
10093 Jim_ListLength(interp
, argv
[i
+1], &listsEnd
[i
]);
10094 Jim_ListLength(interp
, argv
[i
+2], &listsEnd
[i
+1]);
10095 if (listsEnd
[i
] == 0) {
10096 Jim_SetResultString(interp
, "foreach varlist is empty", -1);
10099 cnt
= div(listsEnd
[i
+1], listsEnd
[i
]);
10100 count
= cnt
.quot
+ (cnt
.rem
? 1 : 0);
10101 if (count
> nbrOfLoops
)
10102 nbrOfLoops
= count
;
10104 for (; nbrOfLoops
-- > 0; ) {
10105 for (i
=0; i
< nbrOfLists
; ++i
) {
10106 int varIdx
= 0, var
= i
* 2;
10107 while (varIdx
< listsEnd
[var
]) {
10108 Jim_Obj
*varName
, *ele
;
10109 int lst
= i
* 2 + 1;
10110 if (Jim_ListIndex(interp
, argv
[var
+1], varIdx
, &varName
, JIM_ERRMSG
)
10113 if (listsIdx
[i
] < listsEnd
[lst
]) {
10114 if (Jim_ListIndex(interp
, argv
[lst
+1], listsIdx
[i
], &ele
, JIM_ERRMSG
)
10117 if (Jim_SetVariable(interp
, varName
, ele
) != JIM_OK
) {
10118 Jim_SetResultString(interp
, "couldn't set loop variable: ", -1);
10121 ++listsIdx
[i
]; /* Remember next iterator of current list */
10122 } else if (Jim_SetVariable(interp
, varName
, emptyStr
) != JIM_OK
) {
10123 Jim_SetResultString(interp
, "couldn't set loop variable: ", -1);
10126 ++varIdx
; /* Next variable */
10129 switch (result
= Jim_EvalObj(interp
, script
)) {
10132 Jim_ListAppendElement(interp
, mapRes
, interp
->result
);
10146 Jim_SetResult(interp
, mapRes
);
10148 Jim_SetEmptyResult(interp
);
10151 Jim_DecrRefCount(interp
, mapRes
);
10152 Jim_DecrRefCount(interp
, emptyStr
);
10153 Jim_Free(listsIdx
);
10154 Jim_Free(listsEnd
);
10159 static int Jim_ForeachCoreCommand(Jim_Interp
*interp
, int argc
,
10160 Jim_Obj
*const *argv
)
10162 return JimForeachMapHelper(interp
, argc
, argv
, 0);
10166 static int Jim_LmapCoreCommand(Jim_Interp
*interp
, int argc
,
10167 Jim_Obj
*const *argv
)
10169 return JimForeachMapHelper(interp
, argc
, argv
, 1);
10173 static int Jim_IfCoreCommand(Jim_Interp
*interp
, int argc
,
10174 Jim_Obj
*const *argv
)
10176 int boolean
, retval
, current
= 1, falsebody
= 0;
10179 /* Far not enough arguments given! */
10180 if (current
>= argc
) goto err
;
10181 if ((retval
= Jim_GetBoolFromExpr(interp
,
10182 argv
[current
++], &boolean
))
10185 /* There lacks something, isn't it? */
10186 if (current
>= argc
) goto err
;
10187 if (Jim_CompareStringImmediate(interp
, argv
[current
],
10188 "then")) current
++;
10189 /* Tsk tsk, no then-clause? */
10190 if (current
>= argc
) goto err
;
10192 return Jim_EvalObj(interp
, argv
[current
]);
10193 /* Ok: no else-clause follows */
10194 if (++current
>= argc
) {
10195 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
10198 falsebody
= current
++;
10199 if (Jim_CompareStringImmediate(interp
, argv
[falsebody
],
10201 /* IIICKS - else-clause isn't last cmd? */
10202 if (current
!= argc
-1) goto err
;
10203 return Jim_EvalObj(interp
, argv
[current
]);
10204 } else if (Jim_CompareStringImmediate(interp
,
10205 argv
[falsebody
], "elseif"))
10206 /* Ok: elseif follows meaning all the stuff
10207 * again (how boring...) */
10209 /* OOPS - else-clause is not last cmd?*/
10210 else if (falsebody
!= argc
-1)
10212 return Jim_EvalObj(interp
, argv
[falsebody
]);
10217 Jim_WrongNumArgs(interp
, 1, argv
, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
10221 enum {SWITCH_EXACT
, SWITCH_GLOB
, SWITCH_RE
, SWITCH_CMD
, SWITCH_UNKNOWN
};
10224 static int Jim_SwitchCoreCommand(Jim_Interp
*interp
, int argc
,
10225 Jim_Obj
*const *argv
)
10227 int retcode
= JIM_ERR
, matchOpt
= SWITCH_EXACT
, opt
=1, patCount
, i
;
10228 Jim_Obj
*command
= 0, *const *caseList
= 0, *strObj
;
10229 Jim_Obj
*script
= 0;
10230 if (argc
< 3) goto wrongnumargs
;
10231 for (opt
=1; opt
< argc
; ++opt
) {
10232 const char *option
= Jim_GetString(argv
[opt
], 0);
10233 if (*option
!= '-') break;
10234 else if (strncmp(option
, "--", 2) == 0) { ++opt
; break; }
10235 else if (strncmp(option
, "-exact", 2) == 0) matchOpt
= SWITCH_EXACT
;
10236 else if (strncmp(option
, "-glob", 2) == 0) matchOpt
= SWITCH_GLOB
;
10237 else if (strncmp(option
, "-regexp", 2) == 0) matchOpt
= SWITCH_RE
;
10238 else if (strncmp(option
, "-command", 2) == 0) { matchOpt
= SWITCH_CMD
;
10239 if ((argc
- opt
) < 2) goto wrongnumargs
;
10240 command
= argv
[++opt
];
10242 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
10243 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
10244 "bad option \"", option
, "\": must be -exact, -glob, "
10245 "-regexp, -command procname or --", 0);
10248 if ((argc
- opt
) < 2) goto wrongnumargs
;
10250 strObj
= argv
[opt
++];
10251 patCount
= argc
- opt
;
10252 if (patCount
== 1) {
10254 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
10257 caseList
= &argv
[opt
];
10258 if (patCount
== 0 || patCount
% 2 != 0) goto wrongnumargs
;
10259 for (i
=0; script
== 0 && i
< patCount
; i
+= 2) {
10260 Jim_Obj
*patObj
= caseList
[i
];
10261 if (!Jim_CompareStringImmediate(interp
, patObj
, "default")
10262 || i
< (patCount
-2)) {
10263 switch (matchOpt
) {
10265 if (Jim_StringEqObj(strObj
, patObj
, 0))
10266 script
= caseList
[i
+1];
10269 if (Jim_StringMatchObj(patObj
, strObj
, 0))
10270 script
= caseList
[i
+1];
10273 command
= Jim_NewStringObj(interp
, "regexp", -1);
10274 /* Fall thru intentionally */
10276 Jim_Obj
*parms
[] = {command
, patObj
, strObj
};
10277 int rc
= Jim_EvalObjVector(interp
, 3, parms
);
10279 /* After the execution of a command we need to
10280 * make sure to reconvert the object into a list
10281 * again. Only for the single-list style [switch]. */
10282 if (argc
-opt
== 1) {
10284 JimListGetElements(interp
, argv
[opt
], &patCount
,
10288 /* command is here already decref'd */
10289 if (rc
!= JIM_OK
) {
10293 rc
= Jim_GetLong(interp
, Jim_GetResult(interp
), &matching
);
10294 if (rc
!= JIM_OK
) {
10299 script
= caseList
[i
+1];
10303 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
10304 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
10305 "internal error: no such option implemented", 0);
10309 script
= caseList
[i
+1];
10312 for(; i
< patCount
&& Jim_CompareStringImmediate(interp
, script
, "-");
10314 script
= caseList
[i
+1];
10315 if (script
&& Jim_CompareStringImmediate(interp
, script
, "-")) {
10316 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
10317 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
10318 "no body specified for pattern \"",
10319 Jim_GetString(caseList
[i
-2], 0), "\"", 0);
10323 Jim_SetEmptyResult(interp
);
10325 retcode
= Jim_EvalObj(interp
, script
);
10328 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string "
10329 "pattern body ... ?default body? or "
10330 "{pattern body ?pattern body ...?}");
10336 static int Jim_ListCoreCommand(Jim_Interp
*interp
, int argc
,
10337 Jim_Obj
*const *argv
)
10339 Jim_Obj
*listObjPtr
;
10341 listObjPtr
= Jim_NewListObj(interp
, argv
+1, argc
-1);
10342 Jim_SetResult(interp
, listObjPtr
);
10347 static int Jim_LindexCoreCommand(Jim_Interp
*interp
, int argc
,
10348 Jim_Obj
*const *argv
)
10350 Jim_Obj
*objPtr
, *listObjPtr
;
10355 Jim_WrongNumArgs(interp
, 1, argv
, "list index ?...?");
10359 Jim_IncrRefCount(objPtr
);
10360 for (i
= 2; i
< argc
; i
++) {
10361 listObjPtr
= objPtr
;
10362 if (Jim_GetIndex(interp
, argv
[i
], &index
) != JIM_OK
) {
10363 Jim_DecrRefCount(interp
, listObjPtr
);
10366 if (Jim_ListIndex(interp
, listObjPtr
, index
, &objPtr
,
10367 JIM_NONE
) != JIM_OK
) {
10368 /* Returns an empty object if the index
10369 * is out of range. */
10370 Jim_DecrRefCount(interp
, listObjPtr
);
10371 Jim_SetEmptyResult(interp
);
10374 Jim_IncrRefCount(objPtr
);
10375 Jim_DecrRefCount(interp
, listObjPtr
);
10377 Jim_SetResult(interp
, objPtr
);
10378 Jim_DecrRefCount(interp
, objPtr
);
10383 static int Jim_LlengthCoreCommand(Jim_Interp
*interp
, int argc
,
10384 Jim_Obj
*const *argv
)
10389 Jim_WrongNumArgs(interp
, 1, argv
, "list");
10392 Jim_ListLength(interp
, argv
[1], &len
);
10393 Jim_SetResult(interp
, Jim_NewIntObj(interp
, len
));
10398 static int Jim_LappendCoreCommand(Jim_Interp
*interp
, int argc
,
10399 Jim_Obj
*const *argv
)
10401 Jim_Obj
*listObjPtr
;
10405 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
10408 listObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_NONE
);
10410 /* Create the list if it does not exists */
10411 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10412 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
10413 Jim_FreeNewObj(interp
, listObjPtr
);
10417 shared
= Jim_IsShared(listObjPtr
);
10419 listObjPtr
= Jim_DuplicateObj(interp
, listObjPtr
);
10420 for (i
= 2; i
< argc
; i
++)
10421 Jim_ListAppendElement(interp
, listObjPtr
, argv
[i
]);
10422 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
10424 Jim_FreeNewObj(interp
, listObjPtr
);
10427 Jim_SetResult(interp
, listObjPtr
);
10432 static int Jim_LinsertCoreCommand(Jim_Interp
*interp
, int argc
,
10433 Jim_Obj
*const *argv
)
10439 Jim_WrongNumArgs(interp
, 1, argv
, "list index element "
10444 if (Jim_IsShared(listPtr
))
10445 listPtr
= Jim_DuplicateObj(interp
, listPtr
);
10446 if (Jim_GetIndex(interp
, argv
[2], &index
) != JIM_OK
)
10448 Jim_ListLength(interp
, listPtr
, &len
);
10451 else if (index
< 0)
10452 index
= len
+ index
+ 1;
10453 Jim_ListInsertElements(interp
, listPtr
, index
, argc
-3, &argv
[3]);
10454 Jim_SetResult(interp
, listPtr
);
10457 if (listPtr
!= argv
[1]) {
10458 Jim_FreeNewObj(interp
, listPtr
);
10464 static int Jim_LsetCoreCommand(Jim_Interp
*interp
, int argc
,
10465 Jim_Obj
*const *argv
)
10468 Jim_WrongNumArgs(interp
, 1, argv
, "listVar ?index...? newVal");
10470 } else if (argc
== 3) {
10471 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
10473 Jim_SetResult(interp
, argv
[2]);
10476 if (Jim_SetListIndex(interp
, argv
[1], argv
+2, argc
-3, argv
[argc
-1])
10477 == JIM_ERR
) return JIM_ERR
;
10482 static int Jim_LsortCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const argv
[])
10484 const char *options
[] = {
10485 "-ascii", "-nocase", "-increasing", "-decreasing", NULL
10487 enum {OPT_ASCII
, OPT_NOCASE
, OPT_INCREASING
, OPT_DECREASING
};
10489 int i
, lsortType
= JIM_LSORT_ASCII
; /* default sort type */
10490 int decreasing
= 0;
10493 Jim_WrongNumArgs(interp
, 1, argv
, "?options? list");
10496 for (i
= 1; i
< (argc
-1); i
++) {
10499 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, "option", JIM_ERRMSG
)
10503 case OPT_ASCII
: lsortType
= JIM_LSORT_ASCII
; break;
10504 case OPT_NOCASE
: lsortType
= JIM_LSORT_NOCASE
; break;
10505 case OPT_INCREASING
: decreasing
= 0; break;
10506 case OPT_DECREASING
: decreasing
= 1; break;
10510 switch(lsortType
) {
10511 case JIM_LSORT_ASCII
: lsortType
= JIM_LSORT_ASCII_DECR
; break;
10512 case JIM_LSORT_NOCASE
: lsortType
= JIM_LSORT_NOCASE_DECR
; break;
10515 resObj
= Jim_DuplicateObj(interp
, argv
[argc
-1]);
10516 ListSortElements(interp
, resObj
, lsortType
);
10517 Jim_SetResult(interp
, resObj
);
10522 static int Jim_AppendCoreCommand(Jim_Interp
*interp
, int argc
,
10523 Jim_Obj
*const *argv
)
10525 Jim_Obj
*stringObjPtr
;
10529 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
10533 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
10534 if (!stringObjPtr
) return JIM_ERR
;
10536 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_NONE
);
10537 if (!stringObjPtr
) {
10538 /* Create the string if it does not exists */
10539 stringObjPtr
= Jim_NewEmptyStringObj(interp
);
10540 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
)
10542 Jim_FreeNewObj(interp
, stringObjPtr
);
10547 shared
= Jim_IsShared(stringObjPtr
);
10549 stringObjPtr
= Jim_DuplicateObj(interp
, stringObjPtr
);
10550 for (i
= 2; i
< argc
; i
++)
10551 Jim_AppendObj(interp
, stringObjPtr
, argv
[i
]);
10552 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
) != JIM_OK
) {
10554 Jim_FreeNewObj(interp
, stringObjPtr
);
10557 Jim_SetResult(interp
, stringObjPtr
);
10562 static int Jim_DebugCoreCommand(Jim_Interp
*interp
, int argc
,
10563 Jim_Obj
*const *argv
)
10565 const char *options
[] = {
10566 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
10571 OPT_REFCOUNT
, OPT_OBJCOUNT
, OPT_OBJECTS
, OPT_INVSTR
, OPT_SCRIPTLEN
,
10572 OPT_EXPRLEN
, OPT_EXPRBC
10577 Jim_WrongNumArgs(interp
, 1, argv
, "option ?...?");
10580 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "option",
10581 JIM_ERRMSG
) != JIM_OK
)
10583 if (option
== OPT_REFCOUNT
) {
10585 Jim_WrongNumArgs(interp
, 2, argv
, "object");
10588 Jim_SetResult(interp
, Jim_NewIntObj(interp
, argv
[2]->refCount
));
10590 } else if (option
== OPT_OBJCOUNT
) {
10591 int freeobj
= 0, liveobj
= 0;
10596 Jim_WrongNumArgs(interp
, 2, argv
, "");
10599 /* Count the number of free objects. */
10600 objPtr
= interp
->freeList
;
10603 objPtr
= objPtr
->nextObjPtr
;
10605 /* Count the number of live objects. */
10606 objPtr
= interp
->liveList
;
10609 objPtr
= objPtr
->nextObjPtr
;
10611 /* Set the result string and return. */
10612 sprintf(buf
, "free %d used %d", freeobj
, liveobj
);
10613 Jim_SetResultString(interp
, buf
, -1);
10615 } else if (option
== OPT_OBJECTS
) {
10616 Jim_Obj
*objPtr
, *listObjPtr
, *subListObjPtr
;
10617 /* Count the number of live objects. */
10618 objPtr
= interp
->liveList
;
10619 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10622 const char *type
= objPtr
->typePtr
?
10623 objPtr
->typePtr
->name
: "";
10624 subListObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10625 sprintf(buf
, "%p", objPtr
);
10626 Jim_ListAppendElement(interp
, subListObjPtr
,
10627 Jim_NewStringObj(interp
, buf
, -1));
10628 Jim_ListAppendElement(interp
, subListObjPtr
,
10629 Jim_NewStringObj(interp
, type
, -1));
10630 Jim_ListAppendElement(interp
, subListObjPtr
,
10631 Jim_NewIntObj(interp
, objPtr
->refCount
));
10632 Jim_ListAppendElement(interp
, subListObjPtr
, objPtr
);
10633 Jim_ListAppendElement(interp
, listObjPtr
, subListObjPtr
);
10634 objPtr
= objPtr
->nextObjPtr
;
10636 Jim_SetResult(interp
, listObjPtr
);
10638 } else if (option
== OPT_INVSTR
) {
10642 Jim_WrongNumArgs(interp
, 2, argv
, "object");
10646 if (objPtr
->typePtr
!= NULL
)
10647 Jim_InvalidateStringRep(objPtr
);
10648 Jim_SetEmptyResult(interp
);
10650 } else if (option
== OPT_SCRIPTLEN
) {
10653 Jim_WrongNumArgs(interp
, 2, argv
, "script");
10656 script
= Jim_GetScript(interp
, argv
[2]);
10657 Jim_SetResult(interp
, Jim_NewIntObj(interp
, script
->len
));
10659 } else if (option
== OPT_EXPRLEN
) {
10660 ExprByteCode
*expr
;
10662 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
10665 expr
= Jim_GetExpression(interp
, argv
[2]);
10668 Jim_SetResult(interp
, Jim_NewIntObj(interp
, expr
->len
));
10670 } else if (option
== OPT_EXPRBC
) {
10672 ExprByteCode
*expr
;
10676 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
10679 expr
= Jim_GetExpression(interp
, argv
[2]);
10682 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
10683 for (i
= 0; i
< expr
->len
; i
++) {
10685 Jim_ExprOperator
*op
;
10687 switch(expr
->opcode
[i
]) {
10688 case JIM_EXPROP_NUMBER
: type
= "number"; break;
10689 case JIM_EXPROP_COMMAND
: type
= "command"; break;
10690 case JIM_EXPROP_VARIABLE
: type
= "variable"; break;
10691 case JIM_EXPROP_DICTSUGAR
: type
= "dictsugar"; break;
10692 case JIM_EXPROP_SUBST
: type
= "subst"; break;
10693 case JIM_EXPROP_STRING
: type
= "string"; break;
10695 op
= JimExprOperatorInfo(Jim_GetString(expr
->obj
[i
], NULL
));
10703 Jim_ListAppendElement(interp
, objPtr
,
10704 Jim_NewStringObj(interp
, type
, -1));
10705 Jim_ListAppendElement(interp
, objPtr
, expr
->obj
[i
]);
10707 Jim_SetResult(interp
, objPtr
);
10710 Jim_SetResultString(interp
,
10711 "bad option. Valid options are refcount, "
10712 "objcount, objects, invstr", -1);
10715 return JIM_OK
; /* unreached */
10719 static int Jim_EvalCoreCommand(Jim_Interp
*interp
, int argc
,
10720 Jim_Obj
*const *argv
)
10723 return Jim_EvalObj(interp
, argv
[1]);
10724 } else if (argc
> 2) {
10728 objPtr
= Jim_ConcatObj(interp
, argc
-1, argv
+1);
10729 Jim_IncrRefCount(objPtr
);
10730 retcode
= Jim_EvalObj(interp
, objPtr
);
10731 Jim_DecrRefCount(interp
, objPtr
);
10734 Jim_WrongNumArgs(interp
, 1, argv
, "script ?...?");
10740 static int Jim_UplevelCoreCommand(Jim_Interp
*interp
, int argc
,
10741 Jim_Obj
*const *argv
)
10744 int retcode
, newLevel
, oldLevel
;
10745 Jim_CallFrame
*savedCallFrame
, *targetCallFrame
;
10749 /* Save the old callframe pointer */
10750 savedCallFrame
= interp
->framePtr
;
10752 /* Lookup the target frame pointer */
10753 str
= Jim_GetString(argv
[1], NULL
);
10754 if ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#')
10756 if (Jim_GetCallFrameByLevel(interp
, argv
[1],
10758 &newLevel
) != JIM_OK
)
10763 if (Jim_GetCallFrameByLevel(interp
, NULL
,
10765 &newLevel
) != JIM_OK
)
10771 Jim_WrongNumArgs(interp
, 1, argv
,
10772 "?level? command ?arg ...?");
10775 /* Eval the code in the target callframe. */
10776 interp
->framePtr
= targetCallFrame
;
10777 oldLevel
= interp
->numLevels
;
10778 interp
->numLevels
= newLevel
;
10780 retcode
= Jim_EvalObj(interp
, argv
[1]);
10782 objPtr
= Jim_ConcatObj(interp
, argc
-1, argv
+1);
10783 Jim_IncrRefCount(objPtr
);
10784 retcode
= Jim_EvalObj(interp
, objPtr
);
10785 Jim_DecrRefCount(interp
, objPtr
);
10787 interp
->numLevels
= oldLevel
;
10788 interp
->framePtr
= savedCallFrame
;
10791 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
10797 static int Jim_ExprCoreCommand(Jim_Interp
*interp
, int argc
,
10798 Jim_Obj
*const *argv
)
10800 Jim_Obj
*exprResultPtr
;
10804 retcode
= Jim_EvalExpression(interp
, argv
[1], &exprResultPtr
);
10805 } else if (argc
> 2) {
10808 objPtr
= Jim_ConcatObj(interp
, argc
-1, argv
+1);
10809 Jim_IncrRefCount(objPtr
);
10810 retcode
= Jim_EvalExpression(interp
, objPtr
, &exprResultPtr
);
10811 Jim_DecrRefCount(interp
, objPtr
);
10813 Jim_WrongNumArgs(interp
, 1, argv
, "expression ?...?");
10816 if (retcode
!= JIM_OK
) return retcode
;
10817 Jim_SetResult(interp
, exprResultPtr
);
10818 Jim_DecrRefCount(interp
, exprResultPtr
);
10823 static int Jim_BreakCoreCommand(Jim_Interp
*interp
, int argc
,
10824 Jim_Obj
*const *argv
)
10827 Jim_WrongNumArgs(interp
, 1, argv
, "");
10834 static int Jim_ContinueCoreCommand(Jim_Interp
*interp
, int argc
,
10835 Jim_Obj
*const *argv
)
10838 Jim_WrongNumArgs(interp
, 1, argv
, "");
10841 return JIM_CONTINUE
;
10845 static int Jim_ReturnCoreCommand(Jim_Interp
*interp
, int argc
,
10846 Jim_Obj
*const *argv
)
10850 } else if (argc
== 2) {
10851 Jim_SetResult(interp
, argv
[1]);
10852 interp
->returnCode
= JIM_OK
;
10854 } else if (argc
== 3 || argc
== 4) {
10856 if (Jim_GetReturnCode(interp
, argv
[2], &returnCode
) == JIM_ERR
)
10858 interp
->returnCode
= returnCode
;
10860 Jim_SetResult(interp
, argv
[3]);
10863 Jim_WrongNumArgs(interp
, 1, argv
, "?-code code? ?result?");
10866 return JIM_RETURN
; /* unreached */
10870 static int Jim_TailcallCoreCommand(Jim_Interp
*interp
, int argc
,
10871 Jim_Obj
*const *argv
)
10875 objPtr
= Jim_NewListObj(interp
, argv
+1, argc
-1);
10876 Jim_SetResult(interp
, objPtr
);
10881 static int Jim_ProcCoreCommand(Jim_Interp
*interp
, int argc
,
10882 Jim_Obj
*const *argv
)
10885 int arityMin
, arityMax
;
10887 if (argc
!= 4 && argc
!= 5) {
10888 Jim_WrongNumArgs(interp
, 1, argv
, "name arglist ?statics? body");
10891 Jim_ListLength(interp
, argv
[2], &argListLen
);
10892 arityMin
= arityMax
= argListLen
+1;
10896 Jim_Obj
*lastArgPtr
;
10898 Jim_ListIndex(interp
, argv
[2], argListLen
-1, &lastArgPtr
, JIM_NONE
);
10899 str
= Jim_GetString(lastArgPtr
, &len
);
10900 if (len
== 4 && memcmp(str
, "args", 4) == 0) {
10906 return Jim_CreateProcedure(interp
, Jim_GetString(argv
[1], NULL
),
10907 argv
[2], NULL
, argv
[3], arityMin
, arityMax
);
10909 return Jim_CreateProcedure(interp
, Jim_GetString(argv
[1], NULL
),
10910 argv
[2], argv
[3], argv
[4], arityMin
, arityMax
);
10915 static int Jim_ConcatCoreCommand(Jim_Interp
*interp
, int argc
,
10916 Jim_Obj
*const *argv
)
10918 Jim_SetResult(interp
, Jim_ConcatObj(interp
, argc
-1, argv
+1));
10923 static int Jim_UpvarCoreCommand(Jim_Interp
*interp
, int argc
,
10924 Jim_Obj
*const *argv
)
10928 Jim_CallFrame
*targetCallFrame
;
10930 /* Lookup the target frame pointer */
10931 str
= Jim_GetString(argv
[1], NULL
);
10933 ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#'))
10935 if (Jim_GetCallFrameByLevel(interp
, argv
[1],
10936 &targetCallFrame
, NULL
) != JIM_OK
)
10941 if (Jim_GetCallFrameByLevel(interp
, NULL
,
10942 &targetCallFrame
, NULL
) != JIM_OK
)
10945 /* Check for arity */
10946 if (argc
< 3 || ((argc
-1)%2) != 0) {
10947 Jim_WrongNumArgs(interp
, 1, argv
, "?level? otherVar localVar ?otherVar localVar ...?");
10950 /* Now... for every other/local couple: */
10951 for (i
= 1; i
< argc
; i
+= 2) {
10952 if (Jim_SetVariableLink(interp
, argv
[i
+1], argv
[i
],
10953 targetCallFrame
) != JIM_OK
) return JIM_ERR
;
10959 static int Jim_GlobalCoreCommand(Jim_Interp
*interp
, int argc
,
10960 Jim_Obj
*const *argv
)
10965 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
10968 /* Link every var to the toplevel having the same name */
10969 if (interp
->numLevels
== 0) return JIM_OK
; /* global at toplevel... */
10970 for (i
= 1; i
< argc
; i
++) {
10971 if (Jim_SetVariableLink(interp
, argv
[i
], argv
[i
],
10972 interp
->topFramePtr
) != JIM_OK
) return JIM_ERR
;
10977 /* does the [string map] operation. On error NULL is returned,
10978 * otherwise a new string object with the result, having refcount = 0,
10980 static Jim_Obj
*JimStringMap(Jim_Interp
*interp
, Jim_Obj
*mapListObjPtr
,
10981 Jim_Obj
*objPtr
, int nocase
)
10984 const char **key
, *str
, *noMatchStart
= NULL
;
10986 int *keyLen
, strLen
, i
;
10987 Jim_Obj
*resultObjPtr
;
10989 Jim_ListLength(interp
, mapListObjPtr
, &numMaps
);
10991 Jim_SetResultString(interp
,
10992 "list must contain an even number of elements", -1);
10995 /* Initialization */
10997 key
= Jim_Alloc(sizeof(char*)*numMaps
);
10998 keyLen
= Jim_Alloc(sizeof(int)*numMaps
);
10999 value
= Jim_Alloc(sizeof(Jim_Obj
*)*numMaps
);
11000 resultObjPtr
= Jim_NewStringObj(interp
, "", 0);
11001 for (i
= 0; i
< numMaps
; i
++) {
11002 Jim_Obj
*eleObjPtr
;
11004 Jim_ListIndex(interp
, mapListObjPtr
, i
*2, &eleObjPtr
, JIM_NONE
);
11005 key
[i
] = Jim_GetString(eleObjPtr
, &keyLen
[i
]);
11006 Jim_ListIndex(interp
, mapListObjPtr
, i
*2+1, &eleObjPtr
, JIM_NONE
);
11007 value
[i
] = eleObjPtr
;
11009 str
= Jim_GetString(objPtr
, &strLen
);
11012 for (i
= 0; i
< numMaps
; i
++) {
11013 if (strLen
>= keyLen
[i
] && keyLen
[i
]) {
11014 if (!JimStringCompare(str
, keyLen
[i
], key
[i
], keyLen
[i
],
11017 if (noMatchStart
) {
11018 Jim_AppendString(interp
, resultObjPtr
,
11019 noMatchStart
, str
-noMatchStart
);
11020 noMatchStart
= NULL
;
11022 Jim_AppendObj(interp
, resultObjPtr
, value
[i
]);
11024 strLen
-= keyLen
[i
];
11029 if (i
== numMaps
) { /* no match */
11030 if (noMatchStart
== NULL
)
11031 noMatchStart
= str
;
11036 if (noMatchStart
) {
11037 Jim_AppendString(interp
, resultObjPtr
,
11038 noMatchStart
, str
-noMatchStart
);
11040 Jim_Free((void*)key
);
11043 return resultObjPtr
;
11047 static int Jim_StringCoreCommand(Jim_Interp
*interp
, int argc
,
11048 Jim_Obj
*const *argv
)
11051 const char *options
[] = {
11052 "length", "compare", "match", "equal", "range", "map", "repeat",
11053 "index", "first", "tolower", "toupper", NULL
11056 OPT_LENGTH
, OPT_COMPARE
, OPT_MATCH
, OPT_EQUAL
, OPT_RANGE
,
11057 OPT_MAP
, OPT_REPEAT
, OPT_INDEX
, OPT_FIRST
, OPT_TOLOWER
, OPT_TOUPPER
11061 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
11064 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "option",
11065 JIM_ERRMSG
) != JIM_OK
)
11068 if (option
== OPT_LENGTH
) {
11072 Jim_WrongNumArgs(interp
, 2, argv
, "string");
11075 Jim_GetString(argv
[2], &len
);
11076 Jim_SetResult(interp
, Jim_NewIntObj(interp
, len
));
11078 } else if (option
== OPT_COMPARE
) {
11080 if ((argc
!= 4 && argc
!= 5) ||
11081 (argc
== 5 && Jim_CompareStringImmediate(interp
,
11082 argv
[2], "-nocase") == 0)) {
11083 Jim_WrongNumArgs(interp
, 2, argv
, "string1 string2");
11090 Jim_SetResult(interp
, Jim_NewIntObj(interp
,
11091 Jim_StringCompareObj(argv
[2],
11092 argv
[3], nocase
)));
11094 } else if (option
== OPT_MATCH
) {
11096 if ((argc
!= 4 && argc
!= 5) ||
11097 (argc
== 5 && Jim_CompareStringImmediate(interp
,
11098 argv
[2], "-nocase") == 0)) {
11099 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? pattern "
11107 Jim_SetResult(interp
,
11108 Jim_NewIntObj(interp
, Jim_StringMatchObj(argv
[2],
11109 argv
[3], nocase
)));
11111 } else if (option
== OPT_EQUAL
) {
11113 Jim_WrongNumArgs(interp
, 2, argv
, "string1 string2");
11116 Jim_SetResult(interp
,
11117 Jim_NewIntObj(interp
, Jim_StringEqObj(argv
[2],
11120 } else if (option
== OPT_RANGE
) {
11124 Jim_WrongNumArgs(interp
, 2, argv
, "string first last");
11127 objPtr
= Jim_StringRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
11128 if (objPtr
== NULL
)
11130 Jim_SetResult(interp
, objPtr
);
11132 } else if (option
== OPT_MAP
) {
11136 if ((argc
!= 4 && argc
!= 5) ||
11137 (argc
== 5 && Jim_CompareStringImmediate(interp
,
11138 argv
[2], "-nocase") == 0)) {
11139 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? mapList "
11147 objPtr
= JimStringMap(interp
, argv
[2], argv
[3], nocase
);
11148 if (objPtr
== NULL
)
11150 Jim_SetResult(interp
, objPtr
);
11152 } else if (option
== OPT_REPEAT
) {
11157 Jim_WrongNumArgs(interp
, 2, argv
, "string count");
11160 if (Jim_GetWide(interp
, argv
[3], &count
) != JIM_OK
)
11162 objPtr
= Jim_NewStringObj(interp
, "", 0);
11164 Jim_AppendObj(interp
, objPtr
, argv
[2]);
11166 Jim_SetResult(interp
, objPtr
);
11168 } else if (option
== OPT_INDEX
) {
11173 Jim_WrongNumArgs(interp
, 2, argv
, "string index");
11176 if (Jim_GetIndex(interp
, argv
[3], &index
) != JIM_OK
)
11178 str
= Jim_GetString(argv
[2], &len
);
11179 if (index
!= INT_MIN
&& index
!= INT_MAX
)
11180 index
= JimRelToAbsIndex(len
, index
);
11181 if (index
< 0 || index
>= len
) {
11182 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11185 Jim_SetResult(interp
, Jim_NewStringObj(interp
, str
+index
, 1));
11188 } else if (option
== OPT_FIRST
) {
11189 int index
= 0, l1
, l2
;
11190 const char *s1
, *s2
;
11192 if (argc
!= 4 && argc
!= 5) {
11193 Jim_WrongNumArgs(interp
, 2, argv
, "subString string ?startIndex?");
11196 s1
= Jim_GetString(argv
[2], &l1
);
11197 s2
= Jim_GetString(argv
[3], &l2
);
11199 if (Jim_GetIndex(interp
, argv
[4], &index
) != JIM_OK
)
11201 index
= JimRelToAbsIndex(l2
, index
);
11203 Jim_SetResult(interp
, Jim_NewIntObj(interp
,
11204 JimStringFirst(s1
, l1
, s2
, l2
, index
)));
11206 } else if (option
== OPT_TOLOWER
) {
11208 Jim_WrongNumArgs(interp
, 2, argv
, "string");
11211 Jim_SetResult(interp
, JimStringToLower(interp
, argv
[2]));
11212 } else if (option
== OPT_TOUPPER
) {
11214 Jim_WrongNumArgs(interp
, 2, argv
, "string");
11217 Jim_SetResult(interp
, JimStringToUpper(interp
, argv
[2]));
11223 static int Jim_TimeCoreCommand(Jim_Interp
*interp
, int argc
,
11224 Jim_Obj
*const *argv
)
11227 jim_wide start
, elapsed
;
11229 const char *fmt
= "%" JIM_WIDE_MODIFIER
" microseconds per iteration";
11232 Jim_WrongNumArgs(interp
, 1, argv
, "script ?count?");
11236 if (Jim_GetLong(interp
, argv
[2], &count
) != JIM_OK
)
11242 start
= JimClock();
11246 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
)
11249 elapsed
= JimClock() - start
;
11250 sprintf(buf
, fmt
, elapsed
/count
);
11251 Jim_SetResultString(interp
, buf
, -1);
11256 static int Jim_ExitCoreCommand(Jim_Interp
*interp
, int argc
,
11257 Jim_Obj
*const *argv
)
11262 Jim_WrongNumArgs(interp
, 1, argv
, "?exitCode?");
11266 if (Jim_GetLong(interp
, argv
[1], &exitCode
) != JIM_OK
)
11269 interp
->exitCode
= exitCode
;
11274 static int Jim_CatchCoreCommand(Jim_Interp
*interp
, int argc
,
11275 Jim_Obj
*const *argv
)
11279 if (argc
!= 2 && argc
!= 3) {
11280 Jim_WrongNumArgs(interp
, 1, argv
, "script ?varName?");
11283 exitCode
= Jim_EvalObj(interp
, argv
[1]);
11285 if (Jim_SetVariable(interp
, argv
[2], Jim_GetResult(interp
))
11289 Jim_SetResult(interp
, Jim_NewIntObj(interp
, exitCode
));
11294 static int Jim_RefCoreCommand(Jim_Interp
*interp
, int argc
,
11295 Jim_Obj
*const *argv
)
11297 if (argc
!= 3 && argc
!= 4) {
11298 Jim_WrongNumArgs(interp
, 1, argv
, "string tag ?finalizer?");
11302 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], NULL
));
11304 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2],
11311 static int Jim_GetrefCoreCommand(Jim_Interp
*interp
, int argc
,
11312 Jim_Obj
*const *argv
)
11314 Jim_Reference
*refPtr
;
11317 Jim_WrongNumArgs(interp
, 1, argv
, "reference");
11320 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
11322 Jim_SetResult(interp
, refPtr
->objPtr
);
11327 static int Jim_SetrefCoreCommand(Jim_Interp
*interp
, int argc
,
11328 Jim_Obj
*const *argv
)
11330 Jim_Reference
*refPtr
;
11333 Jim_WrongNumArgs(interp
, 1, argv
, "reference newValue");
11336 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
11338 Jim_IncrRefCount(argv
[2]);
11339 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
11340 refPtr
->objPtr
= argv
[2];
11341 Jim_SetResult(interp
, argv
[2]);
11346 static int Jim_CollectCoreCommand(Jim_Interp
*interp
, int argc
,
11347 Jim_Obj
*const *argv
)
11350 Jim_WrongNumArgs(interp
, 1, argv
, "");
11353 Jim_SetResult(interp
, Jim_NewIntObj(interp
, Jim_Collect(interp
)));
11357 /* [finalize] reference ?newValue? */
11358 static int Jim_FinalizeCoreCommand(Jim_Interp
*interp
, int argc
,
11359 Jim_Obj
*const *argv
)
11361 if (argc
!= 2 && argc
!= 3) {
11362 Jim_WrongNumArgs(interp
, 1, argv
, "reference ?finalizerProc?");
11366 Jim_Obj
*cmdNamePtr
;
11368 if (Jim_GetFinalizer(interp
, argv
[1], &cmdNamePtr
) != JIM_OK
)
11370 if (cmdNamePtr
!= NULL
) /* otherwise the null string is returned. */
11371 Jim_SetResult(interp
, cmdNamePtr
);
11373 if (Jim_SetFinalizer(interp
, argv
[1], argv
[2]) != JIM_OK
)
11375 Jim_SetResult(interp
, argv
[2]);
11381 /* [info references] (list of all the references/finalizers) */
11384 static int Jim_RenameCoreCommand(Jim_Interp
*interp
, int argc
,
11385 Jim_Obj
*const *argv
)
11387 const char *oldName
, *newName
;
11390 Jim_WrongNumArgs(interp
, 1, argv
, "oldName newName");
11393 oldName
= Jim_GetString(argv
[1], NULL
);
11394 newName
= Jim_GetString(argv
[2], NULL
);
11395 if (Jim_RenameCommand(interp
, oldName
, newName
) != JIM_OK
) {
11396 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11397 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
11398 "can't rename \"", oldName
, "\": ",
11399 "command doesn't exist", NULL
);
11406 static int Jim_DictCoreCommand(Jim_Interp
*interp
, int argc
,
11407 Jim_Obj
*const *argv
)
11410 const char *options
[] = {
11411 "create", "get", "set", "unset", "exists", NULL
11414 OPT_CREATE
, OPT_GET
, OPT_SET
, OPT_UNSET
, OPT_EXIST
11418 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
11422 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "option",
11423 JIM_ERRMSG
) != JIM_OK
)
11426 if (option
== OPT_CREATE
) {
11430 Jim_WrongNumArgs(interp
, 2, argv
, "?key value ...?");
11433 objPtr
= Jim_NewDictObj(interp
, argv
+2, argc
-2);
11434 Jim_SetResult(interp
, objPtr
);
11436 } else if (option
== OPT_GET
) {
11439 if (Jim_DictKeysVector(interp
, argv
[2], argv
+3, argc
-3, &objPtr
,
11440 JIM_ERRMSG
) != JIM_OK
)
11442 Jim_SetResult(interp
, objPtr
);
11444 } else if (option
== OPT_SET
) {
11446 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...? value");
11449 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+3, argc
-4,
11451 } else if (option
== OPT_UNSET
) {
11453 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...?");
11456 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+3, argc
-3,
11458 } else if (option
== OPT_EXIST
) {
11462 if (Jim_DictKeysVector(interp
, argv
[2], argv
+3, argc
-3, &objPtr
,
11463 JIM_ERRMSG
) == JIM_OK
)
11467 Jim_SetResult(interp
, Jim_NewIntObj(interp
, exists
));
11470 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11471 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
11472 "bad option \"", Jim_GetString(argv
[1], NULL
), "\":",
11473 " must be create, get, set", NULL
);
11480 static int Jim_LoadCoreCommand(Jim_Interp
*interp
, int argc
,
11481 Jim_Obj
*const *argv
)
11484 Jim_WrongNumArgs(interp
, 1, argv
, "libaryFile");
11487 return Jim_LoadLibrary(interp
, Jim_GetString(argv
[1], NULL
));
11491 static int Jim_SubstCoreCommand(Jim_Interp
*interp
, int argc
,
11492 Jim_Obj
*const *argv
)
11498 Jim_WrongNumArgs(interp
, 1, argv
,
11499 "?-nobackslashes? ?-nocommands? ?-novariables? string");
11504 if (Jim_CompareStringImmediate(interp
, argv
[i
+1],
11506 flags
|= JIM_SUBST_NOESC
;
11507 else if (Jim_CompareStringImmediate(interp
, argv
[i
+1],
11509 flags
|= JIM_SUBST_NOVAR
;
11510 else if (Jim_CompareStringImmediate(interp
, argv
[i
+1],
11512 flags
|= JIM_SUBST_NOCMD
;
11514 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11515 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
11516 "bad option \"", Jim_GetString(argv
[i
+1], NULL
),
11517 "\": must be -nobackslashes, -nocommands, or "
11518 "-novariables", NULL
);
11522 if (Jim_SubstObj(interp
, argv
[argc
-1], &objPtr
, flags
) != JIM_OK
)
11524 Jim_SetResult(interp
, objPtr
);
11529 static int Jim_InfoCoreCommand(Jim_Interp
*interp
, int argc
,
11530 Jim_Obj
*const *argv
)
11532 int cmd
, result
= JIM_OK
;
11533 static const char *commands
[] = {
11534 "body", "commands", "exists", "globals", "level", "locals",
11535 "vars", "version", "complete", "args", NULL
11537 enum {INFO_BODY
, INFO_COMMANDS
, INFO_EXISTS
, INFO_GLOBALS
, INFO_LEVEL
,
11538 INFO_LOCALS
, INFO_VARS
, INFO_VERSION
, INFO_COMPLETE
, INFO_ARGS
};
11541 Jim_WrongNumArgs(interp
, 1, argv
, "command ?args ...?");
11544 if (Jim_GetEnum(interp
, argv
[1], commands
, &cmd
, "command", JIM_ERRMSG
)
11549 if (cmd
== INFO_COMMANDS
) {
11550 if (argc
!= 2 && argc
!= 3) {
11551 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
11555 Jim_SetResult(interp
,JimCommandsList(interp
, argv
[2]));
11557 Jim_SetResult(interp
, JimCommandsList(interp
, NULL
));
11558 } else if (cmd
== INFO_EXISTS
) {
11561 Jim_WrongNumArgs(interp
, 2, argv
, "varName");
11564 exists
= Jim_GetVariable(interp
, argv
[2], 0);
11565 Jim_SetResult(interp
, Jim_NewIntObj(interp
, exists
!= 0));
11566 } else if (cmd
== INFO_GLOBALS
|| cmd
== INFO_LOCALS
|| cmd
== INFO_VARS
) {
11569 case INFO_GLOBALS
: mode
= JIM_VARLIST_GLOBALS
; break;
11570 case INFO_LOCALS
: mode
= JIM_VARLIST_LOCALS
; break;
11571 case INFO_VARS
: mode
= JIM_VARLIST_VARS
; break;
11572 default: mode
= 0; /* avoid warning */; break;
11574 if (argc
!= 2 && argc
!= 3) {
11575 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
11579 Jim_SetResult(interp
,JimVariablesList(interp
, argv
[2], mode
));
11581 Jim_SetResult(interp
, JimVariablesList(interp
, NULL
, mode
));
11582 } else if (cmd
== INFO_LEVEL
) {
11586 Jim_SetResult(interp
,
11587 Jim_NewIntObj(interp
, interp
->numLevels
));
11590 if (JimInfoLevel(interp
, argv
[2], &objPtr
) != JIM_OK
)
11592 Jim_SetResult(interp
, objPtr
);
11595 Jim_WrongNumArgs(interp
, 2, argv
, "?levelNum?");
11598 } else if (cmd
== INFO_BODY
|| cmd
== INFO_ARGS
) {
11602 Jim_WrongNumArgs(interp
, 2, argv
, "procname");
11605 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
)
11607 if (cmdPtr
->cmdProc
!= NULL
) {
11608 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11609 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
11610 "command \"", Jim_GetString(argv
[2], NULL
),
11611 "\" is not a procedure", NULL
);
11614 if (cmd
== INFO_BODY
)
11615 Jim_SetResult(interp
, cmdPtr
->bodyObjPtr
);
11617 Jim_SetResult(interp
, cmdPtr
->argListObjPtr
);
11618 } else if (cmd
== INFO_VERSION
) {
11619 char buf
[(JIM_INTEGER_SPACE
* 2) + 1];
11620 sprintf(buf
, "%d.%d",
11621 JIM_VERSION
/ 100, JIM_VERSION
% 100);
11622 Jim_SetResultString(interp
, buf
, -1);
11623 } else if (cmd
== INFO_COMPLETE
) {
11628 Jim_WrongNumArgs(interp
, 2, argv
, "script");
11631 s
= Jim_GetString(argv
[2], &len
);
11632 Jim_SetResult(interp
,
11633 Jim_NewIntObj(interp
, Jim_ScriptIsComplete(s
, len
, NULL
)));
11639 static int Jim_SplitCoreCommand(Jim_Interp
*interp
, int argc
,
11640 Jim_Obj
*const *argv
)
11642 const char *str
, *splitChars
, *noMatchStart
;
11643 int splitLen
, strLen
, i
;
11644 Jim_Obj
*resObjPtr
;
11646 if (argc
!= 2 && argc
!= 3) {
11647 Jim_WrongNumArgs(interp
, 1, argv
, "string ?splitChars?");
11652 splitChars
= " \n\t\r";
11655 splitChars
= Jim_GetString(argv
[2], &splitLen
);
11657 str
= Jim_GetString(argv
[1], &strLen
);
11658 if (!strLen
) return JIM_OK
;
11659 noMatchStart
= str
;
11660 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11664 for (i
= 0; i
< splitLen
; i
++) {
11665 if (*str
== splitChars
[i
]) {
11668 objPtr
= Jim_NewStringObj(interp
, noMatchStart
,
11669 (str
-noMatchStart
));
11670 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
11671 noMatchStart
= str
+1;
11678 Jim_ListAppendElement(interp
, resObjPtr
,
11679 Jim_NewStringObj(interp
, noMatchStart
, (str
-noMatchStart
)));
11681 /* This handles the special case of splitchars eq {}. This
11682 * is trivial but we want to perform object sharing as Tcl does. */
11683 Jim_Obj
*objCache
[256];
11684 const unsigned char *u
= (unsigned char*) str
;
11685 memset(objCache
, 0, sizeof(objCache
));
11686 for (i
= 0; i
< strLen
; i
++) {
11689 if (objCache
[c
] == NULL
)
11690 objCache
[c
] = Jim_NewStringObj(interp
, (char*)u
+i
, 1);
11691 Jim_ListAppendElement(interp
, resObjPtr
, objCache
[c
]);
11694 Jim_SetResult(interp
, resObjPtr
);
11699 static int Jim_JoinCoreCommand(Jim_Interp
*interp
, int argc
,
11700 Jim_Obj
*const *argv
)
11702 const char *joinStr
;
11703 int joinStrLen
, i
, listLen
;
11704 Jim_Obj
*resObjPtr
;
11706 if (argc
!= 2 && argc
!= 3) {
11707 Jim_WrongNumArgs(interp
, 1, argv
, "list ?joinString?");
11715 joinStr
= Jim_GetString(argv
[2], &joinStrLen
);
11717 Jim_ListLength(interp
, argv
[1], &listLen
);
11718 resObjPtr
= Jim_NewStringObj(interp
, NULL
, 0);
11720 for (i
= 0; i
< listLen
; i
++) {
11723 Jim_ListIndex(interp
, argv
[1], i
, &objPtr
, JIM_NONE
);
11724 Jim_AppendObj(interp
, resObjPtr
, objPtr
);
11725 if (i
+1 != listLen
) {
11726 Jim_AppendString(interp
, resObjPtr
, joinStr
, joinStrLen
);
11729 Jim_SetResult(interp
, resObjPtr
);
11734 static int Jim_FormatCoreCommand(Jim_Interp
*interp
, int argc
,
11735 Jim_Obj
*const *argv
)
11740 Jim_WrongNumArgs(interp
, 1, argv
, "formatString ?arg arg ...?");
11743 objPtr
= Jim_FormatString(interp
, argv
[1], argc
-2, argv
+2);
11744 if (objPtr
== NULL
)
11746 Jim_SetResult(interp
, objPtr
);
11751 static int Jim_ScanCoreCommand(Jim_Interp
*interp
, int argc
,
11752 Jim_Obj
*const *argv
)
11754 Jim_Obj
*listPtr
, **outVec
;
11755 int outc
, i
, count
= 0;
11758 Jim_WrongNumArgs(interp
, 1, argv
, "string formatString ?varName ...?");
11761 if (argv
[2]->typePtr
!= &scanFmtStringObjType
)
11762 SetScanFmtFromAny(interp
, argv
[2]);
11763 if (FormatGetError(argv
[2]) != 0) {
11764 Jim_SetResultString(interp
, FormatGetError(argv
[2]), -1);
11768 int maxPos
= FormatGetMaxPos(argv
[2]);
11769 int count
= FormatGetCnvCount(argv
[2]);
11770 if (maxPos
> argc
-3) {
11771 Jim_SetResultString(interp
, "\"%n$\" argument index out of range", -1);
11773 } else if (count
!= 0 && count
< argc
-3) {
11774 Jim_SetResultString(interp
, "variable is not assigned by any "
11775 "conversion specifiers", -1);
11777 } else if (count
> argc
-3) {
11778 Jim_SetResultString(interp
, "different numbers of variable names and "
11779 "field specifiers", -1);
11783 listPtr
= Jim_ScanString(interp
, argv
[1], argv
[2], JIM_ERRMSG
);
11788 if (listPtr
!= 0 && listPtr
!= (Jim_Obj
*)EOF
)
11789 Jim_ListLength(interp
, listPtr
, &len
);
11790 if (listPtr
== (Jim_Obj
*)EOF
|| len
== 0) { // XXX
11791 Jim_SetResult(interp
, Jim_NewIntObj(interp
, -1));
11794 JimListGetElements(interp
, listPtr
, &outc
, &outVec
);
11795 for (i
= 0; i
< outc
; ++i
) {
11796 if (Jim_Length(outVec
[i
]) > 0) {
11798 if (Jim_SetVariable(interp
, argv
[3+i
], outVec
[i
]) != JIM_OK
)
11802 Jim_FreeNewObj(interp
, listPtr
);
11803 Jim_SetResult(interp
, Jim_NewIntObj(interp
, count
));
11805 if (listPtr
== (Jim_Obj
*)EOF
) {
11806 Jim_SetResult(interp
, Jim_NewListObj(interp
, 0, 0));
11809 Jim_SetResult(interp
, listPtr
);
11813 Jim_FreeNewObj(interp
, listPtr
);
11818 static int Jim_ErrorCoreCommand(Jim_Interp
*interp
, int argc
,
11819 Jim_Obj
*const *argv
)
11822 Jim_WrongNumArgs(interp
, 1, argv
, "message");
11825 Jim_SetResult(interp
, argv
[1]);
11830 static int Jim_LrangeCoreCommand(Jim_Interp
*interp
, int argc
,
11831 Jim_Obj
*const *argv
)
11836 Jim_WrongNumArgs(interp
, 1, argv
, "list first last");
11839 if ((objPtr
= Jim_ListRange(interp
, argv
[1], argv
[2], argv
[3])) == NULL
)
11841 Jim_SetResult(interp
, objPtr
);
11846 static int Jim_EnvCoreCommand(Jim_Interp
*interp
, int argc
,
11847 Jim_Obj
*const *argv
)
11853 Jim_WrongNumArgs(interp
, 1, argv
, "varName");
11856 key
= Jim_GetString(argv
[1], NULL
);
11859 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11860 Jim_AppendStrings(interp
, Jim_GetResult(interp
),
11861 "environment variable \"",
11862 key
, "\" does not exist", NULL
);
11865 Jim_SetResult(interp
, Jim_NewStringObj(interp
, val
, -1));
11870 static int Jim_SourceCoreCommand(Jim_Interp
*interp
, int argc
,
11871 Jim_Obj
*const *argv
)
11876 Jim_WrongNumArgs(interp
, 1, argv
, "fileName");
11879 retval
= Jim_EvalFile(interp
, Jim_GetString(argv
[1], NULL
));
11880 if (retval
== JIM_RETURN
)
11886 static int Jim_LreverseCoreCommand(Jim_Interp
*interp
, int argc
,
11887 Jim_Obj
*const *argv
)
11889 Jim_Obj
*revObjPtr
, **ele
;
11893 Jim_WrongNumArgs(interp
, 1, argv
, "list");
11896 JimListGetElements(interp
, argv
[1], &len
, &ele
);
11898 revObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11900 ListAppendElement(revObjPtr
, ele
[len
--]);
11901 Jim_SetResult(interp
, revObjPtr
);
11905 static int JimRangeLen(jim_wide start
, jim_wide end
, jim_wide step
)
11909 if (step
== 0) return -1;
11910 if (start
== end
) return 0;
11911 else if (step
> 0 && start
> end
) return -1;
11912 else if (step
< 0 && end
> start
) return -1;
11914 if (len
< 0) len
= -len
; /* abs(len) */
11915 if (step
< 0) step
= -step
; /* abs(step) */
11916 len
= 1 + ((len
-1)/step
);
11917 /* We can truncate safely to INT_MAX, the range command
11918 * will always return an error for a such long range
11919 * because Tcl lists can't be so long. */
11920 if (len
> INT_MAX
) len
= INT_MAX
;
11921 return (int)((len
< 0) ? -1 : len
);
11925 static int Jim_RangeCoreCommand(Jim_Interp
*interp
, int argc
,
11926 Jim_Obj
*const *argv
)
11928 jim_wide start
= 0, end
, step
= 1;
11932 if (argc
< 2 || argc
> 4) {
11933 Jim_WrongNumArgs(interp
, 1, argv
, "?start? end ?step?");
11937 if (Jim_GetWide(interp
, argv
[1], &end
) != JIM_OK
)
11940 if (Jim_GetWide(interp
, argv
[1], &start
) != JIM_OK
||
11941 Jim_GetWide(interp
, argv
[2], &end
) != JIM_OK
)
11943 if (argc
== 4 && Jim_GetWide(interp
, argv
[3], &step
) != JIM_OK
)
11946 if ((len
= JimRangeLen(start
, end
, step
)) == -1) {
11947 Jim_SetResultString(interp
, "Invalid (infinite?) range specified", -1);
11950 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
11951 for (i
= 0; i
< len
; i
++)
11952 ListAppendElement(objPtr
, Jim_NewIntObj(interp
, start
+i
*step
));
11953 Jim_SetResult(interp
, objPtr
);
11958 static int Jim_RandCoreCommand(Jim_Interp
*interp
, int argc
,
11959 Jim_Obj
*const *argv
)
11961 jim_wide min
= 0, max
, len
, maxMul
;
11963 if (argc
< 1 || argc
> 3) {
11964 Jim_WrongNumArgs(interp
, 1, argv
, "?min? max");
11968 max
= JIM_WIDE_MAX
;
11969 } else if (argc
== 2) {
11970 if (Jim_GetWide(interp
, argv
[1], &max
) != JIM_OK
)
11972 } else if (argc
== 3) {
11973 if (Jim_GetWide(interp
, argv
[1], &min
) != JIM_OK
||
11974 Jim_GetWide(interp
, argv
[2], &max
) != JIM_OK
)
11979 Jim_SetResultString(interp
, "Invalid arguments (max < min)", -1);
11982 maxMul
= JIM_WIDE_MAX
- (len
? (JIM_WIDE_MAX
%len
) : 0);
11986 JimRandomBytes(interp
, &r
, sizeof(jim_wide
));
11987 if (r
< 0 || r
>= maxMul
) continue;
11988 r
= (len
== 0) ? 0 : r
%len
;
11989 Jim_SetResult(interp
, Jim_NewIntObj(interp
, min
+r
));
11995 static int Jim_PackageCoreCommand(Jim_Interp
*interp
, int argc
,
11996 Jim_Obj
*const *argv
)
11999 const char *options
[] = {
12000 "require", "provide", NULL
12002 enum {OPT_REQUIRE
, OPT_PROVIDE
};
12005 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
12008 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "option",
12009 JIM_ERRMSG
) != JIM_OK
)
12012 if (option
== OPT_REQUIRE
) {
12016 if (Jim_CompareStringImmediate(interp
, argv
[2], "-exact")) {
12021 if (argc
!= 3 && argc
!= 4) {
12022 Jim_WrongNumArgs(interp
, 2, argv
, "?-exact? package ?version?");
12025 ver
= Jim_PackageRequire(interp
, Jim_GetString(argv
[2], NULL
),
12026 argc
== 4 ? Jim_GetString(argv
[3], NULL
) : "",
12030 Jim_SetResultString(interp
, ver
, -1);
12031 } else if (option
== OPT_PROVIDE
) {
12033 Jim_WrongNumArgs(interp
, 2, argv
, "package version");
12036 return Jim_PackageProvide(interp
, Jim_GetString(argv
[2], NULL
),
12037 Jim_GetString(argv
[3], NULL
), JIM_ERRMSG
);
12044 Jim_CmdProc cmdProc
;
12045 } Jim_CoreCommandsTable
[] = {
12046 {"set", Jim_SetCoreCommand
},
12047 {"unset", Jim_UnsetCoreCommand
},
12048 {"puts", Jim_PutsCoreCommand
},
12049 {"+", Jim_AddCoreCommand
},
12050 {"*", Jim_MulCoreCommand
},
12051 {"-", Jim_SubCoreCommand
},
12052 {"/", Jim_DivCoreCommand
},
12053 {"incr", Jim_IncrCoreCommand
},
12054 {"while", Jim_WhileCoreCommand
},
12055 {"for", Jim_ForCoreCommand
},
12056 {"foreach", Jim_ForeachCoreCommand
},
12057 {"lmap", Jim_LmapCoreCommand
},
12058 {"if", Jim_IfCoreCommand
},
12059 {"switch", Jim_SwitchCoreCommand
},
12060 {"list", Jim_ListCoreCommand
},
12061 {"lindex", Jim_LindexCoreCommand
},
12062 {"lset", Jim_LsetCoreCommand
},
12063 {"llength", Jim_LlengthCoreCommand
},
12064 {"lappend", Jim_LappendCoreCommand
},
12065 {"linsert", Jim_LinsertCoreCommand
},
12066 {"lsort", Jim_LsortCoreCommand
},
12067 {"append", Jim_AppendCoreCommand
},
12068 {"debug", Jim_DebugCoreCommand
},
12069 {"eval", Jim_EvalCoreCommand
},
12070 {"uplevel", Jim_UplevelCoreCommand
},
12071 {"expr", Jim_ExprCoreCommand
},
12072 {"break", Jim_BreakCoreCommand
},
12073 {"continue", Jim_ContinueCoreCommand
},
12074 {"proc", Jim_ProcCoreCommand
},
12075 {"concat", Jim_ConcatCoreCommand
},
12076 {"return", Jim_ReturnCoreCommand
},
12077 {"upvar", Jim_UpvarCoreCommand
},
12078 {"global", Jim_GlobalCoreCommand
},
12079 {"string", Jim_StringCoreCommand
},
12080 {"time", Jim_TimeCoreCommand
},
12081 {"exit", Jim_ExitCoreCommand
},
12082 {"catch", Jim_CatchCoreCommand
},
12083 {"ref", Jim_RefCoreCommand
},
12084 {"getref", Jim_GetrefCoreCommand
},
12085 {"setref", Jim_SetrefCoreCommand
},
12086 {"finalize", Jim_FinalizeCoreCommand
},
12087 {"collect", Jim_CollectCoreCommand
},
12088 {"rename", Jim_RenameCoreCommand
},
12089 {"dict", Jim_DictCoreCommand
},
12090 {"load", Jim_LoadCoreCommand
},
12091 {"subst", Jim_SubstCoreCommand
},
12092 {"info", Jim_InfoCoreCommand
},
12093 {"split", Jim_SplitCoreCommand
},
12094 {"join", Jim_JoinCoreCommand
},
12095 {"format", Jim_FormatCoreCommand
},
12096 {"scan", Jim_ScanCoreCommand
},
12097 {"error", Jim_ErrorCoreCommand
},
12098 {"lrange", Jim_LrangeCoreCommand
},
12099 {"env", Jim_EnvCoreCommand
},
12100 {"source", Jim_SourceCoreCommand
},
12101 {"lreverse", Jim_LreverseCoreCommand
},
12102 {"range", Jim_RangeCoreCommand
},
12103 {"rand", Jim_RandCoreCommand
},
12104 {"package", Jim_PackageCoreCommand
},
12105 {"tailcall", Jim_TailcallCoreCommand
},
12109 /* Some Jim core command is actually a procedure written in Jim itself. */
12110 static void Jim_RegisterCoreProcedures(Jim_Interp
*interp
)
12112 Jim_Eval(interp
, (char*)
12113 "proc lambda {arglist args} {\n"
12114 " set name [ref {} function lambdaFinalizer]\n"
12115 " uplevel 1 [list proc $name $arglist {expand}$args]\n"
12118 "proc lambdaFinalizer {name val} {\n"
12119 " rename $name {}\n"
12124 void Jim_RegisterCoreCommands(Jim_Interp
*interp
)
12128 while(Jim_CoreCommandsTable
[i
].name
!= NULL
) {
12129 Jim_CreateCommand(interp
,
12130 Jim_CoreCommandsTable
[i
].name
,
12131 Jim_CoreCommandsTable
[i
].cmdProc
,
12135 Jim_RegisterCoreProcedures(interp
);
12138 /* -----------------------------------------------------------------------------
12139 * Interactive prompt
12140 * ---------------------------------------------------------------------------*/
12141 void Jim_PrintErrorMessage(Jim_Interp
*interp
)
12145 Jim_fprintf(interp
, interp
->cookie_stderr
, "Runtime error, file \"%s\", line %d:" JIM_NL
,
12146 interp
->errorFileName
, interp
->errorLine
);
12147 Jim_fprintf(interp
,interp
->cookie_stderr
, " %s" JIM_NL
,
12148 Jim_GetString(interp
->result
, NULL
));
12149 Jim_ListLength(interp
, interp
->stackTrace
, &len
);
12150 for (i
= len
-3; i
>= 0; i
-= 3) {
12152 const char *proc
, *file
, *line
;
12154 Jim_ListIndex(interp
, interp
->stackTrace
, i
, &objPtr
, JIM_NONE
);
12155 proc
= Jim_GetString(objPtr
, NULL
);
12156 Jim_ListIndex(interp
, interp
->stackTrace
, i
+1, &objPtr
,
12158 file
= Jim_GetString(objPtr
, NULL
);
12159 Jim_ListIndex(interp
, interp
->stackTrace
, i
+2, &objPtr
,
12161 line
= Jim_GetString(objPtr
, NULL
);
12162 Jim_fprintf( interp
, interp
->cookie_stderr
,
12163 "In procedure '%s' called at file \"%s\", line %s" JIM_NL
,
12168 int Jim_InteractivePrompt(Jim_Interp
*interp
)
12170 int retcode
= JIM_OK
;
12171 Jim_Obj
*scriptObjPtr
;
12173 Jim_fprintf(interp
,interp
->cookie_stdout
, "Welcome to Jim version %d.%d, "
12174 "Copyright (c) 2005-8 Salvatore Sanfilippo" JIM_NL
,
12175 JIM_VERSION
/ 100, JIM_VERSION
% 100);
12176 Jim_SetVariableStrWithStr(interp
, "jim_interactive", "1");
12179 const char *result
;
12180 const char *retcodestr
[] = {
12181 "ok", "error", "return", "break", "continue", "eval", "exit"
12185 if (retcode
!= 0) {
12186 if (retcode
>= 2 && retcode
<= 6)
12187 Jim_fprintf(interp
,interp
->cookie_stdout
, "[%s] . ", retcodestr
[retcode
]);
12189 Jim_fprintf(interp
,interp
->cookie_stdout
, "[%d] . ", retcode
);
12191 Jim_fprintf( interp
, interp
->cookie_stdout
, ". ");
12192 Jim_fflush( interp
, interp
->cookie_stdout
);
12193 scriptObjPtr
= Jim_NewStringObj(interp
, "", 0);
12194 Jim_IncrRefCount(scriptObjPtr
);
12200 if ( Jim_fgets(interp
, buf
, 1024, interp
->cookie_stdin
) == NULL
) {
12201 Jim_DecrRefCount(interp
, scriptObjPtr
);
12204 Jim_AppendString(interp
, scriptObjPtr
, buf
, -1);
12205 str
= Jim_GetString(scriptObjPtr
, &len
);
12206 if (Jim_ScriptIsComplete(str
, len
, &state
))
12208 Jim_fprintf( interp
, interp
->cookie_stdout
, "%c> ", state
);
12209 Jim_fflush( interp
, interp
->cookie_stdout
);
12211 retcode
= Jim_EvalObj(interp
, scriptObjPtr
);
12212 Jim_DecrRefCount(interp
, scriptObjPtr
);
12213 result
= Jim_GetString(Jim_GetResult(interp
), &reslen
);
12214 if (retcode
== JIM_ERR
) {
12215 Jim_PrintErrorMessage(interp
);
12216 } else if (retcode
== JIM_EXIT
) {
12217 exit(Jim_GetExitCode(interp
));
12220 Jim_fwrite( interp
, result
, 1, reslen
, interp
->cookie_stdout
);
12221 Jim_fprintf( interp
,interp
->cookie_stdout
, JIM_NL
);
12229 /* -----------------------------------------------------------------------------
12230 * Jim's idea of STDIO..
12231 * ---------------------------------------------------------------------------*/
12233 int Jim_fprintf( Jim_Interp
*interp
, void *cookie
, const char *fmt
, ... )
12239 r
= Jim_vfprintf( interp
, cookie
, fmt
,ap
);
12244 int Jim_vfprintf( Jim_Interp
*interp
, void *cookie
, const char *fmt
, va_list ap
)
12246 if( (interp
== NULL
) || (interp
->cb_vfprintf
== NULL
) ){
12250 return (*(interp
->cb_vfprintf
))( cookie
, fmt
, ap
);
12253 size_t Jim_fwrite( Jim_Interp
*interp
, const void *ptr
, size_t size
, size_t n
, void *cookie
)
12255 if( (interp
== NULL
) || (interp
->cb_fwrite
== NULL
) ){
12259 return (*(interp
->cb_fwrite
))( ptr
, size
, n
, cookie
);
12262 size_t Jim_fread( Jim_Interp
*interp
, void *ptr
, size_t size
, size_t n
, void *cookie
)
12264 if( (interp
== NULL
) || (interp
->cb_fread
== NULL
) ){
12268 return (*(interp
->cb_fread
))( ptr
, size
, n
, cookie
);
12271 int Jim_fflush( Jim_Interp
*interp
, void *cookie
)
12273 if( (interp
== NULL
) || (interp
->cb_fflush
== NULL
) ){
12274 /* pretend all is well */
12277 return (*(interp
->cb_fflush
))( cookie
);
12280 char* Jim_fgets( Jim_Interp
*interp
, char *s
, int size
, void *cookie
)
12282 if( (interp
== NULL
) || (interp
->cb_fgets
== NULL
) ){
12286 return (*(interp
->cb_fgets
))( s
, size
, cookie
);
12290 Jim_Nvp_name2value_simple( const Jim_Nvp
*p
, const char *name
)
12293 if( 0 == strcmp( name
, p
->name
) ){
12298 return ((Jim_Nvp
*)(p
));
12302 Jim_Nvp_name2value_nocase_simple( const Jim_Nvp
*p
, const char *name
)
12305 if( 0 == strcasecmp( name
, p
->name
) ){
12310 return ((Jim_Nvp
*)(p
));
12314 Jim_Nvp_name2value_obj( Jim_Interp
*interp
,
12319 return Jim_Nvp_name2value( interp
, p
, Jim_GetString( o
, NULL
), result
);
12324 Jim_Nvp_name2value( Jim_Interp
*interp
,
12331 p
= Jim_Nvp_name2value_simple( _p
, name
);
12335 *result
= (Jim_Nvp
*)(p
);
12347 Jim_Nvp_name2value_obj_nocase( Jim_Interp
*interp
, const Jim_Nvp
*p
, Jim_Obj
*o
, Jim_Nvp
**puthere
)
12349 return Jim_Nvp_name2value_nocase( interp
, p
, Jim_GetString( o
, NULL
), puthere
);
12353 Jim_Nvp_name2value_nocase( Jim_Interp
*interp
, const Jim_Nvp
*_p
, const char *name
, Jim_Nvp
**puthere
)
12357 p
= Jim_Nvp_name2value_nocase_simple( _p
, name
);
12360 *puthere
= (Jim_Nvp
*)(p
);
12372 Jim_Nvp_value2name_obj( Jim_Interp
*interp
, const Jim_Nvp
*p
, Jim_Obj
*o
, Jim_Nvp
**result
)
12377 e
= Jim_GetWide( interp
, o
, &w
);
12382 return Jim_Nvp_value2name( interp
, p
, w
, result
);
12386 Jim_Nvp_value2name_simple( const Jim_Nvp
*p
, int value
)
12389 if( value
== p
->value
){
12394 return ((Jim_Nvp
*)(p
));
12399 Jim_Nvp_value2name( Jim_Interp
*interp
, const Jim_Nvp
*_p
, int value
, Jim_Nvp
**result
)
12403 p
= Jim_Nvp_value2name_simple( _p
, value
);
12406 *result
= (Jim_Nvp
*)(p
);
12418 Jim_GetOpt_Setup( Jim_GetOptInfo
*p
, Jim_Interp
*interp
, int argc
, Jim_Obj
* const * argv
)
12420 memset( p
, 0, sizeof(*p
) );
12421 p
->interp
= interp
;
12429 Jim_GetOpt_Debug( Jim_GetOptInfo
*p
)
12433 Jim_fprintf( p
->interp
, p
->interp
->cookie_stderr
, "---args---\n");
12434 for( x
= 0 ; x
< p
->argc
; x
++ ){
12435 Jim_fprintf( p
->interp
, p
->interp
->cookie_stderr
,
12438 Jim_GetString( p
->argv
[x
], NULL
) );
12440 Jim_fprintf( p
->interp
, p
->interp
->cookie_stderr
, "-------\n");
12445 Jim_GetOpt_Obj( Jim_GetOptInfo
*goi
, Jim_Obj
**puthere
)
12449 o
= NULL
; // failure
12467 Jim_GetOpt_String( Jim_GetOptInfo
*goi
, char **puthere
, int *len
)
12474 r
= Jim_GetOpt_Obj( goi
, &o
);
12476 cp
= Jim_GetString( o
, len
);
12479 *puthere
= (char *)(cp
);
12486 Jim_GetOpt_Double( Jim_GetOptInfo
*goi
, double *puthere
)
12492 if( puthere
== NULL
){
12496 r
= Jim_GetOpt_Obj( goi
, &o
);
12498 r
= Jim_GetDouble( goi
->interp
, o
, puthere
);
12500 Jim_SetResult_sprintf( goi
->interp
,
12501 "not a number: %s",
12502 Jim_GetString( o
, NULL
) );
12509 Jim_GetOpt_Wide( Jim_GetOptInfo
*goi
, jim_wide
*puthere
)
12515 if( puthere
== NULL
){
12519 r
= Jim_GetOpt_Obj( goi
, &o
);
12521 r
= Jim_GetWide( goi
->interp
, o
, puthere
);
12526 int Jim_GetOpt_Nvp( Jim_GetOptInfo
*goi
,
12527 const Jim_Nvp
*nvp
,
12534 if( puthere
== NULL
){
12538 e
= Jim_GetOpt_Obj( goi
, &o
);
12540 e
= Jim_Nvp_name2value_obj( goi
->interp
,
12550 Jim_GetOpt_NvpUnknown( Jim_GetOptInfo
*goi
,
12551 const Jim_Nvp
*nvptable
,
12555 Jim_SetResult_NvpUnknown( goi
->interp
,
12560 Jim_SetResult_NvpUnknown( goi
->interp
,
12569 Jim_GetOpt_Enum( Jim_GetOptInfo
*goi
,
12570 const char * const * lookup
,
12577 if( puthere
== NULL
){
12580 e
= Jim_GetOpt_Obj( goi
, &o
);
12582 e
= Jim_GetEnum( goi
->interp
,
12595 Jim_SetResult_sprintf( Jim_Interp
*interp
, const char *fmt
,... )
12601 buf
= jim_vasprintf( fmt
, ap
);
12604 Jim_SetResultString( interp
, buf
, -1 );
12605 jim_vasprintf_done(buf
);
12612 Jim_SetResult_NvpUnknown( Jim_Interp
*interp
,
12613 Jim_Obj
*param_name
,
12614 Jim_Obj
*param_value
,
12615 const Jim_Nvp
*nvp
)
12618 Jim_SetResult_sprintf( interp
,
12619 "%s: Unknown: %s, try one of: ",
12620 Jim_GetString( param_name
, NULL
),
12621 Jim_GetString( param_value
, NULL
) );
12623 Jim_SetResult_sprintf( interp
,
12624 "Unknown param: %s, try one of: ",
12625 Jim_GetString( param_value
, NULL
) );
12627 while( nvp
->name
){
12631 if( (nvp
+1)->name
){
12638 Jim_AppendStrings( interp
,
12639 Jim_GetResult(interp
),
12646 static Jim_Obj
*debug_string_obj
;
12649 Jim_Debug_ArgvString( Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12653 if( debug_string_obj
){
12654 Jim_FreeObj( interp
, debug_string_obj
);
12657 debug_string_obj
= Jim_NewEmptyStringObj( interp
);
12658 for( x
= 0 ; x
< argc
; x
++ ){
12659 Jim_AppendStrings( interp
,
12661 Jim_GetString( argv
[x
], NULL
),
12666 return Jim_GetString( debug_string_obj
, NULL
);
12672 * Local Variables: ***
12673 * c-basic-offset: 4 ***