7c758ba1ed3810989300e8c0860fd6b1e9166728
[openocd.git] / src / helper / jim.c
1 /* Jim - A small embeddable Tcl interpreter
2 *
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>
10 * Copyright 2008 Steve Bennett <steveb@workware.net.au>
11 *
12 * The FreeBSD license
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 *
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above
21 * copyright notice, this list of conditions and the following
22 * disclaimer in the documentation and/or other materials
23 * provided with the distribution.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
26 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
28 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
30 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
31 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 *
38 * The views and conclusions contained in the software and documentation
39 * are those of the authors and should not be interpreted as representing
40 * official policies, either expressed or implied, of the Jim Tcl Project.
41 **/
42 #define __JIM_CORE__
43 #define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
44
45 #ifdef __ECOS
46 #include <pkgconf/jimtcl.h>
47 #endif
48 #ifndef JIM_ANSIC
49 #define JIM_DYNLIB /* Dynamic library support for UNIX and WIN32 */
50 #endif /* JIM_ANSIC */
51
52 #ifndef _GNU_SOURCE
53 #define _GNU_SOURCE /* for vasprintf() */
54 #endif
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <stdarg.h>
59 #include <ctype.h>
60 #include <limits.h>
61 #include <assert.h>
62 #include <errno.h>
63 #include <time.h>
64 #if defined(WIN32)
65 /* sys/time - need is different */
66 #else
67 #include <sys/time.h> // for gettimeofday()
68 #endif
69
70 #include "replacements.h"
71
72 /* Include the platform dependent libraries for
73 * dynamic loading of libraries. */
74 #ifdef JIM_DYNLIB
75 #if defined(_WIN32) || defined(WIN32)
76 #ifndef WIN32
77 #define WIN32 1
78 #endif
79 #ifndef STRICT
80 #define STRICT
81 #endif
82 #define WIN32_LEAN_AND_MEAN
83 #include <windows.h>
84 #if _MSC_VER >= 1000
85 #pragma warning(disable:4146)
86 #endif /* _MSC_VER */
87 #else
88 #include <dlfcn.h>
89 #endif /* WIN32 */
90 #endif /* JIM_DYNLIB */
91
92 #ifdef HAVE_UNISTD_H
93 #include <unistd.h>
94 #endif
95
96 #ifdef __ECOS
97 #include <cyg/jimtcl/jim.h>
98 #else
99 #include "jim.h"
100 #endif
101
102 #ifdef HAVE_BACKTRACE
103 #include <execinfo.h>
104 #endif
105
106 /* -----------------------------------------------------------------------------
107 * Global variables
108 * ---------------------------------------------------------------------------*/
109
110 /* A shared empty string for the objects string representation.
111 * Jim_InvalidateStringRep knows about it and don't try to free. */
112 static char *JimEmptyStringRep = (char*) "";
113
114 /* -----------------------------------------------------------------------------
115 * Required prototypes of not exported functions
116 * ---------------------------------------------------------------------------*/
117 static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf);
118 static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags);
119 static void JimRegisterCoreApi(Jim_Interp *interp);
120
121 static Jim_HashTableType *getJimVariablesHashTableType(void);
122
123 /* -----------------------------------------------------------------------------
124 * Utility functions
125 * ---------------------------------------------------------------------------*/
126
127 static char *
128 jim_vasprintf( const char *fmt, va_list ap )
129 {
130 #ifndef HAVE_VASPRINTF
131 /* yucky way */
132 static char buf[2048];
133 vsnprintf( buf, sizeof(buf), fmt, ap );
134 /* garentee termination */
135 buf[sizeof(buf)-1] = 0;
136 #else
137 char *buf;
138 int result;
139 result = vasprintf( &buf, fmt, ap );
140 if (result < 0) exit(-1);
141 #endif
142 return buf;
143 }
144
145 static void
146 jim_vasprintf_done( void *buf )
147 {
148 #ifndef HAVE_VASPRINTF
149 (void)(buf);
150 #else
151 free(buf);
152 #endif
153 }
154
155
156 /*
157 * Convert a string to a jim_wide INTEGER.
158 * This function originates from BSD.
159 *
160 * Ignores `locale' stuff. Assumes that the upper and lower case
161 * alphabets and digits are each contiguous.
162 */
163 #ifdef HAVE_LONG_LONG
164 #define JimIsAscii(c) (((c) & ~0x7f) == 0)
165 static jim_wide JimStrtoll(const char *nptr, char **endptr, register int base)
166 {
167 register const char *s;
168 register unsigned jim_wide acc;
169 register unsigned char c;
170 register unsigned jim_wide qbase, cutoff;
171 register int neg, any, cutlim;
172
173 /*
174 * Skip white space and pick up leading +/- sign if any.
175 * If base is 0, allow 0x for hex and 0 for octal, else
176 * assume decimal; if base is already 16, allow 0x.
177 */
178 s = nptr;
179 do {
180 c = *s++;
181 } while (isspace(c));
182 if (c == '-') {
183 neg = 1;
184 c = *s++;
185 } else {
186 neg = 0;
187 if (c == '+')
188 c = *s++;
189 }
190 if ((base == 0 || base == 16) &&
191 c == '0' && (*s == 'x' || *s == 'X')) {
192 c = s[1];
193 s += 2;
194 base = 16;
195 }
196 if (base == 0)
197 base = c == '0' ? 8 : 10;
198
199 /*
200 * Compute the cutoff value between legal numbers and illegal
201 * numbers. That is the largest legal value, divided by the
202 * base. An input number that is greater than this value, if
203 * followed by a legal input character, is too big. One that
204 * is equal to this value may be valid or not; the limit
205 * between valid and invalid numbers is then based on the last
206 * digit. For instance, if the range for quads is
207 * [-9223372036854775808..9223372036854775807] and the input base
208 * is 10, cutoff will be set to 922337203685477580 and cutlim to
209 * either 7 (neg==0) or 8 (neg==1), meaning that if we have
210 * accumulated a value > 922337203685477580, or equal but the
211 * next digit is > 7 (or 8), the number is too big, and we will
212 * return a range error.
213 *
214 * Set any if any `digits' consumed; make it negative to indicate
215 * overflow.
216 */
217 qbase = (unsigned)base;
218 cutoff = neg ? (unsigned jim_wide)-(LLONG_MIN + LLONG_MAX) + LLONG_MAX
219 : LLONG_MAX;
220 cutlim = (int)(cutoff % qbase);
221 cutoff /= qbase;
222 for (acc = 0, any = 0;; c = *s++) {
223 if (!JimIsAscii(c))
224 break;
225 if (isdigit(c))
226 c -= '0';
227 else if (isalpha(c))
228 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
229 else
230 break;
231 if (c >= base)
232 break;
233 if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
234 any = -1;
235 else {
236 any = 1;
237 acc *= qbase;
238 acc += c;
239 }
240 }
241 if (any < 0) {
242 acc = neg ? LLONG_MIN : LLONG_MAX;
243 errno = ERANGE;
244 } else if (neg)
245 acc = -acc;
246 if (endptr != 0)
247 *endptr = (char *)(any ? s - 1 : nptr);
248 return (acc);
249 }
250 #endif
251
252 /* Glob-style pattern matching. */
253 static int JimStringMatch(const char *pattern, int patternLen,
254 const char *string, int stringLen, int nocase)
255 {
256 while(patternLen) {
257 switch(pattern[0]) {
258 case '*':
259 while (pattern[1] == '*') {
260 pattern++;
261 patternLen--;
262 }
263 if (patternLen == 1)
264 return 1; /* match */
265 while(stringLen) {
266 if (JimStringMatch(pattern+1, patternLen-1,
267 string, stringLen, nocase))
268 return 1; /* match */
269 string++;
270 stringLen--;
271 }
272 return 0; /* no match */
273 break;
274 case '?':
275 if (stringLen == 0)
276 return 0; /* no match */
277 string++;
278 stringLen--;
279 break;
280 case '[':
281 {
282 int not, match;
283
284 pattern++;
285 patternLen--;
286 not = pattern[0] == '^';
287 if (not) {
288 pattern++;
289 patternLen--;
290 }
291 match = 0;
292 while(1) {
293 if (pattern[0] == '\\') {
294 pattern++;
295 patternLen--;
296 if (pattern[0] == string[0])
297 match = 1;
298 } else if (pattern[0] == ']') {
299 break;
300 } else if (patternLen == 0) {
301 pattern--;
302 patternLen++;
303 break;
304 } else if (pattern[1] == '-' && patternLen >= 3) {
305 int start = pattern[0];
306 int end = pattern[2];
307 int c = string[0];
308 if (start > end) {
309 int t = start;
310 start = end;
311 end = t;
312 }
313 if (nocase) {
314 start = tolower(start);
315 end = tolower(end);
316 c = tolower(c);
317 }
318 pattern += 2;
319 patternLen -= 2;
320 if (c >= start && c <= end)
321 match = 1;
322 } else {
323 if (!nocase) {
324 if (pattern[0] == string[0])
325 match = 1;
326 } else {
327 if (tolower((int)pattern[0]) == tolower((int)string[0]))
328 match = 1;
329 }
330 }
331 pattern++;
332 patternLen--;
333 }
334 if (not)
335 match = !match;
336 if (!match)
337 return 0; /* no match */
338 string++;
339 stringLen--;
340 break;
341 }
342 case '\\':
343 if (patternLen >= 2) {
344 pattern++;
345 patternLen--;
346 }
347 /* fall through */
348 default:
349 if (!nocase) {
350 if (pattern[0] != string[0])
351 return 0; /* no match */
352 } else {
353 if (tolower((int)pattern[0]) != tolower((int)string[0]))
354 return 0; /* no match */
355 }
356 string++;
357 stringLen--;
358 break;
359 }
360 pattern++;
361 patternLen--;
362 if (stringLen == 0) {
363 while(*pattern == '*') {
364 pattern++;
365 patternLen--;
366 }
367 break;
368 }
369 }
370 if (patternLen == 0 && stringLen == 0)
371 return 1;
372 return 0;
373 }
374
375 int JimStringCompare(const char *s1, int l1, const char *s2, int l2,
376 int nocase)
377 {
378 unsigned char *u1 = (unsigned char*) s1, *u2 = (unsigned char*) s2;
379
380 if (nocase == 0) {
381 while(l1 && l2) {
382 if (*u1 != *u2)
383 return (int)*u1-*u2;
384 u1++; u2++; l1--; l2--;
385 }
386 if (!l1 && !l2) return 0;
387 return l1-l2;
388 } else {
389 while(l1 && l2) {
390 if (tolower((int)*u1) != tolower((int)*u2))
391 return tolower((int)*u1)-tolower((int)*u2);
392 u1++; u2++; l1--; l2--;
393 }
394 if (!l1 && !l2) return 0;
395 return l1-l2;
396 }
397 }
398
399 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
400 * The index of the first occurrence of s1 in s2 is returned.
401 * If s1 is not found inside s2, -1 is returned. */
402 int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int index)
403 {
404 int i;
405
406 if (!l1 || !l2 || l1 > l2) return -1;
407 if (index < 0) index = 0;
408 s2 += index;
409 for (i = index; i <= l2-l1; i++) {
410 if (memcmp(s2, s1, l1) == 0)
411 return i;
412 s2++;
413 }
414 return -1;
415 }
416
417 int Jim_WideToString(char *buf, jim_wide wideValue)
418 {
419 const char *fmt = "%" JIM_WIDE_MODIFIER;
420 return sprintf(buf, fmt, wideValue);
421 }
422
423 int Jim_StringToWide(const char *str, jim_wide *widePtr, int base)
424 {
425 char *endptr;
426
427 #ifdef HAVE_LONG_LONG
428 *widePtr = JimStrtoll(str, &endptr, base);
429 #else
430 *widePtr = strtol(str, &endptr, base);
431 #endif
432 if ((str[0] == '\0') || (str == endptr) )
433 return JIM_ERR;
434 if (endptr[0] != '\0') {
435 while(*endptr) {
436 if (!isspace((int)*endptr))
437 return JIM_ERR;
438 endptr++;
439 }
440 }
441 return JIM_OK;
442 }
443
444 int Jim_StringToIndex(const char *str, int *intPtr)
445 {
446 char *endptr;
447
448 *intPtr = strtol(str, &endptr, 10);
449 if ( (str[0] == '\0') || (str == endptr) )
450 return JIM_ERR;
451 if (endptr[0] != '\0') {
452 while(*endptr) {
453 if (!isspace((int)*endptr))
454 return JIM_ERR;
455 endptr++;
456 }
457 }
458 return JIM_OK;
459 }
460
461 /* The string representation of references has two features in order
462 * to make the GC faster. The first is that every reference starts
463 * with a non common character '~', in order to make the string matching
464 * fater. The second is that the reference string rep his 32 characters
465 * in length, this allows to avoid to check every object with a string
466 * repr < 32, and usually there are many of this objects. */
467
468 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
469
470 static int JimFormatReference(char *buf, Jim_Reference *refPtr, jim_wide id)
471 {
472 const char *fmt = "<reference.<%s>.%020" JIM_WIDE_MODIFIER ">";
473 sprintf(buf, fmt, refPtr->tag, id);
474 return JIM_REFERENCE_SPACE;
475 }
476
477 int Jim_DoubleToString(char *buf, double doubleValue)
478 {
479 char *s;
480 int len;
481
482 len = sprintf(buf, "%.17g", doubleValue);
483 s = buf;
484 while(*s) {
485 if (*s == '.') return len;
486 s++;
487 }
488 /* Add a final ".0" if it's a number. But not
489 * for NaN or InF */
490 if (isdigit((int)buf[0])
491 || ((buf[0] == '-' || buf[0] == '+')
492 && isdigit((int)buf[1]))) {
493 s[0] = '.';
494 s[1] = '0';
495 s[2] = '\0';
496 return len+2;
497 }
498 return len;
499 }
500
501 int Jim_StringToDouble(const char *str, double *doublePtr)
502 {
503 char *endptr;
504
505 *doublePtr = strtod(str, &endptr);
506 if (str[0] == '\0' || endptr[0] != '\0' || (str == endptr) )
507 return JIM_ERR;
508 return JIM_OK;
509 }
510
511 static jim_wide JimPowWide(jim_wide b, jim_wide e)
512 {
513 jim_wide i, res = 1;
514 if ((b==0 && e!=0) || (e<0)) return 0;
515 for(i=0; i<e; i++) {res *= b;}
516 return res;
517 }
518
519 /* -----------------------------------------------------------------------------
520 * Special functions
521 * ---------------------------------------------------------------------------*/
522
523 /* Note that 'interp' may be NULL if not available in the
524 * context of the panic. It's only useful to get the error
525 * file descriptor, it will default to stderr otherwise. */
526 void Jim_Panic(Jim_Interp *interp, const char *fmt, ...)
527 {
528 va_list ap;
529
530 va_start(ap, fmt);
531 /*
532 * Send it here first.. Assuming STDIO still works
533 */
534 fprintf(stderr, JIM_NL "JIM INTERPRETER PANIC: ");
535 vfprintf(stderr, fmt, ap);
536 fprintf(stderr, JIM_NL JIM_NL);
537 va_end(ap);
538
539 #ifdef HAVE_BACKTRACE
540 {
541 void *array[40];
542 int size, i;
543 char **strings;
544
545 size = backtrace(array, 40);
546 strings = backtrace_symbols(array, size);
547 for (i = 0; i < size; i++)
548 fprintf(fp,"[backtrace] %s" JIM_NL, strings[i]);
549 fprintf(fp,"[backtrace] Include the above lines and the output" JIM_NL);
550 fprintf(fp,"[backtrace] of 'nm <executable>' in the bug report." JIM_NL);
551 }
552 #endif
553
554 /* This may actually crash... we do it last */
555 if( interp && interp->cookie_stderr ){
556 Jim_fprintf( interp, interp->cookie_stderr, JIM_NL "JIM INTERPRETER PANIC: ");
557 Jim_vfprintf( interp, interp->cookie_stderr, fmt, ap );
558 Jim_fprintf( interp, interp->cookie_stderr, JIM_NL JIM_NL );
559 }
560 abort();
561 }
562
563 /* -----------------------------------------------------------------------------
564 * Memory allocation
565 * ---------------------------------------------------------------------------*/
566
567 /* Macro used for memory debugging.
568 * In order for they to work you have to rename Jim_Alloc into _Jim_Alloc
569 * and similary for Jim_Realloc and Jim_Free */
570 #if 0
571 #define Jim_Alloc(s) (printf("%s %d: Jim_Alloc(%d)\n",__FILE__,__LINE__,s),_Jim_Alloc(s))
572 #define Jim_Free(p) (printf("%s %d: Jim_Free(%p)\n",__FILE__,__LINE__,p),_Jim_Free(p))
573 #define Jim_Realloc(p,s) (printf("%s %d: Jim_Realloc(%p,%d)\n",__FILE__,__LINE__,p,s),_Jim_Realloc(p,s))
574 #endif
575
576 void *Jim_Alloc(int size)
577 {
578 /* We allocate zero length arrayes, etc. to use a single orthogonal codepath */
579 if (size==0)
580 size=1;
581 void *p = malloc(size);
582 if (p == NULL)
583 Jim_Panic(NULL,"malloc: Out of memory");
584 return p;
585 }
586
587 void Jim_Free(void *ptr) {
588 free(ptr);
589 }
590
591 void *Jim_Realloc(void *ptr, int size)
592 {
593 /* We allocate zero length arrayes, etc. to use a single orthogonal codepath */
594 if (size==0)
595 size=1;
596 void *p = realloc(ptr, size);
597 if (p == NULL)
598 Jim_Panic(NULL,"realloc: Out of memory");
599 return p;
600 }
601
602 char *Jim_StrDup(const char *s)
603 {
604 int l = strlen(s);
605 char *copy = Jim_Alloc(l+1);
606
607 memcpy(copy, s, l+1);
608 return copy;
609 }
610
611 char *Jim_StrDupLen(const char *s, int l)
612 {
613 char *copy = Jim_Alloc(l+1);
614
615 memcpy(copy, s, l+1);
616 copy[l] = 0; /* Just to be sure, original could be substring */
617 return copy;
618 }
619
620 /* -----------------------------------------------------------------------------
621 * Time related functions
622 * ---------------------------------------------------------------------------*/
623 /* Returns microseconds of CPU used since start. */
624 static jim_wide JimClock(void)
625 {
626 #if (defined WIN32) && !(defined JIM_ANSIC)
627 LARGE_INTEGER t, f;
628 QueryPerformanceFrequency(&f);
629 QueryPerformanceCounter(&t);
630 return (long)((t.QuadPart * 1000000) / f.QuadPart);
631 #else /* !WIN32 */
632 clock_t clocks = clock();
633
634 return (long)(clocks*(1000000/CLOCKS_PER_SEC));
635 #endif /* WIN32 */
636 }
637
638 /* -----------------------------------------------------------------------------
639 * Hash Tables
640 * ---------------------------------------------------------------------------*/
641
642 /* -------------------------- private prototypes ---------------------------- */
643 static int JimExpandHashTableIfNeeded(Jim_HashTable *ht);
644 static unsigned int JimHashTableNextPower(unsigned int size);
645 static int JimInsertHashEntry(Jim_HashTable *ht, const void *key);
646
647 /* -------------------------- hash functions -------------------------------- */
648
649 /* Thomas Wang's 32 bit Mix Function */
650 unsigned int Jim_IntHashFunction(unsigned int key)
651 {
652 key += ~(key << 15);
653 key ^= (key >> 10);
654 key += (key << 3);
655 key ^= (key >> 6);
656 key += ~(key << 11);
657 key ^= (key >> 16);
658 return key;
659 }
660
661 /* Identity hash function for integer keys */
662 unsigned int Jim_IdentityHashFunction(unsigned int key)
663 {
664 return key;
665 }
666
667 /* Generic hash function (we are using to multiply by 9 and add the byte
668 * as Tcl) */
669 unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
670 {
671 unsigned int h = 0;
672 while(len--)
673 h += (h<<3)+*buf++;
674 return h;
675 }
676
677 /* ----------------------------- API implementation ------------------------- */
678 /* reset an hashtable already initialized with ht_init().
679 * NOTE: This function should only called by ht_destroy(). */
680 static void JimResetHashTable(Jim_HashTable *ht)
681 {
682 ht->table = NULL;
683 ht->size = 0;
684 ht->sizemask = 0;
685 ht->used = 0;
686 ht->collisions = 0;
687 }
688
689 /* Initialize the hash table */
690 int Jim_InitHashTable(Jim_HashTable *ht, Jim_HashTableType *type,
691 void *privDataPtr)
692 {
693 JimResetHashTable(ht);
694 ht->type = type;
695 ht->privdata = privDataPtr;
696 return JIM_OK;
697 }
698
699 /* Resize the table to the minimal size that contains all the elements,
700 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
701 int Jim_ResizeHashTable(Jim_HashTable *ht)
702 {
703 int minimal = ht->used;
704
705 if (minimal < JIM_HT_INITIAL_SIZE)
706 minimal = JIM_HT_INITIAL_SIZE;
707 return Jim_ExpandHashTable(ht, minimal);
708 }
709
710 /* Expand or create the hashtable */
711 int Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
712 {
713 Jim_HashTable n; /* the new hashtable */
714 unsigned int realsize = JimHashTableNextPower(size), i;
715
716 /* the size is invalid if it is smaller than the number of
717 * elements already inside the hashtable */
718 if (ht->used >= size)
719 return JIM_ERR;
720
721 Jim_InitHashTable(&n, ht->type, ht->privdata);
722 n.size = realsize;
723 n.sizemask = realsize-1;
724 n.table = Jim_Alloc(realsize*sizeof(Jim_HashEntry*));
725
726 /* Initialize all the pointers to NULL */
727 memset(n.table, 0, realsize*sizeof(Jim_HashEntry*));
728
729 /* Copy all the elements from the old to the new table:
730 * note that if the old hash table is empty ht->size is zero,
731 * so Jim_ExpandHashTable just creates an hash table. */
732 n.used = ht->used;
733 for (i = 0; i < ht->size && ht->used > 0; i++) {
734 Jim_HashEntry *he, *nextHe;
735
736 if (ht->table[i] == NULL) continue;
737
738 /* For each hash entry on this slot... */
739 he = ht->table[i];
740 while(he) {
741 unsigned int h;
742
743 nextHe = he->next;
744 /* Get the new element index */
745 h = Jim_HashKey(ht, he->key) & n.sizemask;
746 he->next = n.table[h];
747 n.table[h] = he;
748 ht->used--;
749 /* Pass to the next element */
750 he = nextHe;
751 }
752 }
753 assert(ht->used == 0);
754 Jim_Free(ht->table);
755
756 /* Remap the new hashtable in the old */
757 *ht = n;
758 return JIM_OK;
759 }
760
761 /* Add an element to the target hash table */
762 int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
763 {
764 int index;
765 Jim_HashEntry *entry;
766
767 /* Get the index of the new element, or -1 if
768 * the element already exists. */
769 if ((index = JimInsertHashEntry(ht, key)) == -1)
770 return JIM_ERR;
771
772 /* Allocates the memory and stores key */
773 entry = Jim_Alloc(sizeof(*entry));
774 entry->next = ht->table[index];
775 ht->table[index] = entry;
776
777 /* Set the hash entry fields. */
778 Jim_SetHashKey(ht, entry, key);
779 Jim_SetHashVal(ht, entry, val);
780 ht->used++;
781 return JIM_OK;
782 }
783
784 /* Add an element, discarding the old if the key already exists */
785 int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
786 {
787 Jim_HashEntry *entry;
788
789 /* Try to add the element. If the key
790 * does not exists Jim_AddHashEntry will suceed. */
791 if (Jim_AddHashEntry(ht, key, val) == JIM_OK)
792 return JIM_OK;
793 /* It already exists, get the entry */
794 entry = Jim_FindHashEntry(ht, key);
795 /* Free the old value and set the new one */
796 Jim_FreeEntryVal(ht, entry);
797 Jim_SetHashVal(ht, entry, val);
798 return JIM_OK;
799 }
800
801 /* Search and remove an element */
802 int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
803 {
804 unsigned int h;
805 Jim_HashEntry *he, *prevHe;
806
807 if (ht->size == 0)
808 return JIM_ERR;
809 h = Jim_HashKey(ht, key) & ht->sizemask;
810 he = ht->table[h];
811
812 prevHe = NULL;
813 while(he) {
814 if (Jim_CompareHashKeys(ht, key, he->key)) {
815 /* Unlink the element from the list */
816 if (prevHe)
817 prevHe->next = he->next;
818 else
819 ht->table[h] = he->next;
820 Jim_FreeEntryKey(ht, he);
821 Jim_FreeEntryVal(ht, he);
822 Jim_Free(he);
823 ht->used--;
824 return JIM_OK;
825 }
826 prevHe = he;
827 he = he->next;
828 }
829 return JIM_ERR; /* not found */
830 }
831
832 /* Destroy an entire hash table */
833 int Jim_FreeHashTable(Jim_HashTable *ht)
834 {
835 unsigned int i;
836
837 /* Free all the elements */
838 for (i = 0; i < ht->size && ht->used > 0; i++) {
839 Jim_HashEntry *he, *nextHe;
840
841 if ((he = ht->table[i]) == NULL) continue;
842 while(he) {
843 nextHe = he->next;
844 Jim_FreeEntryKey(ht, he);
845 Jim_FreeEntryVal(ht, he);
846 Jim_Free(he);
847 ht->used--;
848 he = nextHe;
849 }
850 }
851 /* Free the table and the allocated cache structure */
852 Jim_Free(ht->table);
853 /* Re-initialize the table */
854 JimResetHashTable(ht);
855 return JIM_OK; /* never fails */
856 }
857
858 Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
859 {
860 Jim_HashEntry *he;
861 unsigned int h;
862
863 if (ht->size == 0) return NULL;
864 h = Jim_HashKey(ht, key) & ht->sizemask;
865 he = ht->table[h];
866 while(he) {
867 if (Jim_CompareHashKeys(ht, key, he->key))
868 return he;
869 he = he->next;
870 }
871 return NULL;
872 }
873
874 Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
875 {
876 Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
877
878 iter->ht = ht;
879 iter->index = -1;
880 iter->entry = NULL;
881 iter->nextEntry = NULL;
882 return iter;
883 }
884
885 Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
886 {
887 while (1) {
888 if (iter->entry == NULL) {
889 iter->index++;
890 if (iter->index >=
891 (signed)iter->ht->size) break;
892 iter->entry = iter->ht->table[iter->index];
893 } else {
894 iter->entry = iter->nextEntry;
895 }
896 if (iter->entry) {
897 /* We need to save the 'next' here, the iterator user
898 * may delete the entry we are returning. */
899 iter->nextEntry = iter->entry->next;
900 return iter->entry;
901 }
902 }
903 return NULL;
904 }
905
906 /* ------------------------- private functions ------------------------------ */
907
908 /* Expand the hash table if needed */
909 static int JimExpandHashTableIfNeeded(Jim_HashTable *ht)
910 {
911 /* If the hash table is empty expand it to the intial size,
912 * if the table is "full" dobule its size. */
913 if (ht->size == 0)
914 return Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
915 if (ht->size == ht->used)
916 return Jim_ExpandHashTable(ht, ht->size*2);
917 return JIM_OK;
918 }
919
920 /* Our hash table capability is a power of two */
921 static unsigned int JimHashTableNextPower(unsigned int size)
922 {
923 unsigned int i = JIM_HT_INITIAL_SIZE;
924
925 if (size >= 2147483648U)
926 return 2147483648U;
927 while(1) {
928 if (i >= size)
929 return i;
930 i *= 2;
931 }
932 }
933
934 /* Returns the index of a free slot that can be populated with
935 * an hash entry for the given 'key'.
936 * If the key already exists, -1 is returned. */
937 static int JimInsertHashEntry(Jim_HashTable *ht, const void *key)
938 {
939 unsigned int h;
940 Jim_HashEntry *he;
941
942 /* Expand the hashtable if needed */
943 if (JimExpandHashTableIfNeeded(ht) == JIM_ERR)
944 return -1;
945 /* Compute the key hash value */
946 h = Jim_HashKey(ht, key) & ht->sizemask;
947 /* Search if this slot does not already contain the given key */
948 he = ht->table[h];
949 while(he) {
950 if (Jim_CompareHashKeys(ht, key, he->key))
951 return -1;
952 he = he->next;
953 }
954 return h;
955 }
956
957 /* ----------------------- StringCopy Hash Table Type ------------------------*/
958
959 static unsigned int JimStringCopyHTHashFunction(const void *key)
960 {
961 return Jim_GenHashFunction(key, strlen(key));
962 }
963
964 static const void *JimStringCopyHTKeyDup(void *privdata, const void *key)
965 {
966 int len = strlen(key);
967 char *copy = Jim_Alloc(len+1);
968 JIM_NOTUSED(privdata);
969
970 memcpy(copy, key, len);
971 copy[len] = '\0';
972 return copy;
973 }
974
975 static void *JimStringKeyValCopyHTValDup(void *privdata, const void *val)
976 {
977 int len = strlen(val);
978 char *copy = Jim_Alloc(len+1);
979 JIM_NOTUSED(privdata);
980
981 memcpy(copy, val, len);
982 copy[len] = '\0';
983 return copy;
984 }
985
986 static int JimStringCopyHTKeyCompare(void *privdata, const void *key1,
987 const void *key2)
988 {
989 JIM_NOTUSED(privdata);
990
991 return strcmp(key1, key2) == 0;
992 }
993
994 static void JimStringCopyHTKeyDestructor(void *privdata, const void *key)
995 {
996 JIM_NOTUSED(privdata);
997
998 Jim_Free((void*)key); /* ATTENTION: const cast */
999 }
1000
1001 static void JimStringKeyValCopyHTValDestructor(void *privdata, void *val)
1002 {
1003 JIM_NOTUSED(privdata);
1004
1005 Jim_Free((void*)val); /* ATTENTION: const cast */
1006 }
1007
1008 static Jim_HashTableType JimStringCopyHashTableType = {
1009 JimStringCopyHTHashFunction, /* hash function */
1010 JimStringCopyHTKeyDup, /* key dup */
1011 NULL, /* val dup */
1012 JimStringCopyHTKeyCompare, /* key compare */
1013 JimStringCopyHTKeyDestructor, /* key destructor */
1014 NULL /* val destructor */
1015 };
1016
1017 /* This is like StringCopy but does not auto-duplicate the key.
1018 * It's used for intepreter's shared strings. */
1019 static Jim_HashTableType JimSharedStringsHashTableType = {
1020 JimStringCopyHTHashFunction, /* hash function */
1021 NULL, /* key dup */
1022 NULL, /* val dup */
1023 JimStringCopyHTKeyCompare, /* key compare */
1024 JimStringCopyHTKeyDestructor, /* key destructor */
1025 NULL /* val destructor */
1026 };
1027
1028 /* This is like StringCopy but also automatically handle dynamic
1029 * allocated C strings as values. */
1030 static Jim_HashTableType JimStringKeyValCopyHashTableType = {
1031 JimStringCopyHTHashFunction, /* hash function */
1032 JimStringCopyHTKeyDup, /* key dup */
1033 JimStringKeyValCopyHTValDup, /* val dup */
1034 JimStringCopyHTKeyCompare, /* key compare */
1035 JimStringCopyHTKeyDestructor, /* key destructor */
1036 JimStringKeyValCopyHTValDestructor, /* val destructor */
1037 };
1038
1039 typedef struct AssocDataValue {
1040 Jim_InterpDeleteProc *delProc;
1041 void *data;
1042 } AssocDataValue;
1043
1044 static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
1045 {
1046 AssocDataValue *assocPtr = (AssocDataValue *)data;
1047 if (assocPtr->delProc != NULL)
1048 assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
1049 Jim_Free(data);
1050 }
1051
1052 static Jim_HashTableType JimAssocDataHashTableType = {
1053 JimStringCopyHTHashFunction, /* hash function */
1054 JimStringCopyHTKeyDup, /* key dup */
1055 NULL, /* val dup */
1056 JimStringCopyHTKeyCompare, /* key compare */
1057 JimStringCopyHTKeyDestructor, /* key destructor */
1058 JimAssocDataHashTableValueDestructor /* val destructor */
1059 };
1060
1061 /* -----------------------------------------------------------------------------
1062 * Stack - This is a simple generic stack implementation. It is used for
1063 * example in the 'expr' expression compiler.
1064 * ---------------------------------------------------------------------------*/
1065 void Jim_InitStack(Jim_Stack *stack)
1066 {
1067 stack->len = 0;
1068 stack->maxlen = 0;
1069 stack->vector = NULL;
1070 }
1071
1072 void Jim_FreeStack(Jim_Stack *stack)
1073 {
1074 Jim_Free(stack->vector);
1075 }
1076
1077 int Jim_StackLen(Jim_Stack *stack)
1078 {
1079 return stack->len;
1080 }
1081
1082 void Jim_StackPush(Jim_Stack *stack, void *element) {
1083 int neededLen = stack->len+1;
1084 if (neededLen > stack->maxlen) {
1085 stack->maxlen = neededLen*2;
1086 stack->vector = Jim_Realloc(stack->vector, sizeof(void*)*stack->maxlen);
1087 }
1088 stack->vector[stack->len] = element;
1089 stack->len++;
1090 }
1091
1092 void *Jim_StackPop(Jim_Stack *stack)
1093 {
1094 if (stack->len == 0) return NULL;
1095 stack->len--;
1096 return stack->vector[stack->len];
1097 }
1098
1099 void *Jim_StackPeek(Jim_Stack *stack)
1100 {
1101 if (stack->len == 0) return NULL;
1102 return stack->vector[stack->len-1];
1103 }
1104
1105 void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr))
1106 {
1107 int i;
1108
1109 for (i = 0; i < stack->len; i++)
1110 freeFunc(stack->vector[i]);
1111 }
1112
1113 /* -----------------------------------------------------------------------------
1114 * Parser
1115 * ---------------------------------------------------------------------------*/
1116
1117 /* Token types */
1118 #define JIM_TT_NONE -1 /* No token returned */
1119 #define JIM_TT_STR 0 /* simple string */
1120 #define JIM_TT_ESC 1 /* string that needs escape chars conversion */
1121 #define JIM_TT_VAR 2 /* var substitution */
1122 #define JIM_TT_DICTSUGAR 3 /* Syntax sugar for [dict get], $foo(bar) */
1123 #define JIM_TT_CMD 4 /* command substitution */
1124 #define JIM_TT_SEP 5 /* word separator */
1125 #define JIM_TT_EOL 6 /* line separator */
1126
1127 /* Additional token types needed for expressions */
1128 #define JIM_TT_SUBEXPR_START 7
1129 #define JIM_TT_SUBEXPR_END 8
1130 #define JIM_TT_EXPR_NUMBER 9
1131 #define JIM_TT_EXPR_OPERATOR 10
1132
1133 /* Parser states */
1134 #define JIM_PS_DEF 0 /* Default state */
1135 #define JIM_PS_QUOTE 1 /* Inside "" */
1136
1137 /* Parser context structure. The same context is used both to parse
1138 * Tcl scripts and lists. */
1139 struct JimParserCtx {
1140 const char *prg; /* Program text */
1141 const char *p; /* Pointer to the point of the program we are parsing */
1142 int len; /* Left length of 'prg' */
1143 int linenr; /* Current line number */
1144 const char *tstart;
1145 const char *tend; /* Returned token is at tstart-tend in 'prg'. */
1146 int tline; /* Line number of the returned token */
1147 int tt; /* Token type */
1148 int eof; /* Non zero if EOF condition is true. */
1149 int state; /* Parser state */
1150 int comment; /* Non zero if the next chars may be a comment. */
1151 };
1152
1153 #define JimParserEof(c) ((c)->eof)
1154 #define JimParserTstart(c) ((c)->tstart)
1155 #define JimParserTend(c) ((c)->tend)
1156 #define JimParserTtype(c) ((c)->tt)
1157 #define JimParserTline(c) ((c)->tline)
1158
1159 static int JimParseScript(struct JimParserCtx *pc);
1160 static int JimParseSep(struct JimParserCtx *pc);
1161 static int JimParseEol(struct JimParserCtx *pc);
1162 static int JimParseCmd(struct JimParserCtx *pc);
1163 static int JimParseVar(struct JimParserCtx *pc);
1164 static int JimParseBrace(struct JimParserCtx *pc);
1165 static int JimParseStr(struct JimParserCtx *pc);
1166 static int JimParseComment(struct JimParserCtx *pc);
1167 static char *JimParserGetToken(struct JimParserCtx *pc,
1168 int *lenPtr, int *typePtr, int *linePtr);
1169
1170 /* Initialize a parser context.
1171 * 'prg' is a pointer to the program text, linenr is the line
1172 * number of the first line contained in the program. */
1173 void JimParserInit(struct JimParserCtx *pc, const char *prg,
1174 int len, int linenr)
1175 {
1176 pc->prg = prg;
1177 pc->p = prg;
1178 pc->len = len;
1179 pc->tstart = NULL;
1180 pc->tend = NULL;
1181 pc->tline = 0;
1182 pc->tt = JIM_TT_NONE;
1183 pc->eof = 0;
1184 pc->state = JIM_PS_DEF;
1185 pc->linenr = linenr;
1186 pc->comment = 1;
1187 }
1188
1189 int JimParseScript(struct JimParserCtx *pc)
1190 {
1191 while(1) { /* the while is used to reiterate with continue if needed */
1192 if (!pc->len) {
1193 pc->tstart = pc->p;
1194 pc->tend = pc->p-1;
1195 pc->tline = pc->linenr;
1196 pc->tt = JIM_TT_EOL;
1197 pc->eof = 1;
1198 return JIM_OK;
1199 }
1200 switch(*(pc->p)) {
1201 case '\\':
1202 if (*(pc->p+1) == '\n')
1203 return JimParseSep(pc);
1204 else {
1205 pc->comment = 0;
1206 return JimParseStr(pc);
1207 }
1208 break;
1209 case ' ':
1210 case '\t':
1211 case '\r':
1212 if (pc->state == JIM_PS_DEF)
1213 return JimParseSep(pc);
1214 else {
1215 pc->comment = 0;
1216 return JimParseStr(pc);
1217 }
1218 break;
1219 case '\n':
1220 case ';':
1221 pc->comment = 1;
1222 if (pc->state == JIM_PS_DEF)
1223 return JimParseEol(pc);
1224 else
1225 return JimParseStr(pc);
1226 break;
1227 case '[':
1228 pc->comment = 0;
1229 return JimParseCmd(pc);
1230 break;
1231 case '$':
1232 pc->comment = 0;
1233 if (JimParseVar(pc) == JIM_ERR) {
1234 pc->tstart = pc->tend = pc->p++; pc->len--;
1235 pc->tline = pc->linenr;
1236 pc->tt = JIM_TT_STR;
1237 return JIM_OK;
1238 } else
1239 return JIM_OK;
1240 break;
1241 case '#':
1242 if (pc->comment) {
1243 JimParseComment(pc);
1244 continue;
1245 } else {
1246 return JimParseStr(pc);
1247 }
1248 default:
1249 pc->comment = 0;
1250 return JimParseStr(pc);
1251 break;
1252 }
1253 return JIM_OK;
1254 }
1255 }
1256
1257 int JimParseSep(struct JimParserCtx *pc)
1258 {
1259 pc->tstart = pc->p;
1260 pc->tline = pc->linenr;
1261 while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' ||
1262 (*pc->p == '\\' && *(pc->p+1) == '\n')) {
1263 if (*pc->p == '\\') {
1264 pc->p++; pc->len--;
1265 pc->linenr++;
1266 }
1267 pc->p++; pc->len--;
1268 }
1269 pc->tend = pc->p-1;
1270 pc->tt = JIM_TT_SEP;
1271 return JIM_OK;
1272 }
1273
1274 int JimParseEol(struct JimParserCtx *pc)
1275 {
1276 pc->tstart = pc->p;
1277 pc->tline = pc->linenr;
1278 while (*pc->p == ' ' || *pc->p == '\n' ||
1279 *pc->p == '\t' || *pc->p == '\r' || *pc->p == ';') {
1280 if (*pc->p == '\n')
1281 pc->linenr++;
1282 pc->p++; pc->len--;
1283 }
1284 pc->tend = pc->p-1;
1285 pc->tt = JIM_TT_EOL;
1286 return JIM_OK;
1287 }
1288
1289 /* Todo. Don't stop if ']' appears inside {} or quoted.
1290 * Also should handle the case of puts [string length "]"] */
1291 int JimParseCmd(struct JimParserCtx *pc)
1292 {
1293 int level = 1;
1294 int blevel = 0;
1295
1296 pc->tstart = ++pc->p; pc->len--;
1297 pc->tline = pc->linenr;
1298 while (1) {
1299 if (pc->len == 0) {
1300 break;
1301 } else if (*pc->p == '[' && blevel == 0) {
1302 level++;
1303 } else if (*pc->p == ']' && blevel == 0) {
1304 level--;
1305 if (!level) break;
1306 } else if (*pc->p == '\\') {
1307 pc->p++; pc->len--;
1308 } else if (*pc->p == '{') {
1309 blevel++;
1310 } else if (*pc->p == '}') {
1311 if (blevel != 0)
1312 blevel--;
1313 } else if (*pc->p == '\n')
1314 pc->linenr++;
1315 pc->p++; pc->len--;
1316 }
1317 pc->tend = pc->p-1;
1318 pc->tt = JIM_TT_CMD;
1319 if (*pc->p == ']') {
1320 pc->p++; pc->len--;
1321 }
1322 return JIM_OK;
1323 }
1324
1325 int JimParseVar(struct JimParserCtx *pc)
1326 {
1327 int brace = 0, stop = 0, ttype = JIM_TT_VAR;
1328
1329 pc->tstart = ++pc->p; pc->len--; /* skip the $ */
1330 pc->tline = pc->linenr;
1331 if (*pc->p == '{') {
1332 pc->tstart = ++pc->p; pc->len--;
1333 brace = 1;
1334 }
1335 if (brace) {
1336 while (!stop) {
1337 if (*pc->p == '}' || pc->len == 0) {
1338 pc->tend = pc->p-1;
1339 stop = 1;
1340 if (pc->len == 0)
1341 break;
1342 }
1343 else if (*pc->p == '\n')
1344 pc->linenr++;
1345 pc->p++; pc->len--;
1346 }
1347 } else {
1348 /* Include leading colons */
1349 while (*pc->p == ':') {
1350 pc->p++;
1351 pc->len--;
1352 }
1353 while (!stop) {
1354 if (!((*pc->p >= 'a' && *pc->p <= 'z') ||
1355 (*pc->p >= 'A' && *pc->p <= 'Z') ||
1356 (*pc->p >= '0' && *pc->p <= '9') || *pc->p == '_'))
1357 stop = 1;
1358 else {
1359 pc->p++; pc->len--;
1360 }
1361 }
1362 /* Parse [dict get] syntax sugar. */
1363 if (*pc->p == '(') {
1364 while (*pc->p != ')' && pc->len) {
1365 pc->p++; pc->len--;
1366 if (*pc->p == '\\' && pc->len >= 2) {
1367 pc->p += 2; pc->len -= 2;
1368 }
1369 }
1370 if (*pc->p != '\0') {
1371 pc->p++; pc->len--;
1372 }
1373 ttype = JIM_TT_DICTSUGAR;
1374 }
1375 pc->tend = pc->p-1;
1376 }
1377 /* Check if we parsed just the '$' character.
1378 * That's not a variable so an error is returned
1379 * to tell the state machine to consider this '$' just
1380 * a string. */
1381 if (pc->tstart == pc->p) {
1382 pc->p--; pc->len++;
1383 return JIM_ERR;
1384 }
1385 pc->tt = ttype;
1386 return JIM_OK;
1387 }
1388
1389 int JimParseBrace(struct JimParserCtx *pc)
1390 {
1391 int level = 1;
1392
1393 pc->tstart = ++pc->p; pc->len--;
1394 pc->tline = pc->linenr;
1395 while (1) {
1396 if (*pc->p == '\\' && pc->len >= 2) {
1397 pc->p++; pc->len--;
1398 if (*pc->p == '\n')
1399 pc->linenr++;
1400 } else if (*pc->p == '{') {
1401 level++;
1402 } else if (pc->len == 0 || *pc->p == '}') {
1403 level--;
1404 if (pc->len == 0 || level == 0) {
1405 pc->tend = pc->p-1;
1406 if (pc->len != 0) {
1407 pc->p++; pc->len--;
1408 }
1409 pc->tt = JIM_TT_STR;
1410 return JIM_OK;
1411 }
1412 } else if (*pc->p == '\n') {
1413 pc->linenr++;
1414 }
1415 pc->p++; pc->len--;
1416 }
1417 return JIM_OK; /* unreached */
1418 }
1419
1420 int JimParseStr(struct JimParserCtx *pc)
1421 {
1422 int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
1423 pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR);
1424 if (newword && *pc->p == '{') {
1425 return JimParseBrace(pc);
1426 } else if (newword && *pc->p == '"') {
1427 pc->state = JIM_PS_QUOTE;
1428 pc->p++; pc->len--;
1429 }
1430 pc->tstart = pc->p;
1431 pc->tline = pc->linenr;
1432 while (1) {
1433 if (pc->len == 0) {
1434 pc->tend = pc->p-1;
1435 pc->tt = JIM_TT_ESC;
1436 return JIM_OK;
1437 }
1438 switch(*pc->p) {
1439 case '\\':
1440 if (pc->state == JIM_PS_DEF &&
1441 *(pc->p+1) == '\n') {
1442 pc->tend = pc->p-1;
1443 pc->tt = JIM_TT_ESC;
1444 return JIM_OK;
1445 }
1446 if (pc->len >= 2) {
1447 pc->p++; pc->len--;
1448 }
1449 break;
1450 case '$':
1451 case '[':
1452 pc->tend = pc->p-1;
1453 pc->tt = JIM_TT_ESC;
1454 return JIM_OK;
1455 case ' ':
1456 case '\t':
1457 case '\n':
1458 case '\r':
1459 case ';':
1460 if (pc->state == JIM_PS_DEF) {
1461 pc->tend = pc->p-1;
1462 pc->tt = JIM_TT_ESC;
1463 return JIM_OK;
1464 } else if (*pc->p == '\n') {
1465 pc->linenr++;
1466 }
1467 break;
1468 case '"':
1469 if (pc->state == JIM_PS_QUOTE) {
1470 pc->tend = pc->p-1;
1471 pc->tt = JIM_TT_ESC;
1472 pc->p++; pc->len--;
1473 pc->state = JIM_PS_DEF;
1474 return JIM_OK;
1475 }
1476 break;
1477 }
1478 pc->p++; pc->len--;
1479 }
1480 return JIM_OK; /* unreached */
1481 }
1482
1483 int JimParseComment(struct JimParserCtx *pc)
1484 {
1485 while (*pc->p) {
1486 if (*pc->p == '\n') {
1487 pc->linenr++;
1488 if (*(pc->p-1) != '\\') {
1489 pc->p++; pc->len--;
1490 return JIM_OK;
1491 }
1492 }
1493 pc->p++; pc->len--;
1494 }
1495 return JIM_OK;
1496 }
1497
1498 /* xdigitval and odigitval are helper functions for JimParserGetToken() */
1499 static int xdigitval(int c)
1500 {
1501 if (c >= '0' && c <= '9') return c-'0';
1502 if (c >= 'a' && c <= 'f') return c-'a'+10;
1503 if (c >= 'A' && c <= 'F') return c-'A'+10;
1504 return -1;
1505 }
1506
1507 static int odigitval(int c)
1508 {
1509 if (c >= '0' && c <= '7') return c-'0';
1510 return -1;
1511 }
1512
1513 /* Perform Tcl escape substitution of 's', storing the result
1514 * string into 'dest'. The escaped string is guaranteed to
1515 * be the same length or shorted than the source string.
1516 * Slen is the length of the string at 's', if it's -1 the string
1517 * length will be calculated by the function.
1518 *
1519 * The function returns the length of the resulting string. */
1520 static int JimEscape(char *dest, const char *s, int slen)
1521 {
1522 char *p = dest;
1523 int i, len;
1524
1525 if (slen == -1)
1526 slen = strlen(s);
1527
1528 for (i = 0; i < slen; i++) {
1529 switch(s[i]) {
1530 case '\\':
1531 switch(s[i+1]) {
1532 case 'a': *p++ = 0x7; i++; break;
1533 case 'b': *p++ = 0x8; i++; break;
1534 case 'f': *p++ = 0xc; i++; break;
1535 case 'n': *p++ = 0xa; i++; break;
1536 case 'r': *p++ = 0xd; i++; break;
1537 case 't': *p++ = 0x9; i++; break;
1538 case 'v': *p++ = 0xb; i++; break;
1539 case '\0': *p++ = '\\'; i++; break;
1540 case '\n': *p++ = ' '; i++; break;
1541 default:
1542 if (s[i+1] == 'x') {
1543 int val = 0;
1544 int c = xdigitval(s[i+2]);
1545 if (c == -1) {
1546 *p++ = 'x';
1547 i++;
1548 break;
1549 }
1550 val = c;
1551 c = xdigitval(s[i+3]);
1552 if (c == -1) {
1553 *p++ = val;
1554 i += 2;
1555 break;
1556 }
1557 val = (val*16)+c;
1558 *p++ = val;
1559 i += 3;
1560 break;
1561 } else if (s[i+1] >= '0' && s[i+1] <= '7')
1562 {
1563 int val = 0;
1564 int c = odigitval(s[i+1]);
1565 val = c;
1566 c = odigitval(s[i+2]);
1567 if (c == -1) {
1568 *p++ = val;
1569 i ++;
1570 break;
1571 }
1572 val = (val*8)+c;
1573 c = odigitval(s[i+3]);
1574 if (c == -1) {
1575 *p++ = val;
1576 i += 2;
1577 break;
1578 }
1579 val = (val*8)+c;
1580 *p++ = val;
1581 i += 3;
1582 } else {
1583 *p++ = s[i+1];
1584 i++;
1585 }
1586 break;
1587 }
1588 break;
1589 default:
1590 *p++ = s[i];
1591 break;
1592 }
1593 }
1594 len = p-dest;
1595 *p++ = '\0';
1596 return len;
1597 }
1598
1599 /* Returns a dynamically allocated copy of the current token in the
1600 * parser context. The function perform conversion of escapes if
1601 * the token is of type JIM_TT_ESC.
1602 *
1603 * Note that after the conversion, tokens that are grouped with
1604 * braces in the source code, are always recognizable from the
1605 * identical string obtained in a different way from the type.
1606 *
1607 * For exmple the string:
1608 *
1609 * {expand}$a
1610 *
1611 * will return as first token "expand", of type JIM_TT_STR
1612 *
1613 * While the string:
1614 *
1615 * expand$a
1616 *
1617 * will return as first token "expand", of type JIM_TT_ESC
1618 */
1619 char *JimParserGetToken(struct JimParserCtx *pc,
1620 int *lenPtr, int *typePtr, int *linePtr)
1621 {
1622 const char *start, *end;
1623 char *token;
1624 int len;
1625
1626 start = JimParserTstart(pc);
1627 end = JimParserTend(pc);
1628 if (start > end) {
1629 if (lenPtr) *lenPtr = 0;
1630 if (typePtr) *typePtr = JimParserTtype(pc);
1631 if (linePtr) *linePtr = JimParserTline(pc);
1632 token = Jim_Alloc(1);
1633 token[0] = '\0';
1634 return token;
1635 }
1636 len = (end-start)+1;
1637 token = Jim_Alloc(len+1);
1638 if (JimParserTtype(pc) != JIM_TT_ESC) {
1639 /* No escape conversion needed? Just copy it. */
1640 memcpy(token, start, len);
1641 token[len] = '\0';
1642 } else {
1643 /* Else convert the escape chars. */
1644 len = JimEscape(token, start, len);
1645 }
1646 if (lenPtr) *lenPtr = len;
1647 if (typePtr) *typePtr = JimParserTtype(pc);
1648 if (linePtr) *linePtr = JimParserTline(pc);
1649 return token;
1650 }
1651
1652 /* The following functin is not really part of the parsing engine of Jim,
1653 * but it somewhat related. Given an string and its length, it tries
1654 * to guess if the script is complete or there are instead " " or { }
1655 * open and not completed. This is useful for interactive shells
1656 * implementation and for [info complete].
1657 *
1658 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1659 * '{' on scripts incomplete missing one or more '}' to be balanced.
1660 * '"' on scripts incomplete missing a '"' char.
1661 *
1662 * If the script is complete, 1 is returned, otherwise 0. */
1663 int Jim_ScriptIsComplete(const char *s, int len, char *stateCharPtr)
1664 {
1665 int level = 0;
1666 int state = ' ';
1667
1668 while(len) {
1669 switch (*s) {
1670 case '\\':
1671 if (len > 1)
1672 s++;
1673 break;
1674 case '"':
1675 if (state == ' ') {
1676 state = '"';
1677 } else if (state == '"') {
1678 state = ' ';
1679 }
1680 break;
1681 case '{':
1682 if (state == '{') {
1683 level++;
1684 } else if (state == ' ') {
1685 state = '{';
1686 level++;
1687 }
1688 break;
1689 case '}':
1690 if (state == '{') {
1691 level--;
1692 if (level == 0)
1693 state = ' ';
1694 }
1695 break;
1696 }
1697 s++;
1698 len--;
1699 }
1700 if (stateCharPtr)
1701 *stateCharPtr = state;
1702 return state == ' ';
1703 }
1704
1705 /* -----------------------------------------------------------------------------
1706 * Tcl Lists parsing
1707 * ---------------------------------------------------------------------------*/
1708 static int JimParseListSep(struct JimParserCtx *pc);
1709 static int JimParseListStr(struct JimParserCtx *pc);
1710
1711 int JimParseList(struct JimParserCtx *pc)
1712 {
1713 if (pc->len == 0) {
1714 pc->tstart = pc->tend = pc->p;
1715 pc->tline = pc->linenr;
1716 pc->tt = JIM_TT_EOL;
1717 pc->eof = 1;
1718 return JIM_OK;
1719 }
1720 switch(*pc->p) {
1721 case ' ':
1722 case '\n':
1723 case '\t':
1724 case '\r':
1725 if (pc->state == JIM_PS_DEF)
1726 return JimParseListSep(pc);
1727 else
1728 return JimParseListStr(pc);
1729 break;
1730 default:
1731 return JimParseListStr(pc);
1732 break;
1733 }
1734 return JIM_OK;
1735 }
1736
1737 int JimParseListSep(struct JimParserCtx *pc)
1738 {
1739 pc->tstart = pc->p;
1740 pc->tline = pc->linenr;
1741 while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == '\n')
1742 {
1743 pc->p++; pc->len--;
1744 }
1745 pc->tend = pc->p-1;
1746 pc->tt = JIM_TT_SEP;
1747 return JIM_OK;
1748 }
1749
1750 int JimParseListStr(struct JimParserCtx *pc)
1751 {
1752 int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
1753 pc->tt == JIM_TT_NONE);
1754 if (newword && *pc->p == '{') {
1755 return JimParseBrace(pc);
1756 } else if (newword && *pc->p == '"') {
1757 pc->state = JIM_PS_QUOTE;
1758 pc->p++; pc->len--;
1759 }
1760 pc->tstart = pc->p;
1761 pc->tline = pc->linenr;
1762 while (1) {
1763 if (pc->len == 0) {
1764 pc->tend = pc->p-1;
1765 pc->tt = JIM_TT_ESC;
1766 return JIM_OK;
1767 }
1768 switch(*pc->p) {
1769 case '\\':
1770 pc->p++; pc->len--;
1771 break;
1772 case ' ':
1773 case '\t':
1774 case '\n':
1775 case '\r':
1776 if (pc->state == JIM_PS_DEF) {
1777 pc->tend = pc->p-1;
1778 pc->tt = JIM_TT_ESC;
1779 return JIM_OK;
1780 } else if (*pc->p == '\n') {
1781 pc->linenr++;
1782 }
1783 break;
1784 case '"':
1785 if (pc->state == JIM_PS_QUOTE) {
1786 pc->tend = pc->p-1;
1787 pc->tt = JIM_TT_ESC;
1788 pc->p++; pc->len--;
1789 pc->state = JIM_PS_DEF;
1790 return JIM_OK;
1791 }
1792 break;
1793 }
1794 pc->p++; pc->len--;
1795 }
1796 return JIM_OK; /* unreached */
1797 }
1798
1799 /* -----------------------------------------------------------------------------
1800 * Jim_Obj related functions
1801 * ---------------------------------------------------------------------------*/
1802
1803 /* Return a new initialized object. */
1804 Jim_Obj *Jim_NewObj(Jim_Interp *interp)
1805 {
1806 Jim_Obj *objPtr;
1807
1808 /* -- Check if there are objects in the free list -- */
1809 if (interp->freeList != NULL) {
1810 /* -- Unlink the object from the free list -- */
1811 objPtr = interp->freeList;
1812 interp->freeList = objPtr->nextObjPtr;
1813 } else {
1814 /* -- No ready to use objects: allocate a new one -- */
1815 objPtr = Jim_Alloc(sizeof(*objPtr));
1816 }
1817
1818 /* Object is returned with refCount of 0. Every
1819 * kind of GC implemented should take care to don't try
1820 * to scan objects with refCount == 0. */
1821 objPtr->refCount = 0;
1822 /* All the other fields are left not initialized to save time.
1823 * The caller will probably want set they to the right
1824 * value anyway. */
1825
1826 /* -- Put the object into the live list -- */
1827 objPtr->prevObjPtr = NULL;
1828 objPtr->nextObjPtr = interp->liveList;
1829 if (interp->liveList)
1830 interp->liveList->prevObjPtr = objPtr;
1831 interp->liveList = objPtr;
1832
1833 return objPtr;
1834 }
1835
1836 /* Free an object. Actually objects are never freed, but
1837 * just moved to the free objects list, where they will be
1838 * reused by Jim_NewObj(). */
1839 void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
1840 {
1841 /* Check if the object was already freed, panic. */
1842 if (objPtr->refCount != 0) {
1843 Jim_Panic(interp,"!!!Object %p freed with bad refcount %d", objPtr,
1844 objPtr->refCount);
1845 }
1846 /* Free the internal representation */
1847 Jim_FreeIntRep(interp, objPtr);
1848 /* Free the string representation */
1849 if (objPtr->bytes != NULL) {
1850 if (objPtr->bytes != JimEmptyStringRep)
1851 Jim_Free(objPtr->bytes);
1852 }
1853 /* Unlink the object from the live objects list */
1854 if (objPtr->prevObjPtr)
1855 objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
1856 if (objPtr->nextObjPtr)
1857 objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
1858 if (interp->liveList == objPtr)
1859 interp->liveList = objPtr->nextObjPtr;
1860 /* Link the object into the free objects list */
1861 objPtr->prevObjPtr = NULL;
1862 objPtr->nextObjPtr = interp->freeList;
1863 if (interp->freeList)
1864 interp->freeList->prevObjPtr = objPtr;
1865 interp->freeList = objPtr;
1866 objPtr->refCount = -1;
1867 }
1868
1869 /* Invalidate the string representation of an object. */
1870 void Jim_InvalidateStringRep(Jim_Obj *objPtr)
1871 {
1872 if (objPtr->bytes != NULL) {
1873 if (objPtr->bytes != JimEmptyStringRep)
1874 Jim_Free(objPtr->bytes);
1875 }
1876 objPtr->bytes = NULL;
1877 }
1878
1879 #define Jim_SetStringRep(o, b, l) \
1880 do { (o)->bytes = b; (o)->length = l; } while (0)
1881
1882 /* Set the initial string representation for an object.
1883 * Does not try to free an old one. */
1884 void Jim_InitStringRep(Jim_Obj *objPtr, const char *bytes, int length)
1885 {
1886 if (length == 0) {
1887 objPtr->bytes = JimEmptyStringRep;
1888 objPtr->length = 0;
1889 } else {
1890 objPtr->bytes = Jim_Alloc(length+1);
1891 objPtr->length = length;
1892 memcpy(objPtr->bytes, bytes, length);
1893 objPtr->bytes[length] = '\0';
1894 }
1895 }
1896
1897 /* Duplicate an object. The returned object has refcount = 0. */
1898 Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
1899 {
1900 Jim_Obj *dupPtr;
1901
1902 dupPtr = Jim_NewObj(interp);
1903 if (objPtr->bytes == NULL) {
1904 /* Object does not have a valid string representation. */
1905 dupPtr->bytes = NULL;
1906 } else {
1907 Jim_InitStringRep(dupPtr, objPtr->bytes, objPtr->length);
1908 }
1909 if (objPtr->typePtr != NULL) {
1910 if (objPtr->typePtr->dupIntRepProc == NULL) {
1911 dupPtr->internalRep = objPtr->internalRep;
1912 } else {
1913 objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
1914 }
1915 dupPtr->typePtr = objPtr->typePtr;
1916 } else {
1917 dupPtr->typePtr = NULL;
1918 }
1919 return dupPtr;
1920 }
1921
1922 /* Return the string representation for objPtr. If the object
1923 * string representation is invalid, calls the method to create
1924 * a new one starting from the internal representation of the object. */
1925 const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
1926 {
1927 if (objPtr->bytes == NULL) {
1928 /* Invalid string repr. Generate it. */
1929 if (objPtr->typePtr->updateStringProc == NULL) {
1930 Jim_Panic(NULL,"UpdataStringProc called against '%s' type.",
1931 objPtr->typePtr->name);
1932 }
1933 objPtr->typePtr->updateStringProc(objPtr);
1934 }
1935 if (lenPtr)
1936 *lenPtr = objPtr->length;
1937 return objPtr->bytes;
1938 }
1939
1940 /* Just returns the length of the object's string rep */
1941 int Jim_Length(Jim_Obj *objPtr)
1942 {
1943 int len;
1944
1945 Jim_GetString(objPtr, &len);
1946 return len;
1947 }
1948
1949 /* -----------------------------------------------------------------------------
1950 * String Object
1951 * ---------------------------------------------------------------------------*/
1952 static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
1953 static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
1954
1955 static Jim_ObjType stringObjType = {
1956 "string",
1957 NULL,
1958 DupStringInternalRep,
1959 NULL,
1960 JIM_TYPE_REFERENCES,
1961 };
1962
1963 void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
1964 {
1965 JIM_NOTUSED(interp);
1966
1967 /* This is a bit subtle: the only caller of this function
1968 * should be Jim_DuplicateObj(), that will copy the
1969 * string representaion. After the copy, the duplicated
1970 * object will not have more room in teh buffer than
1971 * srcPtr->length bytes. So we just set it to length. */
1972 dupPtr->internalRep.strValue.maxLength = srcPtr->length;
1973 }
1974
1975 int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
1976 {
1977 /* Get a fresh string representation. */
1978 (void) Jim_GetString(objPtr, NULL);
1979 /* Free any other internal representation. */
1980 Jim_FreeIntRep(interp, objPtr);
1981 /* Set it as string, i.e. just set the maxLength field. */
1982 objPtr->typePtr = &stringObjType;
1983 objPtr->internalRep.strValue.maxLength = objPtr->length;
1984 return JIM_OK;
1985 }
1986
1987 Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
1988 {
1989 Jim_Obj *objPtr = Jim_NewObj(interp);
1990
1991 if (len == -1)
1992 len = strlen(s);
1993 /* Alloc/Set the string rep. */
1994 if (len == 0) {
1995 objPtr->bytes = JimEmptyStringRep;
1996 objPtr->length = 0;
1997 } else {
1998 objPtr->bytes = Jim_Alloc(len+1);
1999 objPtr->length = len;
2000 memcpy(objPtr->bytes, s, len);
2001 objPtr->bytes[len] = '\0';
2002 }
2003
2004 /* No typePtr field for the vanilla string object. */
2005 objPtr->typePtr = NULL;
2006 return objPtr;
2007 }
2008
2009 /* This version does not try to duplicate the 's' pointer, but
2010 * use it directly. */
2011 Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
2012 {
2013 Jim_Obj *objPtr = Jim_NewObj(interp);
2014
2015 if (len == -1)
2016 len = strlen(s);
2017 Jim_SetStringRep(objPtr, s, len);
2018 objPtr->typePtr = NULL;
2019 return objPtr;
2020 }
2021
2022 /* Low-level string append. Use it only against objects
2023 * of type "string". */
2024 void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
2025 {
2026 int needlen;
2027
2028 if (len == -1)
2029 len = strlen(str);
2030 needlen = objPtr->length + len;
2031 if (objPtr->internalRep.strValue.maxLength < needlen ||
2032 objPtr->internalRep.strValue.maxLength == 0) {
2033 if (objPtr->bytes == JimEmptyStringRep) {
2034 objPtr->bytes = Jim_Alloc((needlen*2)+1);
2035 } else {
2036 objPtr->bytes = Jim_Realloc(objPtr->bytes, (needlen*2)+1);
2037 }
2038 objPtr->internalRep.strValue.maxLength = needlen*2;
2039 }
2040 memcpy(objPtr->bytes + objPtr->length, str, len);
2041 objPtr->bytes[objPtr->length+len] = '\0';
2042 objPtr->length += len;
2043 }
2044
2045 /* Low-level wrapper to append an object. */
2046 void StringAppendObj(Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
2047 {
2048 int len;
2049 const char *str;
2050
2051 str = Jim_GetString(appendObjPtr, &len);
2052 StringAppendString(objPtr, str, len);
2053 }
2054
2055 /* Higher level API to append strings to objects. */
2056 void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str,
2057 int len)
2058 {
2059 if (Jim_IsShared(objPtr))
2060 Jim_Panic(interp,"Jim_AppendString called with shared object");
2061 if (objPtr->typePtr != &stringObjType)
2062 SetStringFromAny(interp, objPtr);
2063 StringAppendString(objPtr, str, len);
2064 }
2065
2066 void Jim_AppendString_sprintf( Jim_Interp *interp, Jim_Obj *objPtr, const char *fmt, ... )
2067 {
2068 char *buf;
2069 va_list ap;
2070
2071 va_start( ap, fmt );
2072 buf = jim_vasprintf( fmt, ap );
2073 va_end(ap);
2074
2075 if( buf ){
2076 Jim_AppendString( interp, objPtr, buf, -1 );
2077 jim_vasprintf_done(buf);
2078 }
2079 }
2080
2081
2082 void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr,
2083 Jim_Obj *appendObjPtr)
2084 {
2085 int len;
2086 const char *str;
2087
2088 str = Jim_GetString(appendObjPtr, &len);
2089 Jim_AppendString(interp, objPtr, str, len);
2090 }
2091
2092 void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
2093 {
2094 va_list ap;
2095
2096 if (objPtr->typePtr != &stringObjType)
2097 SetStringFromAny(interp, objPtr);
2098 va_start(ap, objPtr);
2099 while (1) {
2100 char *s = va_arg(ap, char*);
2101
2102 if (s == NULL) break;
2103 Jim_AppendString(interp, objPtr, s, -1);
2104 }
2105 va_end(ap);
2106 }
2107
2108 int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr, int nocase)
2109 {
2110 const char *aStr, *bStr;
2111 int aLen, bLen, i;
2112
2113 if (aObjPtr == bObjPtr) return 1;
2114 aStr = Jim_GetString(aObjPtr, &aLen);
2115 bStr = Jim_GetString(bObjPtr, &bLen);
2116 if (aLen != bLen) return 0;
2117 if (nocase == 0)
2118 return memcmp(aStr, bStr, aLen) == 0;
2119 for (i = 0; i < aLen; i++) {
2120 if (tolower((int)aStr[i]) != tolower((int)bStr[i]))
2121 return 0;
2122 }
2123 return 1;
2124 }
2125
2126 int Jim_StringMatchObj(Jim_Obj *patternObjPtr, Jim_Obj *objPtr,
2127 int nocase)
2128 {
2129 const char *pattern, *string;
2130 int patternLen, stringLen;
2131
2132 pattern = Jim_GetString(patternObjPtr, &patternLen);
2133 string = Jim_GetString(objPtr, &stringLen);
2134 return JimStringMatch(pattern, patternLen, string, stringLen, nocase);
2135 }
2136
2137 int Jim_StringCompareObj(Jim_Obj *firstObjPtr,
2138 Jim_Obj *secondObjPtr, int nocase)
2139 {
2140 const char *s1, *s2;
2141 int l1, l2;
2142
2143 s1 = Jim_GetString(firstObjPtr, &l1);
2144 s2 = Jim_GetString(secondObjPtr, &l2);
2145 return JimStringCompare(s1, l1, s2, l2, nocase);
2146 }
2147
2148 /* Convert a range, as returned by Jim_GetRange(), into
2149 * an absolute index into an object of the specified length.
2150 * This function may return negative values, or values
2151 * bigger or equal to the length of the list if the index
2152 * is out of range. */
2153 static int JimRelToAbsIndex(int len, int index)
2154 {
2155 if (index < 0)
2156 return len + index;
2157 return index;
2158 }
2159
2160 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2161 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2162 * for implementation of commands like [string range] and [lrange].
2163 *
2164 * The resulting range is guaranteed to address valid elements of
2165 * the structure. */
2166 static void JimRelToAbsRange(int len, int first, int last,
2167 int *firstPtr, int *lastPtr, int *rangeLenPtr)
2168 {
2169 int rangeLen;
2170
2171 if (first > last) {
2172 rangeLen = 0;
2173 } else {
2174 rangeLen = last-first+1;
2175 if (rangeLen) {
2176 if (first < 0) {
2177 rangeLen += first;
2178 first = 0;
2179 }
2180 if (last >= len) {
2181 rangeLen -= (last-(len-1));
2182 last = len-1;
2183 }
2184 }
2185 }
2186 if (rangeLen < 0) rangeLen = 0;
2187
2188 *firstPtr = first;
2189 *lastPtr = last;
2190 *rangeLenPtr = rangeLen;
2191 }
2192
2193 Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
2194 Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
2195 {
2196 int first, last;
2197 const char *str;
2198 int len, rangeLen;
2199
2200 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
2201 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
2202 return NULL;
2203 str = Jim_GetString(strObjPtr, &len);
2204 first = JimRelToAbsIndex(len, first);
2205 last = JimRelToAbsIndex(len, last);
2206 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
2207 return Jim_NewStringObj(interp, str+first, rangeLen);
2208 }
2209
2210 static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
2211 {
2212 char *buf;
2213 int i;
2214 if (strObjPtr->typePtr != &stringObjType) {
2215 SetStringFromAny(interp, strObjPtr);
2216 }
2217
2218 buf = Jim_Alloc(strObjPtr->length+1);
2219
2220 memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);
2221 for (i = 0; i < strObjPtr->length; i++)
2222 buf[i] = tolower(buf[i]);
2223 return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);
2224 }
2225
2226 static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
2227 {
2228 char *buf;
2229 int i;
2230 if (strObjPtr->typePtr != &stringObjType) {
2231 SetStringFromAny(interp, strObjPtr);
2232 }
2233
2234 buf = Jim_Alloc(strObjPtr->length+1);
2235
2236 memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);
2237 for (i = 0; i < strObjPtr->length; i++)
2238 buf[i] = toupper(buf[i]);
2239 return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);
2240 }
2241
2242 /* This is the core of the [format] command.
2243 * TODO: Lots of things work - via a hack
2244 * However, no format item can be >= JIM_MAX_FMT
2245 */
2246 #define JIM_MAX_FMT 2048
2247 static Jim_Obj *Jim_FormatString_Inner(Jim_Interp *interp, Jim_Obj *fmtObjPtr,
2248 int objc, Jim_Obj *const *objv, char *sprintf_buf)
2249 {
2250 const char *fmt, *_fmt;
2251 int fmtLen;
2252 Jim_Obj *resObjPtr;
2253
2254
2255 fmt = Jim_GetString(fmtObjPtr, &fmtLen);
2256 _fmt = fmt;
2257 resObjPtr = Jim_NewStringObj(interp, "", 0);
2258 while (fmtLen) {
2259 const char *p = fmt;
2260 char spec[2], c;
2261 jim_wide wideValue;
2262 double doubleValue;
2263 /* we cheat and use Sprintf()! */
2264 char fmt_str[100];
2265 char *cp;
2266 int width;
2267 int ljust;
2268 int zpad;
2269 int spad;
2270 int altfm;
2271 int forceplus;
2272 int prec;
2273 int inprec;
2274 int haveprec;
2275 int accum;
2276
2277 while (*fmt != '%' && fmtLen) {
2278 fmt++; fmtLen--;
2279 }
2280 Jim_AppendString(interp, resObjPtr, p, fmt-p);
2281 if (fmtLen == 0)
2282 break;
2283 fmt++; fmtLen--; /* skip '%' */
2284 zpad = 0;
2285 spad = 0;
2286 width = -1;
2287 ljust = 0;
2288 altfm = 0;
2289 forceplus = 0;
2290 inprec = 0;
2291 haveprec = 0;
2292 prec = -1; /* not found yet */
2293 next_fmt:
2294 if( fmtLen <= 0 ){
2295 break;
2296 }
2297 switch( *fmt ){
2298 /* terminals */
2299 case 'b': /* binary - not all printfs() do this */
2300 case 's': /* string */
2301 case 'i': /* integer */
2302 case 'd': /* decimal */
2303 case 'x': /* hex */
2304 case 'X': /* CAP hex */
2305 case 'c': /* char */
2306 case 'o': /* octal */
2307 case 'u': /* unsigned */
2308 case 'f': /* float */
2309 break;
2310
2311 /* non-terminals */
2312 case '0': /* zero pad */
2313 zpad = 1;
2314 fmt++; fmtLen--;
2315 goto next_fmt;
2316 break;
2317 case '+':
2318 forceplus = 1;
2319 fmt++; fmtLen--;
2320 goto next_fmt;
2321 break;
2322 case ' ': /* sign space */
2323 spad = 1;
2324 fmt++; fmtLen--;
2325 goto next_fmt;
2326 break;
2327 case '-':
2328 ljust = 1;
2329 fmt++; fmtLen--;
2330 goto next_fmt;
2331 break;
2332 case '#':
2333 altfm = 1;
2334 fmt++; fmtLen--;
2335 goto next_fmt;
2336
2337 case '.':
2338 inprec = 1;
2339 fmt++; fmtLen--;
2340 goto next_fmt;
2341 break;
2342 case '1':
2343 case '2':
2344 case '3':
2345 case '4':
2346 case '5':
2347 case '6':
2348 case '7':
2349 case '8':
2350 case '9':
2351 accum = 0;
2352 while( isdigit(*fmt) && (fmtLen > 0) ){
2353 accum = (accum * 10) + (*fmt - '0');
2354 fmt++; fmtLen--;
2355 }
2356 if( inprec ){
2357 haveprec = 1;
2358 prec = accum;
2359 } else {
2360 width = accum;
2361 }
2362 goto next_fmt;
2363 case '*':
2364 /* suck up the next item as an integer */
2365 fmt++; fmtLen--;
2366 objc--;
2367 if( objc <= 0 ){
2368 goto not_enough_args;
2369 }
2370 if( Jim_GetWide(interp,objv[0],&wideValue )== JIM_ERR ){
2371 Jim_FreeNewObj(interp, resObjPtr );
2372 return NULL;
2373 }
2374 if( inprec ){
2375 haveprec = 1;
2376 prec = wideValue;
2377 if( prec < 0 ){
2378 /* man 3 printf says */
2379 /* if prec is negative, it is zero */
2380 prec = 0;
2381 }
2382 } else {
2383 width = wideValue;
2384 if( width < 0 ){
2385 ljust = 1;
2386 width = -width;
2387 }
2388 }
2389 objv++;
2390 goto next_fmt;
2391 break;
2392 }
2393
2394
2395 if (*fmt != '%') {
2396 if (objc == 0) {
2397 not_enough_args:
2398 Jim_FreeNewObj(interp, resObjPtr);
2399 Jim_SetResultString(interp,
2400 "not enough arguments for all format specifiers", -1);
2401 return NULL;
2402 } else {
2403 objc--;
2404 }
2405 }
2406
2407 /*
2408 * Create the formatter
2409 * cause we cheat and use sprintf()
2410 */
2411 cp = fmt_str;
2412 *cp++ = '%';
2413 if( altfm ){
2414 *cp++ = '#';
2415 }
2416 if( forceplus ){
2417 *cp++ = '+';
2418 } else if( spad ){
2419 /* PLUS overrides */
2420 *cp++ = ' ';
2421 }
2422 if( ljust ){
2423 *cp++ = '-';
2424 }
2425 if( zpad ){
2426 *cp++ = '0';
2427 }
2428 if( width > 0 ){
2429 sprintf( cp, "%d", width );
2430 /* skip ahead */
2431 cp = strchr(cp,0);
2432 }
2433 /* did we find a period? */
2434 if( inprec ){
2435 /* then add it */
2436 *cp++ = '.';
2437 /* did something occur after the period? */
2438 if( haveprec ){
2439 sprintf( cp, "%d", prec );
2440 }
2441 cp = strchr(cp,0);
2442 }
2443 *cp = 0;
2444
2445 /* here we do the work */
2446 /* actually - we make sprintf() do it for us */
2447 switch(*fmt) {
2448 case 's':
2449 *cp++ = 's';
2450 *cp = 0;
2451 /* BUG: we do not handled embeded NULLs */
2452 snprintf( sprintf_buf, JIM_MAX_FMT, fmt_str, Jim_GetString( objv[0], NULL ));
2453 break;
2454 case 'c':
2455 *cp++ = 'c';
2456 *cp = 0;
2457 if (Jim_GetWide(interp, objv[0], &wideValue) == JIM_ERR) {
2458 Jim_FreeNewObj(interp, resObjPtr);
2459 return NULL;
2460 }
2461 c = (char) wideValue;
2462 snprintf( sprintf_buf, JIM_MAX_FMT, fmt_str, c );
2463 break;
2464 case 'f':
2465 case 'F':
2466 case 'g':
2467 case 'G':
2468 case 'e':
2469 case 'E':
2470 *cp++ = *fmt;
2471 *cp = 0;
2472 if( Jim_GetDouble( interp, objv[0], &doubleValue ) == JIM_ERR ){
2473 Jim_FreeNewObj( interp, resObjPtr );
2474 return NULL;
2475 }
2476 snprintf( sprintf_buf, JIM_MAX_FMT, fmt_str, doubleValue );
2477 break;
2478 case 'b':
2479 case 'd':
2480 case 'o':
2481 case 'i':
2482 case 'u':
2483 case 'x':
2484 case 'X':
2485 /* jim widevaluse are 64bit */
2486 if( sizeof(jim_wide) == sizeof(long long) ){
2487 *cp++ = 'l';
2488 *cp++ = 'l';
2489 } else {
2490 *cp++ = 'l';
2491 }
2492 *cp++ = *fmt;
2493 *cp = 0;
2494 if (Jim_GetWide(interp, objv[0], &wideValue) == JIM_ERR) {
2495 Jim_FreeNewObj(interp, resObjPtr);
2496 return NULL;
2497 }
2498 snprintf(sprintf_buf, JIM_MAX_FMT, fmt_str, wideValue );
2499 break;
2500 case '%':
2501 sprintf_buf[0] = '%';
2502 sprintf_buf[1] = 0;
2503 objv--; /* undo the objv++ below */
2504 break;
2505 default:
2506 spec[0] = *fmt; spec[1] = '\0';
2507 Jim_FreeNewObj(interp, resObjPtr);
2508 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2509 Jim_AppendStrings(interp, Jim_GetResult(interp),
2510 "bad field specifier \"", spec, "\"", NULL);
2511 return NULL;
2512 }
2513 /* force terminate */
2514 #if 0
2515 printf("FMT was: %s\n", fmt_str );
2516 printf("RES was: |%s|\n", sprintf_buf );
2517 #endif
2518
2519 sprintf_buf[ JIM_MAX_FMT - 1] = 0;
2520 Jim_AppendString( interp, resObjPtr, sprintf_buf, strlen(sprintf_buf) );
2521 /* next obj */
2522 objv++;
2523 fmt++;
2524 fmtLen--;
2525 }
2526 return resObjPtr;
2527 }
2528
2529 Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr,
2530 int objc, Jim_Obj *const *objv)
2531 {
2532 char *sprintf_buf=malloc(JIM_MAX_FMT);
2533 Jim_Obj *t=Jim_FormatString_Inner(interp, fmtObjPtr, objc, objv, sprintf_buf);
2534 free(sprintf_buf);
2535 return t;
2536 }
2537
2538 /* -----------------------------------------------------------------------------
2539 * Compared String Object
2540 * ---------------------------------------------------------------------------*/
2541
2542 /* This is strange object that allows to compare a C literal string
2543 * with a Jim object in very short time if the same comparison is done
2544 * multiple times. For example every time the [if] command is executed,
2545 * Jim has to check if a given argument is "else". This comparions if
2546 * the code has no errors are true most of the times, so we can cache
2547 * inside the object the pointer of the string of the last matching
2548 * comparison. Because most C compilers perform literal sharing,
2549 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2550 * this works pretty well even if comparisons are at different places
2551 * inside the C code. */
2552
2553 static Jim_ObjType comparedStringObjType = {
2554 "compared-string",
2555 NULL,
2556 NULL,
2557 NULL,
2558 JIM_TYPE_REFERENCES,
2559 };
2560
2561 /* The only way this object is exposed to the API is via the following
2562 * function. Returns true if the string and the object string repr.
2563 * are the same, otherwise zero is returned.
2564 *
2565 * Note: this isn't binary safe, but it hardly needs to be.*/
2566 int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr,
2567 const char *str)
2568 {
2569 if (objPtr->typePtr == &comparedStringObjType &&
2570 objPtr->internalRep.ptr == str)
2571 return 1;
2572 else {
2573 const char *objStr = Jim_GetString(objPtr, NULL);
2574 if (strcmp(str, objStr) != 0) return 0;
2575 if (objPtr->typePtr != &comparedStringObjType) {
2576 Jim_FreeIntRep(interp, objPtr);
2577 objPtr->typePtr = &comparedStringObjType;
2578 }
2579 objPtr->internalRep.ptr = (char*)str; /*ATTENTION: const cast */
2580 return 1;
2581 }
2582 }
2583
2584 int qsortCompareStringPointers(const void *a, const void *b)
2585 {
2586 char * const *sa = (char * const *)a;
2587 char * const *sb = (char * const *)b;
2588 return strcmp(*sa, *sb);
2589 }
2590
2591 int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
2592 const char * const *tablePtr, int *indexPtr, const char *name, int flags)
2593 {
2594 const char * const *entryPtr = NULL;
2595 char **tablePtrSorted;
2596 int i, count = 0;
2597
2598 *indexPtr = -1;
2599 for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
2600 if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
2601 *indexPtr = i;
2602 return JIM_OK;
2603 }
2604 count++; /* If nothing matches, this will reach the len of tablePtr */
2605 }
2606 if (flags & JIM_ERRMSG) {
2607 if (name == NULL)
2608 name = "option";
2609 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2610 Jim_AppendStrings(interp, Jim_GetResult(interp),
2611 "bad ", name, " \"", Jim_GetString(objPtr, NULL), "\": must be one of ",
2612 NULL);
2613 tablePtrSorted = Jim_Alloc(sizeof(char*)*count);
2614 memcpy(tablePtrSorted, tablePtr, sizeof(char*)*count);
2615 qsort(tablePtrSorted, count, sizeof(char*), qsortCompareStringPointers);
2616 for (i = 0; i < count; i++) {
2617 if (i+1 == count && count > 1)
2618 Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
2619 Jim_AppendString(interp, Jim_GetResult(interp),
2620 tablePtrSorted[i], -1);
2621 if (i+1 != count)
2622 Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
2623 }
2624 Jim_Free(tablePtrSorted);
2625 }
2626 return JIM_ERR;
2627 }
2628
2629 int Jim_GetNvp(Jim_Interp *interp,
2630 Jim_Obj *objPtr,
2631 const Jim_Nvp *nvp_table,
2632 const Jim_Nvp ** result)
2633 {
2634 Jim_Nvp *n;
2635 int e;
2636
2637 e = Jim_Nvp_name2value_obj( interp, nvp_table, objPtr, &n );
2638 if( e == JIM_ERR ){
2639 return e;
2640 }
2641
2642 /* Success? found? */
2643 if( n->name ){
2644 /* remove const */
2645 *result = (Jim_Nvp *)n;
2646 return JIM_OK;
2647 } else {
2648 return JIM_ERR;
2649 }
2650 }
2651
2652 /* -----------------------------------------------------------------------------
2653 * Source Object
2654 *
2655 * This object is just a string from the language point of view, but
2656 * in the internal representation it contains the filename and line number
2657 * where this given token was read. This information is used by
2658 * Jim_EvalObj() if the object passed happens to be of type "source".
2659 *
2660 * This allows to propagate the information about line numbers and file
2661 * names and give error messages with absolute line numbers.
2662 *
2663 * Note that this object uses shared strings for filenames, and the
2664 * pointer to the filename together with the line number is taken into
2665 * the space for the "inline" internal represenation of the Jim_Object,
2666 * so there is almost memory zero-overhead.
2667 *
2668 * Also the object will be converted to something else if the given
2669 * token it represents in the source file is not something to be
2670 * evaluated (not a script), and will be specialized in some other way,
2671 * so the time overhead is alzo null.
2672 * ---------------------------------------------------------------------------*/
2673
2674 static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2675 static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2676
2677 static Jim_ObjType sourceObjType = {
2678 "source",
2679 FreeSourceInternalRep,
2680 DupSourceInternalRep,
2681 NULL,
2682 JIM_TYPE_REFERENCES,
2683 };
2684
2685 void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2686 {
2687 Jim_ReleaseSharedString(interp,
2688 objPtr->internalRep.sourceValue.fileName);
2689 }
2690
2691 void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2692 {
2693 dupPtr->internalRep.sourceValue.fileName =
2694 Jim_GetSharedString(interp,
2695 srcPtr->internalRep.sourceValue.fileName);
2696 dupPtr->internalRep.sourceValue.lineNumber =
2697 dupPtr->internalRep.sourceValue.lineNumber;
2698 dupPtr->typePtr = &sourceObjType;
2699 }
2700
2701 static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
2702 const char *fileName, int lineNumber)
2703 {
2704 if (Jim_IsShared(objPtr))
2705 Jim_Panic(interp,"JimSetSourceInfo called with shared object");
2706 if (objPtr->typePtr != NULL)
2707 Jim_Panic(interp,"JimSetSourceInfo called with typePtr != NULL");
2708 objPtr->internalRep.sourceValue.fileName =
2709 Jim_GetSharedString(interp, fileName);
2710 objPtr->internalRep.sourceValue.lineNumber = lineNumber;
2711 objPtr->typePtr = &sourceObjType;
2712 }
2713
2714 /* -----------------------------------------------------------------------------
2715 * Script Object
2716 * ---------------------------------------------------------------------------*/
2717
2718 #define JIM_CMDSTRUCT_EXPAND -1
2719
2720 static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2721 static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2722 static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
2723
2724 static Jim_ObjType scriptObjType = {
2725 "script",
2726 FreeScriptInternalRep,
2727 DupScriptInternalRep,
2728 NULL,
2729 JIM_TYPE_REFERENCES,
2730 };
2731
2732 /* The ScriptToken structure represents every token into a scriptObj.
2733 * Every token contains an associated Jim_Obj that can be specialized
2734 * by commands operating on it. */
2735 typedef struct ScriptToken {
2736 int type;
2737 Jim_Obj *objPtr;
2738 int linenr;
2739 } ScriptToken;
2740
2741 /* This is the script object internal representation. An array of
2742 * ScriptToken structures, with an associated command structure array.
2743 * The command structure is a pre-computed representation of the
2744 * command length and arguments structure as a simple liner array
2745 * of integers.
2746 *
2747 * For example the script:
2748 *
2749 * puts hello
2750 * set $i $x$y [foo]BAR
2751 *
2752 * will produce a ScriptObj with the following Tokens:
2753 *
2754 * ESC puts
2755 * SEP
2756 * ESC hello
2757 * EOL
2758 * ESC set
2759 * EOL
2760 * VAR i
2761 * SEP
2762 * VAR x
2763 * VAR y
2764 * SEP
2765 * CMD foo
2766 * ESC BAR
2767 * EOL
2768 *
2769 * This is a description of the tokens, separators, and of lines.
2770 * The command structure instead represents the number of arguments
2771 * of every command, followed by the tokens of which every argument
2772 * is composed. So for the example script, the cmdstruct array will
2773 * contain:
2774 *
2775 * 2 1 1 4 1 1 2 2
2776 *
2777 * Because "puts hello" has two args (2), composed of single tokens (1 1)
2778 * While "set $i $x$y [foo]BAR" has four (4) args, the first two
2779 * composed of single tokens (1 1) and the last two of double tokens
2780 * (2 2).
2781 *
2782 * The precomputation of the command structure makes Jim_Eval() faster,
2783 * and simpler because there aren't dynamic lengths / allocations.
2784 *
2785 * -- {expand} handling --
2786 *
2787 * Expand is handled in a special way. When a command
2788 * contains at least an argument with the {expand} prefix,
2789 * the command structure presents a -1 before the integer
2790 * describing the number of arguments. This is used in order
2791 * to send the command exection to a different path in case
2792 * of {expand} and guarantee a fast path for the more common
2793 * case. Also, the integers describing the number of tokens
2794 * are expressed with negative sign, to allow for fast check
2795 * of what's an {expand}-prefixed argument and what not.
2796 *
2797 * For example the command:
2798 *
2799 * list {expand}{1 2}
2800 *
2801 * Will produce the following cmdstruct array:
2802 *
2803 * -1 2 1 -2
2804 *
2805 * -- the substFlags field of the structure --
2806 *
2807 * The scriptObj structure is used to represent both "script" objects
2808 * and "subst" objects. In the second case, the cmdStruct related
2809 * fields are not used at all, but there is an additional field used
2810 * that is 'substFlags': this represents the flags used to turn
2811 * the string into the intenral representation used to perform the
2812 * substitution. If this flags are not what the application requires
2813 * the scriptObj is created again. For example the script:
2814 *
2815 * subst -nocommands $string
2816 * subst -novariables $string
2817 *
2818 * Will recreate the internal representation of the $string object
2819 * two times.
2820 */
2821 typedef struct ScriptObj {
2822 int len; /* Length as number of tokens. */
2823 int commands; /* number of top-level commands in script. */
2824 ScriptToken *token; /* Tokens array. */
2825 int *cmdStruct; /* commands structure */
2826 int csLen; /* length of the cmdStruct array. */
2827 int substFlags; /* flags used for the compilation of "subst" objects */
2828 int inUse; /* Used to share a ScriptObj. Currently
2829 only used by Jim_EvalObj() as protection against
2830 shimmering of the currently evaluated object. */
2831 char *fileName;
2832 } ScriptObj;
2833
2834 void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2835 {
2836 int i;
2837 struct ScriptObj *script = (void*) objPtr->internalRep.ptr;
2838
2839 script->inUse--;
2840 if (script->inUse != 0) return;
2841 for (i = 0; i < script->len; i++) {
2842 if (script->token[i].objPtr != NULL)
2843 Jim_DecrRefCount(interp, script->token[i].objPtr);
2844 }
2845 Jim_Free(script->token);
2846 Jim_Free(script->cmdStruct);
2847 Jim_Free(script->fileName);
2848 Jim_Free(script);
2849 }
2850
2851 void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2852 {
2853 JIM_NOTUSED(interp);
2854 JIM_NOTUSED(srcPtr);
2855
2856 /* Just returns an simple string. */
2857 dupPtr->typePtr = NULL;
2858 }
2859
2860 /* Add a new token to the internal repr of a script object */
2861 static void ScriptObjAddToken(Jim_Interp *interp, struct ScriptObj *script,
2862 char *strtoken, int len, int type, char *filename, int linenr)
2863 {
2864 int prevtype;
2865 struct ScriptToken *token;
2866
2867 prevtype = (script->len == 0) ? JIM_TT_EOL : \
2868 script->token[script->len-1].type;
2869 /* Skip tokens without meaning, like words separators
2870 * following a word separator or an end of command and
2871 * so on. */
2872 if (prevtype == JIM_TT_EOL) {
2873 if (type == JIM_TT_EOL || type == JIM_TT_SEP) {
2874 Jim_Free(strtoken);
2875 return;
2876 }
2877 } else if (prevtype == JIM_TT_SEP) {
2878 if (type == JIM_TT_SEP) {
2879 Jim_Free(strtoken);
2880 return;
2881 } else if (type == JIM_TT_EOL) {
2882 /* If an EOL is following by a SEP, drop the previous
2883 * separator. */
2884 script->len--;
2885 Jim_DecrRefCount(interp, script->token[script->len].objPtr);
2886 }
2887 } else if (prevtype != JIM_TT_EOL && prevtype != JIM_TT_SEP &&
2888 type == JIM_TT_ESC && len == 0)
2889 {
2890 /* Don't add empty tokens used in interpolation */
2891 Jim_Free(strtoken);
2892 return;
2893 }
2894 /* Make space for a new istruction */
2895 script->len++;
2896 script->token = Jim_Realloc(script->token,
2897 sizeof(ScriptToken)*script->len);
2898 /* Initialize the new token */
2899 token = script->token+(script->len-1);
2900 token->type = type;
2901 /* Every object is intially as a string, but the
2902 * internal type may be specialized during execution of the
2903 * script. */
2904 token->objPtr = Jim_NewStringObjNoAlloc(interp, strtoken, len);
2905 /* To add source info to SEP and EOL tokens is useless because
2906 * they will never by called as arguments of Jim_EvalObj(). */
2907 if (filename && type != JIM_TT_SEP && type != JIM_TT_EOL)
2908 JimSetSourceInfo(interp, token->objPtr, filename, linenr);
2909 Jim_IncrRefCount(token->objPtr);
2910 token->linenr = linenr;
2911 }
2912
2913 /* Add an integer into the command structure field of the script object. */
2914 static void ScriptObjAddInt(struct ScriptObj *script, int val)
2915 {
2916 script->csLen++;
2917 script->cmdStruct = Jim_Realloc(script->cmdStruct,
2918 sizeof(int)*script->csLen);
2919 script->cmdStruct[script->csLen-1] = val;
2920 }
2921
2922 /* Search a Jim_Obj contained in 'script' with the same stinrg repr.
2923 * of objPtr. Search nested script objects recursively. */
2924 static Jim_Obj *ScriptSearchLiteral(Jim_Interp *interp, ScriptObj *script,
2925 ScriptObj *scriptBarrier, Jim_Obj *objPtr)
2926 {
2927 int i;
2928
2929 for (i = 0; i < script->len; i++) {
2930 if (script->token[i].objPtr != objPtr &&
2931 Jim_StringEqObj(script->token[i].objPtr, objPtr, 0)) {
2932 return script->token[i].objPtr;
2933 }
2934 /* Enter recursively on scripts only if the object
2935 * is not the same as the one we are searching for
2936 * shared occurrences. */
2937 if (script->token[i].objPtr->typePtr == &scriptObjType &&
2938 script->token[i].objPtr != objPtr) {
2939 Jim_Obj *foundObjPtr;
2940
2941 ScriptObj *subScript =
2942 script->token[i].objPtr->internalRep.ptr;
2943 /* Don't recursively enter the script we are trying
2944 * to make shared to avoid circular references. */
2945 if (subScript == scriptBarrier) continue;
2946 if (subScript != script) {
2947 foundObjPtr =
2948 ScriptSearchLiteral(interp, subScript,
2949 scriptBarrier, objPtr);
2950 if (foundObjPtr != NULL)
2951 return foundObjPtr;
2952 }
2953 }
2954 }
2955 return NULL;
2956 }
2957
2958 /* Share literals of a script recursively sharing sub-scripts literals. */
2959 static void ScriptShareLiterals(Jim_Interp *interp, ScriptObj *script,
2960 ScriptObj *topLevelScript)
2961 {
2962 int i, j;
2963
2964 return;
2965 /* Try to share with toplevel object. */
2966 if (topLevelScript != NULL) {
2967 for (i = 0; i < script->len; i++) {
2968 Jim_Obj *foundObjPtr;
2969 char *str = script->token[i].objPtr->bytes;
2970
2971 if (script->token[i].objPtr->refCount != 1) continue;
2972 if (script->token[i].objPtr->typePtr == &scriptObjType) continue;
2973 if (strchr(str, ' ') || strchr(str, '\n')) continue;
2974 foundObjPtr = ScriptSearchLiteral(interp,
2975 topLevelScript,
2976 script, /* barrier */
2977 script->token[i].objPtr);
2978 if (foundObjPtr != NULL) {
2979 Jim_IncrRefCount(foundObjPtr);
2980 Jim_DecrRefCount(interp,
2981 script->token[i].objPtr);
2982 script->token[i].objPtr = foundObjPtr;
2983 }
2984 }
2985 }
2986 /* Try to share locally */
2987 for (i = 0; i < script->len; i++) {
2988 char *str = script->token[i].objPtr->bytes;
2989
2990 if (script->token[i].objPtr->refCount != 1) continue;
2991 if (strchr(str, ' ') || strchr(str, '\n')) continue;
2992 for (j = 0; j < script->len; j++) {
2993 if (script->token[i].objPtr !=
2994 script->token[j].objPtr &&
2995 Jim_StringEqObj(script->token[i].objPtr,
2996 script->token[j].objPtr, 0))
2997 {
2998 Jim_IncrRefCount(script->token[j].objPtr);
2999 Jim_DecrRefCount(interp,
3000 script->token[i].objPtr);
3001 script->token[i].objPtr =
3002 script->token[j].objPtr;
3003 }
3004 }
3005 }
3006 }
3007
3008 /* This method takes the string representation of an object
3009 * as a Tcl script, and generates the pre-parsed internal representation
3010 * of the script. */
3011 int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
3012 {
3013 int scriptTextLen;
3014 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
3015 struct JimParserCtx parser;
3016 struct ScriptObj *script = Jim_Alloc(sizeof(*script));
3017 ScriptToken *token;
3018 int args, tokens, start, end, i;
3019 int initialLineNumber;
3020 int propagateSourceInfo = 0;
3021
3022 script->len = 0;
3023 script->csLen = 0;
3024 script->commands = 0;
3025 script->token = NULL;
3026 script->cmdStruct = NULL;
3027 script->inUse = 1;
3028 /* Try to get information about filename / line number */
3029 if (objPtr->typePtr == &sourceObjType) {
3030 script->fileName =
3031 Jim_StrDup(objPtr->internalRep.sourceValue.fileName);
3032 initialLineNumber = objPtr->internalRep.sourceValue.lineNumber;
3033 propagateSourceInfo = 1;
3034 } else {
3035 script->fileName = Jim_StrDup("");
3036 initialLineNumber = 1;
3037 }
3038
3039 JimParserInit(&parser, scriptText, scriptTextLen, initialLineNumber);
3040 while(!JimParserEof(&parser)) {
3041 char *token;
3042 int len, type, linenr;
3043
3044 JimParseScript(&parser);
3045 token = JimParserGetToken(&parser, &len, &type, &linenr);
3046 ScriptObjAddToken(interp, script, token, len, type,
3047 propagateSourceInfo ? script->fileName : NULL,
3048 linenr);
3049 }
3050 token = script->token;
3051
3052 /* Compute the command structure array
3053 * (see the ScriptObj struct definition for more info) */
3054 start = 0; /* Current command start token index */
3055 end = -1; /* Current command end token index */
3056 while (1) {
3057 int expand = 0; /* expand flag. set to 1 on {expand} form. */
3058 int interpolation = 0; /* set to 1 if there is at least one
3059 argument of the command obtained via
3060 interpolation of more tokens. */
3061 /* Search for the end of command, while
3062 * count the number of args. */
3063 start = ++end;
3064 if (start >= script->len) break;
3065 args = 1; /* Number of args in current command */
3066 while (token[end].type != JIM_TT_EOL) {
3067 if (end == 0 || token[end-1].type == JIM_TT_SEP ||
3068 token[end-1].type == JIM_TT_EOL)
3069 {
3070 if (token[end].type == JIM_TT_STR &&
3071 token[end+1].type != JIM_TT_SEP &&
3072 token[end+1].type != JIM_TT_EOL &&
3073 (!strcmp(token[end].objPtr->bytes, "expand") ||
3074 !strcmp(token[end].objPtr->bytes, "*")))
3075 expand++;
3076 }
3077 if (token[end].type == JIM_TT_SEP)
3078 args++;
3079 end++;
3080 }
3081 interpolation = !((end-start+1) == args*2);
3082 /* Add the 'number of arguments' info into cmdstruct.
3083 * Negative value if there is list expansion involved. */
3084 if (expand)
3085 ScriptObjAddInt(script, -1);
3086 ScriptObjAddInt(script, args);
3087 /* Now add info about the number of tokens. */
3088 tokens = 0; /* Number of tokens in current argument. */
3089 expand = 0;
3090 for (i = start; i <= end; i++) {
3091 if (token[i].type == JIM_TT_SEP ||
3092 token[i].type == JIM_TT_EOL)
3093 {
3094 if (tokens == 1 && expand)
3095 expand = 0;
3096 ScriptObjAddInt(script,
3097 expand ? -tokens : tokens);
3098
3099 expand = 0;
3100 tokens = 0;
3101 continue;
3102 } else if (tokens == 0 && token[i].type == JIM_TT_STR &&
3103 (!strcmp(token[i].objPtr->bytes, "expand") ||
3104 !strcmp(token[i].objPtr->bytes, "*")))
3105 {
3106 expand++;
3107 }
3108 tokens++;
3109 }
3110 }
3111 /* Perform literal sharing, but only for objects that appear
3112 * to be scripts written as literals inside the source code,
3113 * and not computed at runtime. Literal sharing is a costly
3114 * operation that should be done only against objects that
3115 * are likely to require compilation only the first time, and
3116 * then are executed multiple times. */
3117 if (propagateSourceInfo && interp->framePtr->procBodyObjPtr) {
3118 Jim_Obj *bodyObjPtr = interp->framePtr->procBodyObjPtr;
3119 if (bodyObjPtr->typePtr == &scriptObjType) {
3120 ScriptObj *bodyScript =
3121 bodyObjPtr->internalRep.ptr;
3122 ScriptShareLiterals(interp, script, bodyScript);
3123 }
3124 } else if (propagateSourceInfo) {
3125 ScriptShareLiterals(interp, script, NULL);
3126 }
3127 /* Free the old internal rep and set the new one. */
3128 Jim_FreeIntRep(interp, objPtr);
3129 Jim_SetIntRepPtr(objPtr, script);
3130 objPtr->typePtr = &scriptObjType;
3131 return JIM_OK;
3132 }
3133
3134 ScriptObj *Jim_GetScript(Jim_Interp *interp, Jim_Obj *objPtr)
3135 {
3136 if (objPtr->typePtr != &scriptObjType) {
3137 SetScriptFromAny(interp, objPtr);
3138 }
3139 return (ScriptObj*) Jim_GetIntRepPtr(objPtr);
3140 }
3141
3142 /* -----------------------------------------------------------------------------
3143 * Commands
3144 * ---------------------------------------------------------------------------*/
3145
3146 /* Commands HashTable Type.
3147 *
3148 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3149 static void Jim_CommandsHT_ValDestructor(void *interp, void *val)
3150 {
3151 Jim_Cmd *cmdPtr = (void*) val;
3152
3153 if (cmdPtr->cmdProc == NULL) {
3154 Jim_DecrRefCount(interp, cmdPtr->argListObjPtr);
3155 Jim_DecrRefCount(interp, cmdPtr->bodyObjPtr);
3156 if (cmdPtr->staticVars) {
3157 Jim_FreeHashTable(cmdPtr->staticVars);
3158 Jim_Free(cmdPtr->staticVars);
3159 }
3160 } else if (cmdPtr->delProc != NULL) {
3161 /* If it was a C coded command, call the delProc if any */
3162 cmdPtr->delProc(interp, cmdPtr->privData);
3163 }
3164 Jim_Free(val);
3165 }
3166
3167 static Jim_HashTableType JimCommandsHashTableType = {
3168 JimStringCopyHTHashFunction, /* hash function */
3169 JimStringCopyHTKeyDup, /* key dup */
3170 NULL, /* val dup */
3171 JimStringCopyHTKeyCompare, /* key compare */
3172 JimStringCopyHTKeyDestructor, /* key destructor */
3173 Jim_CommandsHT_ValDestructor /* val destructor */
3174 };
3175
3176 /* ------------------------- Commands related functions --------------------- */
3177
3178 int Jim_CreateCommand(Jim_Interp *interp, const char *cmdName,
3179 Jim_CmdProc cmdProc, void *privData, Jim_DelCmdProc delProc)
3180 {
3181 Jim_HashEntry *he;
3182 Jim_Cmd *cmdPtr;
3183
3184 he = Jim_FindHashEntry(&interp->commands, cmdName);
3185 if (he == NULL) { /* New command to create */
3186 cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
3187 Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);
3188 } else {
3189 Jim_InterpIncrProcEpoch(interp);
3190 /* Free the arglist/body objects if it was a Tcl procedure */
3191 cmdPtr = he->val;
3192 if (cmdPtr->cmdProc == NULL) {
3193 Jim_DecrRefCount(interp, cmdPtr->argListObjPtr);
3194 Jim_DecrRefCount(interp, cmdPtr->bodyObjPtr);
3195 if (cmdPtr->staticVars) {
3196 Jim_FreeHashTable(cmdPtr->staticVars);
3197 Jim_Free(cmdPtr->staticVars);
3198 }
3199 cmdPtr->staticVars = NULL;
3200 } else if (cmdPtr->delProc != NULL) {
3201 /* If it was a C coded command, call the delProc if any */
3202 cmdPtr->delProc(interp, cmdPtr->privData);
3203 }
3204 }
3205
3206 /* Store the new details for this proc */
3207 cmdPtr->delProc = delProc;
3208 cmdPtr->cmdProc = cmdProc;
3209 cmdPtr->privData = privData;
3210
3211 /* There is no need to increment the 'proc epoch' because
3212 * creation of a new procedure can never affect existing
3213 * cached commands. We don't do negative caching. */
3214 return JIM_OK;
3215 }
3216
3217 int Jim_CreateProcedure(Jim_Interp *interp, const char *cmdName,
3218 Jim_Obj *argListObjPtr, Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr,
3219 int arityMin, int arityMax)
3220 {
3221 Jim_Cmd *cmdPtr;
3222
3223 cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
3224 cmdPtr->cmdProc = NULL; /* Not a C coded command */
3225 cmdPtr->argListObjPtr = argListObjPtr;
3226 cmdPtr->bodyObjPtr = bodyObjPtr;
3227 Jim_IncrRefCount(argListObjPtr);
3228 Jim_IncrRefCount(bodyObjPtr);
3229 cmdPtr->arityMin = arityMin;
3230 cmdPtr->arityMax = arityMax;
3231 cmdPtr->staticVars = NULL;
3232
3233 /* Create the statics hash table. */
3234 if (staticsListObjPtr) {
3235 int len, i;
3236
3237 Jim_ListLength(interp, staticsListObjPtr, &len);
3238 if (len != 0) {
3239 cmdPtr->staticVars = Jim_Alloc(sizeof(Jim_HashTable));
3240 Jim_InitHashTable(cmdPtr->staticVars, getJimVariablesHashTableType(),
3241 interp);
3242 for (i = 0; i < len; i++) {
3243 Jim_Obj *objPtr, *initObjPtr, *nameObjPtr;
3244 Jim_Var *varPtr;
3245 int subLen;
3246
3247 Jim_ListIndex(interp, staticsListObjPtr, i, &objPtr, JIM_NONE);
3248 /* Check if it's composed of two elements. */
3249 Jim_ListLength(interp, objPtr, &subLen);
3250 if (subLen == 1 || subLen == 2) {
3251 /* Try to get the variable value from the current
3252 * environment. */
3253 Jim_ListIndex(interp, objPtr, 0, &nameObjPtr, JIM_NONE);
3254 if (subLen == 1) {
3255 initObjPtr = Jim_GetVariable(interp, nameObjPtr,
3256 JIM_NONE);
3257 if (initObjPtr == NULL) {
3258 Jim_SetResult(interp,
3259 Jim_NewEmptyStringObj(interp));
3260 Jim_AppendStrings(interp, Jim_GetResult(interp),
3261 "variable for initialization of static \"",
3262 Jim_GetString(nameObjPtr, NULL),
3263 "\" not found in the local context",
3264 NULL);
3265 goto err;
3266 }
3267 } else {
3268 Jim_ListIndex(interp, objPtr, 1, &initObjPtr, JIM_NONE);
3269 }
3270 varPtr = Jim_Alloc(sizeof(*varPtr));
3271 varPtr->objPtr = initObjPtr;
3272 Jim_IncrRefCount(initObjPtr);
3273 varPtr->linkFramePtr = NULL;
3274 if (Jim_AddHashEntry(cmdPtr->staticVars,
3275 Jim_GetString(nameObjPtr, NULL),
3276 varPtr) != JIM_OK)
3277 {
3278 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3279 Jim_AppendStrings(interp, Jim_GetResult(interp),
3280 "static variable name \"",
3281 Jim_GetString(objPtr, NULL), "\"",
3282 " duplicated in statics list", NULL);
3283 Jim_DecrRefCount(interp, initObjPtr);
3284 Jim_Free(varPtr);
3285 goto err;
3286 }
3287 } else {
3288 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3289 Jim_AppendStrings(interp, Jim_GetResult(interp),
3290 "too many fields in static specifier \"",
3291 objPtr, "\"", NULL);
3292 goto err;
3293 }
3294 }
3295 }
3296 }
3297
3298 /* Add the new command */
3299
3300 /* it may already exist, so we try to delete the old one */
3301 if (Jim_DeleteHashEntry(&interp->commands, cmdName) != JIM_ERR) {
3302 /* There was an old procedure with the same name, this requires
3303 * a 'proc epoch' update. */
3304 Jim_InterpIncrProcEpoch(interp);
3305 }
3306 /* If a procedure with the same name didn't existed there is no need
3307 * to increment the 'proc epoch' because creation of a new procedure
3308 * can never affect existing cached commands. We don't do
3309 * negative caching. */
3310 Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);
3311 return JIM_OK;
3312
3313 err:
3314 Jim_FreeHashTable(cmdPtr->staticVars);
3315 Jim_Free(cmdPtr->staticVars);
3316 Jim_DecrRefCount(interp, argListObjPtr);
3317 Jim_DecrRefCount(interp, bodyObjPtr);
3318 Jim_Free(cmdPtr);
3319 return JIM_ERR;
3320 }
3321
3322 int Jim_DeleteCommand(Jim_Interp *interp, const char *cmdName)
3323 {
3324 if (Jim_DeleteHashEntry(&interp->commands, cmdName) == JIM_ERR)
3325 return JIM_ERR;
3326 Jim_InterpIncrProcEpoch(interp);
3327 return JIM_OK;
3328 }
3329
3330 int Jim_RenameCommand(Jim_Interp *interp, const char *oldName,
3331 const char *newName)
3332 {
3333 Jim_Cmd *cmdPtr;
3334 Jim_HashEntry *he;
3335 Jim_Cmd *copyCmdPtr;
3336
3337 if (newName[0] == '\0') /* Delete! */
3338 return Jim_DeleteCommand(interp, oldName);
3339 /* Rename */
3340 he = Jim_FindHashEntry(&interp->commands, oldName);
3341 if (he == NULL)
3342 return JIM_ERR; /* Invalid command name */
3343 cmdPtr = he->val;
3344 copyCmdPtr = Jim_Alloc(sizeof(Jim_Cmd));
3345 *copyCmdPtr = *cmdPtr;
3346 /* In order to avoid that a procedure will get arglist/body/statics
3347 * freed by the hash table methods, fake a C-coded command
3348 * setting cmdPtr->cmdProc as not NULL */
3349 cmdPtr->cmdProc = (void*)1;
3350 /* Also make sure delProc is NULL. */
3351 cmdPtr->delProc = NULL;
3352 /* Destroy the old command, and make sure the new is freed
3353 * as well. */
3354 Jim_DeleteHashEntry(&interp->commands, oldName);
3355 Jim_DeleteHashEntry(&interp->commands, newName);
3356 /* Now the new command. We are sure it can't fail because
3357 * the target name was already freed. */
3358 Jim_AddHashEntry(&interp->commands, newName, copyCmdPtr);
3359 /* Increment the epoch */
3360 Jim_InterpIncrProcEpoch(interp);
3361 return JIM_OK;
3362 }
3363
3364 /* -----------------------------------------------------------------------------
3365 * Command object
3366 * ---------------------------------------------------------------------------*/
3367
3368 static int SetCommandFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3369
3370 static Jim_ObjType commandObjType = {
3371 "command",
3372 NULL,
3373 NULL,
3374 NULL,
3375 JIM_TYPE_REFERENCES,
3376 };
3377
3378 int SetCommandFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
3379 {
3380 Jim_HashEntry *he;
3381 const char *cmdName;
3382
3383 /* Get the string representation */
3384 cmdName = Jim_GetString(objPtr, NULL);
3385 /* Lookup this name into the commands hash table */
3386 he = Jim_FindHashEntry(&interp->commands, cmdName);
3387 if (he == NULL)
3388 return JIM_ERR;
3389
3390 /* Free the old internal repr and set the new one. */
3391 Jim_FreeIntRep(interp, objPtr);
3392 objPtr->typePtr = &commandObjType;
3393 objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
3394 objPtr->internalRep.cmdValue.cmdPtr = (void*)he->val;
3395 return JIM_OK;
3396 }
3397
3398 /* This function returns the command structure for the command name
3399 * stored in objPtr. It tries to specialize the objPtr to contain
3400 * a cached info instead to perform the lookup into the hash table
3401 * every time. The information cached may not be uptodate, in such
3402 * a case the lookup is performed and the cache updated. */
3403 Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
3404 {
3405 if ((objPtr->typePtr != &commandObjType ||
3406 objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch) &&
3407 SetCommandFromAny(interp, objPtr) == JIM_ERR) {
3408 if (flags & JIM_ERRMSG) {
3409 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3410 Jim_AppendStrings(interp, Jim_GetResult(interp),
3411 "invalid command name \"", objPtr->bytes, "\"",
3412 NULL);
3413 }
3414 return NULL;
3415 }
3416 return objPtr->internalRep.cmdValue.cmdPtr;
3417 }
3418
3419 /* -----------------------------------------------------------------------------
3420 * Variables
3421 * ---------------------------------------------------------------------------*/
3422
3423 /* Variables HashTable Type.
3424 *
3425 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3426 static void JimVariablesHTValDestructor(void *interp, void *val)
3427 {
3428 Jim_Var *varPtr = (void*) val;
3429
3430 Jim_DecrRefCount(interp, varPtr->objPtr);
3431 Jim_Free(val);
3432 }
3433
3434 static Jim_HashTableType JimVariablesHashTableType = {
3435 JimStringCopyHTHashFunction, /* hash function */
3436 JimStringCopyHTKeyDup, /* key dup */
3437 NULL, /* val dup */
3438 JimStringCopyHTKeyCompare, /* key compare */
3439 JimStringCopyHTKeyDestructor, /* key destructor */
3440 JimVariablesHTValDestructor /* val destructor */
3441 };
3442
3443 static Jim_HashTableType *getJimVariablesHashTableType(void)
3444 {
3445 return &JimVariablesHashTableType;
3446 }
3447
3448 /* -----------------------------------------------------------------------------
3449 * Variable object
3450 * ---------------------------------------------------------------------------*/
3451
3452 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3453
3454 static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3455
3456 static Jim_ObjType variableObjType = {
3457 "variable",
3458 NULL,
3459 NULL,
3460 NULL,
3461 JIM_TYPE_REFERENCES,
3462 };
3463
3464 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3465 * is in the form "varname(key)". */
3466 static int Jim_NameIsDictSugar(const char *str, int len)
3467 {
3468 if (len == -1)
3469 len = strlen(str);
3470 if (len && str[len-1] == ')' && strchr(str, '(') != NULL)
3471 return 1;
3472 return 0;
3473 }
3474
3475 /* This method should be called only by the variable API.
3476 * It returns JIM_OK on success (variable already exists),
3477 * JIM_ERR if it does not exists, JIM_DICT_GLUE if it's not
3478 * a variable name, but syntax glue for [dict] i.e. the last
3479 * character is ')' */
3480 int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
3481 {
3482 Jim_HashEntry *he;
3483 const char *varName;
3484 int len;
3485
3486 /* Check if the object is already an uptodate variable */
3487 if (objPtr->typePtr == &variableObjType &&
3488 objPtr->internalRep.varValue.callFrameId == interp->framePtr->id)
3489 return JIM_OK; /* nothing to do */
3490 /* Get the string representation */
3491 varName = Jim_GetString(objPtr, &len);
3492 /* Make sure it's not syntax glue to get/set dict. */
3493 if (Jim_NameIsDictSugar(varName, len))
3494 return JIM_DICT_SUGAR;
3495 if (varName[0] == ':' && varName[1] == ':') {
3496 he = Jim_FindHashEntry(&interp->topFramePtr->vars, varName + 2);
3497 if (he == NULL) {
3498 return JIM_ERR;
3499 }
3500 }
3501 else {
3502 /* Lookup this name into the variables hash table */
3503 he = Jim_FindHashEntry(&interp->framePtr->vars, varName);
3504 if (he == NULL) {
3505 /* Try with static vars. */
3506 if (interp->framePtr->staticVars == NULL)
3507 return JIM_ERR;
3508 if (!(he = Jim_FindHashEntry(interp->framePtr->staticVars, varName)))
3509 return JIM_ERR;
3510 }
3511 }
3512 /* Free the old internal repr and set the new one. */
3513 Jim_FreeIntRep(interp, objPtr);
3514 objPtr->typePtr = &variableObjType;
3515 objPtr->internalRep.varValue.callFrameId = interp->framePtr->id;
3516 objPtr->internalRep.varValue.varPtr = (void*)he->val;
3517 return JIM_OK;
3518 }
3519
3520 /* -------------------- Variables related functions ------------------------- */
3521 static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr,
3522 Jim_Obj *valObjPtr);
3523 static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr);
3524
3525 /* For now that's dummy. Variables lookup should be optimized
3526 * in many ways, with caching of lookups, and possibly with
3527 * a table of pre-allocated vars in every CallFrame for local vars.
3528 * All the caching should also have an 'epoch' mechanism similar
3529 * to the one used by Tcl for procedures lookup caching. */
3530
3531 int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
3532 {
3533 const char *name;
3534 Jim_Var *var;
3535 int err;
3536
3537 if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {
3538 /* Check for [dict] syntax sugar. */
3539 if (err == JIM_DICT_SUGAR)
3540 return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
3541 /* New variable to create */
3542 name = Jim_GetString(nameObjPtr, NULL);
3543
3544 var = Jim_Alloc(sizeof(*var));
3545 var->objPtr = valObjPtr;
3546 Jim_IncrRefCount(valObjPtr);
3547 var->linkFramePtr = NULL;
3548 /* Insert the new variable */
3549 if (name[0] == ':' && name[1] == ':') {
3550 /* Into to the top evel frame */
3551 Jim_AddHashEntry(&interp->topFramePtr->vars, name + 2, var);
3552 }
3553 else {
3554 Jim_AddHashEntry(&interp->framePtr->vars, name, var);
3555 }
3556 /* Make the object int rep a variable */
3557 Jim_FreeIntRep(interp, nameObjPtr);
3558 nameObjPtr->typePtr = &variableObjType;
3559 nameObjPtr->internalRep.varValue.callFrameId =
3560 interp->framePtr->id;
3561 nameObjPtr->internalRep.varValue.varPtr = var;
3562 } else {
3563 var = nameObjPtr->internalRep.varValue.varPtr;
3564 if (var->linkFramePtr == NULL) {
3565 Jim_IncrRefCount(valObjPtr);
3566 Jim_DecrRefCount(interp, var->objPtr);
3567 var->objPtr = valObjPtr;
3568 } else { /* Else handle the link */
3569 Jim_CallFrame *savedCallFrame;
3570
3571 savedCallFrame = interp->framePtr;
3572 interp->framePtr = var->linkFramePtr;
3573 err = Jim_SetVariable(interp, var->objPtr, valObjPtr);
3574 interp->framePtr = savedCallFrame;
3575 if (err != JIM_OK)
3576 return err;
3577 }
3578 }
3579 return JIM_OK;
3580 }
3581
3582 int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
3583 {
3584 Jim_Obj *nameObjPtr;
3585 int result;
3586
3587 nameObjPtr = Jim_NewStringObj(interp, name, -1);
3588 Jim_IncrRefCount(nameObjPtr);
3589 result = Jim_SetVariable(interp, nameObjPtr, objPtr);
3590 Jim_DecrRefCount(interp, nameObjPtr);
3591 return result;
3592 }
3593
3594 int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
3595 {
3596 Jim_CallFrame *savedFramePtr;
3597 int result;
3598
3599 savedFramePtr = interp->framePtr;
3600 interp->framePtr = interp->topFramePtr;
3601 result = Jim_SetVariableStr(interp, name, objPtr);
3602 interp->framePtr = savedFramePtr;
3603 return result;
3604 }
3605
3606 int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
3607 {
3608 Jim_Obj *nameObjPtr, *valObjPtr;
3609 int result;
3610
3611 nameObjPtr = Jim_NewStringObj(interp, name, -1);
3612 valObjPtr = Jim_NewStringObj(interp, val, -1);
3613 Jim_IncrRefCount(nameObjPtr);
3614 Jim_IncrRefCount(valObjPtr);
3615 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3616 Jim_DecrRefCount(interp, nameObjPtr);
3617 Jim_DecrRefCount(interp, valObjPtr);
3618 return result;
3619 }
3620
3621 int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
3622 Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
3623 {
3624 const char *varName;
3625 int len;
3626
3627 /* Check for cycles. */
3628 if (interp->framePtr == targetCallFrame) {
3629 Jim_Obj *objPtr = targetNameObjPtr;
3630 Jim_Var *varPtr;
3631 /* Cycles are only possible with 'uplevel 0' */
3632 while(1) {
3633 if (Jim_StringEqObj(objPtr, nameObjPtr, 0)) {
3634 Jim_SetResultString(interp,
3635 "can't upvar from variable to itself", -1);
3636 return JIM_ERR;
3637 }
3638 if (SetVariableFromAny(interp, objPtr) != JIM_OK)
3639 break;
3640 varPtr = objPtr->internalRep.varValue.varPtr;
3641 if (varPtr->linkFramePtr != targetCallFrame) break;
3642 objPtr = varPtr->objPtr;
3643 }
3644 }
3645 varName = Jim_GetString(nameObjPtr, &len);
3646 if (Jim_NameIsDictSugar(varName, len)) {
3647 Jim_SetResultString(interp,
3648 "Dict key syntax invalid as link source", -1);
3649 return JIM_ERR;
3650 }
3651 /* Perform the binding */
3652 Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
3653 /* We are now sure 'nameObjPtr' type is variableObjType */
3654 nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;
3655 return JIM_OK;
3656 }
3657
3658 /* Return the Jim_Obj pointer associated with a variable name,
3659 * or NULL if the variable was not found in the current context.
3660 * The same optimization discussed in the comment to the
3661 * 'SetVariable' function should apply here. */
3662 Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
3663 {
3664 int err;
3665
3666 /* All the rest is handled here */
3667 if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {
3668 /* Check for [dict] syntax sugar. */
3669 if (err == JIM_DICT_SUGAR)
3670 return JimDictSugarGet(interp, nameObjPtr);
3671 if (flags & JIM_ERRMSG) {
3672 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3673 Jim_AppendStrings(interp, Jim_GetResult(interp),
3674 "can't read \"", nameObjPtr->bytes,
3675 "\": no such variable", NULL);
3676 }
3677 return NULL;
3678 } else {
3679 Jim_Var *varPtr;
3680 Jim_Obj *objPtr;
3681 Jim_CallFrame *savedCallFrame;
3682
3683 varPtr = nameObjPtr->internalRep.varValue.varPtr;
3684 if (varPtr->linkFramePtr == NULL)
3685 return varPtr->objPtr;
3686 /* The variable is a link? Resolve it. */
3687 savedCallFrame = interp->framePtr;
3688 interp->framePtr = varPtr->linkFramePtr;
3689 objPtr = Jim_GetVariable(interp, varPtr->objPtr, JIM_NONE);
3690 if (objPtr == NULL && flags & JIM_ERRMSG) {
3691 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3692 Jim_AppendStrings(interp, Jim_GetResult(interp),
3693 "can't read \"", nameObjPtr->bytes,
3694 "\": no such variable", NULL);
3695 }
3696 interp->framePtr = savedCallFrame;
3697 return objPtr;
3698 }
3699 }
3700
3701 Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr,
3702 int flags)
3703 {
3704 Jim_CallFrame *savedFramePtr;
3705 Jim_Obj *objPtr;
3706
3707 savedFramePtr = interp->framePtr;
3708 interp->framePtr = interp->topFramePtr;
3709 objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
3710 interp->framePtr = savedFramePtr;
3711
3712 return objPtr;
3713 }
3714
3715 Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
3716 {
3717 Jim_Obj *nameObjPtr, *varObjPtr;
3718
3719 nameObjPtr = Jim_NewStringObj(interp, name, -1);
3720 Jim_IncrRefCount(nameObjPtr);
3721 varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
3722 Jim_DecrRefCount(interp, nameObjPtr);
3723 return varObjPtr;
3724 }
3725
3726 Jim_Obj *Jim_GetGlobalVariableStr