-
Notifications
You must be signed in to change notification settings - Fork 4
/
pickle.c
4038 lines (3780 loc) · 119 KB
/
pickle.c
1
2
3
4
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
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
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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
/**@file pickle.c
* @brief Pickle interpreter, a TCL like language based on 'picol'.
* BSD license: See <https://github.com/howerj/pickle/blob/master/LICENSE>
* Copyright (c) 2007-2016, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2018-2020, Richard James Howe <howe.r.j.89@gmail.com>
* See 'https://github.com/howerj/pickle' for the project repository.
* And <http://oldblog.antirez.com/post/picol.html> for the original. */
#include "pickle.h"
#include <assert.h> /* !defined(NDEBUG): assert */
#include <ctype.h> /* toupper, tolower, isalnum, isalpha, ... */
#include <stdint.h> /* intptr_t */
#include <limits.h> /* CHAR_BIT, LONG_MAX, LONG_MIN */
#include <stdarg.h> /* va_list, va_start, va_end */
#include <stdio.h> /* vsnprintf see <https://github.com/mpaland/printf> if you lack this */
#include <string.h> /* memset, memchr, strstr, strcmp, strncmp, strcpy, strlen, strchr */
#define SMALL_RESULT_BUF_SZ (96)
#define PRINT_NUMBER_BUF_SZ (64 /* base 2 */ + 1 /* '-'/'+' */ + 1 /* NUL */)
#define UNUSED(X) ((void)(X))
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
#define check(EXP) assert(EXP)
#define implies(P, Q) implication(!!(P), !!(Q)) /* material implication, immaterial if NDEBUG defined */
#define mutual(P, Q) (implies((P), (Q)), implies((Q), (P)))
#define member_size(TYPE, MEMBER) (sizeof(((TYPE *)0)->MEMBER)) /* apparently fine */
#define MIN(X, Y) ((X) > (Y) ? (Y) : (X))
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
#ifndef PREPACK
#define PREPACK
#endif
#ifndef POSTPACK
#define POSTPACK
#endif
#ifdef NDEBUG
#define DEBUGGING (0)
#else
#define DEBUGGING (1)
#endif
#ifndef DEFINE_TESTS
#define DEFINE_TESTS (1)
#endif
#ifndef DEFINE_MATHS
#define DEFINE_MATHS (1)
#endif
#ifndef DEFINE_STRING
#define DEFINE_STRING (1)
#endif
#ifndef DEFINE_LIST
#define DEFINE_LIST (1)
#endif
#ifndef DEFINE_REGEX
#define DEFINE_REGEX (1)
#endif
#ifndef DEFINE_HELP
#define DEFINE_HELP (0)
#endif
#ifndef PICKLE_MAX_RECURSION
#define PICKLE_MAX_RECURSION (128) /* Recursion limit */
#endif
#ifndef USE_MAX_STRING
#define USE_MAX_STRING (0)
#endif
#ifndef PICKLE_MAX_STRING
#define PICKLE_MAX_STRING (768) /* Max string/Data structure size, if USE_MAX_STRING != 0 */
#endif
#ifndef STRICT_NUMERIC_CONVERSION
#define STRICT_NUMERIC_CONVERSION (1)
#endif
#if DEFINE_HELP == 1
#define ARITY(COMP, MSG) if ((COMP)) { return picolSetResultArgError(i, __LINE__, #COMP, (MSG), argc, argv); }
#else
#define ARITY(COMP, MSG) if ((COMP)) { return picolSetResultArgError(i, __LINE__, "", "", argc, argv); }
#endif
#ifndef PICKLE_VERSION
#define PICKLE_VERSION (0x000000ul) /* all zeros = built incorrectly */
#endif
#define ok(i, ...) pickle_result_set(i, PICKLE_OK, __VA_ARGS__)
#ifndef PICKLE_LINE_NUMBER
#define error(i, ...) pickle_result_set(i, PICKLE_ERROR, __VA_ARGS__)
#else
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define error(i, ...) pickle_result_set(i, PICKLE_ERROR, TOSTRING(__LINE__) ": " __VA_ARGS__)
#endif
enum { PT_ESC, PT_STR, PT_CMD, PT_VAR, PT_SEP, PT_EOL, PT_EOF };
typedef struct {
unsigned nocommands :1, /* turn off commands */
noescape :1, /* turn off escape sequences */
novars :1, /* turn off variables */
noeval :1; /* turn off command evaluation */
} pickle_parser_opts_t; /* options for parser/evaluator */
typedef PREPACK struct {
const char *text; /* the program */
const char *p; /* current text position */
const char *start; /* token start */
const char *end; /* token end */
int len; /* remaining length */
int type; /* token type, PT_... */
pickle_parser_opts_t o; /* parser options */
unsigned inside_quote: 1; /* true if inside " " */
} POSTPACK pickle_parser_t; /* Parsing structure */
typedef PREPACK struct {
char buf[SMALL_RESULT_BUF_SZ]; /* small temporary buffer */
char *p; /* either points to buf or is allocated */
size_t length; /* length of 'p' */
} POSTPACK pickle_stack_or_heap_t; /* allocate on stack, or move to heap, depending on needs */
enum { PV_STRING, PV_SMALL_STRING, PV_LINK, };
typedef union {
char *ptr, /* pointer to string that has spilled over 'small' in size */
small[sizeof(char*)]; /* string small enough to be stored in a pointer (including NUL terminator)*/
} compact_string_t; /* either a pointer to a string, or a string stored in a pointer */
PREPACK struct pickle_var { /* strings are stored as either pointers, or as 'small' strings */
compact_string_t name; /* name of variable */
union {
compact_string_t val; /* value */
struct pickle_var *link; /* link to another variable */
} data;
struct pickle_var *next; /* next variable in list of variables */
unsigned type : 2; /* type of data; string (pointer/small), or link (NB. Could add number type) */
unsigned smallname : 1; /* if true, name is stored as small string */
} POSTPACK;
PREPACK struct pickle_command {
char *name; /* name of function, it would be nice if this was a 'compact_string_t' */
pickle_func_t func; /* pointer to function that implements this command */
struct pickle_command *next; /* next command in list (chained hash table) */
void *privdata; /* (optional) private data for function */
} POSTPACK;
PREPACK struct pickle_call_frame { /* A call frame, organized as a linked list */
struct pickle_var *vars; /* first variable in linked list of variables */
struct pickle_call_frame *parent; /* parent is NULL at top level */
} POSTPACK;
PREPACK struct pickle_interpreter { /* The Pickle Interpreter! */
char result_buf[SMALL_RESULT_BUF_SZ];/* store small results here without allocating */
allocator_fn allocator; /* custom allocator, if desired */
void *arena; /* arena for custom allocator, if needed */
const char *result; /* result of an evaluation */
struct pickle_call_frame *callframe; /* call stack */
struct pickle_command **table; /* hash table */
long length; /* buckets in hash table */
long cmdcount; /* total number of commands invoked in this interpreter */
int level, evals; /* level of functional call and evaluation nesting */
unsigned initialized :1; /* if true, interpreter is initialized and ready to use */
unsigned static_result :1; /* internal use only: if true, result should not be freed */
unsigned inside_uplevel :1; /* true if executing inside an uplevel command */
unsigned inside_unknown :1; /* true if executing inside the 'unknown' proc */
unsigned fatal :1; /* true if a fatal error has occurred */
unsigned inside_trace :1; /* true if we are inside the trace function */
unsigned trace :1; /* true if tracing is on */
} POSTPACK;
typedef PREPACK struct {
const char *start, /* start of match, NULL if no match */
*end; /* end of match, NULL if no match */
int max; /* maximum recursion depth (0 = unlimited) */
unsigned type :2, /* select regex type; lazy, greedy or possessive */
nocase :1; /* ignore case when matching */
} POSTPACK pickle_regex_t; /* used to specify a regex and return start/end of match */
typedef struct PREPACK { int argc; char **argv; } POSTPACK args_t;
typedef struct pickle_var pickle_var_t;
typedef struct pickle_call_frame pickle_call_frame_t;
typedef struct pickle_command pickle_command_t;
typedef long number_t;
typedef unsigned long unumber_t;
#define NUMBER_MIN (LONG_MIN)
#define NUMBER_MAX (LONG_MAX)
static const char string_empty[] = ""; /* Space saving measure */
static const char string_oom[] = "Error out of memory"; /* Cannot allocate this, obviously */
static const char *string_white_space = " \t\n\r\v";
static const char *string_digits = "0123456789abcdefghijklmnopqrstuvwxyz";
static int picolForceResult(pickle_t *i, const char *result, const int is_static);
static int picolSetResultString(pickle_t *i, const char *s);
static inline void implication(const int p, const int q) {
UNUSED(p); UNUSED(q); /* warning suppression if NDEBUG defined */
check((!p) || q);
}
static inline void static_assertions(void) { /* A neat place to put these */
BUILD_BUG_ON(PICKLE_MAX_STRING < 128);
BUILD_BUG_ON(sizeof (struct pickle_interpreter) > PICKLE_MAX_STRING);
BUILD_BUG_ON(sizeof (string_oom) > SMALL_RESULT_BUF_SZ);
BUILD_BUG_ON(PICKLE_MAX_RECURSION < 8);
BUILD_BUG_ON(PICKLE_OK != 0);
BUILD_BUG_ON(PICKLE_ERROR != -1);
}
static inline void *locateByte(const void *m, const int c, const size_t n) {
check(m);
return memchr(m, c, n);
}
static inline void pre(pickle_t *i) { /* assert API pre-conditions */
UNUSED(i); /* warning suppression when NDEBUG defined */
check(i);
check(i->initialized);
check(i->result);
check(i->length > 0);
check(!!locateByte(i->result_buf, 0, sizeof i->result_buf));
check(i->level >= 0);
}
static inline int post(pickle_t *i, const int r) { /* assert API post-conditions */
pre(i);
check(r >= PICKLE_ERROR && r <= PICKLE_CONTINUE);
return i->fatal ? PICKLE_ERROR : r;
}
static inline int compare(const char *a, const char *b) {
check(a);
check(b);
if (USE_MAX_STRING)
return strncmp(a, b, PICKLE_MAX_STRING);
return strcmp(a, b);
}
static inline size_t picolStrnlen(const char *s, size_t length) {
check(s);
size_t r = 0;
for (r = 0; r < length && *s; s++, r++)
;
return r;
}
static inline size_t picolStrlen(const char *s) {
check(s);
return USE_MAX_STRING ? picolStrnlen(s, PICKLE_MAX_STRING) : strlen(s);
}
static inline void *move(void *dst, const void *src, const size_t length) {
check(dst);
check(src);
return memmove(dst, src, length);
}
static inline void *zero(void *m, const size_t length) {
check(m);
if (length == 0)
return m;
return memset(m, 0, length);
}
static inline char *copy(char *dst, const char *src) {
check(src);
check(dst);
return strcpy(dst, src);
}
static inline char *find(const char *haystack, const char *needle) {
check(haystack);
check(needle);
return strstr(haystack, needle);
}
static inline const char *rfind(const char *haystack, const char *needle) {
check(haystack);
check(needle);
const size_t hay = strlen(haystack);
for (size_t i = 0; i < hay; i++)
if (strstr(&haystack[hay - i - 1], needle))
return &haystack[hay - i - 1];
return NULL;
}
static inline char *locateChar(const char *s, const int c) {
check(s);
return strchr(s, c);
}
static void *picolMalloc(pickle_t *i, size_t size) {
check(i);
check(size > 0); /* we do not allocate any zero length objects in this code */
if (i->fatal || (USE_MAX_STRING && size > PICKLE_MAX_STRING))
goto fail;
void *r = i->allocator(i->arena, NULL, 0, size);
if (!r && size)
goto fail;
return r;
fail:
i->fatal = 1;
(void)picolForceResult(i, string_oom, 1);
return NULL;
}
static void *picolRealloc(pickle_t *i, void *p, size_t size) {
check(i);
if (i->fatal || (USE_MAX_STRING && size > PICKLE_MAX_STRING))
goto fail;
void *r = i->allocator(i->arena, p, 0, size);
if (!r && size)
goto fail;
return r;
fail:
i->fatal = 1;
(void)picolForceResult(i, string_oom, 1); /* does not allocate, may free */
return NULL;
}
static int picolFree(pickle_t *i, void *p) {
check(i);
check(i->allocator);
const void *r = i->allocator(i->arena, p, 0, 0);
if (r != NULL) {
static const char msg[] = "Error free";
BUILD_BUG_ON(sizeof(msg) > SMALL_RESULT_BUF_SZ);
i->fatal = 1;
(void)picolSetResultString(i, msg);
return PICKLE_ERROR;
}
return PICKLE_OK;
}
static inline int picolIsBaseValid(const int base) {
return base >= 2 && base <= 36; /* Base '0' is not a special case */
}
static inline int picolDigit(const int digit) {
const char *found = locateChar(string_digits, tolower(digit));
return found ? (int)(found - string_digits) : -1;
}
static inline int picolIsDigit(const int digit, const int base) {
check(picolIsBaseValid(base));
const int r = picolDigit(digit);
return r < base ? r : -1;
}
static int picolConvertBaseNNumber(pickle_t *i, const char *s, number_t *out, int base) {
check(i);
check(i->initialized);
check(s);
check(picolIsBaseValid(base));
static const size_t max = MIN(PRINT_NUMBER_BUF_SZ, PICKLE_MAX_STRING);
number_t result = 0;
int ch = s[0];
const int negate = ch == '-';
const int prefix = negate || s[0] == '+';
*out = 0;
if (STRICT_NUMERIC_CONVERSION && prefix && !s[prefix])
return error(i, "Error number");
if (STRICT_NUMERIC_CONVERSION && !ch)
return error(i, "Error number");
for (size_t j = prefix; j < max && (ch = s[j]); j++) {
const number_t digit = picolIsDigit(ch, base);
if (digit < 0)
break;
result = digit + (result * (number_t)base);
}
if (STRICT_NUMERIC_CONVERSION && ch)
return error(i, "Error number");
*out = negate ? -result : result;
return PICKLE_OK;
}
/* NB. We could make a version of this that could also process 'end' and
* 'end-#' numbers for indexing, it would require a length however. This
* would be useful for commands like 'string index' and some of the list
* manipulation commands. */
static int picolStringToNumber(pickle_t *i, const char *s, number_t *out) {
check(i);
check(s);
check(out);
return picolConvertBaseNNumber(i, s, out, 10);
}
static inline int picolCompareCaseInsensitive(const char *a, const char *b) {
check(a);
check(b);
for (size_t i = 0; ; i++) {
const int ach = tolower(a[i]);
const int bch = tolower(b[i]);
const int diff = ach - bch;
if (!ach || diff)
return diff;
}
return 0;
}
static inline int picolLogarithm(number_t a, const number_t b, number_t *c) {
check(c);
number_t r = -1;
*c = r;
if (a <= 0 || b < 2)
return PICKLE_ERROR;
do r++; while (a /= b);
*c = r;
return PICKLE_OK;
}
static inline int picolPower(number_t base, number_t exp, number_t *r) {
check(r);
number_t result = 1, negative = 0;
*r = 0;
if (exp < 0)
return PICKLE_ERROR;
if (base < 0) {
base = -base;
negative = exp & 1;
}
for (;;) {
if (exp & 1)
result *= base;
exp /= 2;
if (!exp)
break;
base *= base;
}
*r = negative ? -result : result;
return PICKLE_OK;
}
/* This is may seem like an odd function, say for small allocation we want to
* keep them on the stack, but move them to the heap when they get too big, we can use
* the 'picolStackOrHeapAlloc'/'picolStackOrHeapFree' functions to manage this. */
static int picolStackOrHeapAlloc(pickle_t *i, pickle_stack_or_heap_t *s, size_t needed) {
check(i);
check(s);
if (s->p == NULL) { /* take care of initialization */
s->p = s->buf;
s->length = sizeof (s->buf);
zero(s->buf, sizeof (s->buf));
}
if (needed <= s->length)
return PICKLE_OK;
if (USE_MAX_STRING && needed > PICKLE_MAX_STRING)
return PICKLE_ERROR;
if (s->p == s->buf) {
if (!(s->p = picolMalloc(i, needed)))
return PICKLE_ERROR;
s->length = needed;
move(s->p, s->buf, sizeof (s->buf));
return PICKLE_OK;
}
char *old = s->p;
if ((s->p = picolRealloc(i, s->p, needed)) == NULL) {
(void)picolFree(i, old);
return PICKLE_ERROR;
}
s->length = needed;
return PICKLE_OK;
}
static int picolStackOrHeapFree(pickle_t *i, pickle_stack_or_heap_t *s) {
check(i);
check(s);
if (s->p != s->buf) {
const int r = picolFree(i, s->p);
s->p = NULL; /* prevent double free */
s->length = 0;
return r;
}
return PICKLE_OK; /* pointer == buffer, no need to free */
}
static int picolOnHeap(pickle_t *i, pickle_stack_or_heap_t *s) {
check(i); UNUSED(i);
check(s);
return s->p && s->p != s->buf;
}
static char *picolStrdup(pickle_t *i, const char *s) {
check(i);
check(s);
const size_t l = picolStrlen(s);
char *r = picolMalloc(i, l + 1);
return r ? move(r, s, l + 1) : r;
}
static inline unsigned long picolHashString(const char *s) { /* DJB2 Hash, <http://www.cse.yorku.ca/~oz/hash.html> */
check(s);
unsigned long h = 5381, ch = 0; /* NB. strictly speaking 'uint32_t' should be used here */
for (size_t i = 0; (ch = s[i]); i++) {
implies(USE_MAX_STRING, i < PICKLE_MAX_STRING);
h = ((h << 5) + h) + ch;
}
return h;
}
static inline pickle_command_t *picolGetCommand(pickle_t *i, const char *s) {
check(s);
check(i);
pickle_command_t *np = NULL;
for (np = i->table[picolHashString(s) % i->length]; np != NULL; np = np->next)
if (!compare(s, np->name))
return np; /* found */
return NULL; /* not found */
}
static int picolFreeResult(pickle_t *i) {
check(i);
return i->static_result ? PICKLE_OK : picolFree(i, (char*)i->result);
}
static int picolSetResultString(pickle_t *i, const char *s) {
check(s);
int is_static = 1;
char *r = i->result_buf;
const size_t sl = picolStrlen(s) + 1;
if (sizeof(i->result_buf) < sl) {
is_static = 0;
r = picolMalloc(i, sl);
if (!r)
return PICKLE_ERROR;
}
move(r, s, sl);
const int fr = picolFreeResult(i);
i->static_result = is_static;
i->result = r;
return fr;
}
static int picolForceResult(pickle_t *i, const char *result, const int is_static) {
check(i);
check(result);
int r = picolFreeResult(i);
i->static_result = is_static;
i->result = result;
return r;
}
static int picolSetResultEmpty(pickle_t *i) {
check(i);
return picolForceResult(i, string_empty, 1);
}
static int picolSetResultArgError(pickle_t *i, const unsigned line, const char *comp, const char *help, const int argc, char **argv);
static int picolCommandCallProc(pickle_t *i, const int argc, char **argv, void *pd);
static int picolIsDefinedProc(pickle_func_t func) {
return func == picolCommandCallProc;
}
/* <https://stackoverflow.com/questions/4384359/> */
static int picolRegisterCommand(pickle_t *i, const char *name, pickle_func_t func, void *privdata) {
check(i);
check(name);
check(func);
pickle_command_t *np = picolGetCommand(i, name);
if (np) {
if (picolIsDefinedProc(func)) {
char **procdata = privdata;
(void)picolFree(i, procdata[0]);
(void)picolFree(i, procdata[1]);
(void)picolFree(i, procdata);
}
return error(i, "Error option %s", name);
}
np = picolMalloc(i, sizeof(*np));
if (np == NULL || (np->name = picolStrdup(i, name)) == NULL) {
(void)picolFree(i, np);
return PICKLE_ERROR;
}
const unsigned long hashval = picolHashString(name) % i->length;
np->next = i->table[hashval];
i->table[hashval] = np;
np->func = func;
np->privdata = privdata;
return PICKLE_OK;
}
static int picolFreeCmd(pickle_t *i, pickle_command_t *p);
static int picolUnsetCommand(pickle_t *i, const char *name) {
check(i);
check(name);
pickle_command_t **p = &i->table[picolHashString(name) % i->length];
pickle_command_t *c = *p;
for (; c; c = c->next) {
if (!compare(c->name, name)) {
*p = c->next;
return picolFreeCmd(i, c);
}
p = &c->next;
}
return error(i, "Error variable %s", name);
}
static int advance(pickle_parser_t *p) {
check(p);
if (p->len <= 0)
return PICKLE_ERROR;
if (p->len && !(*p->p))
return PICKLE_ERROR;
p->p++;
p->len--;
if (p->len && !(*p->p))
return PICKLE_ERROR;
return PICKLE_OK;
}
static inline void picolParserInitialize(pickle_parser_t *p, pickle_parser_opts_t *o, const char *text) {
/* NB. check(o || !o); */
check(p);
check(text);
zero(p, sizeof *p);
p->text = text;
p->p = text;
p->len = strlen(text); /* unbounded! */
p->type = PT_EOL;
p->o = o ? *o : p->o;
}
static inline int picolIsSpaceChar(const int ch) {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
}
static inline int picolParseSep(pickle_parser_t *p) {
check(p);
p->start = p->p;
while (*p->p == ' ' || *p->p == '\t')
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
p->end = p->p - 1;
p->type = PT_SEP;
return PICKLE_OK;
}
static inline int picolParseEol(pickle_parser_t *p) {
check(p);
p->start = p->p;
while (picolIsSpaceChar(*p->p) || *p->p == ';')
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
p->end = p->p - 1;
p->type = PT_EOL;
return PICKLE_OK;
}
static inline int picolParseCommand(pickle_parser_t *p) {
check(p);
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
p->start = p->p;
for (int level = 1, blevel = 0; p->len;) {
if (*p->p == '[' && blevel == 0) {
level++;
} else if (*p->p == ']' && blevel == 0) {
if (!--level)
break;
} else if (*p->p == '\\') {
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
} else if (*p->p == '{') {
blevel++;
} else if (*p->p == '}') {
if (blevel != 0)
blevel--;
}
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
}
if (*p->p != ']')
return PICKLE_ERROR;
p->end = p->p - 1;
p->type = PT_CMD;
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
return PICKLE_OK;
}
static inline int picolIsVarChar(const int ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_';
}
static inline int picolParseVar(pickle_parser_t *p) {
check(p);
int br = 0;
if (advance(p) != PICKLE_OK) /* skip the $ */
return PICKLE_ERROR;
if (*p->p == '{') {
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
br = 1;
}
p->start = p->p;
for (;picolIsVarChar(*p->p);)
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
p->end = p->p - 1;
if (br) {
if (*p->p != '}')
return PICKLE_ERROR;
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
}
if (!br && p->start == p->p) { /* It's just a single char string "$" */
p->start = p->p - 1;
p->type = PT_STR;
} else {
p->type = PT_VAR;
}
return PICKLE_OK;
}
static inline int picolParseBrace(pickle_parser_t *p) {
check(p);
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
p->start = p->p;
for (int level = 1;;) {
if (p->len >= 2 && *p->p == '\\') {
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
} else if (p->len == 0) {
return PICKLE_ERROR;
} else if (*p->p == '}') {
level--;
if (level == 0) {
p->end = p->p - 1;
p->type = PT_STR;
if (p->len)
return advance(p); /* Skip final closed brace */
return PICKLE_OK;
}
} else if (*p->p == '{') {
level++;
}
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
}
return PICKLE_OK; /* unreached */
}
static int picolParseString(pickle_parser_t *p) {
check(p);
const int newword = (p->type == PT_SEP || p->type == PT_EOL || p->type == PT_STR);
if (newword && *p->p == '{') {
return picolParseBrace(p);
} else if (newword && *p->p == '"') {
p->inside_quote = 1;
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
}
p->start = p->p;
for (;p->len;) {
switch (*p->p) {
case '\\':
if (p->o.noescape)
break;
if (p->len >= 2)
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
break;
case '$':
if (p->o.novars)
break;
p->end = p->p - 1;
p->type = PT_ESC;
return PICKLE_OK;
case '[':
if (p->o.nocommands)
break;
p->end = p->p - 1;
p->type = PT_ESC;
return PICKLE_OK;
case '\n': case ' ': case '\t': case '\r': case ';':
if (!p->inside_quote) {
p->end = p->p - 1;
p->type = PT_ESC;
return PICKLE_OK;
}
break;
case '"':
if (p->inside_quote) {
p->end = p->p - 1;
p->type = PT_ESC;
p->inside_quote = 0;
return advance(p);
}
break;
}
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
}
if (p->inside_quote)
return PICKLE_ERROR;
p->end = p->p - 1;
p->type = PT_ESC;
return PICKLE_OK;
}
static inline int picolParseComment(pickle_parser_t *p) {
check(p);
while (p->len && *p->p != '\n') {
if (*p->p == '\\' && p->p[1] == '\n') /* Unix line endings only */
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
if (advance(p) != PICKLE_OK)
return PICKLE_ERROR;
}
return PICKLE_OK;
}
static int picolGetToken(pickle_parser_t *p) {
check(p);
for (;p->len;) {
switch (*p->p) {
case ' ': case '\t':
if (p->inside_quote)
return picolParseString(p);
return picolParseSep(p);
case '\r': case '\n': case ';':
if (p->inside_quote)
return picolParseString(p);
return picolParseEol(p);
case '[': {
const int r = picolParseCommand(p);
if (r == PICKLE_OK && p->o.nocommands && p->type == PT_CMD) {
p->start--, p->end++;
p->type = PT_STR;
check(*p->start == '[' && *p->end == ']');
}
return r;
}
case '$':
return p->o.novars ? picolParseString(p) : picolParseVar(p);
case '#':
if (p->type == PT_EOL) {
if (picolParseComment(p) != PICKLE_OK)
return PICKLE_ERROR;
continue;
}
return picolParseString(p);
default:
return picolParseString(p);
}
}
if (p->type != PT_EOL && p->type != PT_EOF)
p->type = PT_EOL;
else
p->type = PT_EOF;
return PICKLE_OK;
}
static pickle_var_t *picolGetVar(pickle_t *i, const char *name, int link) {
check(i);
check(name);
pickle_var_t *v = i->callframe->vars;
while (v) {
const char *n = v->smallname ? &v->name.small[0] : v->name.ptr;
check(n);
if (!compare(n, name)) {
if (link)
while (v->type == PV_LINK) { /* NB. Could resolve link at creation? */
check(v != v->data.link); /* Cycle? */
v = v->data.link;
}
implies(v->type == PV_STRING, v->data.val.ptr);
return v;
}
/* See <https://en.wikipedia.org/wiki/Cycle_detection>,
* <https://stackoverflow.com/questions/2663115>, or "Floyd's
* cycle-finding algorithm" for proper loop detection */
check(v != v->next); /* Cycle? */
v = v->next;
}
return NULL;
}
static int picolFreeVarName(pickle_t *i, pickle_var_t *v) {
check(i);
check(v);
return v->smallname ? PICKLE_OK : picolFree(i, v->name.ptr);
}
static int picolFreeVarVal(pickle_t *i, pickle_var_t *v) {
check(i);
check(v);
return v->type == PV_STRING ? picolFree(i, v->data.val.ptr) : PICKLE_OK;
}
/* return: non-zero if and only if val fits in a small string */
static inline int picolIsSmallString(const char *val) {
check(val);
return !!locateByte(val, 0, member_size(compact_string_t, small));
}
static int picolSetVarString(pickle_t *i, pickle_var_t *v, const char *val) {
check(i);
check(v);
check(val);
if (picolIsSmallString(val)) {
v->type = PV_SMALL_STRING;
copy(v->data.val.small, val);
return PICKLE_OK;
}
v->type = PV_STRING;
return (v->data.val.ptr = picolStrdup(i, val)) ? PICKLE_OK : PICKLE_ERROR;
}
static inline int picolSetVarName(pickle_t *i, pickle_var_t *v, const char *name) {
check(i);
check(v);
check(name);
if (picolIsSmallString(name)) {
v->smallname = 1;
copy(v->name.small, name);
return PICKLE_OK;
}
v->smallname = 0;
return (v->name.ptr = picolStrdup(i, name)) ? PICKLE_OK : PICKLE_ERROR;
}
static const char *picolGetVarVal(pickle_var_t *v) {
check(v);
check((v->type == PV_SMALL_STRING) || (v->type == PV_STRING));
switch (v->type) {
case PV_SMALL_STRING: return v->data.val.small;
case PV_STRING: return v->data.val.ptr;
}
return NULL;
}
static inline void picolSwapString(char **a, char **b) {
check(a);
check(b);
char *t = *a;
*a = *b;
*b = t;
}
static inline void picolSwapChar(char * const a, char * const b) {
check(a);
check(b);
const char t = *a;
*a = *b;
*b = t;
}
static inline char *reverse(char *s, size_t length) { /* Modifies Argument */
check(s);
for (size_t i = 0; i < (length/2); i++)
picolSwapChar(&s[i], &s[(length - i) - 1]);
return s;
}
static int picolNumberToString(char buf[/*static*/ 64/*base 2*/ + 1/*'+'/'-'*/ + 1/*NUL*/], number_t in, int base) {
check(buf);
int negate = 0;
size_t i = 0;
unumber_t dv = in;
if (!picolIsBaseValid(base))
return PICKLE_ERROR;
if (in < 0) {
dv = -(unumber_t)in;
negate = 1;
}
do
buf[i++] = string_digits[dv % base];
while ((dv /= base));
if (negate)
buf[i++] = '-';
buf[i] = 0;
reverse(buf, i);
return PICKLE_OK;
}
static char *picolVsprintf(pickle_t *i, const char *fmt, va_list ap) {
check(i);
check(fmt);
pickle_stack_or_heap_t h = { .p = NULL };
BUILD_BUG_ON(sizeof (h.buf) != SMALL_RESULT_BUF_SZ);
int needed = SMALL_RESULT_BUF_SZ;
if (picolStackOrHeapAlloc(i, &h, needed) != PICKLE_OK)
return NULL;
for (;;) {
va_list mine;
va_copy(mine, ap);