-
Notifications
You must be signed in to change notification settings - Fork 3
/
jsemtblgen.c
1531 lines (1390 loc) · 41.7 KB
/
jsemtblgen.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
/*
* jsemtblgen - generate JSON semantics table
*
* "Because specs w/o version numbers are forced to commit to their original design flaws." :-)
*
* This JSON parser was co-developed in 2022 by:
*
* @xexyl
* https://xexyl.net Cody Boone Ferguson
* https://ioccc.xexyl.net
* and:
* chongo (Landon Curt Noll, http://www.isthe.com/chongo/index.html) /\oo/\
*
* "Because sometimes even the IOCCC Judges need some help." :-)
*
* The concept of the JSON semantics tables was developed by Landon Curt Noll.
*
* "Share and Enjoy!"
* -- Sirius Cybernetics Corporation Complaints Division, JSON spec department. :-)
*/
/* special comments for the seqcexit tool */
/* exit code out of numerical order - ignore in sequencing - ooo */
/* exit code change of order - use new value in sequencing - coo */
#include <stdio.h>
#include <unistd.h>
/*
* jsemtblgen - generate JSON semantics table
*/
#include "jsemtblgen.h"
/*
* definitions
*/
#define REQUIRED_ARGS (1) /* number of required arguments on the command line */
#define CHUNK (16) /* allocate CHUNK elements at a time */
#define STRLEN(s) (sizeof (s)-1)
/*
* static globals
*/
static bool h_mode = false; /* -I - true ==> output as .h include file, false ==> output as .c src */
static char *tbl_name = "sem_tbl"; /* -N name - name of the semantic table */
static char *def_func = NULL; /* -D def_func - validate with def_func() unless overridden */
static char *prefix = NULL; /* -P prefix - validate JTYPE_MEMBER with prefix_name() or NULL */
static char *number_func = NULL; /* -1 func - validate JTYPE_NUMBER JSON nodes or NULL */
static char *string_func = NULL; /* -S func - validate JTYPE_STRING JSON nodes or NULL */
static char *bool_func = NULL; /* -B func - validate JTYPE_BOOL JSON nodes or NULL */
static char *null_func = NULL; /* -0 func - validate JTYPE_NULL JSON nodes or NULL */
static char *member_func = NULL; /* -M func - validate JTYPE_MEMBER JSON nodes or NULL */
static char *object_func = NULL; /* -O func - validate JTYPE_OBJECT JSON nodes or NULL */
static char *array_func = NULL; /* -A func - validate JTYPE_ARRAY JSON nodes or NULL */
static char *unknown_func = NULL; /* -U func - validate nodes with unknown types or NULL */
/*
* usage message
*/
static const char * const usage_msg =
"usage: %s [-h] [-v level] [-J level] [-q] [-V] [-s] [-I] [-N name] [-D def_func] [-P prefix]\n"
"\t\t [-1 func] [-S func] [-B func] [-0 func] [-M func] [-O func] [-A func] [-U func] json_arg\n"
"\n"
"\t-h\t\tprint help message and exit\n"
"\t-v level\tset verbosity level (def level: %d)\n"
"\t-J level\tset JSON verbosity level (def level: %d)\n"
"\t-q\t\tquiet mode: silence msg(), warn(), warnp() if -v 0 (def: loud :-) )\n"
"\t-V\t\tprint version string and exit\n"
"\t-s\t\targ is a string (def: arg is a filename)\n"
"\n"
"\t-I\t\toutput as .h include file (def: output as .c src)\n"
"\n"
"\t-N name\t\tname of the semantics table (def: sem_tbl)\n"
"\n"
"\t-D def_func\tvalidate with def_func() unless overridden by another flag (def: NULL)\n"
"\n"
"\t-P prefix\tvalidate JTYPE_MEMBER JSON nodes with prefix() (def: do not)\n"
"\n"
"\t\t\tNOTE: The name is based on the JTYPE_MEMBER JSON decoded name string.\n"
"\t\t\tNOTE: Underscore (_) replaces any name chars that are not valid in a C function name.\n"
"\t\t\tNOTE: -P overrides any use of -M.\n"
"\n"
"\t-1 func\t\tvalidate JTYPE_NUMBER JSON nodes with func() (def: NULL)\n"
"\t-S func\t\tvalidate JTYPE_STRING JSON nodes with func() (def: NULL)\n"
"\t-B func\t\tvalidate JTYPE_BOOL JSON nodes with func() (def: NULL)\n"
"\t-0 func\t\tvalidate JTYPE_NULL JSON nodes with func() (def: NULL)\n"
"\t-M func\t\tvalidate JTYPE_MEMBER JSON nodes with func() (def: use JSON member name)\n"
"\t-O func\t\tvalidate JTYPE_OBJECT JSON nodes with func() (def: NULL)\n"
"\t-A func\t\tvalidate JTYPE_ARRAY JSON nodes with func() (def: NULL)\n"
"\t-U func\t\tvalidate nodes with unknown types with func() (def: NULL)\n"
"\n"
"\tjson_arg\tgenerate JSON semantics table for string (if -s), file (w/o -s), or stdin (if arg is -)\n"
"\n"
"Exit codes:\n"
" 0\t\tJSON is valid\n"
" 1\t\tJSON is invalid\n"
" 2\t\t-h and help string printed or -V and version string printed\n"
" 3\t\tcommand line error\n"
" >=10\tinternal error\n"
"\n"
"jsemtblgen version: %s\n"
"jparse UTF-8 version: %s\n"
"jparse library version: %s";
/*
* IOCCC Judge's remarks:
*
* The following editorial plea expresses a view shared by more than zero
* IOCCC judges. It may not represent the opinion of all those involved
* with this code nor the International Obfuscated C Code Contest as a whole:
*
* The long list of reserved words below should be a source
* of embarrassment to some of those involved in standardizing C.
* The growing list of reserved words, along with an expanding set of
* linguistic inventions has the appearance of feature
* creep that, if left unchecked, risks turning a beautifully elegant
* language into a steaming pile of biological excretion.
*
* The history of the IOCCC has taught us that even minor changes
* to the language are not always well understood by compiler writers,
* let alone the standards body who publishes them. We have enormous
* sympathy for C compiler writers who must keep up with the creeping
* featurism. We are aware of some C standards members who share
* these concerns. Alas, they seem to be a minority.
*
* The C standards body as a whole, before they emit yet more mountains of new
* standardese, might wish consider the option of moth-balling their committee.
* Or if they must produce a new standard, consider naming whatever
* follows c11 as CNC (C's Not C). :-)
*/
/*
* C reserved words, plus a few #preprocessor tokens, that count as 1
*
* NOTE: For a good list of reserved words in C, see:
*
* http://www.bezem.de/pdf/ReservedWordsInC.pdf
*
* by Johan Bezem of JB Enterprises:
*
* See http://www.bezem.de/en/
*/
typedef struct {
size_t length;
const char *word;
} Word;
static Word cwords[] = {
/* Yes Virginia, we left #define off the list on purpose! */
{ STRLEN("#elif"), "#elif" } ,
{ STRLEN("#else"), "#else" } ,
{ STRLEN("#endif"), "#endif" } ,
{ STRLEN("#error"), "#error" } ,
{ STRLEN("#ident"), "#ident" } ,
{ STRLEN("#if"), "#if" } ,
{ STRLEN("#ifdef"), "#ifdef" } ,
{ STRLEN("#ifndef"), "#ifndef" } ,
{ STRLEN("#include"), "#include" } ,
{ STRLEN("#line"), "#line" } ,
{ STRLEN("#pragma"), "#pragma" } ,
{ STRLEN("#sccs"), "#sccs" } ,
{ STRLEN("#warning"), "#warning" } ,
{ STRLEN("_Alignas"), "_Alignas" } ,
{ STRLEN("_Alignof"), "_Alignof" } ,
{ STRLEN("_Atomic"), "_Atomic" } ,
{ STRLEN("_Bool"), "_Bool" } ,
{ STRLEN("_Complex"), "_Complex" } ,
{ STRLEN("_Generic"), "_Generic" } ,
{ STRLEN("_Imaginary"), "_Imaginary" } ,
{ STRLEN("_Noreturn"), "_Noreturn" } ,
{ STRLEN("_Pragma"), "_Pragma" } ,
{ STRLEN("_Static_assert"), "_Static_assert" } ,
{ STRLEN("_Thread_local"), "_Thread_local" } ,
{ STRLEN("alignas"), "alignas" } ,
{ STRLEN("alignof"), "alignof" } ,
{ STRLEN("and"), "and" } ,
{ STRLEN("and_eq"), "and_eq" } ,
{ STRLEN("auto"), "auto" } ,
{ STRLEN("bitand"), "bitand" } ,
{ STRLEN("bitor"), "bitor" } ,
{ STRLEN("bool"), "bool" } ,
{ STRLEN("break"), "break" } ,
{ STRLEN("case"), "case" } ,
{ STRLEN("char"), "char" } ,
{ STRLEN("compl"), "compl" } ,
{ STRLEN("const"), "const" } ,
{ STRLEN("continue"), "continue" } ,
{ STRLEN("default"), "default" } ,
{ STRLEN("do"), "do" } ,
{ STRLEN("double"), "double" } ,
{ STRLEN("else"), "else" } ,
{ STRLEN("enum"), "enum" } ,
{ STRLEN("extern"), "extern" } ,
{ STRLEN("false"), "false" } ,
{ STRLEN("float"), "float" } ,
{ STRLEN("for"), "for" } ,
{ STRLEN("goto"), "goto" } ,
{ STRLEN("if"), "if" } ,
{ STRLEN("inline"), "inline" } ,
{ STRLEN("int"), "int" } ,
{ STRLEN("long"), "long" } ,
{ STRLEN("noreturn"), "noreturn" } ,
{ STRLEN("not"), "not" } ,
{ STRLEN("not_eq"), "not_eq" } ,
{ STRLEN("or"), "or" } ,
{ STRLEN("or_eq"), "or_eq" } ,
{ STRLEN("register"), "register" } ,
{ STRLEN("restrict"), "restrict" } ,
{ STRLEN("return"), "return" } ,
{ STRLEN("short"), "short" } ,
{ STRLEN("signed"), "signed" } ,
{ STRLEN("sizeof"), "sizeof" } ,
{ STRLEN("static"), "static" } ,
{ STRLEN("static_assert"), "static_assert" } ,
{ STRLEN("struct"), "struct" } ,
{ STRLEN("switch"), "switch" } ,
{ STRLEN("thread_local"), "thread_local" } ,
{ STRLEN("true"), "true" } ,
{ STRLEN("typedef"), "typedef" } ,
{ STRLEN("union"), "union" } ,
{ STRLEN("unsigned"), "unsigned" } ,
{ STRLEN("void"), "void" } ,
{ STRLEN("volatile"), "volatile" } ,
{ STRLEN("while"), "while" } ,
{ STRLEN("xor"), "xor" } ,
{ STRLEN("xor_eq"), "xor_eq" } ,
{ 0, NULL }
};
/*
* forward declarations
*/
static void gen_sem_tbl(struct json *tree, unsigned int max_depth, ...);
static void vupdate_tbl(struct json *node, unsigned int depth, va_list ap);
static int sem_cmp(void const *a, void const *b);
static char *alloc_c_funct_name(char const *prefix, char const *str);
static bool append_unique_str(struct dyn_array *tbl, char *str);
static void print_sem_c_src(struct dyn_array *tbl, char *tbl_name, char *cap_tbl_name);
static void print_sem_h_src(struct dyn_array *tbl, char *tbl_name, char *cap_tbl_name);
static Word *find_member(Word *table, const char *string);
static bool test_reserved(const char *string);
static void usage(int exitcode, char const *prog, char const *str) __attribute__((noreturn));
int
main(int argc, char **argv)
{
struct dyn_array *tbl = NULL; /* semantic table - array of struct json_sem */
char const *program = NULL; /* our name */
extern char *optarg; /* option argument */
extern int optind; /* argv index of the next arg */
bool string_flag_used = false; /* true ==> -S string was used */
bool valid_json = false; /* true ==> JSON parse was valid */
struct json *tree = NULL; /* JSON parse tree or NULL */
int arg_count = 0; /* number of args to process */
char *cap_tbl_name = NULL; /* UPPER case copy of tbl_name */
size_t len = 0; /* length of tbl_name */
int i;
size_t c;
/*
* parse args
*/
program = argv[0];
while ((i = getopt(argc, argv, ":hv:J:qVsIN:D:P:1:S:B:0:M:O:A:U:")) != -1) {
switch (i) {
case 'h': /* -h - print help to stderr and exit 0 */
usage(2, program, ""); /*ooo*/
not_reached();
break;
case 'v': /* -v verbosity */
/*
* parse verbosity
*/
verbosity_level = parse_verbosity(optarg);
if (verbosity_level < 0) {
usage(3, program, "invalid -v verbosity"); /*ooo*/
not_reached();
}
break;
case 'J': /* -J level - JSON parser verbosity level */
/*
* parse json verbosity level
*/
json_verbosity_level = parse_verbosity(optarg);
if (verbosity_level < 0) {
usage(3, program, "invalid -J json_verbosity"); /*ooo*/
not_reached();
}
break;
case 'q': /* -q - quiet mode: silence msg(), warn(), warnp() if -v 0 */
msg_warn_silent = true;
break;
case 'V': /* -V - print version and exit */
print("%s version: %s\n", JSEMTBLGEN_BASENAME, JSEMTBLGEN_VERSION);
print("jparse UTF-8 version: %s\n", JPARSE_UTF8_VERSION);
print("jparse library version: %s\n", JPARSE_LIBRARY_VERSION);
exit(2); /*ooo*/
not_reached();
break;
case 's': /* -s - arg is a string */
string_flag_used = true;
break;
case 'I':
h_mode = true;
break;
case 'N': /* -N name - name of the semantic table */
tbl_name = optarg;
break;
case 'D': /* -D def_func - validate with def_func() unless overridden */
def_func = optarg;
break;
case 'P': /* -P prefix - validate JTYPE_MEMBER with prefix_name() */
prefix = optarg;
break;
case '1': /* -1 func - validate JTYPE_NUMBER JSON nodes */
number_func = optarg;
break;
case 'S': /* -S func - validate JTYPE_STRING JSON nodes */
string_func = optarg;
break;
case 'B': /* -B func - validate JTYPE_BOOL JSON nodes */
bool_func = optarg;
break;
case '0': /* -0 func - validate JTYPE_NULL JSON nodes */
null_func = optarg;
break;
case 'M': /* -M func - validate JTYPE_MEMBER JSON nodes */
member_func = optarg;
break;
case 'O': /* -O func - validate JTYPE_NULL JSON nodes */
object_func = optarg;
break;
case 'A': /* -A func - validate JTYPE_ARRAY JSON nodes */
array_func = optarg;
break;
case 'U': /* -U func - validate nodes with unknown types */
unknown_func = optarg;
break;
case ':': /* option requires an argument */
case '?': /* illegal option */
default: /* anything else but should not actually happen */
check_invalid_option(program, i, optopt);
usage(3, program, ""); /*ooo*/
not_reached();
break;
}
}
arg_count = argc - optind;
if (arg_count != REQUIRED_ARGS) {
usage(3, program, "wrong number of arguments"); /*ooo*/
not_reached();
}
/*
* form upper case table name
*/
errno = 0; /* pre-clear errno for errp() */
cap_tbl_name = strdup(tbl_name);
if (cap_tbl_name == NULL) {
errp(10, program, "strdup of tbl_name failed");
not_reached();
}
len = strlen(tbl_name);
if (len <= 0) {
errp(11, program, "tbl_name cannot be an empty string");
not_reached();
}
for (c=0; c < len; ++c) {
if (isascii(tbl_name[c]) && islower(tbl_name[c])) {
cap_tbl_name[c] = (char)toupper(tbl_name[c]);
}
}
dbg(DBG_MED, "output_mode: %s", h_mode ? ".h include file" : ".c src file");
dbg(DBG_MED, "tbl_name: <%s>", tbl_name);
dbg(DBG_MED, "cap_tbl_name: <%s>", cap_tbl_name);
/*
* enable bison internal debugging if -J is verbose enough
*/
if (json_dbg_allowed(JSON_DBG_VHIGH)) {
jparse_debug = 1; /* verbose bison debug on */
dbg(DBG_VHIGH, "jparse_debug: enabled");
} else {
jparse_debug = 0; /* verbose bison debug off */
dbg(DBG_VHIGH, "jparse_debug: disabled");
}
/*
* case: process -s arg
*/
if (string_flag_used == true) {
/* parse arg as a block of json input */
dbg(DBG_HIGH, "Calling parse_json(\"%s\", %ju, NULL, &valid_json):",
argv[argc-1], (uintmax_t)strlen(argv[argc-1]));
tree = parse_json(argv[argc-1], strlen(argv[argc-1]), NULL, &valid_json);
/*
* case: process file arg
*/
} else {
/* parse arg as a json filename */
dbg(DBG_HIGH, "Calling parse_json_file(\"%s\", &valid_json):", argv[argc-1]);
tree = parse_json_file(argv[argc-1], &valid_json);
}
/*
* firewall - JSON parser must have returned a valid JSON parse tree
*/
if (!valid_json) {
err(1, program, "invalid JSON"); /*ooo*/
not_reached();
}
if (tree == NULL) {
err(1, program, "JSON parse tree is NULL"); /*ooo*/
not_reached();
}
/*
* create an empty semantic table
*/
tbl = dyn_array_create(sizeof(struct json_sem), CHUNK, CHUNK, true);
if (tbl == NULL) {
err(12, program, "NULL dynamic array");
not_reached();
}
/*
* generate the semantic table from the parsed JSON node tree
*/
gen_sem_tbl(tree, JSON_INFINITE_DEPTH, tbl);
/*
* print a sorted semantic table as a C structure
*/
if (h_mode == true) {
print_sem_h_src(tbl, tbl_name, cap_tbl_name);
} else {
print_sem_c_src(tbl, tbl_name, cap_tbl_name);
}
/*
* free the JSON parse tree
*/
if (tree != NULL) {
json_tree_free(tree, JSON_INFINITE_DEPTH);
free(tree);
tree = NULL;
}
/*
* free the capitalised name
*/
if (cap_tbl_name != NULL) {
free(cap_tbl_name);
cap_tbl_name = NULL;
}
/*
* exit based on JSON parse success or failure
*
* NOTE: this check is not strictly needed because if the JSON is not valid
* it's a fatal error and so we'd never get here.
*/
if (!valid_json) {
exit(1); /*ooo*/
}
exit(0); /*ooo*/
}
/*
* gen_sem_tbl - update semantic table from the parsed JSON node tree
*
* given:
* tree pointer to root of a JSON parse tree
* max_depth maximum tree depth to descend, or 0 ==> infinite depth
* NOTE: Use JSON_INFINITE_DEPTH for infinite depth
* ... extra args for vcallback, required extra args:
*
* tbl dynamic array of semantic table entries
*
* NOTE: This function does nothing if tree is NULL.
*/
static void
gen_sem_tbl(struct json *tree, unsigned int max_depth, ...)
{
va_list ap; /* variable argument list */
/*
* firewall - nothing to do for a NULL tree
*/
if (tree == NULL) {
return;
}
/*
* stdarg variable argument list setup
*/
va_start(ap, max_depth);
/*
* update semantic table from the parsed JSON node tree
*/
vjson_tree_walk(tree, max_depth, 0, true, vupdate_tbl, ap);
/*
* stdarg variable argument list cleanup
*/
va_end(ap);
return;
}
/*
* vupdate_tbl - tree walk callback to update semantic table for a given JSON node
*
* If the JSON node is represented in the semantic table, update the count.
* If the JSON node is not in the semantic table, this function will add a
* new entry to the semantic table.
*
* Because the semantic table is not expected to be huge, we will perform
* a simple linear search. If the semantic table an entry for the JSON node
* is missing, we will simply append a new entry.
*
* given:
* node pointer to a JSON parser tree node to free
* depth current tree depth (0 ==> top of tree)
* ap variable argument list, required ap args:
*
* tbl dynamic array of semantic table entries
*
* NOTE: This function does not return if given NULL pointers or on error.
*/
static void
vupdate_tbl(struct json *node, unsigned int depth, va_list ap)
{
struct dyn_array *tbl = NULL; /* semantic table - array of struct json_sem */
struct json_sem *p = NULL; /* i-th entry in the semantics table */
struct json_sem new; /* new semantic table entry */
va_list ap2; /* copy of va_list ap */
intmax_t len = 0; /* number of semantic table entries */
bool match = false; /* true ==> semantic table entry match found */
intmax_t i;
/*
* firewall
*/
if (node == NULL) {
err(13, __func__, "node is NULL");
not_reached();
}
/*
* duplicate va_list ap
*/
va_copy(ap2, ap);
/*
* obtain the array of struct json_sem
*/
tbl = va_arg(ap2, struct dyn_array *);
if (tbl == NULL) {
err(14, __func__, "tbl va_arg is NULL");
not_reached();
}
len = dyn_array_tell(tbl);
/*
* scan the semantic table
*/
for (i = 0; i < len; ++i) {
/*
* note the semantic table entry we will work with
*/
p = dyn_array_addr(tbl, struct json_sem, i);
/* paranoia */
if (p == NULL) {
err(15, __func__, "semantic tbl[%jd] is NULL", i);
not_reached();
}
/*
* match tree depth
*/
if (depth != p->depth) {
continue;
}
/*
* match node type
*/
if (node->type != p->type) {
continue;
}
/*
* case: if JTYPE_MEMBER - match non-NULL non-empty JSON decoded name
*/
if (node->type == JTYPE_MEMBER && p->type == JTYPE_MEMBER && p->name != NULL) {
struct json_member const *item = &(node->item.member);
/*
* match decoded name
*/
/* paranoia */
if (item->name == NULL) {
err(16, __func__, "item->name is NULL");
not_reached();
}
if (item->name_str_len != p->name_len ||
memcmp(item->name_str, p->name, p->name_len) != 0) {
continue;
}
}
/*
* we have a match in the semantic table, increment count
*/
++p->count;
match = true;
break;
}
/*
* case: no semantic table match - add a new entry
*/
if (match == false) {
/*
* construct a new semantic table entry for this node
*/
memset(&new, 0, sizeof(struct json_sem));
new.depth = depth;
new.type = node->type;
if (node->type == JTYPE_MEMBER) {
struct json_member const *item = &(node->item.member);
new.name = item->name_str;
new.name_len = item->name_str_len;
} else {
new.name = NULL;
}
new.validate = NULL;
new.count = 1;
/*
* append new new semantic table entry to semantic table
*/
(void) dyn_array_append_value(tbl, &new);
}
/*
* stdarg variable argument list cleanup
*/
va_end(ap2);
return;
}
/*
* sem_cmp - compare two semantic table entries
*
* Produce a semantic table that is in some canonical order.
*
* NOTE: Since the table is not very large, we do not need to
* optimize lookups in this table. It is better to reverse
* sort by depth for human understanding. This will help
* put the more common nodes early in the table.
*
* given:
* a pointer to first semantic table entry to compare
* b pointer to second semantic table entry to compare
*
* returns:
* -1 a < b
* 0 a == b
* 1 a > b
*/
static int
sem_cmp(void const *a, void const *b)
{
const struct json_sem *first = NULL; /* first entry to compare */
const struct json_sem *second = NULL; /* second entry to compare */
int cmp = 0; /* byte string comparison */
/*
* firewall
*/
if (a == NULL) {
err(17, __func__, "a is NULL");
not_reached();
}
if (b == NULL) {
err(18, __func__, "b is NULL");
not_reached();
}
first = (const struct json_sem *)a;
second = (const struct json_sem *)b;
/*
* compare depth in reverse order
*/
if (first->depth < second->depth) {
return 1; /* first > second */
} else if (first->depth > second->depth) {
return -1; /* first < second */
}
/* case: depth matches */
/*
* compare numeric type of JSON node
*/
if ((int)first->type > (int)second->type) {
return 1; /* first > second */
} else if ((int)first->type < (int)second->type) {
return -1; /* first < second */
}
/* case: type matches */
/*
* compare match decoded name if not NULL
*/
if (first->name != NULL) {
if (second->name != NULL) {
cmp = strcmp(first->name, second->name);
if (cmp > 0) {
return 1; /* first > second */
} else if (cmp < 0) {
return -1; /* first < second */
}
} else {
return -1; /* first < NULL second */
}
} else if (second->name != NULL) {
return 1; /* NULL first > second */
}
/* case: name matches */
/*
* entries match
*/
return 0;
}
/*
* alloc_c_funct_name - allocate a string as a C function name
*
* Prints str as a valid C function name. Any character that is not
* alphanumeric is printed as an underscore ("_") character.
*
* If the first character of str is a digit,
* a leading x ("x") will be printed before str is processed.
*
* If the first character of str is an underscore ("_"),
* a leading x ("x") will be printed before str is processed.
* C names starting with underscore ("_") are reserved, so this
* rule prevents the function from being a reserved function.
*
* An empty string will cause x ("x") to be printed.
*
* If a C reserved word would otherwise be printed, a leading
* x ("x") will be printed before str is processed.
*
* Examples (how both prefix and str are processed):
*
* "foo" ==> "foo"
* "23209" ==> "x23209"
* "3foo" ==> "x3foo"
* "curds&whey++.*" ==> "curds_whey____"
* "_foo" ==> "x_foo"
* "++" ==> "x__"
* "" ==> "x"
* "Hello, world!\n" ==> "Hello_world__"
* "if" ==> "xif"
* "#if" ==> "x_if"
* "_Pragma" ==> "x_Pragma"
*
* If prefix is NULL, then the string formed is just str as processed.
* If prefix is non-NULL, then the string formed starts with a processed
* prefix, followed by _ (underscore), followed by str as processed.
*
* given:
* prefix != NULL ==> prefix to add (before str), along with a trailing _
* str string to process
*
* returns:
* allocated string as a C function name
*
* NOTE: This function will not return on error.
*
* NOTE: This function does NOT return NULL.
*/
static char *
alloc_c_funct_name(char const *prefix, char const *str)
{
bool prefix_is_reserved = false; /* true ==> prefix is a reserved word in C */
bool str_is_reserved = false; /* true ==> str is a reserved word in C */
size_t len = 0; /* length of allocated string */
char *ret = NULL; /* allocated string to return */
char *p = NULL; /* next character to add */
/*
* firewall
*/
if (str == NULL) {
err(19, __func__, "str is NULL");
not_reached();
}
/*
* allocated space for the string
*/
if (prefix != NULL) {
prefix_is_reserved = test_reserved(prefix);
len = strlen(prefix) + (prefix_is_reserved ? 1 : 0) + 1; /* + 1 for _ after prefix */
}
str_is_reserved = test_reserved(str);
len += strlen(str) + (str_is_reserved ? 1 : 0) + 1; /* + 1 for NUL */
ret = calloc(len + 1, sizeof(char)); /* + 1 for guard byte paranoia */
if (ret == NULL) {
errp(20, __func__, "calloc of %ju bytes failed", (uintmax_t)len);
not_reached();
}
p = ret;
/*
* if we have a prefix, process each prefix character in C, converting non-alphanumeric characters to underscore.
*/
if (prefix != NULL) {
/*
* case: prefix is a C reserved word
* case: prefix is an empty string
* case: prefix begins with a digit
* case: prefix begins with an underscore
*/
if (prefix_is_reserved == true || prefix[0] == '\0' || (isascii(prefix[0]) && isdigit(prefix[0])) || prefix[0] == '_') {
/* add x due to the cases mentioned above */
*p++ = 'x';
}
/*
* process prefix
*/
while (prefix[0] != '\0') {
if (!isascii(prefix[0]) || !isalnum(prefix[0])) {
/* convert non-C name character to underscore */
*p++ = '_';
} else {
*p++ = prefix[0];
}
++prefix;
}
/*
* append _ after prefix
*/
*p++ = '_';
}
/*
* case: str is a C reserved word
* case: str is an empty string
* case: str begins with a digit
* case: str begins with an underscore
*/
if (str_is_reserved == true || str[0] == '\0' || (isascii(str[0]) && isdigit(str[0])) || str[0] == '_') {
/* add x due to the cases mentioned above */
*p++ = 'x';
}
/*
* process each str character in C, converting non-alphanumeric characters to underscore.
*/
while (str[0] != '\0') {
if (!isascii(str[0]) || !isalnum(str[0])) {
/* convert non-C name character to underscore */
*p++ = '_';
} else {
*p++ = str[0];
}
++str;
}
*p = '\0'; /* paranoia */
/*
* return calloced string
*/
return ret;
}
/*
* append_unique_str - append string pointer to dynamic array if not already found
*
* Given a pointer to string, we search a dynamic array of pointers to strings.
* If an exact match is found (i.e. the string is already in the dynamic array),
* nothing is done other than to return false. If no match is found, the pointer
* to the string is appended to the dynamic array and we return true.
*
* given:
* tbl dynamic array of pointers to strings
* str string to search tbl and append if not already found
*
* returns:
* true str was not already in dynamic array and has now been appended
* false str was already in the dynamic array, table is unchanged
*
* NOTE: This function does not return if given NULL pointers or on other errors.
*/
static bool
append_unique_str(struct dyn_array *tbl, char *str)
{
intmax_t unique_len = 0; /* number of unique function name entries */
char *u = NULL; /* unique name pointer */
intmax_t i;
/*
* firewall
*/
if (tbl == NULL) {
err(21, __func__, "tbl is NULL");
not_reached();
}
if (str == NULL) {
err(22, __func__, "str is NULL");
not_reached();
}
/*
* search tbl for the string
*
* NOTE: We realize calling the function with unique strings will
* cause the execution time to grow as O(n^2). However the
* usual number of strings in a unique function name dynamic array
* is almost certainly small. Therefore we do not need to
* employ a more optimized dynamic array search mechanism.
*/
unique_len = dyn_array_tell(tbl);
for (i=0; i < unique_len; ++i) {
/* get next string pointer */
u = dyn_array_value(tbl, char *, i);
if (u == NULL) { /* paranoia */
err(23, __func__, "found NULL pointer in function name dynamic array element: %ju", (uintmax_t)i);
not_reached();
}
/* look for match */
if (strcmp(str, u) == 0) {
/* str found in function name dynamic array, not unique */
return false;
}
}
/*
* function name is unique, append to function name dynamic array
*/
(void) dyn_array_append_value(tbl, &str);
return true; /* pointer to string was appended */
}
/*
* print_sem_c_src - print a sorted semantic table as a .c src file
*
* given:
* tbl dynamic array of semantic table entries
* tbl_name name of the semantic table
* cap_tbl_name UPPER case copy of tbl_name
*
* NOTE: This function does not return if given NULL pointers or on error.
*/
static void
print_sem_c_src(struct dyn_array *tbl, char *tbl_name, char *cap_tbl_name)
{
struct json_sem *p = NULL; /* current semantic table to print */
char *func_name = NULL; /* function name (allocated) to print */
intmax_t len = 0; /* number of semantic table entries */
intmax_t i;
/*
* firewall
*/
if (tbl == NULL) {
err(24, __func__, "tbl is NULL");
not_reached();