jim.c 397 KB
Newer Older
1
/* Jim - A small embeddable Tcl interpreter
oharboe's avatar
oharboe committed
2
 *
3
4
 * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
 * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
oharboe's avatar
oharboe committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net> 
 * Copyright 2008 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
 * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
 * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
 * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
 * 
 * The FreeBSD license
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation
 * are those of the authors and should not be interpreted as representing
 * official policies, either expressed or implied, of the Jim Tcl Project.
 **/
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#define __JIM_CORE__
#define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */

#ifdef __ECOS
#include <pkgconf/jimtcl.h>
#endif
#ifndef JIM_ANSIC
#define JIM_DYNLIB      /* Dynamic library support for UNIX and WIN32 */
#endif /* JIM_ANSIC */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <limits.h>
#include <assert.h>
#include <errno.h>
#include <time.h>

ntfreak's avatar
ntfreak committed
61
62
#include "replacements.h"

63
64
65
66
67
68
69
/* Include the platform dependent libraries for
 * dynamic loading of libraries. */
#ifdef JIM_DYNLIB
#if defined(_WIN32) || defined(WIN32)
#ifndef WIN32
#define WIN32 1
#endif
ntfreak's avatar
ntfreak committed
70
#ifndef STRICT
71
#define STRICT
ntfreak's avatar
ntfreak committed
72
#endif
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#if _MSC_VER >= 1000
#pragma warning(disable:4146)
#endif /* _MSC_VER */
#else
#include <dlfcn.h>
#endif /* WIN32 */
#endif /* JIM_DYNLIB */

#ifdef __ECOS
#include <cyg/jimtcl/jim.h>
#else
#include "jim.h"
#endif

#ifdef HAVE_BACKTRACE
#include <execinfo.h>
#endif

/* -----------------------------------------------------------------------------
 * Global variables
 * ---------------------------------------------------------------------------*/

/* A shared empty string for the objects string representation.
 * Jim_InvalidateStringRep knows about it and don't try to free. */
static char *JimEmptyStringRep = (char*) "";

/* -----------------------------------------------------------------------------
 * Required prototypes of not exported functions
 * ---------------------------------------------------------------------------*/
static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf);
static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags);
static void JimRegisterCoreApi(Jim_Interp *interp);

static Jim_HashTableType JimVariablesHashTableType;

/* -----------------------------------------------------------------------------
 * Utility functions
 * ---------------------------------------------------------------------------*/

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
static char *
jim_vasprintf( const char *fmt, va_list ap )
{
#ifndef HAVE_VASPRINTF
	/* yucky way */
static char buf[2048];
	vsnprintf( buf, sizeof(buf), fmt, ap );
	/* garentee termination */
	buf[sizeof(buf)-1] = 0;
#else
	char *buf;
	vasprintf( &buf, fmt, ap );
#endif
	return buf;
}

static void
jim_vasprintf_done( void *buf )
{
#ifndef HAVE_VASPRINTF
	(void)(buf);
#else
	free(buf);
#endif
}
	

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
 * Convert a string to a jim_wide INTEGER.
 * This function originates from BSD.
 *
 * Ignores `locale' stuff.  Assumes that the upper and lower case
 * alphabets and digits are each contiguous.
 */
#ifdef HAVE_LONG_LONG
#define JimIsAscii(c) (((c) & ~0x7f) == 0)
static jim_wide JimStrtoll(const char *nptr, char **endptr, register int base)
{
    register const char *s;
    register unsigned jim_wide acc;
    register unsigned char c;
    register unsigned jim_wide qbase, cutoff;
    register int neg, any, cutlim;

    /*
     * Skip white space and pick up leading +/- sign if any.
     * If base is 0, allow 0x for hex and 0 for octal, else
     * assume decimal; if base is already 16, allow 0x.
     */
    s = nptr;
    do {
        c = *s++;
    } while (isspace(c));
    if (c == '-') {
        neg = 1;
        c = *s++;
    } else {
        neg = 0;
        if (c == '+')
            c = *s++;
    }
    if ((base == 0 || base == 16) &&
        c == '0' && (*s == 'x' || *s == 'X')) {
        c = s[1];
        s += 2;
        base = 16;
    }
    if (base == 0)
        base = c == '0' ? 8 : 10;

    /*
     * Compute the cutoff value between legal numbers and illegal
     * numbers.  That is the largest legal value, divided by the
     * base.  An input number that is greater than this value, if
     * followed by a legal input character, is too big.  One that
     * is equal to this value may be valid or not; the limit
     * between valid and invalid numbers is then based on the last
     * digit.  For instance, if the range for quads is
     * [-9223372036854775808..9223372036854775807] and the input base
     * is 10, cutoff will be set to 922337203685477580 and cutlim to
     * either 7 (neg==0) or 8 (neg==1), meaning that if we have
     * accumulated a value > 922337203685477580, or equal but the
     * next digit is > 7 (or 8), the number is too big, and we will
     * return a range error.
     *
     * Set any if any `digits' consumed; make it negative to indicate
     * overflow.
     */
    qbase = (unsigned)base;
    cutoff = neg ? (unsigned jim_wide)-(LLONG_MIN + LLONG_MAX) + LLONG_MAX
        : LLONG_MAX;
    cutlim = (int)(cutoff % qbase);
    cutoff /= qbase;
    for (acc = 0, any = 0;; c = *s++) {
        if (!JimIsAscii(c))
            break;
        if (isdigit(c))
            c -= '0';
        else if (isalpha(c))
            c -= isupper(c) ? 'A' - 10 : 'a' - 10;
        else
            break;
        if (c >= base)
            break;
        if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
            any = -1;
        else {
            any = 1;
            acc *= qbase;
            acc += c;
        }
    }
    if (any < 0) {
        acc = neg ? LLONG_MIN : LLONG_MAX;
        errno = ERANGE;
    } else if (neg)
        acc = -acc;
    if (endptr != 0)
        *endptr = (char *)(any ? s - 1 : nptr);
    return (acc);
}
#endif

/* Glob-style pattern matching. */
static int JimStringMatch(const char *pattern, int patternLen,
        const char *string, int stringLen, int nocase)
{
    while(patternLen) {
        switch(pattern[0]) {
        case '*':
            while (pattern[1] == '*') {
                pattern++;
                patternLen--;
            }
            if (patternLen == 1)
                return 1; /* match */
            while(stringLen) {
                if (JimStringMatch(pattern+1, patternLen-1,
                            string, stringLen, nocase))
                    return 1; /* match */
                string++;
                stringLen--;
            }
            return 0; /* no match */
            break;
        case '?':
            if (stringLen == 0)
                return 0; /* no match */
            string++;
            stringLen--;
            break;
        case '[':
        {
            int not, match;

            pattern++;
            patternLen--;
            not = pattern[0] == '^';
            if (not) {
                pattern++;
                patternLen--;
            }
            match = 0;
            while(1) {
                if (pattern[0] == '\\') {
                    pattern++;
                    patternLen--;
                    if (pattern[0] == string[0])
                        match = 1;
                } else if (pattern[0] == ']') {
                    break;
                } else if (patternLen == 0) {
                    pattern--;
                    patternLen++;
                    break;
                } else if (pattern[1] == '-' && patternLen >= 3) {
                    int start = pattern[0];
                    int end = pattern[2];
                    int c = string[0];
                    if (start > end) {
                        int t = start;
                        start = end;
                        end = t;
                    }
                    if (nocase) {
                        start = tolower(start);
                        end = tolower(end);
                        c = tolower(c);
                    }
                    pattern += 2;
                    patternLen -= 2;
                    if (c >= start && c <= end)
                        match = 1;
                } else {
                    if (!nocase) {
                        if (pattern[0] == string[0])
                            match = 1;
                    } else {
                        if (tolower((int)pattern[0]) == tolower((int)string[0]))
                            match = 1;
                    }
                }
                pattern++;
                patternLen--;
            }
            if (not)
                match = !match;
            if (!match)
                return 0; /* no match */
            string++;
            stringLen--;
            break;
        }
        case '\\':
            if (patternLen >= 2) {
                pattern++;
                patternLen--;
            }
            /* fall through */
        default:
            if (!nocase) {
                if (pattern[0] != string[0])
                    return 0; /* no match */
            } else {
                if (tolower((int)pattern[0]) != tolower((int)string[0]))
                    return 0; /* no match */
            }
            string++;
            stringLen--;
            break;
        }
        pattern++;
        patternLen--;
        if (stringLen == 0) {
            while(*pattern == '*') {
                pattern++;
                patternLen--;
            }
            break;
        }
    }
    if (patternLen == 0 && stringLen == 0)
        return 1;
    return 0;
}

int JimStringCompare(const char *s1, int l1, const char *s2, int l2,
        int nocase)
{
    unsigned char *u1 = (unsigned char*) s1, *u2 = (unsigned char*) s2;

    if (nocase == 0) {
        while(l1 && l2) {
            if (*u1 != *u2)
                return (int)*u1-*u2;
            u1++; u2++; l1--; l2--;
        }
        if (!l1 && !l2) return 0;
        return l1-l2;
    } else {
        while(l1 && l2) {
            if (tolower((int)*u1) != tolower((int)*u2))
                return tolower((int)*u1)-tolower((int)*u2);
            u1++; u2++; l1--; l2--;
        }
        if (!l1 && !l2) return 0;
        return l1-l2;
    }
}

/* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
 * The index of the first occurrence of s1 in s2 is returned. 
 * If s1 is not found inside s2, -1 is returned. */
int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int index)
{
    int i;

    if (!l1 || !l2 || l1 > l2) return -1;
    if (index < 0) index = 0;
    s2 += index;
    for (i = index; i <= l2-l1; i++) {
        if (memcmp(s2, s1, l1) == 0)
            return i;
        s2++;
    }
    return -1;
}

int Jim_WideToString(char *buf, jim_wide wideValue)
{
    const char *fmt = "%" JIM_WIDE_MODIFIER;
    return sprintf(buf, fmt, wideValue);
}

int Jim_StringToWide(const char *str, jim_wide *widePtr, int base)
{
    char *endptr;

#ifdef HAVE_LONG_LONG
    *widePtr = JimStrtoll(str, &endptr, base);
#else
    *widePtr = strtol(str, &endptr, base);
#endif
oharboe's avatar
oharboe committed
417
    if ((str[0] == '\0') || (str == endptr) )
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
        return JIM_ERR;
    if (endptr[0] != '\0') {
        while(*endptr) {
            if (!isspace((int)*endptr))
                return JIM_ERR;
            endptr++;
        }
    }
    return JIM_OK;
}

int Jim_StringToIndex(const char *str, int *intPtr)
{
    char *endptr;

    *intPtr = strtol(str, &endptr, 10);
oharboe's avatar
oharboe committed
434
    if ( (str[0] == '\0') || (str == endptr) )
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
        return JIM_ERR;
    if (endptr[0] != '\0') {
        while(*endptr) {
            if (!isspace((int)*endptr))
                return JIM_ERR;
            endptr++;
        }
    }
    return JIM_OK;
}

/* The string representation of references has two features in order
 * to make the GC faster. The first is that every reference starts
 * with a non common character '~', in order to make the string matching
 * fater. The second is that the reference string rep his 32 characters
 * in length, this allows to avoid to check every object with a string
 * repr < 32, and usually there are many of this objects. */

#define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)

static int JimFormatReference(char *buf, Jim_Reference *refPtr, jim_wide id)
{
    const char *fmt = "<reference.<%s>.%020" JIM_WIDE_MODIFIER ">";
    sprintf(buf, fmt, refPtr->tag, id);
    return JIM_REFERENCE_SPACE;
}

int Jim_DoubleToString(char *buf, double doubleValue)
{
    char *s;
    int len;

    len = sprintf(buf, "%.17g", doubleValue);
    s = buf;
    while(*s) {
        if (*s == '.') return len;
        s++;
    }
    /* Add a final ".0" if it's a number. But not
     * for NaN or InF */
    if (isdigit((int)buf[0])
        || ((buf[0] == '-' || buf[0] == '+')
            && isdigit((int)buf[1]))) {
        s[0] = '.';
        s[1] = '0';
        s[2] = '\0';
        return len+2;
    }
    return len;
}

int Jim_StringToDouble(const char *str, double *doublePtr)
{
    char *endptr;

    *doublePtr = strtod(str, &endptr);
oharboe's avatar
oharboe committed
491
    if (str[0] == '\0' || endptr[0] != '\0' || (str == endptr) )
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
        return JIM_ERR;
    return JIM_OK;
}

static jim_wide JimPowWide(jim_wide b, jim_wide e)
{
    jim_wide i, res = 1;
    if ((b==0 && e!=0) || (e<0)) return 0;
    for(i=0; i<e; i++) {res *= b;}
    return res;
}

/* -----------------------------------------------------------------------------
 * Special functions
 * ---------------------------------------------------------------------------*/

/* Note that 'interp' may be NULL if not available in the
 * context of the panic. It's only useful to get the error
 * file descriptor, it will default to stderr otherwise. */
void Jim_Panic(Jim_Interp *interp, const char *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
oharboe's avatar
oharboe committed
516
517
518
519
520
521
	/* 
	 * Send it here first.. Assuming STDIO still works
	 */
    fprintf(stderr, JIM_NL "JIM INTERPRETER PANIC: ");
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, JIM_NL JIM_NL);
522
    va_end(ap);
oharboe's avatar
oharboe committed
523

524
525
526
527
528
529
530
531
532
533
534
535
536
537
#ifdef HAVE_BACKTRACE
    {
        void *array[40];
        int size, i;
        char **strings;

        size = backtrace(array, 40);
        strings = backtrace_symbols(array, size);
        for (i = 0; i < size; i++)
            fprintf(fp,"[backtrace] %s" JIM_NL, strings[i]);
        fprintf(fp,"[backtrace] Include the above lines and the output" JIM_NL);
        fprintf(fp,"[backtrace] of 'nm <executable>' in the bug report." JIM_NL);
    }
#endif
oharboe's avatar
oharboe committed
538
539
540
541
542
543
544
	
	/* This may actually crash... we do it last */
	if( interp && interp->cookie_stderr ){
		Jim_fprintf(  interp, interp->cookie_stderr, JIM_NL "JIM INTERPRETER PANIC: ");
		Jim_vfprintf( interp, interp->cookie_stderr, fmt, ap );
		Jim_fprintf(  interp, interp->cookie_stderr, JIM_NL JIM_NL );
	}
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
    abort();
}

/* -----------------------------------------------------------------------------
 * Memory allocation
 * ---------------------------------------------------------------------------*/

/* Macro used for memory debugging.
 * In order for they to work you have to rename Jim_Alloc into _Jim_Alloc
 * and similary for Jim_Realloc and Jim_Free */
#if 0
#define Jim_Alloc(s) (printf("%s %d: Jim_Alloc(%d)\n",__FILE__,__LINE__,s),_Jim_Alloc(s))
#define Jim_Free(p) (printf("%s %d: Jim_Free(%p)\n",__FILE__,__LINE__,p),_Jim_Free(p))
#define Jim_Realloc(p,s) (printf("%s %d: Jim_Realloc(%p,%d)\n",__FILE__,__LINE__,p,s),_Jim_Realloc(p,s))
#endif

void *Jim_Alloc(int size)
{
	/* We allocate zero length arrayes, etc. to use a single orthogonal codepath */
	if (size==0)
		size=1;
    void *p = malloc(size);
    if (p == NULL)
        Jim_Panic(NULL,"malloc: Out of memory");
    return p;
}

void Jim_Free(void *ptr) {
    free(ptr);
}

void *Jim_Realloc(void *ptr, int size)
{
	/* We allocate zero length arrayes, etc. to use a single orthogonal codepath */
	if (size==0)
		size=1;
    void *p = realloc(ptr, size);
    if (p == NULL)
        Jim_Panic(NULL,"realloc: Out of memory");
    return p;
}

char *Jim_StrDup(const char *s)
{
    int l = strlen(s);
    char *copy = Jim_Alloc(l+1);

    memcpy(copy, s, l+1);
    return copy;
}

char *Jim_StrDupLen(const char *s, int l)
{
    char *copy = Jim_Alloc(l+1);
    
    memcpy(copy, s, l+1);
    copy[l] = 0;    /* Just to be sure, original could be substring */
    return copy;
}

/* -----------------------------------------------------------------------------
 * Time related functions
 * ---------------------------------------------------------------------------*/
/* Returns microseconds of CPU used since start. */
static jim_wide JimClock(void)
{
#if (defined WIN32) && !(defined JIM_ANSIC)
    LARGE_INTEGER t, f;
    QueryPerformanceFrequency(&f);
    QueryPerformanceCounter(&t);
    return (long)((t.QuadPart * 1000000) / f.QuadPart);
#else /* !WIN32 */
    clock_t clocks = clock();

    return (long)(clocks*(1000000/CLOCKS_PER_SEC));
#endif /* WIN32 */
}

/* -----------------------------------------------------------------------------
 * Hash Tables
 * ---------------------------------------------------------------------------*/

/* -------------------------- private prototypes ---------------------------- */
static int JimExpandHashTableIfNeeded(Jim_HashTable *ht);
static unsigned int JimHashTableNextPower(unsigned int size);
static int JimInsertHashEntry(Jim_HashTable *ht, const void *key);

/* -------------------------- hash functions -------------------------------- */

/* Thomas Wang's 32 bit Mix Function */
unsigned int Jim_IntHashFunction(unsigned int key)
{
    key += ~(key << 15);
    key ^=  (key >> 10);
    key +=  (key << 3);
    key ^=  (key >> 6);
    key += ~(key << 11);
    key ^=  (key >> 16);
    return key;
}

/* Identity hash function for integer keys */
unsigned int Jim_IdentityHashFunction(unsigned int key)
{
    return key;
}

/* Generic hash function (we are using to multiply by 9 and add the byte
 * as Tcl) */
unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
{
    unsigned int h = 0;
    while(len--)
        h += (h<<3)+*buf++;
    return h;
}

/* ----------------------------- API implementation ------------------------- */
/* reset an hashtable already initialized with ht_init().
 * NOTE: This function should only called by ht_destroy(). */
static void JimResetHashTable(Jim_HashTable *ht)
{
    ht->table = NULL;
    ht->size = 0;
    ht->sizemask = 0;
    ht->used = 0;
    ht->collisions = 0;
}

/* Initialize the hash table */
int Jim_InitHashTable(Jim_HashTable *ht, Jim_HashTableType *type,
        void *privDataPtr)
{
    JimResetHashTable(ht);
    ht->type = type;
    ht->privdata = privDataPtr;
    return JIM_OK;
}

/* Resize the table to the minimal size that contains all the elements,
 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
int Jim_ResizeHashTable(Jim_HashTable *ht)
{
    int minimal = ht->used;

    if (minimal < JIM_HT_INITIAL_SIZE)
        minimal = JIM_HT_INITIAL_SIZE;
    return Jim_ExpandHashTable(ht, minimal);
}

/* Expand or create the hashtable */
int Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
{
    Jim_HashTable n; /* the new hashtable */
    unsigned int realsize = JimHashTableNextPower(size), i;

    /* the size is invalid if it is smaller than the number of
     * elements already inside the hashtable */
    if (ht->used >= size)
        return JIM_ERR;

    Jim_InitHashTable(&n, ht->type, ht->privdata);
    n.size = realsize;
    n.sizemask = realsize-1;
    n.table = Jim_Alloc(realsize*sizeof(Jim_HashEntry*));

    /* Initialize all the pointers to NULL */
    memset(n.table, 0, realsize*sizeof(Jim_HashEntry*));

    /* Copy all the elements from the old to the new table:
     * note that if the old hash table is empty ht->size is zero,
     * so Jim_ExpandHashTable just creates an hash table. */
    n.used = ht->used;
    for (i = 0; i < ht->size && ht->used > 0; i++) {
        Jim_HashEntry *he, *nextHe;

        if (ht->table[i] == NULL) continue;
        
        /* For each hash entry on this slot... */
        he = ht->table[i];
        while(he) {
            unsigned int h;

            nextHe = he->next;
            /* Get the new element index */
            h = Jim_HashKey(ht, he->key) & n.sizemask;
            he->next = n.table[h];
            n.table[h] = he;
            ht->used--;
            /* Pass to the next element */
            he = nextHe;
        }
    }
    assert(ht->used == 0);
    Jim_Free(ht->table);

    /* Remap the new hashtable in the old */
    *ht = n;
    return JIM_OK;
}

/* Add an element to the target hash table */
int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
{
    int index;
    Jim_HashEntry *entry;

    /* Get the index of the new element, or -1 if
     * the element already exists. */
    if ((index = JimInsertHashEntry(ht, key)) == -1)
        return JIM_ERR;

    /* Allocates the memory and stores key */
    entry = Jim_Alloc(sizeof(*entry));
    entry->next = ht->table[index];
    ht->table[index] = entry;

    /* Set the hash entry fields. */
    Jim_SetHashKey(ht, entry, key);
    Jim_SetHashVal(ht, entry, val);
    ht->used++;
    return JIM_OK;
}

/* Add an element, discarding the old if the key already exists */
int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
{
    Jim_HashEntry *entry;

    /* Try to add the element. If the key
     * does not exists Jim_AddHashEntry will suceed. */
    if (Jim_AddHashEntry(ht, key, val) == JIM_OK)
        return JIM_OK;
    /* It already exists, get the entry */
    entry = Jim_FindHashEntry(ht, key);
    /* Free the old value and set the new one */
    Jim_FreeEntryVal(ht, entry);
    Jim_SetHashVal(ht, entry, val);
    return JIM_OK;
}

/* Search and remove an element */
int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
{
    unsigned int h;
    Jim_HashEntry *he, *prevHe;

    if (ht->size == 0)
        return JIM_ERR;
    h = Jim_HashKey(ht, key) & ht->sizemask;
    he = ht->table[h];

    prevHe = NULL;
    while(he) {
        if (Jim_CompareHashKeys(ht, key, he->key)) {
            /* Unlink the element from the list */
            if (prevHe)
                prevHe->next = he->next;
            else
                ht->table[h] = he->next;
            Jim_FreeEntryKey(ht, he);
            Jim_FreeEntryVal(ht, he);
            Jim_Free(he);
            ht->used--;
            return JIM_OK;
        }
        prevHe = he;
        he = he->next;
    }
    return JIM_ERR; /* not found */
}

/* Destroy an entire hash table */
int Jim_FreeHashTable(Jim_HashTable *ht)
{
    unsigned int i;

    /* Free all the elements */
    for (i = 0; i < ht->size && ht->used > 0; i++) {
        Jim_HashEntry *he, *nextHe;

        if ((he = ht->table[i]) == NULL) continue;
        while(he) {
            nextHe = he->next;
            Jim_FreeEntryKey(ht, he);
            Jim_FreeEntryVal(ht, he);
            Jim_Free(he);
            ht->used--;
            he = nextHe;
        }
    }
    /* Free the table and the allocated cache structure */
    Jim_Free(ht->table);
    /* Re-initialize the table */
    JimResetHashTable(ht);
    return JIM_OK; /* never fails */
}

Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
{
    Jim_HashEntry *he;
    unsigned int h;

    if (ht->size == 0) return NULL;
    h = Jim_HashKey(ht, key) & ht->sizemask;
    he = ht->table[h];
    while(he) {
        if (Jim_CompareHashKeys(ht, key, he->key))
            return he;
        he = he->next;
    }
    return NULL;
}

Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
{
    Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));

    iter->ht = ht;
    iter->index = -1;
    iter->entry = NULL;
    iter->nextEntry = NULL;
    return iter;
}

Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
{
    while (1) {
        if (iter->entry == NULL) {
            iter->index++;
            if (iter->index >=
                    (signed)iter->ht->size) break;
            iter->entry = iter->ht->table[iter->index];
        } else {
            iter->entry = iter->nextEntry;
        }
        if (iter->entry) {
            /* We need to save the 'next' here, the iterator user
             * may delete the entry we are returning. */
            iter->nextEntry = iter->entry->next;
            return iter->entry;
        }
    }
    return NULL;
}

/* ------------------------- private functions ------------------------------ */

/* Expand the hash table if needed */
static int JimExpandHashTableIfNeeded(Jim_HashTable *ht)
{
    /* If the hash table is empty expand it to the intial size,
     * if the table is "full" dobule its size. */
    if (ht->size == 0)
        return Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
    if (ht->size == ht->used)
        return Jim_ExpandHashTable(ht, ht->size*2);
    return JIM_OK;
}

/* Our hash table capability is a power of two */
static unsigned int JimHashTableNextPower(unsigned int size)
{
    unsigned int i = JIM_HT_INITIAL_SIZE;

    if (size >= 2147483648U)
        return 2147483648U;
    while(1) {
        if (i >= size)
            return i;
        i *= 2;
    }
}

/* Returns the index of a free slot that can be populated with
 * an hash entry for the given 'key'.
 * If the key already exists, -1 is returned. */
static int JimInsertHashEntry(Jim_HashTable *ht, const void *key)
{
    unsigned int h;
    Jim_HashEntry *he;

    /* Expand the hashtable if needed */
    if (JimExpandHashTableIfNeeded(ht) == JIM_ERR)
        return -1;
    /* Compute the key hash value */
    h = Jim_HashKey(ht, key) & ht->sizemask;
    /* Search if this slot does not already contain the given key */
    he = ht->table[h];
    while(he) {
        if (Jim_CompareHashKeys(ht, key, he->key))
            return -1;
        he = he->next;
    }
    return h;
}

/* ----------------------- StringCopy Hash Table Type ------------------------*/

static unsigned int JimStringCopyHTHashFunction(const void *key)
{
    return Jim_GenHashFunction(key, strlen(key));
}

static const void *JimStringCopyHTKeyDup(void *privdata, const void *key)
{
    int len = strlen(key);
    char *copy = Jim_Alloc(len+1);
    JIM_NOTUSED(privdata);

    memcpy(copy, key, len);
    copy[len] = '\0';
    return copy;
}

static void *JimStringKeyValCopyHTValDup(void *privdata, const void *val)
{
    int len = strlen(val);
    char *copy = Jim_Alloc(len+1);
    JIM_NOTUSED(privdata);

    memcpy(copy, val, len);
    copy[len] = '\0';
    return copy;
}

static int JimStringCopyHTKeyCompare(void *privdata, const void *key1,
        const void *key2)
{
    JIM_NOTUSED(privdata);

    return strcmp(key1, key2) == 0;
}

static void JimStringCopyHTKeyDestructor(void *privdata, const void *key)
{
    JIM_NOTUSED(privdata);

    Jim_Free((void*)key); /* ATTENTION: const cast */
}

static void JimStringKeyValCopyHTValDestructor(void *privdata, void *val)
{
    JIM_NOTUSED(privdata);

    Jim_Free((void*)val); /* ATTENTION: const cast */
}

static Jim_HashTableType JimStringCopyHashTableType = {
    JimStringCopyHTHashFunction,        /* hash function */
    JimStringCopyHTKeyDup,              /* key dup */
    NULL,                               /* val dup */
    JimStringCopyHTKeyCompare,          /* key compare */
    JimStringCopyHTKeyDestructor,       /* key destructor */
    NULL                                /* val destructor */
};

/* This is like StringCopy but does not auto-duplicate the key.
 * It's used for intepreter's shared strings. */
static Jim_HashTableType JimSharedStringsHashTableType = {
    JimStringCopyHTHashFunction,        /* hash function */
    NULL,                               /* key dup */
    NULL,                               /* val dup */
    JimStringCopyHTKeyCompare,          /* key compare */
    JimStringCopyHTKeyDestructor,       /* key destructor */
    NULL                                /* val destructor */
};

/* This is like StringCopy but also automatically handle dynamic
 * allocated C strings as values. */
static Jim_HashTableType JimStringKeyValCopyHashTableType = {
    JimStringCopyHTHashFunction,        /* hash function */
    JimStringCopyHTKeyDup,              /* key dup */
    JimStringKeyValCopyHTValDup,        /* val dup */
    JimStringCopyHTKeyCompare,          /* key compare */
    JimStringCopyHTKeyDestructor,       /* key destructor */
    JimStringKeyValCopyHTValDestructor, /* val destructor */
};

typedef struct AssocDataValue {
    Jim_InterpDeleteProc *delProc;
    void *data;
} AssocDataValue;

static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
{
    AssocDataValue *assocPtr = (AssocDataValue *)data;
    if (assocPtr->delProc != NULL)
        assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
    Jim_Free(data);
}

static Jim_HashTableType JimAssocDataHashTableType = {
    JimStringCopyHTHashFunction,         /* hash function */
    JimStringCopyHTKeyDup,               /* key dup */
    NULL,                                /* val dup */
    JimStringCopyHTKeyCompare,           /* key compare */
    JimStringCopyHTKeyDestructor,        /* key destructor */
    JimAssocDataHashTableValueDestructor /* val destructor */
};

/* -----------------------------------------------------------------------------
 * Stack - This is a simple generic stack implementation. It is used for
 * example in the 'expr' expression compiler.
 * ---------------------------------------------------------------------------*/
void Jim_InitStack(Jim_Stack *stack)
{
    stack->len = 0;
    stack->maxlen = 0;
    stack->vector = NULL;
}

void Jim_FreeStack(Jim_Stack *stack)
{
    Jim_Free(stack->vector);
}

int Jim_StackLen(Jim_Stack *stack)
{
    return stack->len;
}

void Jim_StackPush(Jim_Stack *stack, void *element) {
    int neededLen = stack->len+1;
    if (neededLen > stack->maxlen) {
        stack->maxlen = neededLen*2;
        stack->vector = Jim_Realloc(stack->vector, sizeof(void*)*stack->maxlen);
    }
    stack->vector[stack->len] = element;
    stack->len++;
}

void *Jim_StackPop(Jim_Stack *stack)
{
    if (stack->len == 0) return NULL;
    stack->len--;
    return stack->vector[stack->len];
}

void *Jim_StackPeek(Jim_Stack *stack)
{
    if (stack->len == 0) return NULL;
    return stack->vector[stack->len-1];
}

void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr))
{
    int i;

    for (i = 0; i < stack->len; i++)
        freeFunc(stack->vector[i]);
}

/* -----------------------------------------------------------------------------
 * Parser
 * ---------------------------------------------------------------------------*/

/* Token types */
#define JIM_TT_NONE -1        /* No token returned */
#define JIM_TT_STR 0        /* simple string */
#define JIM_TT_ESC 1        /* string that needs escape chars conversion */
#define JIM_TT_VAR 2        /* var substitution */
#define JIM_TT_DICTSUGAR 3    /* Syntax sugar for [dict get], $foo(bar) */
#define JIM_TT_CMD 4        /* command substitution */
#define JIM_TT_SEP 5        /* word separator */
#define JIM_TT_EOL 6        /* line separator */

/* Additional token types needed for expressions */
#define JIM_TT_SUBEXPR_START 7
#define JIM_TT_SUBEXPR_END 8
#define JIM_TT_EXPR_NUMBER 9
#define JIM_TT_EXPR_OPERATOR 10

/* Parser states */
#define JIM_PS_DEF 0        /* Default state */
#define JIM_PS_QUOTE 1        /* Inside "" */

/* Parser context structure. The same context is used both to parse
 * Tcl scripts and lists. */
struct JimParserCtx {
    const char *prg;     /* Program text */
    const char *p;       /* Pointer to the point of the program we are parsing */
    int len;             /* Left length of 'prg' */
    int linenr;          /* Current line number */
    const char *tstart;
    const char *tend;    /* Returned token is at tstart-tend in 'prg'. */
    int tline;           /* Line number of the returned token */
    int tt;              /* Token type */
    int eof;             /* Non zero if EOF condition is true. */
    int state;           /* Parser state */
    int comment;         /* Non zero if the next chars may be a comment. */
};

#define JimParserEof(c) ((c)->eof)
#define JimParserTstart(c) ((c)->tstart)
#define JimParserTend(c) ((c)->tend)
#define JimParserTtype(c) ((c)->tt)
#define JimParserTline(c) ((c)->tline)

static int JimParseScript(struct JimParserCtx *pc);
static int JimParseSep(struct JimParserCtx *pc);
static int JimParseEol(struct JimParserCtx *pc);
static int JimParseCmd(struct JimParserCtx *pc);
static int JimParseVar(struct JimParserCtx *pc);
static int JimParseBrace(struct JimParserCtx *pc);
static int JimParseStr(struct JimParserCtx *pc);
static int JimParseComment(struct JimParserCtx *pc);
static char *JimParserGetToken(struct JimParserCtx *pc,
        int *lenPtr, int *typePtr, int *linePtr);

/* Initialize a parser context.
 * 'prg' is a pointer to the program text, linenr is the line
 * number of the first line contained in the program. */
void JimParserInit(struct JimParserCtx *pc, const char *prg, 
        int len, int linenr)
{
    pc->prg = prg;
    pc->p = prg;
    pc->len = len;
    pc->tstart = NULL;
    pc->tend = NULL;
    pc->tline = 0;
    pc->tt = JIM_TT_NONE;
    pc->eof = 0;
    pc->state = JIM_PS_DEF;
    pc->linenr = linenr;
    pc->comment = 1;
}

int JimParseScript(struct JimParserCtx *pc)
{
    while(1) { /* the while is used to reiterate with continue if needed */
        if (!pc->len) {
            pc->tstart = pc->p;
            pc->tend = pc->p-1;
            pc->tline = pc->linenr;
            pc->tt = JIM_TT_EOL;
            pc->eof = 1;
            return JIM_OK;
        }
        switch(*(pc->p)) {
        case '\\':
            if (*(pc->p+1) == '\n')
                return JimParseSep(pc);
            else {
                pc->comment = 0;
                return JimParseStr(pc);
            }
            break;
        case ' ':
        case '\t':
        case '\r':
            if (pc->state == JIM_PS_DEF)
                return JimParseSep(pc);
            else {
                pc->comment = 0;
                return JimParseStr(pc);
            }
            break;
        case '\n':
        case ';':
            pc->comment = 1;
            if (pc->state == JIM_PS_DEF)
                return JimParseEol(pc);
            else
                return JimParseStr(pc);
            break;
        case '[':
            pc->comment = 0;
            return JimParseCmd(pc);
            break;
        case '$':
            pc->comment = 0;
            if (JimParseVar(pc) == JIM_ERR) {
                pc->tstart = pc->tend = pc->p++; pc->len--;
                pc->tline = pc->linenr;
                pc->tt = JIM_TT_STR;
                return JIM_OK;
            } else
                return JIM_OK;
            break;
        case '#':
            if (pc->comment) {
                JimParseComment(pc);
                continue;
            } else {
                return JimParseStr(pc);
            }
        default:
            pc->comment = 0;
            return JimParseStr(pc);
            break;
        }
        return JIM_OK;
    }
}

int JimParseSep(struct JimParserCtx *pc)
{
    pc->tstart = pc->p;
    pc->tline = pc->linenr;
    while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' ||
           (*pc->p == '\\' && *(pc->p+1) == '\n')) {
        if (*pc->p == '\\') {
            pc->p++; pc->len--;
            pc->linenr++;
        }
        pc->p++; pc->len--;
    }
    pc->tend = pc->p-1;
    pc->tt = JIM_TT_SEP;
    return JIM_OK;
}

int JimParseEol(struct JimParserCtx *pc)
{
    pc->tstart = pc->p;
    pc->tline = pc->linenr;
    while (*pc->p == ' ' || *pc->p == '\n' ||
           *pc->p == '\t' || *pc->p == '\r' || *pc->p == ';') {
        if (*pc->p == '\n')
            pc->linenr++;
        pc->p++; pc->len--;
    }
    pc->tend = pc->p-1;
    pc->tt = JIM_TT_EOL;
    return JIM_OK;
}

/* Todo. Don't stop if ']' appears inside {} or quoted.
 * Also should handle the case of puts [string length "]"] */
int JimParseCmd(struct JimParserCtx *pc)
{
    int level = 1;
    int blevel = 0;

    pc->tstart = ++pc->p; pc->len--;
    pc->tline = pc->linenr;
    while (1) {
        if (pc->len == 0) {
            break;
        } else if (*pc->p == '[' && blevel == 0) {
            level++;
        } else if (*pc->p == ']' && blevel == 0) {
            level--;
            if (!level) break;
        } else if (*pc->p == '\\') {
            pc->p++; pc->len--;
        } else if (*pc->p == '{') {
            blevel++;
        } else if (*pc->p == '}') {
            if (blevel != 0)
                blevel--;
        } else if (*pc->p == '\n')
            pc->linenr++;
        pc->p++; pc->len--;
    }
    pc->tend = pc->p-1;
    pc->tt = JIM_TT_CMD;
    if (*pc->p == ']') {
        pc->p++; pc->len--;
    }
    return JIM_OK;
}

int JimParseVar(struct JimParserCtx *pc)
{
    int brace = 0, stop = 0, ttype = JIM_TT_VAR;

    pc->tstart = ++pc->p; pc->len--; /* skip the $ */
    pc->tline = pc->linenr;
    if (*pc->p == '{') {
        pc->tstart = ++pc->p; pc->len--;
        brace = 1;
    }
    if (brace) {
        while (!stop) {
            if (*pc->p == '}' || pc->len == 0) {
                stop = 1;
                if (pc->len == 0)
                    continue;
            }
            else if (*pc->p == '\n')
                pc->linenr++;
            pc->p++; pc->len--;
        }
        if (pc->len == 0)
            pc->tend = pc->p-1;
        else
            pc->tend = pc->p-2;
    } else {
        while (!stop) {
            if (!((*pc->p >= 'a' && *pc->p <= 'z') ||
                (*pc->p >= 'A' && *pc->p <= 'Z') ||
                (*pc->p >= '0' && *pc->p <= '9') || *pc->p == '_'))
                stop = 1;
            else {
                pc->p++; pc->len--;
            }
        }
        /* Parse [dict get] syntax sugar. */
        if (*pc->p == '(') {
            while (*pc->p != ')' && pc->len) {
                pc->p++; pc->len--;
                if (*pc->p == '\\' && pc->len >= 2) {
                    pc->p += 2; pc->len -= 2;
                }
            }
            if (*pc->p != '\0') {
                pc->p++; pc->len--;
            }
            ttype = JIM_TT_DICTSUGAR;
        }
        pc->tend = pc->p-1;
    }
    /* Check if we parsed just the '$' character.
     * That's not a variable so an error is returned
     * to tell the state machine to consider this '$' just
     * a string. */
    if (pc->tstart == pc->p) {
        pc->p--; pc->len++;
        return JIM_ERR;
    }
    pc->tt = ttype;
    return JIM_OK;
}

int JimParseBrace(struct JimParserCtx *pc)
{
    int level = 1;

    pc->tstart = ++pc->p; pc->len--;
    pc->tline = pc->linenr;
    while (1) {
        if (*pc->p == '\\' && pc->len >= 2) {
            pc->p++; pc->len--;
            if (*pc->p == '\n')
                pc->linenr++;
        } else if (*pc->p == '{') {
            level++;
        } else if (pc->len == 0 || *pc->p == '}') {
            level--;
            if (pc->len == 0 || level == 0) {
                pc->tend = pc->p-1;
                if (pc->len != 0) {
                    pc->p++; pc->len--;
                }
                pc->tt = JIM_TT_STR;
                return JIM_OK;
            }
        } else if (*pc->p == '\n') {
            pc->linenr++;
        }
        pc->p++; pc->len--;
    }
    return JIM_OK; /* unreached */
}

int JimParseStr(struct JimParserCtx *pc)
{
    int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
            pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR);
    if (newword && *pc->p == '{') {
        return JimParseBrace(pc);
    } else if (newword && *pc->p == '"') {
        pc->state = JIM_PS_QUOTE;
        pc->p++; pc->len--;
    }
    pc->tstart = pc->p;
    pc->tline = pc->linenr;
    while (1) {
        if (pc->len == 0) {
            pc->tend = pc->p-1;
            pc->tt = JIM_TT_ESC;
            return JIM_OK;
        }
        switch(*pc->p) {
        case '\\':
            if (pc->state == JIM_PS_DEF &&
                *(pc->p+1) == '\n') {
                pc->tend = pc->p-1;
                pc->tt = JIM_TT_ESC;
                return JIM_OK;
            }
            if (pc->len >= 2) {
                pc->p++; pc->len--;
            }
            break;
        case '$':
        case '[':
            pc->tend = pc->p-1;
            pc->tt = JIM_TT_ESC;
            return JIM_OK;
        case ' ':
        case '\t':
        case '\n':
        case '\r':
        case ';':
            if (pc->state == JIM_PS_DEF) {
                pc->tend = pc->p-1;
                pc->tt = JIM_TT_ESC;
                return JIM_OK;
            } else if (*pc->p == '\n') {
                pc->linenr++;
            }
            break;
        case '"':
            if (pc->state == JIM_PS_QUOTE) {
                pc->tend = pc->p-1;
                pc->tt = JIM_TT_ESC;
                pc->p++; pc->len--;
                pc->state = JIM_PS_DEF;
                return JIM_OK;
            }
            break;
        }
        pc->p++; pc->len--;
    }
    return JIM_OK; /* unreached */
}

int JimParseComment(struct JimParserCtx *pc)
{
    while (*pc->p) {
        if (*pc->p == '\n') {
            pc->linenr++;
            if (*(pc->p-1) != '\\') {
                pc->p++; pc->len--;
                return JIM_OK;
            }
        }
        pc->p++; pc->len--;
    }
    return JIM_OK;
}

/* xdigitval and odigitval are helper functions for JimParserGetToken() */
static int xdigitval(int c)
{
    if (c >= '0' && c <= '9') return c-'0';
    if (c >= 'a' && c <= 'f') return c-'a'+10;
    if (c >= 'A' && c <= 'F') return c-'A'+10;
    return -1;
}

static int odigitval(int c)
{
    if (c >= '0' && c <= '7') return c-'0';
    return -1;
}

/* Perform Tcl escape substitution of 's', storing the result
 * string into 'dest'. The escaped string is guaranteed to
 * be the same length or shorted than the source string.
 * Slen is the length of the string at 's', if it's -1 the string
 * length will be calculated by the function.
 *
 * The function returns the length of the resulting string. */
static int JimEscape(char *dest, const char *s, int slen)
{
    char *p = dest;
    int i, len;
    
    if (slen == -1)
        slen = strlen(s);

    for (i = 0; i < slen; i++) {
        switch(s[i]) {
        case '\\':
            switch(s[i+1]) {
            case 'a': *p++ = 0x7; i++; break;
            case 'b': *p++ = 0x8; i++; break;
            case 'f': *p++ = 0xc; i++; break;
            case 'n': *p++ = 0xa; i++; break;
            case 'r': *p++ = 0xd; i++; break;
            case 't': *p++ = 0x9; i++; break;
            case 'v': *p++ = 0xb; i++; break;
            case '\0': *p++ = '\\'; i++; break;
            case '\n': *p++ = ' '; i++; break;
            default:
                  if (s[i+1] == 'x') {
                    int val = 0;
                    int c = xdigitval(s[i+2]);
                    if (c == -1) {
                        *p++ = 'x';
                        i++;
                        break;
                    }
                    val = c;
                    c = xdigitval(s[i+3]);
                    if (c == -1) {
                        *p++ = val;
                        i += 2;
                        break;
                    }
                    val = (val*16)+c;
                    *p++ = val;
                    i += 3;
                    break;
                  } else if (s[i+1] >= '0' && s[i+1] <= '7')
                  {
                    int val = 0;
                    int c = odigitval(s[i+1]);
                    val = c;
                    c = odigitval(s[i+2]);
                    if (c == -1) {
                        *p++ = val;
                        i ++;
                        break;
                    }
                    val = (val*8)+c;
                    c = odigitval(s[i+3]);
                    if (c == -1) {
                        *p++ = val;
                        i += 2;
                        break;
                    }
                    val = (val*8)+c;
                    *p++ = val;
                    i += 3;
                  } else {
                    *p++ = s[i+1];
                    i++;
                  }
                  break;
            }
            break;
        default:
            *p++ = s[i];
            break;
        }
    }
    len = p-dest;
    *p++ = '\0';
    return len;
}

/* Returns a dynamically allocated copy of the current token in the
 * parser context. The function perform conversion of escapes if
 * the token is of type JIM_TT_ESC.
 *
 * Note that after the conversion, tokens that are grouped with
 * braces in the source code, are always recognizable from the
 * identical string obtained in a different way from the type.
 *
 * For exmple the string:
 *
 * {expand}$a
 * 
 * will return as first token "expand", of type JIM_TT_STR
 *
 * While the string:
 *
 * expand$a
 *
 * will return as first token "expand", of type JIM_TT_ESC
 */
char *JimParserGetToken(struct JimParserCtx *pc,
        int *lenPtr, int *typePtr, int *linePtr)
{
    const char *start, *end;
    char *token;
    int len;

    start = JimParserTstart(pc);
    end = JimParserTend(pc);
    if (start > end) {
        if (lenPtr) *lenPtr = 0;
        if (typePtr) *typePtr = JimParserTtype(pc);
        if (linePtr) *linePtr = JimParserTline(pc);
        token = Jim_Alloc(1);
        token[0] = '\0';
        return token;
    }
    len = (end-start)+1;
    token = Jim_Alloc(len+1);
    if (JimParserTtype(pc) != JIM_TT_ESC) {
        /* No escape conversion needed? Just copy it. */
        memcpy(token, start, len);
        token[len] = '\0';
    } else {
        /* Else convert the escape chars. */
        len = JimEscape(token, start, len);
    }
    if (lenPtr) *lenPtr = len;
    if (typePtr) *typePtr = JimParserTtype(pc);
    if (linePtr) *linePtr = JimParserTline(pc);
    return token;
}

/* The following functin is not really part of the parsing engine of Jim,
 * but it somewhat related. Given an string and its length, it tries
 * to guess if the script is complete or there are instead " " or { }
 * open and not completed. This is useful for interactive shells
 * implementation and for [info complete].
 *
 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
 * '{' on scripts incomplete missing one or more '}' to be balanced.
 * '"' on scripts incomplete missing a '"' char.
 *
 * If the script is complete, 1 is returned, otherwise 0. */
int Jim_ScriptIsComplete(const char *s, int len, char *stateCharPtr)
{
    int level = 0;
    int state = ' ';

    while(len) {
        switch (*s) {
            case '\\':
                if (len > 1)
                    s++;
                break;
            case '"':
                if (state == ' ') {
                    state = '"';
                } else if (state == '"') {
                    state = ' ';
                }
                break;
            case '{':
                if (state == '{') {
                    level++;
                } else if (state == ' ') {
                    state = '{';
                    level++;
                }
                break;
            case '}':
                if (state == '{') {
                    level--;
                    if (level == 0)
                        state = ' ';
                }
                break;
        }
        s++;
        len--;
    }
    if (stateCharPtr)
        *stateCharPtr = state;
    return state == ' ';
}

/* -----------------------------------------------------------------------------
 * Tcl Lists parsing
 * ---------------------------------------------------------------------------*/
static int JimParseListSep(struct JimParserCtx *pc);
static int JimParseListStr(struct JimParserCtx *pc);

int JimParseList(struct JimParserCtx *pc)
{
    if (pc->len == 0) {
        pc->tstart = pc->tend = pc->p;
        pc->tline = pc->linenr;
        pc->tt = JIM_TT_EOL;
        pc->eof = 1;
        return JIM_OK;
    }
    switch(*pc->p) {
    case ' ':
    case '\n':
    case '\t':
    case '\r':
        if (pc->state == JIM_PS_DEF)
            return JimParseListSep(pc);
        else
            return JimParseListStr(pc);
        break;
    default:
        return JimParseListStr(pc);
        break;
    }
    return JIM_OK;
}

int JimParseListSep(struct JimParserCtx *pc)
{
    pc->tstart = pc->p;
    pc->tline = pc->linenr;
    while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == '\n')
    {
        pc->p++; pc->len--;
    }
    pc->tend = pc->p-1;
    pc->tt = JIM_TT_SEP;
    return JIM_OK;
}

int JimParseListStr(struct JimParserCtx *pc)
{
    int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
            pc->tt == JIM_TT_NONE);
    if (newword && *pc->p == '{') {
        return JimParseBrace(pc);
    } else if (newword && *pc->p == '"') {
        pc->state = JIM_PS_QUOTE;
        pc->p++; pc->len--;
    }
    pc->tstart = pc->p;
    pc->tline = pc->linenr;
    while (1) {
        if (pc->len == 0) {
            pc->tend = pc->p-1;
            pc->tt = JIM_TT_ESC;
            return JIM_OK;
        }
        switch(*pc->p) {
        case '\\':
            pc->p++; pc->len--;
            break;
        case ' ':
        case '\t':
        case '\n':
        case '\r':
            if (pc->state == JIM_PS_DEF) {
                pc->tend = pc->p-1;
                pc->tt = JIM_TT_ESC;
                return JIM_OK;
            } else if (*pc->p == '\n') {
                pc->linenr++;
            }
            break;
        case '"':
            if (pc->state == JIM_PS_QUOTE) {
                pc->tend = pc->p-1;
                pc->tt = JIM_TT_ESC;
                pc->p++; pc->len--;
                pc->state = JIM_PS_DEF;
                return JIM_OK;
            }
            break;
        }
        pc->p++; pc->len--;
    }
    return JIM_OK; /* unreached */
}

/* -----------------------------------------------------------------------------
 * Jim_Obj related functions
 * ---------------------------------------------------------------------------*/

/* Return a new initialized object. */
Jim_Obj *Jim_NewObj(Jim_Interp *interp)
{
    Jim_Obj *objPtr;

    /* -- Check if there are objects in the free list -- */
    if (interp->freeList != NULL) {
        /* -- Unlink the object from the free list -- */
        objPtr = interp->freeList;
        interp->freeList = objPtr->nextObjPtr;
    } else {
        /* -- No ready to use objects: allocate a new one -- */
        objPtr = Jim_Alloc(sizeof(*objPtr));
    }

    /* Object is returned with refCount of 0. Every
     * kind of GC implemented should take care to don't try
     * to scan objects with refCount == 0. */
    objPtr->refCount = 0;
    /* All the other fields are left not initialized to save time.
     * The caller will probably want set they to the right
     * value anyway. */

    /* -- Put the object into the live list -- */
    objPtr->prevObjPtr = NULL;
    objPtr->nextObjPtr = interp->liveList;
    if (interp->liveList)
        interp->liveList->prevObjPtr = objPtr;
    interp->liveList = objPtr;

    return objPtr;
}

/* Free an object. Actually objects are never freed, but
 * just moved to the free objects list, where they will be
 * reused by Jim_NewObj(). */
void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
{
    /* Check if the object was already freed, panic. */
    if (objPtr->refCount != 0)  {
        Jim_Panic(interp,"!!!Object %p freed with bad refcount %d", objPtr,
                objPtr->refCount);
    }
    /* Free the internal representation */
    Jim_FreeIntRep(interp, objPtr);
    /* Free the string representation */
    if (objPtr->bytes != NULL) {
        if (objPtr->bytes != JimEmptyStringRep)
            Jim_Free(objPtr->bytes);
    }
    /* Unlink the object from the live objects list */
    if (objPtr->prevObjPtr)
        objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
    if (objPtr->nextObjPtr)
        objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
    if (interp->liveList == objPtr)
        interp->liveList = objPtr->nextObjPtr;
    /* Link the object into the free objects list */
    objPtr->prevObjPtr = NULL;
    objPtr->nextObjPtr = interp->freeList;
    if (interp->freeList)
        interp->freeList->prevObjPtr = objPtr;
    interp->freeList = objPtr;
    objPtr->refCount = -1;
}

/* Invalidate the string representation of an object. */
void Jim_InvalidateStringRep(Jim_Obj *objPtr)
{
    if (objPtr->bytes != NULL) {
        if (objPtr->bytes != JimEmptyStringRep)
            Jim_Free(objPtr->bytes);
    }
    objPtr->bytes = NULL;
}

#define Jim_SetStringRep(o, b, l) \
    do { (o)->bytes = b; (o)->length = l; } while (0)

/* Set the initial string representation for an object.
 * Does not try to free an old one. */
void Jim_InitStringRep(Jim_Obj *objPtr, const char *bytes, int length)
{
    if (length == 0) {
        objPtr->bytes = JimEmptyStringRep;
        objPtr->length = 0;
    } else {
        objPtr->bytes = Jim_Alloc(length+1);
        objPtr->length = length;
        memcpy(objPtr->bytes, bytes, length);
        objPtr->bytes[length] = '\0';
    }
}

/* Duplicate an object. The returned object has refcount = 0. */
Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
{
    Jim_Obj *dupPtr;

    dupPtr = Jim_NewObj(interp);
    if (objPtr->bytes == NULL) {
        /* Object does not have a valid string representation. */
        dupPtr->bytes = NULL;
    } else {
        Jim_InitStringRep(dupPtr, objPtr->bytes, objPtr->length);
    }
    if (objPtr->typePtr != NULL) {
        if (objPtr->typePtr->dupIntRepProc == NULL) {
            dupPtr->internalRep = objPtr->internalRep;
        } else {
            objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
        }
        dupPtr->typePtr = objPtr->typePtr;
    } else {
        dupPtr->typePtr = NULL;
    }
    return dupPtr;
}

/* Return the string representation for objPtr. If the object
 * string representation is invalid, calls the method to create
 * a new one starting from the internal representation of the object. */
const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
{
    if (objPtr->bytes == NULL) {
        /* Invalid string repr. Generate it. */
        if (objPtr->typePtr->updateStringProc == NULL) {
            Jim_Panic(NULL,"UpdataStringProc called against '%s' type.",
                objPtr->typePtr->name);
        }
        objPtr->typePtr->updateStringProc(objPtr);
    }
    if (lenPtr)
        *lenPtr = objPtr->length;
    return objPtr->bytes;
}

/* Just returns the length of the object's string rep */
int Jim_Length(Jim_Obj *objPtr)
{
    int len;

    Jim_GetString(objPtr, &len);
    return len;
}

/* -----------------------------------------------------------------------------
 * String Object
 * ---------------------------------------------------------------------------*/
static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);

static Jim_ObjType stringObjType = {
    "string",
    NULL,
    DupStringInternalRep,
    NULL,
    JIM_TYPE_REFERENCES,
};

void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
{
    JIM_NOTUSED(interp);

    /* This is a bit subtle: the only caller of this function
     * should be Jim_DuplicateObj(), that will copy the
     * string representaion. After the copy, the duplicated
     * object will not have more room in teh buffer than
     * srcPtr->length bytes. So we just set it to length. */
    dupPtr->internalRep.strValue.maxLength = srcPtr->length;
}

int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
{
    /* Get a fresh string representation. */
    (void) Jim_GetString(objPtr, NULL);
    /* Free any other internal representation. */
    Jim_FreeIntRep(interp, objPtr);
    /* Set it as string, i.e. just set the maxLength field. */
    objPtr->typePtr = &stringObjType;
    objPtr->internalRep.strValue.maxLength = objPtr->length;
    return JIM_OK;
}

Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
{
    Jim_Obj *objPtr = Jim_NewObj(interp);

    if (len == -1)
        len = strlen(s);
    /* Alloc/Set the string rep. */
    if (len == 0) {
        objPtr->bytes = JimEmptyStringRep;
        objPtr->length = 0;
    } else {
        objPtr->bytes = Jim_Alloc(len+1);
        objPtr->length = len;
        memcpy(objPtr->bytes, s, len);
        objPtr->bytes[len] = '\0';
    }

    /* No typePtr field for the vanilla string object. */
    objPtr->typePtr = NULL;
    return objPtr;
}

/* This version does not try to duplicate the 's' pointer, but
 * use it directly. */
Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
{
    Jim_Obj *objPtr = Jim_NewObj(interp);

    if (len == -1)
        len = strlen(s);
    Jim_SetStringRep(objPtr, s, len);
    objPtr->typePtr = NULL;
    return objPtr;
}

/* Low-level string append. Use it only against objects
 * of type "string". */
void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
{
    int needlen;

    if (len == -1)
        len = strlen(str);
    needlen = objPtr->length + len;
    if (objPtr->internalRep.strValue.maxLength < needlen ||
        objPtr->internalRep.strValue.maxLength == 0) {
        if (objPtr->bytes == JimEmptyStringRep) {
            objPtr->bytes = Jim_Alloc((needlen*2)+1);
        } else {
            objPtr->bytes = Jim_Realloc(objPtr->bytes, (needlen*2)+1);
        }
        objPtr->internalRep.strValue.maxLength = needlen*2;
    }
    memcpy(objPtr->bytes + objPtr->length, str, len);
    objPtr->bytes[objPtr->length+len] = '\0';
    objPtr->length += len;
}

/* Low-level wrapper to append an object. */
void StringAppendObj(Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
{
    int len;
    const char *str;

    str = Jim_GetString(appendObjPtr, &len);
    StringAppendString(objPtr, str, len);
}

/* Higher level API to append strings to objects. */
void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str,
        int len)
{
    if (Jim_IsShared(objPtr))
        Jim_Panic(interp,"Jim_AppendString called with shared object");
    if (objPtr->typePtr != &stringObjType)
        SetStringFromAny(interp, objPtr);
    StringAppendString(objPtr, str, len);
}

2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
void Jim_AppendString_sprintf( Jim_Interp *interp, Jim_Obj *objPtr, const char *fmt, ... )
{
	char *buf;
	va_list ap;

	va_start( ap, fmt );
	buf = jim_vasprintf( fmt, ap );
	va_end(ap);

	if( buf ){
		Jim_AppendString( interp, objPtr, buf, -1 );
		jim_vasprintf_done(buf);
	}
}


2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr,
        Jim_Obj *appendObjPtr)
{
    int len;
    const char *str;

    str = Jim_GetString(appendObjPtr, &len);
    Jim_AppendString(interp, objPtr, str, len);
}

void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
{
    va_list ap;

    if (objPtr->typePtr != &stringObjType)
        SetStringFromAny(interp, objPtr);
    va_start(ap, objPtr);
    while (1) {
        char *s = va_arg(ap, char*);

        if (s == NULL) break;
        Jim_AppendString(interp, objPtr, s, -1);
    }
    va_end(ap);
}

int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr, int nocase)
{
    const char *aStr, *bStr;
    int aLen, bLen, i;

    if (aObjPtr == bObjPtr) return 1;
    aStr = Jim_GetString(aObjPtr, &aLen);
    bStr = Jim_GetString(bObjPtr, &bLen);
    if (aLen != bLen) return 0;
    if (nocase == 0)
        return memcmp(aStr, bStr, aLen) == 0;
    for (i = 0; i < aLen; i++) {
        if (tolower((int)aStr[i]) != tolower((int)bStr[i]))
            return 0;
    }
    return 1;
}

int Jim_StringMatchObj(Jim_Obj *patternObjPtr, Jim_Obj *objPtr,
        int nocase)
{
    const char *pattern, *string;
    int patternLen, stringLen;

    pattern = Jim_GetString(patternObjPtr, &patternLen);
    string = Jim_GetString(objPtr, &stringLen);
    return JimStringMatch(pattern, patternLen, string, stringLen, nocase);
}

int Jim_StringCompareObj(Jim_Obj *firstObjPtr,
        Jim_Obj *secondObjPtr, int nocase)
{
    const char *s1, *s2;
    int l1, l2;

    s1 = Jim_GetString(firstObjPtr, &l1);
    s2 = Jim_GetString(secondObjPtr, &l2);
    return JimStringCompare(s1, l1, s2, l2, nocase);
}

/* Convert a range, as returned by Jim_GetRange(), into
 * an absolute index into an object of the specified length.
 * This function may return negative values, or values
 * bigger or equal to the length of the list if the index
 * is out of range. */
static int JimRelToAbsIndex(int len, int index)
{
    if (index < 0)
        return len + index;
    return index;
}

/* Convert a pair of index as normalize by JimRelToAbsIndex(),
 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
 * for implementation of commands like [string range] and [lrange].
 *
 * The resulting range is guaranteed to address valid elements of
 * the structure. */
static void JimRelToAbsRange(int len, int first, int last,
        int *firstPtr, int *lastPtr, int *rangeLenPtr)
{
    int rangeLen;

    if (first > last) {
        rangeLen = 0;
    } else {
        rangeLen = last-first+1;
        if (rangeLen) {
            if (first < 0) {
                rangeLen += first;
                first = 0;
            }
            if (last >= len) {
                rangeLen -= (last-(len-1));
                last = len-1;
            }
        }
    }
    if (rangeLen < 0) rangeLen = 0;

    *firstPtr = first;
    *lastPtr = last;
    *rangeLenPtr = rangeLen;
}

Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
        Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
{
    int first, last;
    const char *str;
    int len, rangeLen;

    if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
        Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
        return NULL;
    str = Jim_GetString(strObjPtr, &len);
    first = JimRelToAbsIndex(len, first);
    last = JimRelToAbsIndex(len, last);
    JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
    return Jim_NewStringObj(interp, str+first, rangeLen);
}

static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
{
    char *buf = Jim_Alloc(strObjPtr->length+1);
    int i;

    memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);
    for (i = 0; i < strObjPtr->length; i++)
        buf[i] = tolower(buf[i]);
    return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);
}

static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
{
    char *buf = Jim_Alloc(strObjPtr->length+1);
    int i;

    memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);
    for (i = 0; i < strObjPtr->length; i++)
        buf[i] = toupper(buf[i]);
    return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);
}

/* This is the core of the [format] command.
oharboe's avatar
oharboe committed
2216
2217
2218
 * TODO: Lots of things work - via a hack
 *       However, no format item can be >= JIM_MAX_FMT 
 */
oharboe's avatar
oharboe committed
2219
2220
2221
#define JIM_MAX_FMT 2048
static Jim_Obj *Jim_FormatString_Inner(Jim_Interp *interp, Jim_Obj *fmtObjPtr,
        int objc, Jim_Obj *const *objv, char *sprintf_buf)
2222
{
oharboe's avatar
oharboe committed
2223
    const char *fmt, *_fmt;
2224
2225
    int fmtLen;
    Jim_Obj *resObjPtr;
oharboe's avatar
oharboe committed
2226
    
2227
2228

    fmt = Jim_GetString(fmtObjPtr, &fmtLen);
oharboe's avatar
oharboe committed
2229
	_fmt = fmt;
2230
2231
2232
2233
2234
    resObjPtr = Jim_NewStringObj(interp, "", 0);
    while (fmtLen) {
        const char *p = fmt;
        char spec[2], c;
        jim_wide wideValue;
oharboe's avatar
oharboe committed
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
		double doubleValue;
		/* we cheat and use Sprintf()! */
		char fmt_str[100];
		char *cp;
		int width;
		int ljust;
		int zpad;
		int spad;
		int altfm;
		int forceplus;
2245
2246
2247
2248
		int prec;
		int inprec;
		int haveprec;
		int accum;
2249
2250
2251
2252
2253
2254
2255
2256

        while (*fmt != '%' && fmtLen) {
            fmt++; fmtLen--;
        }
        Jim_AppendString(interp, resObjPtr, p, fmt-p);
        if (fmtLen == 0)
            break;
        fmt++; fmtLen--; /* skip '%' */
oharboe's avatar
oharboe committed
2257
2258
2259
2260
2261
2262
		zpad = 0;
		spad = 0;
		width = -1;
		ljust = 0;
		altfm = 0;
		forceplus = 0;
2263
2264
2265
		inprec = 0;
		haveprec = 0;
		prec = -1; /* not found yet */
oharboe's avatar
oharboe committed
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
    next_fmt:
		if( fmtLen <= 0 ){
			break;
		}
		switch( *fmt ){
			/* terminals */
        case 'b': /* binary - not all printfs() do this */
		case 's': /* string */
		case 'i': /* integer */
		case 'd': /* decimal */
		case 'x': /* hex */
		case 'X': /* CAP hex */
		case 'c': /* char */
		case 'o': /* octal */
		case 'u': /* unsigned */
		case 'f': /* float */
			break;
			
			/* non-terminals */
		case '0': /* zero pad */
			zpad = 1;
			*fmt++;  fmtLen--;
			goto next_fmt;
			break;
		case '+':
			forceplus = 1;
			*fmt++;  fmtLen--;
			goto next_fmt;
			break;
		case ' ': /* sign space */
			spad = 1;
			*fmt++;  fmtLen--;
			goto next_fmt;
			break;
		case '-':
			ljust = 1;
			*fmt++;  fmtLen--;
			goto next_fmt;
			break;
		case '#':
			altfm = 1;
			*fmt++; fmtLen--;
 			goto next_fmt;
2309
2310
2311
2312
2313
2314

		case '.':
			inprec = 1;
			*fmt++; fmtLen--;
 			goto next_fmt;
			break;
oharboe's avatar
oharboe committed
2315
2316
2317
2318
2319
2320
2321
2322
2323
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
2324
			accum = 0;
oharboe's avatar
oharboe committed
2325
			while( isdigit(*fmt) && (fmtLen > 0) ){
2326
				accum = (accum * 10) + (*fmt - '0');
oharboe's avatar
oharboe committed
2327
2328
				fmt++;  fmtLen--;
			}
2329
2330
2331
2332
2333
2334
			if( inprec ){
				haveprec = 1;
				prec = accum;
			} else {
				width = accum;
			}
oharboe's avatar
oharboe committed
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
			goto next_fmt;
		case '*':
			/* suck up the next item as an integer */
			*fmt++;  fmtLen--;
			objc--;
			if( objc <= 0 ){
				goto not_enough_args;
			}
			if( Jim_GetWide(interp,objv[0],&wideValue )== JIM_ERR ){
				Jim_FreeNewObj(interp, resObjPtr );
				return NULL;
			}
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
			if( inprec ){
				haveprec = 1;
				prec = wideValue;
				if( prec < 0 ){
					/* man 3 printf says */
					/* if prec is negative, it is zero */
					prec = 0;
				}
			} else {
				width = wideValue;
				if( width < 0 ){
					ljust = 1;
					width = -width;
				}
oharboe's avatar
oharboe committed
2361
2362
2363
2364
2365
2366
2367
2368
			}
			objv++;
			goto next_fmt;
			break;
		}
		
		
		if (*fmt != '%') {
2369
            if (objc == 0) {
oharboe's avatar
oharboe committed
2370
			not_enough_args:
2371
2372
                Jim_FreeNewObj(interp, resObjPtr);
                Jim_SetResultString(interp,
oharboe's avatar
oharboe committed
2373
									"not enough arguments for all format specifiers", -1);
2374
2375
2376
2377
2378
                return NULL;
            } else {
                objc--;
            }
        }
oharboe's avatar
oharboe committed
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
		
		/*
		 * Create the formatter
		 * cause we cheat and use sprintf()
		 */
		cp = fmt_str;
		*cp++ = '%';
		if( altfm ){
			*cp++ = '#';
		}
		if( forceplus ){
			*cp++ = '+';
		} else if( spad ){
			/* PLUS overrides */
			*cp++ = ' ';
		}
		if( ljust ){
			*cp++ = '-';
		}
		if( zpad  ){
			*cp++ = '0';
		}
		if( width > 0 ){
			sprintf( cp, "%d", width );
			/* skip ahead */
			cp = strchr(cp,0);
		}
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
		/* did we find a period? */
		if( inprec ){
			/* then add it */
			*cp++ = '.';
			/* did something occur after the period? */
			if( haveprec ){
				sprintf( cp, "%d", prec );
			}
			cp = strchr(cp,0);
		}
oharboe's avatar
oharboe committed
2416
2417
2418
2419
		*cp = 0;

		/* here we do the work */
		/* actually - we make sprintf() do it for us */
2420
2421
        switch(*fmt) {
        case 's':
oharboe's avatar
oharboe committed
2422
2423
2424
2425
			*cp++ = 's';
			*cp   = 0;
			/* BUG: we do not handled embeded NULLs */
			snprintf( sprintf_buf, JIM_MAX_FMT, fmt_str, Jim_GetString( objv[0], NULL ));
2426
2427
            break;
        case 'c':
oharboe's avatar
oharboe committed
2428
2429
			*cp++ = 'c';
			*cp   = 0;
2430
2431
2432
2433
2434
            if (Jim_GetWide(interp, objv[0], &wideValue) == JIM_ERR) {
                Jim_FreeNewObj(interp, resObjPtr);
                return NULL;
            }
            c = (char) wideValue;
oharboe's avatar
oharboe committed
2435
			snprintf( sprintf_buf, JIM_MAX_FMT, fmt_str, c );
2436
            break;
oharboe's avatar
oharboe committed
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
		case 'f':
		case 'F':
		case 'g':
		case 'G':
		case 'e':
		case 'E':
			*cp++ = *fmt;
			*cp   = 0;
			if( Jim_GetDouble( interp, objv[0], &doubleValue ) == JIM_ERR ){
				Jim_FreeNewObj( interp, resObjPtr );
				return NULL;
			}
			snprintf( sprintf_buf, JIM_MAX_FMT, fmt_str, doubleValue );
			break;
        case 'b':
2452
        case 'd':
oharboe's avatar
oharboe committed
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
		case 'i':
		case 'u':
		case 'x':
		case 'X':
			/* jim widevaluse are 64bit */
			if( sizeof(jim_wide) == sizeof(long long) ){
				*cp++ = 'l'; 
				*cp++ = 'l';
			} else {
				*cp++ = 'l';
			}
			*cp++ = *fmt;
			*cp   = 0;
2466
2467
2468
2469
            if (Jim_GetWide(interp, objv[0], &wideValue) == JIM_ERR) {
                Jim_FreeNewObj(interp, resObjPtr);
                return NULL;
            }
oharboe's avatar
oharboe committed
2470
			snprintf(sprintf_buf, JIM_MAX_FMT, fmt_str, wideValue );
2471
2472
            break;
        case '%':
oharboe's avatar
oharboe committed
2473
2474
2475
			sprintf_buf[0] = '%';
			sprintf_buf[1] = 0;
			objv--; /* undo the objv++ below */
2476
2477
2478
2479
2480
2481
2482
2483
2484
            break;
        default:
            spec[0] = *fmt; spec[1] = '\0';
            Jim_FreeNewObj(interp, resObjPtr);
            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
            Jim_AppendStrings(interp, Jim_GetResult(interp),
                    "bad field specifier \"",  spec, "\"", NULL);
            return NULL;
        }
oharboe's avatar
oharboe committed
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
		/* force terminate */
#if 0
		printf("FMT was: %s\n", fmt_str );
		printf("RES was: |%s|\n", sprintf_buf );
#endif
		
		sprintf_buf[ JIM_MAX_FMT - 1] = 0;
		Jim_AppendString( interp, resObjPtr, sprintf_buf, strlen(sprintf_buf) );
		/* next obj */
		objv++;
2495
2496
2497
2498
2499
2500
        fmt++;
        fmtLen--;
    }
    return resObjPtr;
}

oharboe's avatar
oharboe committed
2501
2502
2503
2504
2505
2506
2507
2508
2509
Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr,
        int objc, Jim_Obj *const *objv)
{
	char *sprintf_buf=malloc(JIM_MAX_FMT);
	Jim_Obj *t=Jim_FormatString_Inner(interp, fmtObjPtr, objc, objv, sprintf_buf);
	free(sprintf_buf);
	return t; 
}

2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520