Debian Codegraph @

utils/ir-ctl/toml.c

raw
1 /*
2 MIT License
3
4 Copyright (c) 2017 - 2019 CK Tan
5 https://github.com/cktan/tomlc99
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in all
15 copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
24 */
25 #define _POSIX_C_SOURCE 200809L
26 #include <stdio.h>
27 #include <setjmp.h>
28 #include <stdlib.h>
29 #include <assert.h>
30 #include <errno.h>
31 #include <stdint.h>
32 #include <ctype.h>
33 #include <string.h>
34 #include "toml.h"
35
36 #ifdef _WIN32
37 char* strndup(const char* s, size_t n)
38 {
39 size_t len = strnlen(s, n);
40 char* p = malloc(len+1);
41 if (p) {
42 memcpy(p, s, len);
43 p[len] = 0;
44 }
45 return p;
46 }
47 #endif
48
49
50 /**
51 * Convert a char in utf8 into UCS, and store it in *ret.
52 * Return #bytes consumed or -1 on failure.
53 */
54 int toml_utf8_to_ucs(const char* orig, int len, int64_t* ret)
55 {
56 const unsigned char* buf = (const unsigned char*) orig;
57 unsigned i = *buf++;
58 int64_t v;
59
60 /* 0x00000000 - 0x0000007F:
61 0xxxxxxx
62 */
63 if (0 == (i >> 7)) {
64 if (len < 1) return -1;
65 v = i;
66 return *ret = v, 1;
67 }
68 /* 0x00000080 - 0x000007FF:
69 110xxxxx 10xxxxxx
70 */
71 if (0x6 == (i >> 5)) {
72 if (len < 2) return -1;
73 v = i & 0x1f;
74 for (int j = 0; j < 1; j++) {
75 i = *buf++;
76 if (0x2 != (i >> 6)) return -1;
77 v = (v << 6) | (i & 0x3f);
78 }
79 return *ret = v, (const char*) buf - orig;
80 }
81
82 /* 0x00000800 - 0x0000FFFF:
83 1110xxxx 10xxxxxx 10xxxxxx
84 */
85 if (0xE == (i >> 4)) {
86 if (len < 3) return -1;
87 v = i & 0x0F;
88 for (int j = 0; j < 2; j++) {
89 i = *buf++;
90 if (0x2 != (i >> 6)) return -1;
91 v = (v << 6) | (i & 0x3f);
92 }
93 return *ret = v, (const char*) buf - orig;
94 }
95
96 /* 0x00010000 - 0x001FFFFF:
97 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
98 */
99 if (0x1E == (i >> 3)) {
100 if (len < 4) return -1;
101 v = i & 0x07;
102 for (int j = 0; j < 3; j++) {
103 i = *buf++;
104 if (0x2 != (i >> 6)) return -1;
105 v = (v << 6) | (i & 0x3f);
106 }
107 return *ret = v, (const char*) buf - orig;
108 }
109
110 /* 0x00200000 - 0x03FFFFFF:
111 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
112 */
113 if (0x3E == (i >> 2)) {
114 if (len < 5) return -1;
115 v = i & 0x03;
116 for (int j = 0; j < 4; j++) {
117 i = *buf++;
118 if (0x2 != (i >> 6)) return -1;
119 v = (v << 6) | (i & 0x3f);
120 }
121 return *ret = v, (const char*) buf - orig;
122 }
123
124 /* 0x04000000 - 0x7FFFFFFF:
125 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
126 */
127 if (0x7e == (i >> 1)) {
128 if (len < 6) return -1;
129 v = i & 0x01;
130 for (int j = 0; j < 5; j++) {
131 i = *buf++;
132 if (0x2 != (i >> 6)) return -1;
133 v = (v << 6) | (i & 0x3f);
134 }
135 return *ret = v, (const char*) buf - orig;
136 }
137 return -1;
138 }
139
140
141 /**
142 * Convert a UCS char to utf8 code, and return it in buf.
143 * Return #bytes used in buf to encode the char, or
144 * -1 on error.
145 */
146 int toml_ucs_to_utf8(int64_t code, char buf[6])
147 {
148 /* http://stackoverflow.com/questions/6240055/manually-converting-unicode-codepoints-into-utf-8-and-utf-16 */
149 /* The UCS code values 0xd800–0xdfff (UTF-16 surrogates) as well
150 * as 0xfffe and 0xffff (UCS noncharacters) should not appear in
151 * conforming UTF-8 streams.
152 */
153 if (0xd800 <= code && code <= 0xdfff) return -1;
154 if (0xfffe <= code && code <= 0xffff) return -1;
155
156 /* 0x00000000 - 0x0000007F:
157 0xxxxxxx
158 */
159 if (code < 0) return -1;
160 if (code <= 0x7F) {
161 buf[0] = (unsigned char) code;
162 return 1;
163 }
164
165 /* 0x00000080 - 0x000007FF:
166 110xxxxx 10xxxxxx
167 */
168 if (code <= 0x000007FF) {
169 buf[0] = 0xc0 | (code >> 6);
170 buf[1] = 0x80 | (code & 0x3f);
171 return 2;
172 }
173
174 /* 0x00000800 - 0x0000FFFF:
175 1110xxxx 10xxxxxx 10xxxxxx
176 */
177 if (code <= 0x0000FFFF) {
178 buf[0] = 0xe0 | (code >> 12);
179 buf[1] = 0x80 | ((code >> 6) & 0x3f);
180 buf[2] = 0x80 | (code & 0x3f);
181 return 3;
182 }
183
184 /* 0x00010000 - 0x001FFFFF:
185 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
186 */
187 if (code <= 0x001FFFFF) {
188 buf[0] = 0xf0 | (code >> 18);
189 buf[1] = 0x80 | ((code >> 12) & 0x3f);
190 buf[2] = 0x80 | ((code >> 6) & 0x3f);
191 buf[3] = 0x80 | (code & 0x3f);
192 return 4;
193 }
194
195 /* 0x00200000 - 0x03FFFFFF:
196 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
197 */
198 if (code <= 0x03FFFFFF) {
199 buf[0] = 0xf8 | (code >> 24);
200 buf[1] = 0x80 | ((code >> 18) & 0x3f);
201 buf[2] = 0x80 | ((code >> 12) & 0x3f);
202 buf[3] = 0x80 | ((code >> 6) & 0x3f);
203 buf[4] = 0x80 | (code & 0x3f);
204 return 5;
205 }
206
207 /* 0x04000000 - 0x7FFFFFFF:
208 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
209 */
210 if (code <= 0x7FFFFFFF) {
211 buf[0] = 0xfc | (code >> 30);
212 buf[1] = 0x80 | ((code >> 24) & 0x3f);
213 buf[2] = 0x80 | ((code >> 18) & 0x3f);
214 buf[3] = 0x80 | ((code >> 12) & 0x3f);
215 buf[4] = 0x80 | ((code >> 6) & 0x3f);
216 buf[5] = 0x80 | (code & 0x3f);
217 return 6;
218 }
219
220 return -1;
221 }
222
223 /*
224 * TOML has 3 data structures: value, array, table.
225 * Each of them can have identification key.
226 */
227 typedef struct toml_keyval_t toml_keyval_t;
228 struct toml_keyval_t {
229 const char* key; /* key to this value */
230 const char* val; /* the raw value */
231 };
232
233
234 struct toml_array_t {
235 const char* key; /* key to this array */
236 int kind; /* element kind: 'v'alue, 'a'rray, or 't'able */
237 int type; /* for value kind: 'i'nt, 'd'ouble, 'b'ool, 's'tring, 't'ime, 'D'ate, 'T'imestamp */
238
239 int nelem; /* number of elements */
240 union {
241 char** val;
242 toml_array_t** arr;
243 toml_table_t** tab;
244 } u;
245 };
246
247
248 struct toml_table_t {
249 const char* key; /* key to this table */
250 int implicit; /* table was created implicitly */
251
252 /* key-values in the table */
253 int nkval;
254 toml_keyval_t** kval;
255
256 /* arrays in the table */
257 int narr;
258 toml_array_t** arr;
259
260 /* tables in the table */
261 int ntab;
262 toml_table_t** tab;
263 };
264
265
266 static inline void xfree(const void* x) { if (x) free((void*)x); }
267
268
269 enum tokentype_t {
270 INVALID,
271 DOT,
272 COMMA,
273 EQUAL,
274 LBRACE,
275 RBRACE,
276 NEWLINE,
277 LBRACKET,
278 RBRACKET,
279 STRING,
280 };
281 typedef enum tokentype_t tokentype_t;
282
283 typedef struct token_t token_t;
284 struct token_t {
285 tokentype_t tok;
286 int lineno;
287 char* ptr; /* points into context->start */
288 int len;
289 int eof;
290 };
291
292
293 typedef struct context_t context_t;
294 struct context_t {
295 char* start;
296 char* stop;
297 char* errbuf;
298 int errbufsz;
299 jmp_buf jmp;
300
301 token_t tok;
302 toml_table_t* root;
303 toml_table_t* curtab;
304
305 struct {
306 int top;
307 char* key[10];
308 token_t tok[10];
309 } tpath;
310
311 };
312
313 #define STRINGIFY(x) #x
314 #define TOSTRING(x) STRINGIFY(x)
315 #define FLINE __FILE__ ":" TOSTRING(__LINE__)
316
317 static tokentype_t next_token(context_t* ctx, int dotisspecial);
318
319 /* error routines. All these functions longjmp to ctx->jmp */
320 static int e_outofmemory(context_t* ctx, const char* fline)
321 {
322 snprintf(ctx->errbuf, ctx->errbufsz, "ERROR: out of memory (%s)", fline);
323 longjmp(ctx->jmp, 1);
324 return -1;
325 }
326
327
328 static int e_internal_error(context_t* ctx, const char* fline)
329 {
330 snprintf(ctx->errbuf, ctx->errbufsz, "internal error (%s)", fline);
331 longjmp(ctx->jmp, 1);
332 return -1;
333 }
334
335 static int e_syntax_error(context_t* ctx, int lineno, const char* msg)
336 {
337 snprintf(ctx->errbuf, ctx->errbufsz, "line %d: %s", lineno, msg);
338 longjmp(ctx->jmp, 1);
339 return -1;
340 }
341
342 static int e_bad_key_error(context_t* ctx, int lineno)
343 {
344 snprintf(ctx->errbuf, ctx->errbufsz, "line %d: bad key", lineno);
345 longjmp(ctx->jmp, 1);
346 return -1;
347 }
348
349 /*
350 static int e_noimpl(context_t* ctx, const char* feature)
351 {
352 snprintf(ctx->errbuf, ctx->errbufsz, "not implemented: %s", feature);
353 longjmp(ctx->jmp, 1);
354 return -1;
355 }
356 */
357
358 static int e_key_exists_error(context_t* ctx, token_t keytok)
359 {
360 char buf[100];
361 int i;
362 for (i = 0; i < keytok.len && i < (int)sizeof(buf) - 1; i++) {
363 buf[i] = keytok.ptr[i];
364 }
365 buf[i] = 0;
366
367 snprintf(ctx->errbuf, ctx->errbufsz,
368 "line %d: key %s exists", keytok.lineno, buf);
369 longjmp(ctx->jmp, 1);
370 return -1;
371 }
372
373
374
375 /*
376 * Convert src to raw unescaped utf-8 string.
377 * Returns NULL if error with errmsg in errbuf.
378 */
379 static char* normalize_string(const char* src, int srclen,
380 int kill_line_ending_backslash,
381 char* errbuf, int errbufsz)
382 {
383 char* dst = 0; /* will write to dst[] and return it */
384 int max = 0; /* max size of dst[] */
385 int off = 0; /* cur offset in dst[] */
386 const char* sp = src;
387 const char* sq = src + srclen;
388 int ch;
389
390 /* scan forward on src */
391 for (;;) {
392 if (off >= max - 10) { /* have some slack for misc stuff */
393 char* x = realloc(dst, max += 100);
394 if (!x) {
395 xfree(dst);
396 snprintf(errbuf, errbufsz, "out of memory");
397 return 0;
398 }
399 dst = x;
400 }
401
402 /* finished? */
403 if (sp >= sq) break;
404
405 ch = *sp++;
406 if (ch != '\\') {
407 // a plain copy suffice
408 dst[off++] = ch;
409 continue;
410 }
411
412 /* ch was backslash. we expect the escape char. */
413 if (sp >= sq) {
414 snprintf(errbuf, errbufsz, "last backslash is invalid");
415 free(dst);
416 return 0;
417 }
418
419 /* if we want to kill line-ending-backslash ... */
420 if (kill_line_ending_backslash) {
421 /* if this is a newline immediately following the backslash ... */
422 if (*sp == '\n' || (*sp == '\r' && sp[1] == '\n')) {
423 /* skip all the following whitespaces */
424 sp += strspn(sp, " \t\r\n");
425 continue;
426 }
427 }
428
429 /* get the escaped char */
430 ch = *sp++;
431 switch (ch) {
432 case 'u': case 'U':
433 {
434 int64_t ucs = 0;
435 int nhex = (ch == 'u' ? 4 : 8);
436 for (int i = 0; i < nhex; i++) {
437 if (sp >= sq) {
438 snprintf(errbuf, errbufsz, "\\%c expects %d hex chars", ch, nhex);
439 free(dst);
440 return 0;
441 }
442 ch = *sp++;
443 int v = ('0' <= ch && ch <= '9')
444 ? ch - '0'
445 : (('A' <= ch && ch <= 'F') ? ch - 'A' + 10 : -1);
446 if (-1 == v) {
447 snprintf(errbuf, errbufsz, "invalid hex chars for \\u or \\U");
448 free(dst);
449 return 0;
450 }
451 ucs = ucs * 16 + v;
452 }
453 int n = toml_ucs_to_utf8(ucs, &dst[off]);
454 if (-1 == n) {
455 snprintf(errbuf, errbufsz, "illegal ucs code in \\u or \\U");
456 free(dst);
457 return 0;
458 }
459 off += n;
460 }
461 continue;
462
463 case 'b': ch = '\b'; break;
464 case 't': ch = '\t'; break;
465 case 'n': ch = '\n'; break;
466 case 'f': ch = '\f'; break;
467 case 'r': ch = '\r'; break;
468 case '"': ch = '"'; break;
469 case '\\': ch = '\\'; break;
470 default:
471 snprintf(errbuf, errbufsz, "illegal escape char \\%c", ch);
472 free(dst);
473 return 0;
474 }
475
476 dst[off++] = ch;
477 }
478
479 // Cap with NUL and return it.
480 dst[off++] = 0;
481 return dst;
482 }
483
484
485 /* Normalize a key. Convert all special chars to raw unescaped utf-8 chars. */
486 static char* normalize_key(context_t* ctx, token_t strtok)
487 {
488 const char* sp = strtok.ptr;
489 const char* sq = strtok.ptr + strtok.len;
490 int lineno = strtok.lineno;
491 char* ret;
492 int ch = *sp;
493 char ebuf[80];
494
495 /* handle quoted string */
496 if (ch == '\'' || ch == '\"') {
497 /* if ''' or """, take 3 chars off front and back. Else, take 1 char off. */
498 if (sp[1] == ch && sp[2] == ch)
499 sp += 3, sq -= 3;
500 else
501 sp++, sq--;
502
503 if (ch == '\'') {
504 /* for single quote, take it verbatim. */
505 if (! (ret = strndup(sp, sq - sp))) {
506 e_outofmemory(ctx, FLINE);
507 return 0; /* not reached */
508 }
509 } else {
510 /* for double quote, we need to normalize */
511 ret = normalize_string(sp, sq - sp, 0, ebuf, sizeof(ebuf));
512 if (!ret) {
513 snprintf(ctx->errbuf, ctx->errbufsz, "line %d: %s", lineno, ebuf);
514 longjmp(ctx->jmp, 1);
515 }
516 }
517
518 /* newlines are not allowed in keys */
519 if (strchr(ret, '\n')) {
520 free(ret);
521 e_bad_key_error(ctx, lineno);
522 return 0; /* not reached */
523 }
524 return ret;
525 }
526
527 /* for bare-key allow only this regex: [A-Za-z0-9_-]+ */
528 const char* xp;
529 for (xp = sp; xp != sq; xp++) {
530 int k = *xp;
531 if (isalnum(k)) continue;
532 if (k == '_' || k == '-') continue;
533 e_bad_key_error(ctx, lineno);
534 return 0; /* not reached */
535 }
536
537 /* dup and return it */
538 if (! (ret = strndup(sp, sq - sp))) {
539 e_outofmemory(ctx, FLINE);
540 return 0; /* not reached */
541 }
542 return ret;
543 }
544
545
546 /*
547 * Look up key in tab. Return 0 if not found, or
548 * 'v'alue, 'a'rray or 't'able depending on the element.
549 */
550 static int check_key(toml_table_t* tab, const char* key,
551 toml_keyval_t** ret_val,
552 toml_array_t** ret_arr,
553 toml_table_t** ret_tab)
554 {
555 int i;
556 void* dummy;
557
558 if (!ret_tab) ret_tab = (toml_table_t**) &dummy;
559 if (!ret_arr) ret_arr = (toml_array_t**) &dummy;
560 if (!ret_val) ret_val = (toml_keyval_t**) &dummy;
561
562 *ret_tab = 0; *ret_arr = 0; *ret_val = 0;
563
564 for (i = 0; i < tab->nkval; i++) {
565 if (0 == strcmp(key, tab->kval[i]->key)) {
566 *ret_val = tab->kval[i];
567 return 'v';
568 }
569 }
570 for (i = 0; i < tab->narr; i++) {
571 if (0 == strcmp(key, tab->arr[i]->key)) {
572 *ret_arr = tab->arr[i];
573 return 'a';
574 }
575 }
576 for (i = 0; i < tab->ntab; i++) {
577 if (0 == strcmp(key, tab->tab[i]->key)) {
578 *ret_tab = tab->tab[i];
579 return 't';
580 }
581 }
582 return 0;
583 }
584
585 /* Create a keyval in the table.
586 */
587 static toml_keyval_t* create_keyval_in_table(context_t* ctx, toml_table_t* tab, token_t keytok)
588 {
589 /* first, normalize the key to be used for lookup.
590 * remember to free it if we error out.
591 */
592 char* newkey = normalize_key(ctx, keytok);
593
594 /* if key exists: error out. */
595 toml_keyval_t* dest = 0;
596 if (check_key(tab, newkey, 0, 0, 0)) {
597 free(newkey);
598 e_key_exists_error(ctx, keytok);
599 return 0; /* not reached */
600 }
601
602 /* make a new entry */
603 int n = tab->nkval;
604 toml_keyval_t** base;
605 if (0 == (base = (toml_keyval_t**) realloc(tab->kval, (n+1) * sizeof(*base)))) {
606 free(newkey);
607 e_outofmemory(ctx, FLINE);
608 return 0; /* not reached */
609 }
610 tab->kval = base;
611
612 if (0 == (base[n] = (toml_keyval_t*) calloc(1, sizeof(*base[n])))) {
613 free(newkey);
614 e_outofmemory(ctx, FLINE);
615 return 0; /* not reached */
616 }
617 dest = tab->kval[tab->nkval++];
618
619 /* save the key in the new value struct */
620 dest->key = newkey;
621 return dest;
622 }
623
624
625 /* Create a table in the table.
626 */
627 static toml_table_t* create_keytable_in_table(context_t* ctx, toml_table_t* tab, token_t keytok)
628 {
629 /* first, normalize the key to be used for lookup.
630 * remember to free it if we error out.
631 */
632 char* newkey = normalize_key(ctx, keytok);
633
634 /* if key exists: error out */
635 toml_table_t* dest = 0;
636 if (check_key(tab, newkey, 0, 0, &dest)) {
637 free(newkey); /* don't need this anymore */
638
639 /* special case: if table exists, but was created implicitly ... */
640 if (dest && dest->implicit) {
641 /* we make it explicit now, and simply return it. */
642 dest->implicit = 0;
643 return dest;
644 }
645 e_key_exists_error(ctx, keytok);
646 return 0; /* not reached */
647 }
648
649 /* create a new table entry */
650 int n = tab->ntab;
651 toml_table_t** base;
652 if (0 == (base = (toml_table_t**) realloc(tab->tab, (n+1) * sizeof(*base)))) {
653 free(newkey);
654 e_outofmemory(ctx, FLINE);
655 return 0; /* not reached */
656 }
657 tab->tab = base;
658
659 if (0 == (base[n] = (toml_table_t*) calloc(1, sizeof(*base[n])))) {
660 free(newkey);
661 e_outofmemory(ctx, FLINE);
662 return 0; /* not reached */
663 }
664 dest = tab->tab[tab->ntab++];
665
666 /* save the key in the new table struct */
667 dest->key = newkey;
668 return dest;
669 }
670
671
672 /* Create an array in the table.
673 */
674 static toml_array_t* create_keyarray_in_table(context_t* ctx,
675 toml_table_t* tab,
676 token_t keytok,
677 int skip_if_exist)
678 {
679 /* first, normalize the key to be used for lookup.
680 * remember to free it if we error out.
681 */
682 char* newkey = normalize_key(ctx, keytok);
683
684 /* if key exists: error out */
685 toml_array_t* dest = 0;
686 if (check_key(tab, newkey, 0, &dest, 0)) {
687 free(newkey); /* don't need this anymore */
688
689 /* special case skip if exists? */
690 if (skip_if_exist) return dest;
691
692 e_key_exists_error(ctx, keytok);
693 return 0; /* not reached */
694 }
695
696 /* make a new array entry */
697 int n = tab->narr;
698 toml_array_t** base;
699 if (0 == (base = (toml_array_t**) realloc(tab->arr, (n+1) * sizeof(*base)))) {
700 free(newkey);
701 e_outofmemory(ctx, FLINE);
702 return 0; /* not reached */
703 }
704 tab->arr = base;
705
706 if (0 == (base[n] = (toml_array_t*) calloc(1, sizeof(*base[n])))) {
707 free(newkey);
708 e_outofmemory(ctx, FLINE);
709 return 0; /* not reached */
710 }
711 dest = tab->arr[tab->narr++];
712
713 /* save the key in the new array struct */
714 dest->key = newkey;
715 return dest;
716 }
717
718 /* Create an array in an array
719 */
720 static toml_array_t* create_array_in_array(context_t* ctx,
721 toml_array_t* parent)
722 {
723 int n = parent->nelem;
724 toml_array_t** base;
725 if (0 == (base = (toml_array_t**) realloc(parent->u.arr, (n+1) * sizeof(*base)))) {
726 e_outofmemory(ctx, FLINE);
727 return 0; /* not reached */
728 }
729 parent->u.arr = base;
730
731 if (0 == (base[n] = (toml_array_t*) calloc(1, sizeof(*base[n])))) {
732 e_outofmemory(ctx, FLINE);
733 return 0; /* not reached */
734 }
735
736 return parent->u.arr[parent->nelem++];
737 }
738
739 /* Create a table in an array
740 */
741 static toml_table_t* create_table_in_array(context_t* ctx,
742 toml_array_t* parent)
743 {
744 int n = parent->nelem;
745 toml_table_t** base;
746 if (0 == (base = (toml_table_t**) realloc(parent->u.tab, (n+1) * sizeof(*base)))) {
747 e_outofmemory(ctx, FLINE);
748 return 0; /* not reached */
749 }
750 parent->u.tab = base;
751
752 if (0 == (base[n] = (toml_table_t*) calloc(1, sizeof(*base[n])))) {
753 e_outofmemory(ctx, FLINE);
754 return 0; /* not reached */
755 }
756
757 return parent->u.tab[parent->nelem++];
758 }
759
760
761 #define SKIP_NEWLINES(ctx) while (ctx->tok.tok == NEWLINE) next_token(ctx, 0)
762 #define EAT_TOKEN(ctx, typ) \
763 if ((ctx)->tok.tok != typ) e_internal_error(ctx, FLINE); else next_token(ctx, 0)
764
765
766 static void parse_keyval(context_t* ctx, toml_table_t* tab);
767
768
769 /* We are at '{ ... }'.
770 * Parse the table.
771 */
772 static void parse_table(context_t* ctx, toml_table_t* tab)
773 {
774 EAT_TOKEN(ctx, LBRACE);
775
776 for (;;) {
777 if (ctx->tok.tok == NEWLINE) {
778 e_syntax_error(ctx, ctx->tok.lineno, "newline not allowed in inline table");
779 return; /* not reached */
780 }
781
782 /* until } */
783 if (ctx->tok.tok == RBRACE) break;
784
785 if (ctx->tok.tok != STRING) {
786 e_syntax_error(ctx, ctx->tok.lineno, "syntax error");
787 return; /* not reached */
788 }
789 parse_keyval(ctx, tab);
790
791 if (ctx->tok.tok == NEWLINE) {
792 e_syntax_error(ctx, ctx->tok.lineno, "newline not allowed in inline table");
793 return; /* not reached */
794 }
795
796 /* on comma, continue to scan for next keyval */
797 if (ctx->tok.tok == COMMA) {
798 EAT_TOKEN(ctx, COMMA);
799 continue;
800 }
801 break;
802 }
803
804 if (ctx->tok.tok != RBRACE) {
805 e_syntax_error(ctx, ctx->tok.lineno, "syntax error");
806 return; /* not reached */
807 }
808
809 EAT_TOKEN(ctx, RBRACE);
810 }
811
812 static int valtype(const char* val)
813 {
814 toml_timestamp_t ts;
815 if (*val == '\'' || *val == '"') return 's';
816 if (0 == toml_rtob(val, 0)) return 'b';
817 if (0 == toml_rtoi(val, 0)) return 'i';
818 if (0 == toml_rtod(val, 0)) return 'd';
819 if (0 == toml_rtots(val, &ts)) {
820 if (ts.year && ts.hour) return 'T'; /* timestamp */
821 if (ts.year) return 'D'; /* date */
822 return 't'; /* time */
823 }
824 return 'u'; /* unknown */
825 }
826
827
828 /* We are at '[...]' */
829 static void parse_array(context_t* ctx, toml_array_t* arr)
830 {
831 EAT_TOKEN(ctx, LBRACKET);
832
833 for (;;) {
834 SKIP_NEWLINES(ctx);
835
836 /* until ] */
837 if (ctx->tok.tok == RBRACKET) break;
838
839 switch (ctx->tok.tok) {
840 case STRING:
841 {
842 char* val = ctx->tok.ptr;
843 int vlen = ctx->tok.len;
844
845 /* set array kind if this will be the first entry */
846 if (arr->kind == 0) arr->kind = 'v';
847 /* check array kind */
848 if (arr->kind != 'v') {
849 e_syntax_error(ctx, ctx->tok.lineno,
850 "a string array can only contain strings");
851 return; /* not reached */
852 }
853
854 /* make a new value in array */
855 char** tmp = (char**) realloc(arr->u.val, (arr->nelem+1) * sizeof(*tmp));
856 if (!tmp) {
857 e_outofmemory(ctx, FLINE);
858 return; /* not reached */
859 }
860 arr->u.val = tmp;
861 if (! (val = strndup(val, vlen))) {
862 e_outofmemory(ctx, FLINE);
863 return; /* not reached */
864 }
865 arr->u.val[arr->nelem++] = val;
866
867 /* set array type if this is the first entry, or check that the types matched. */
868 if (arr->nelem == 1)
869 arr->type = valtype(arr->u.val[0]);
870 else if (arr->type != valtype(val)) {
871 e_syntax_error(ctx, ctx->tok.lineno, "array type mismatch");
872 return; /* not reached */
873 }
874
875 EAT_TOKEN(ctx, STRING);
876 break;
877 }
878
879 case LBRACKET:
880 { /* [ [array], [array] ... ] */
881 /* set the array kind if this will be the first entry */
882 if (arr->kind == 0) arr->kind = 'a';
883 /* check array kind */
884 if (arr->kind != 'a') {
885 e_syntax_error(ctx, ctx->tok.lineno, "array type mismatch");
886 return; /* not reached */
887 }
888 parse_array(ctx, create_array_in_array(ctx, arr));
889 break;
890 }
891
892 case LBRACE:
893 { /* [ {table}, {table} ... ] */
894 /* set the array kind if this will be the first entry */
895 if (arr->kind == 0) arr->kind = 't';
896 /* check array kind */
897 if (arr->kind != 't') {
898 e_syntax_error(ctx, ctx->tok.lineno, "array type mismatch");
899 return; /* not reached */
900 }
901 parse_table(ctx, create_table_in_array(ctx, arr));
902 break;
903 }
904
905 default:
906 e_syntax_error(ctx, ctx->tok.lineno, "syntax error");
907 return; /* not reached */
908 }
909
910 SKIP_NEWLINES(ctx);
911
912 /* on comma, continue to scan for next element */
913 if (ctx->tok.tok == COMMA) {
914 EAT_TOKEN(ctx, COMMA);
915 continue;
916 }
917 break;
918 }
919
920 if (ctx->tok.tok != RBRACKET) {
921 e_syntax_error(ctx, ctx->tok.lineno, "syntax error");
922 return; /* not reached */
923 }
924
925 EAT_TOKEN(ctx, RBRACKET);
926 }
927
928
929
930 /* handle lines like these:
931 key = "value"
932 key = [ array ]
933 key = { table }
934 */
935 static void parse_keyval(context_t* ctx, toml_table_t* tab)
936 {
937 if (ctx->tok.tok != STRING) {
938 e_internal_error(ctx, FLINE);
939 return; /* not reached */
940 }
941
942 token_t key = ctx->tok;
943
944 EAT_TOKEN(ctx, STRING);
945 if (ctx->tok.tok != EQUAL) {
946 e_syntax_error(ctx, ctx->tok.lineno, "missing =");
947 return; /* not reached */
948 }
949
950 EAT_TOKEN(ctx, EQUAL);
951
952 switch (ctx->tok.tok) {
953 case STRING:
954 { /* key = "value" */
955 toml_keyval_t* keyval = create_keyval_in_table(ctx, tab, key);
956 token_t val = ctx->tok;
957 assert(keyval->val == 0);
958 keyval->val = strndup(val.ptr, val.len);
959 if (! keyval->val) {
960 e_outofmemory(ctx, FLINE);
961 return; /* not reached */
962 }
963
964 EAT_TOKEN(ctx, STRING);
965
966 return;
967 }
968
969 case LBRACKET:
970 { /* key = [ array ] */
971 toml_array_t* arr = create_keyarray_in_table(ctx, tab, key, 0);
972 parse_array(ctx, arr);
973 return;
974 }
975
976 case LBRACE:
977 { /* key = { table } */
978 toml_table_t* nxttab = create_keytable_in_table(ctx, tab, key);
979 parse_table(ctx, nxttab);
980 return;
981 }
982
983 default:
984 e_syntax_error(ctx, ctx->tok.lineno, "syntax error");
985 return; /* not reached */
986 }
987 }
988
989
990 typedef struct tabpath_t tabpath_t;
991 struct tabpath_t {
992 int cnt;
993 token_t key[10];
994 };
995
996 /* at [x.y.z] or [[x.y.z]]
997 * Scan forward and fill tabpath until it enters ] or ]]
998 * There will be at least one entry on return.
999 */
1000 static void fill_tabpath(context_t* ctx)
1001 {
1002 int lineno = ctx->tok.lineno;
1003 int i;
1004
1005 /* clear tpath */
1006 for (i = 0; i < ctx->tpath.top; i++) {
1007 char** p = &ctx->tpath.key[i];
1008 xfree(*p);
1009 *p = 0;
1010 }
1011 ctx->tpath.top = 0;
1012
1013 for (;;) {
1014 if (ctx->tpath.top >= 10) {
1015 e_syntax_error(ctx, lineno, "table path is too deep; max allowed is 10.");
1016 return; /* not reached */
1017 }
1018
1019 if (ctx->tok.tok != STRING) {
1020 e_syntax_error(ctx, lineno, "invalid or missing key");
1021 return; /* not reached */
1022 }
1023
1024 ctx->tpath.tok[ctx->tpath.top] = ctx->tok;
1025 ctx->tpath.key[ctx->tpath.top] = normalize_key(ctx, ctx->tok);
1026 ctx->tpath.top++;
1027
1028 next_token(ctx, 1);
1029
1030 if (ctx->tok.tok == RBRACKET) break;
1031
1032 if (ctx->tok.tok != DOT) {
1033 e_syntax_error(ctx, lineno, "invalid key");
1034 return; /* not reached */
1035 }
1036
1037 next_token(ctx, 1);
1038 }
1039
1040 if (ctx->tpath.top <= 0) {
1041 e_syntax_error(ctx, lineno, "empty table selector");
1042 return; /* not reached */
1043 }
1044 }
1045
1046
1047 /* Walk tabpath from the root, and create new tables on the way.
1048 * Sets ctx->curtab to the final table.
1049 */
1050 static void walk_tabpath(context_t* ctx)
1051 {
1052 /* start from root */
1053 toml_table_t* curtab = ctx->root;
1054
1055 for (int i = 0; i < ctx->tpath.top; i++) {
1056 const char* key = ctx->tpath.key[i];
1057
1058 toml_keyval_t* nextval = 0;
1059 toml_array_t* nextarr = 0;
1060 toml_table_t* nexttab = 0;
1061 switch (check_key(curtab, key, &nextval, &nextarr, &nexttab)) {
1062 case 't':
1063 /* found a table. nexttab is where we will go next. */
1064 break;
1065
1066 case 'a':
1067 /* found an array. nexttab is the last table in the array. */
1068 if (nextarr->kind != 't') {
1069 e_internal_error(ctx, FLINE);
1070 return; /* not reached */
1071 }
1072 if (nextarr->nelem == 0) {
1073 e_internal_error(ctx, FLINE);
1074 return; /* not reached */
1075 }
1076 nexttab = nextarr->u.tab[nextarr->nelem-1];
1077 break;
1078
1079 case 'v':
1080 e_key_exists_error(ctx, ctx->tpath.tok[i]);
1081 return; /* not reached */
1082
1083 default:
1084 { /* Not found. Let's create an implicit table. */
1085 int n = curtab->ntab;
1086 toml_table_t** base = (toml_table_t**) realloc(curtab->tab, (n+1) * sizeof(*base));
1087 if (0 == base) {
1088 e_outofmemory(ctx, FLINE);
1089 return; /* not reached */
1090 }
1091 curtab->tab = base;
1092
1093 if (0 == (base[n] = (toml_table_t*) calloc(1, sizeof(*base[n])))) {
1094 e_outofmemory(ctx, FLINE);
1095 return; /* not reached */
1096 }
1097
1098 if (0 == (base[n]->key = strdup(key))) {
1099 e_outofmemory(ctx, FLINE);
1100 return; /* not reached */
1101 }
1102
1103 nexttab = curtab->tab[curtab->ntab++];
1104
1105 /* tabs created by walk_tabpath are considered implicit */
1106 nexttab->implicit = 1;
1107 }
1108 break;
1109 }
1110
1111 /* switch to next tab */
1112 curtab = nexttab;
1113 }
1114
1115 /* save it */
1116 ctx->curtab = curtab;
1117 }
1118
1119
1120 /* handle lines like [x.y.z] or [[x.y.z]] */
1121 static void parse_select(context_t* ctx)
1122 {
1123 assert(ctx->tok.tok == LBRACKET);
1124
1125 /* true if [[ */
1126 int llb = (ctx->tok.ptr + 1 < ctx->stop && ctx->tok.ptr[1] == '[');
1127 /* need to detect '[[' on our own because next_token() will skip whitespace,
1128 and '[ [' would be taken as '[[', which is wrong. */
1129
1130 /* eat [ or [[ */
1131 next_token(ctx, 1 /* DOT IS SPECIAL */);
1132 if (llb) {
1133 assert(ctx->tok.tok == LBRACKET);
1134 next_token(ctx, 1 /* DOT IS SPECIAL */);
1135 }
1136
1137 fill_tabpath(ctx);
1138
1139 /* For [x.y.z] or [[x.y.z]], remove z from tpath.
1140 */
1141 token_t z = ctx->tpath.tok[ctx->tpath.top-1];
1142 free(ctx->tpath.key[ctx->tpath.top-1]);
1143 ctx->tpath.top--;
1144
1145 /* set up ctx->curtab */
1146 walk_tabpath(ctx);
1147
1148 if (! llb) {
1149 /* [x.y.z] -> create z = {} in x.y */
1150 ctx->curtab = create_keytable_in_table(ctx, ctx->curtab, z);
1151 } else {
1152 /* [[x.y.z]] -> create z = [] in x.y */
1153 toml_array_t* arr = create_keyarray_in_table(ctx, ctx->curtab, z,
1154 1 /*skip_if_exist*/);
1155 if (!arr) {
1156 e_syntax_error(ctx, z.lineno, "key exists");
1157 return;
1158 }
1159 if (arr->kind == 0) arr->kind = 't';
1160 if (arr->kind != 't') {
1161 e_syntax_error(ctx, z.lineno, "array mismatch");
1162 return; /* not reached */
1163 }
1164
1165 /* add to z[] */
1166 toml_table_t* dest;
1167 {
1168 int n = arr->nelem;
1169 toml_table_t** base = realloc(arr->u.tab, (n+1) * sizeof(*base));
1170 if (0 == base) {
1171 e_outofmemory(ctx, FLINE);
1172 return; /* not reached */
1173 }
1174 arr->u.tab = base;
1175
1176 if (0 == (base[n] = calloc(1, sizeof(*base[n])))) {
1177 e_outofmemory(ctx, FLINE);
1178 return; /* not reached */
1179 }
1180
1181 if (0 == (base[n]->key = strdup("__anon__"))) {
1182 e_outofmemory(ctx, FLINE);
1183 return; /* not reached */
1184 }
1185
1186 dest = arr->u.tab[arr->nelem++];
1187 }
1188
1189 ctx->curtab = dest;
1190 }
1191
1192 if (ctx->tok.tok != RBRACKET) {
1193 e_syntax_error(ctx, ctx->tok.lineno, "expects ]");
1194 return; /* not reached */
1195 }
1196 if (llb) {
1197 if (! (ctx->tok.ptr + 1 < ctx->stop && ctx->tok.ptr[1] == ']')) {
1198 e_syntax_error(ctx, ctx->tok.lineno, "expects ]]");
1199 return; /* not reached */
1200 }
1201 EAT_TOKEN(ctx, RBRACKET);
1202 }
1203 EAT_TOKEN(ctx, RBRACKET);
1204
1205 if (ctx->tok.tok != NEWLINE) {
1206 e_syntax_error(ctx, ctx->tok.lineno, "extra chars after ] or ]]");
1207 return; /* not reached */
1208 }
1209 }
1210
1211
1212
1213
1214 toml_table_t* toml_parse(char* conf,
1215 char* errbuf,
1216 int errbufsz)
1217 {
1218 context_t ctx;
1219
1220 // clear errbuf
1221 if (errbufsz <= 0) errbufsz = 0;
1222 if (errbufsz > 0) errbuf[0] = 0;
1223
1224 // init context
1225 memset(&ctx, 0, sizeof(ctx));
1226 ctx.start = conf;
1227 ctx.stop = ctx.start + strlen(conf);
1228 ctx.errbuf = errbuf;
1229 ctx.errbufsz = errbufsz;
1230
1231 // start with an artificial newline of length 0
1232 ctx.tok.tok = NEWLINE;
1233 ctx.tok.lineno = 1;
1234 ctx.tok.ptr = conf;
1235 ctx.tok.len = 0;
1236
1237 // make a root table
1238 if (0 == (ctx.root = calloc(1, sizeof(*ctx.root)))) {
1239 /* do not call outofmemory() here... setjmp not done yet */
1240 snprintf(ctx.errbuf, ctx.errbufsz, "ERROR: out of memory (%s)", FLINE);
1241 return 0;
1242 }
1243
1244 // set root as default table
1245 ctx.curtab = ctx.root;
1246
1247 if (0 != setjmp(ctx.jmp)) {
1248 // Got here from a long_jmp. Something bad has happened.
1249 // Free resources and return error.
1250 for (int i = 0; i < ctx.tpath.top; i++) xfree(ctx.tpath.key[i]);
1251 toml_free(ctx.root);
1252 return 0;
1253 }
1254
1255 /* Scan forward until EOF */
1256 for (token_t tok = ctx.tok; ! tok.eof ; tok = ctx.tok) {
1257 switch (tok.tok) {
1258
1259 case NEWLINE:
1260 next_token(&ctx, 1);
1261 break;
1262
1263 case STRING:
1264 parse_keyval(&ctx, ctx.curtab);
1265 if (ctx.tok.tok != NEWLINE) {
1266 e_syntax_error(&ctx, ctx.tok.lineno, "extra chars after value");
1267 return 0; /* not reached */
1268 }
1269
1270 EAT_TOKEN(&ctx, NEWLINE);
1271 break;
1272
1273 case LBRACKET: /* [ x.y.z ] or [[ x.y.z ]] */
1274 parse_select(&ctx);
1275 break;
1276
1277 default:
1278 snprintf(ctx.errbuf, ctx.errbufsz, "line %d: syntax error", tok.lineno);
1279 longjmp(ctx.jmp, 1);
1280 }
1281 }
1282
1283 /* success */
1284 for (int i = 0; i < ctx.tpath.top; i++) xfree(ctx.tpath.key[i]);
1285 return ctx.root;
1286 }
1287
1288
1289 toml_table_t* toml_parse_file(FILE* fp,
1290 char* errbuf,
1291 int errbufsz)
1292 {
1293 int bufsz = 0;
1294 char* buf = 0;
1295 int off = 0;
1296
1297 /* prime the buf[] */
1298 bufsz = 1000;
1299 if (! (buf = malloc(bufsz + 1))) {
1300 snprintf(errbuf, errbufsz, "out of memory");
1301 return 0;
1302 }
1303
1304 /* read from fp into buf */
1305 while (! feof(fp)) {
1306 bufsz += 1000;
1307
1308 /* Allocate 1 extra byte because we will tag on a NUL */
1309 char* x = realloc(buf, bufsz + 1);
1310 if (!x) {
1311 snprintf(errbuf, errbufsz, "out of memory");
1312 xfree(buf);
1313 return 0;
1314 }
1315 buf = x;
1316
1317 errno = 0;
1318 int n = fread(buf + off, 1, bufsz - off, fp);
1319 if (ferror(fp)) {
1320 snprintf(errbuf, errbufsz, "%s",
1321 errno ? strerror(errno) : "Error reading file");
1322 free(buf);
1323 return 0;
1324 }
1325 off += n;
1326 }
1327
1328 /* tag on a NUL to cap the string */
1329 buf[off] = 0; /* we accounted for this byte in the realloc() above. */
1330
1331 /* parse it, cleanup and finish */
1332 toml_table_t* ret = toml_parse(buf, errbuf, errbufsz);
1333 free(buf);
1334 return ret;
1335 }
1336
1337
1338 static void xfree_kval(toml_keyval_t* p)
1339 {
1340 if (!p) return;
1341 xfree(p->key);
1342 xfree(p->val);
1343 xfree(p);
1344 }
1345
1346 static void xfree_tab(toml_table_t* p);
1347
1348 static void xfree_arr(toml_array_t* p)
1349 {
1350 if (!p) return;
1351
1352 xfree(p->key);
1353 switch (p->kind) {
1354 case 'v':
1355 for (int i = 0; i < p->nelem; i++) xfree(p->u.val[i]);
1356 xfree(p->u.val);
1357 break;
1358
1359 case 'a':
1360 for (int i = 0; i < p->nelem; i++) xfree_arr(p->u.arr[i]);
1361 xfree(p->u.arr);
1362 break;
1363
1364 case 't':
1365 for (int i = 0; i < p->nelem; i++) xfree_tab(p->u.tab[i]);
1366 xfree(p->u.tab);
1367 break;
1368 }
1369
1370 xfree(p);
1371 }
1372
1373
1374 static void xfree_tab(toml_table_t* p)
1375 {
1376 int i;
1377
1378 if (!p) return;
1379
1380 xfree(p->key);
1381
1382 for (i = 0; i < p->nkval; i++) xfree_kval(p->kval[i]);
1383 xfree(p->kval);
1384
1385 for (i = 0; i < p->narr; i++) xfree_arr(p->arr[i]);
1386 xfree(p->arr);
1387
1388 for (i = 0; i < p->ntab; i++) xfree_tab(p->tab[i]);
1389 xfree(p->tab);
1390
1391 xfree(p);
1392 }
1393
1394
1395 void toml_free(toml_table_t* tab)
1396 {
1397 xfree_tab(tab);
1398 }
1399
1400
1401 static tokentype_t ret_token(context_t* ctx, tokentype_t tok, int lineno, char* ptr, int len)
1402 {
1403 token_t t;
1404 t.tok = tok;
1405 t.lineno = lineno;
1406 t.ptr = ptr;
1407 t.len = len;
1408 t.eof = 0;
1409 ctx->tok = t;
1410 return tok;
1411 }
1412
1413 static tokentype_t ret_eof(context_t* ctx, int lineno)
1414 {
1415 ret_token(ctx, NEWLINE, lineno, ctx->stop, 0);
1416 ctx->tok.eof = 1;
1417 return ctx->tok.tok;
1418 }
1419
1420
1421 static tokentype_t scan_string(context_t* ctx, char* p, int lineno, int dotisspecial)
1422 {
1423 char* orig = p;
1424 if (0 == strncmp(p, "'''", 3)) {
1425 p = strstr(p + 3, "'''");
1426 if (0 == p) {
1427 e_syntax_error(ctx, lineno, "unterminated triple-s-quote");
1428 return 0; /* not reached */
1429 }
1430
1431 return ret_token(ctx, STRING, lineno, orig, p + 3 - orig);
1432 }
1433
1434 if (0 == strncmp(p, "\"\"\"", 3)) {
1435 int hexreq = 0; /* #hex required */
1436 int escape = 0;
1437 int qcnt = 0; /* count quote */
1438 for (p += 3; *p && qcnt < 3; p++) {
1439 if (escape) {
1440 escape = 0;
1441 if (strchr("btnfr\"\\", *p)) continue;
1442 if (*p == 'u') { hexreq = 4; continue; }
1443 if (*p == 'U') { hexreq = 8; continue; }
1444 if (*p == '\n') continue; /* allow for line ending backslash */
1445 e_syntax_error(ctx, lineno, "bad escape char");
1446 return 0; /* not reached */
1447 }
1448 if (hexreq) {
1449 hexreq--;
1450 if (strchr("0123456789ABCDEF", *p)) continue;
1451 e_syntax_error(ctx, lineno, "expect hex char");
1452 return 0; /* not reached */
1453 }
1454 if (*p == '\\') { escape = 1; continue; }
1455 qcnt = (*p == '"') ? qcnt + 1 : 0;
1456 }
1457 if (qcnt != 3) {
1458 e_syntax_error(ctx, lineno, "unterminated triple-quote");
1459 return 0; /* not reached */
1460 }
1461
1462 return ret_token(ctx, STRING, lineno, orig, p - orig);
1463 }
1464
1465 if ('\'' == *p) {
1466 for (p++; *p && *p != '\n' && *p != '\''; p++);
1467 if (*p != '\'') {
1468 e_syntax_error(ctx, lineno, "unterminated s-quote");
1469 return 0; /* not reached */
1470 }
1471
1472 return ret_token(ctx, STRING, lineno, orig, p + 1 - orig);
1473 }
1474
1475 if ('\"' == *p) {
1476 int hexreq = 0; /* #hex required */
1477 int escape = 0;
1478 for (p++; *p; p++) {
1479 if (escape) {
1480 escape = 0;
1481 if (strchr("btnfr\"\\", *p)) continue;
1482 if (*p == 'u') { hexreq = 4; continue; }
1483 if (*p == 'U') { hexreq = 8; continue; }
1484 e_syntax_error(ctx, lineno, "bad escape char");
1485 return 0; /* not reached */
1486 }
1487 if (hexreq) {
1488 hexreq--;
1489 if (strchr("0123456789ABCDEF", *p)) continue;
1490 e_syntax_error(ctx, lineno, "expect hex char");
1491 return 0; /* not reached */
1492 }
1493 if (*p == '\\') { escape = 1; continue; }
1494 if (*p == '\n') break;
1495 if (*p == '"') break;
1496 }
1497 if (*p != '"') {
1498 e_syntax_error(ctx, lineno, "unterminated quote");
1499 return 0; /* not reached */
1500 }
1501
1502 return ret_token(ctx, STRING, lineno, orig, p + 1 - orig);
1503 }
1504
1505 for ( ; *p && *p != '\n'; p++) {
1506 int ch = *p;
1507 if (ch == '.' && dotisspecial) break;
1508 if ('A' <= ch && ch <= 'Z') continue;
1509 if ('a' <= ch && ch <= 'z') continue;
1510 if ('0' <= ch && ch <= '9') continue;
1511 if (strchr("+-_.:", ch)) continue;
1512 break;
1513 }
1514
1515 return ret_token(ctx, STRING, lineno, orig, p - orig);
1516 }
1517
1518
1519 static tokentype_t next_token(context_t* ctx, int dotisspecial)
1520 {
1521 int lineno = ctx->tok.lineno;
1522 char* p = ctx->tok.ptr;
1523 int i;
1524
1525 /* eat this tok */
1526 for (i = 0; i < ctx->tok.len; i++) {
1527 if (*p++ == '\n')
1528 lineno++;
1529 }
1530
1531 /* make next tok */
1532 while (p < ctx->stop) {
1533 /* skip comment. stop just before the \n. */
1534 if (*p == '#') {
1535 for (p++; p < ctx->stop && *p != '\n'; p++);
1536 continue;
1537 }
1538
1539 if (dotisspecial && *p == '.')
1540 return ret_token(ctx, DOT, lineno, p, 1);
1541
1542 switch (*p) {
1543 case ',': return ret_token(ctx, COMMA, lineno, p, 1);
1544 case '=': return ret_token(ctx, EQUAL, lineno, p, 1);
1545 case '{': return ret_token(ctx, LBRACE, lineno, p, 1);
1546 case '}': return ret_token(ctx, RBRACE, lineno, p, 1);
1547 case '[': return ret_token(ctx, LBRACKET, lineno, p, 1);
1548 case ']': return ret_token(ctx, RBRACKET, lineno, p, 1);
1549 case '\n': return ret_token(ctx, NEWLINE, lineno, p, 1);
1550 case '\r': case ' ': case '\t':
1551 /* ignore white spaces */
1552 p++;
1553 continue;
1554 }
1555
1556 return scan_string(ctx, p, lineno, dotisspecial);
1557 }
1558
1559 return ret_eof(ctx, lineno);
1560 }
1561
1562
1563 const char* toml_key_in(toml_table_t* tab, int keyidx)
1564 {
1565 if (keyidx < tab->nkval) return tab->kval[keyidx]->key;
1566
1567 keyidx -= tab->nkval;
1568 if (keyidx < tab->narr) return tab->arr[keyidx]->key;
1569
1570 keyidx -= tab->narr;
1571 if (keyidx < tab->ntab) return tab->tab[keyidx]->key;
1572
1573 return 0;
1574 }
1575
1576
1577 const char* toml_raw_in(toml_table_t* tab, const char* key)
1578 {
1579 int i;
1580 for (i = 0; i < tab->nkval; i++) {
1581 if (0 == strcmp(key, tab->kval[i]->key))
1582 return tab->kval[i]->val;
1583 }
1584 return 0;
1585 }
1586
1587 toml_array_t* toml_array_in(toml_table_t* tab, const char* key)
1588 {
1589 int i;
1590 for (i = 0; i < tab->narr; i++) {
1591 if (0 == strcmp(key, tab->arr[i]->key))
1592 return tab->arr[i];
1593 }
1594 return 0;
1595 }
1596
1597
1598 toml_table_t* toml_table_in(toml_table_t* tab, const char* key)
1599 {
1600 int i;
1601 for (i = 0; i < tab->ntab; i++) {
1602 if (0 == strcmp(key, tab->tab[i]->key))
1603 return tab->tab[i];
1604 }
1605 return 0;
1606 }
1607
1608 const char* toml_raw_at(toml_array_t* arr, int idx)
1609 {
1610 if (arr->kind != 'v')
1611 return 0;
1612 if (! (0 <= idx && idx < arr->nelem))
1613 return 0;
1614 return arr->u.val[idx];
1615 }
1616
1617 char toml_array_kind(toml_array_t* arr)
1618 {
1619 return arr->kind;
1620 }
1621
1622 char toml_array_type(toml_array_t* arr)
1623 {
1624 if (arr->kind != 'v')
1625 return 0;
1626
1627 if (arr->nelem == 0)
1628 return 0;
1629
1630 return arr->type;
1631 }
1632
1633
1634 int toml_array_nelem(toml_array_t* arr)
1635 {
1636 return arr->nelem;
1637 }
1638
1639 const char* toml_array_key(toml_array_t* arr)
1640 {
1641 return arr ? arr->key : (const char*) NULL;
1642 }
1643
1644 int toml_table_nkval(toml_table_t* tab)
1645 {
1646 return tab->nkval;
1647 }
1648
1649 int toml_table_narr(toml_table_t* tab)
1650 {
1651 return tab->narr;
1652 }
1653
1654 int toml_table_ntab(toml_table_t* tab)
1655 {
1656 return tab->ntab;
1657 }
1658
1659 const char* toml_table_key(toml_table_t* tab)
1660 {
1661 return tab ? tab->key : (const char*) NULL;
1662 }
1663
1664 toml_array_t* toml_array_at(toml_array_t* arr, int idx)
1665 {
1666 if (arr->kind != 'a')
1667 return 0;
1668 if (! (0 <= idx && idx < arr->nelem))
1669 return 0;
1670 return arr->u.arr[idx];
1671 }
1672
1673 toml_table_t* toml_table_at(toml_array_t* arr, int idx)
1674 {
1675 if (arr->kind != 't')
1676 return 0;
1677 if (! (0 <= idx && idx < arr->nelem))
1678 return 0;
1679 return arr->u.tab[idx];
1680 }
1681
1682
1683 int toml_rtots(const char* src_, toml_timestamp_t* ret)
1684 {
1685 if (! src_) return -1;
1686
1687 const char* p = src_;
1688 const char* q = src_ + strlen(src_);
1689 int64_t val;
1690 int i;
1691
1692 memset(ret, 0, sizeof(*ret));
1693
1694 /* parse date YYYY-MM-DD */
1695 val = 0;
1696 if (q - p > 4 && p[4] == '-') {
1697 for (i = 0; i < 10; i++, p++) {
1698 int xx = *p;
1699 if (xx == '-') {
1700 if (i == 4 || i == 7) continue;
1701 return -1;
1702 }
1703 if (! ('0' <= xx && xx <= '9')) return -1;
1704 val = val * 10 + (xx - '0');
1705 }
1706 ret->day = &ret->__buffer.day;
1707 ret->month = &ret->__buffer.month;
1708 ret->year = &ret->__buffer.year;
1709
1710 *ret->day = val % 100; val /= 100;
1711 *ret->month = val % 100; val /= 100;
1712 *ret->year = val;
1713
1714 if (*p) {
1715 // parse the T or space separator
1716 if (*p != 'T' && *p != ' ') return -1;
1717 p++;
1718 }
1719 }
1720 if (q == p) return 0;
1721
1722 /* parse time HH:MM:SS */
1723 val = 0;
1724 if (q - p < 8) return -1;
1725 for (i = 0; i < 8; i++, p++) {
1726 int xx = *p;
1727 if (xx == ':') {
1728 if (i == 2 || i == 5) continue;
1729 return -1;
1730 }
1731 if (! ('0' <= xx && xx <= '9')) return -1;
1732 val = val * 10 + (xx - '0');
1733 }
1734 ret->second = &ret->__buffer.second;
1735 ret->minute = &ret->__buffer.minute;
1736 ret->hour = &ret->__buffer.hour;
1737
1738 *ret->second = val % 100; val /= 100;
1739 *ret->minute = val % 100; val /= 100;
1740 *ret->hour = val;
1741
1742 /* parse millisec */
1743 if (*p == '.') {
1744 val = 0;
1745 p++;
1746 if ('0' <= *p && *p <= '9') {
1747 val = (*p++ - '0') * 100;
1748 if ('0' <= *p && *p <= '9') {
1749 val += (*p++ - '0') * 10;
1750 if ('0' <= *p && *p <= '9') {
1751 val += (*p++ - '0');
1752 }
1753 }
1754 }
1755 ret->millisec = &ret->__buffer.millisec;
1756 *ret->millisec = val;
1757 }
1758 if (q == p) return 0;
1759
1760 /* parse and copy Z */
1761 ret->z = ret->__buffer.z;
1762 char* z = ret->z;
1763 if (*p == 'Z') {
1764 *z++ = *p++;
1765 *z = 0;
1766 return (p == q) ? 0 : -1;
1767 }
1768 if (*p == '+' || *p == '-') {
1769 *z++ = *p++;
1770
1771 if (! (isdigit(p[0]) && isdigit(p[1]))) return -1;
1772 *z++ = *p++;
1773 *z++ = *p++;
1774
1775 if (*p == ':') {
1776 *z++ = *p++;
1777
1778 if (! (isdigit(p[0]) && isdigit(p[1]))) return -1;
1779 *z++ = *p++;
1780 *z++ = *p++;
1781 }
1782
1783 *z = 0;
1784 }
1785 return (p == q) ? 0 : -1;
1786 }
1787
1788
1789 /* Raw to boolean */
1790 int toml_rtob(const char* src, int* ret_)
1791 {
1792 if (!src) return -1;
1793 int dummy;
1794 int* ret = ret_ ? ret_ : &dummy;
1795
1796 if (0 == strcmp(src, "true")) {
1797 *ret = 1;
1798 return 0;
1799 }
1800 if (0 == strcmp(src, "false")) {
1801 *ret = 0;
1802 return 0;
1803 }
1804 return -1;
1805 }
1806
1807
1808 /* Raw to integer */
1809 int toml_rtoi(const char* src, int64_t* ret_)
1810 {
1811 if (!src) return -1;
1812
1813 char buf[100];
1814 char* p = buf;
1815 char* q = p + sizeof(buf);
1816 const char* s = src;
1817 int base = 0;
1818 int64_t dummy;
1819 int64_t* ret = ret_ ? ret_ : &dummy;
1820
1821
1822 /* allow +/- */
1823 if (s[0] == '+' || s[0] == '-')
1824 *p++ = *s++;
1825
1826 /* disallow +_100 */
1827 if (s[0] == '_')
1828 return -1;
1829
1830 /* if 0 ... */
1831 if ('0' == s[0]) {
1832 switch (s[1]) {
1833 case 'x': base = 16; s += 2; break;
1834 case 'o': base = 8; s += 2; break;
1835 case 'b': base = 2; s += 2; break;
1836 case '\0': return *ret = 0, 0;
1837 default:
1838 /* ensure no other digits after it */
1839 if (s[1]) return -1;
1840 }
1841 }
1842
1843 /* just strip underscores and pass to strtoll */
1844 while (*s && p < q) {
1845 int ch = *s++;
1846 switch (ch) {
1847 case '_':
1848 // disallow '__'
1849 if (s[0] == '_') return -1;
1850 continue; /* skip _ */
1851 default:
1852 break;
1853 }
1854 *p++ = ch;
1855 }
1856 if (*s || p == q) return -1;
1857
1858 /* last char cannot be '_' */
1859 if (s[-1] == '_') return -1;
1860
1861 /* cap with NUL */
1862 *p = 0;
1863
1864 /* Run strtoll on buf to get the integer */
1865 char* endp;
1866 errno = 0;
1867 *ret = strtoll(buf, &endp, base);
1868 return (errno || *endp) ? -1 : 0;
1869 }
1870
1871
1872 int toml_rtod_ex(const char* src, double* ret_, char* buf, int buflen)
1873 {
1874 if (!src) return -1;
1875
1876 char* p = buf;
1877 char* q = p + buflen;
1878 const char* s = src;
1879 double dummy;
1880 double* ret = ret_ ? ret_ : &dummy;
1881
1882
1883 /* allow +/- */
1884 if (s[0] == '+' || s[0] == '-')
1885 *p++ = *s++;
1886
1887 /* disallow +_1.00 */
1888 if (s[0] == '_')
1889 return -1;
1890
1891 /* disallow +.99 */
1892 if (s[0] == '.')
1893 return -1;
1894
1895 /* zero must be followed by . or NUL */
1896 if (s[0] == '0' && s[1] && s[1] != '.')
1897 return -1;
1898
1899 /* just strip underscores and pass to strtod */
1900 while (*s && p < q) {
1901 int ch = *s++;
1902 switch (ch) {
1903 case '.':
1904 if (s[-2] == '_') return -1;
1905 if (s[0] == '_') return -1;
1906 break;
1907 case '_':
1908 // disallow '__'
1909 if (s[0] == '_') return -1;
1910 continue; /* skip _ */
1911 default:
1912 break;
1913 }
1914 *p++ = ch;
1915 }
1916 if (*s || p == q) return -1; /* reached end of string or buffer is full? */
1917
1918 /* last char cannot be '_' */
1919 if (s[-1] == '_') return -1;
1920
1921 if (p != buf && p[-1] == '.')
1922 return -1; /* no trailing zero */
1923
1924 /* cap with NUL */
1925 *p = 0;
1926
1927 /* Run strtod on buf to get the value */
1928 char* endp;
1929 errno = 0;
1930 *ret = strtod(buf, &endp);
1931 return (errno || *endp) ? -1 : 0;
1932 }
1933
1934 int toml_rtod(const char* src, double* ret_)
1935 {
1936 char buf[100];
1937 return toml_rtod_ex(src, ret_, buf, sizeof(buf));
1938 }
1939
1940
1941 static char* kill_line_ending_backslash(char* str)
1942 {
1943 if (!str) return 0;
1944
1945 /* first round: find (backslash, \n) */
1946 char* p = str;
1947 while (0 != (p = strstr(p, "\\\n"))) {
1948 char* q = (p + 1);
1949 q += strspn(q, " \t\r\n");
1950 memmove(p, q, strlen(q) + 1);
1951 }
1952 /* second round: find (backslash, \r, \n) */
1953 p = str;
1954 while (0 != (p = strstr(p, "\\\r\n"))) {
1955 char* q = (p + 1);
1956 q += strspn(q, " \t\r\n");
1957 memmove(p, q, strlen(q) + 1);
1958 }
1959
1960 return str;
1961 }
1962
1963
1964 int toml_rtos(const char* src, char** ret)
1965 {
1966 if (!src) return -1;
1967 if (*src != '\'' && *src != '"') return -1;
1968
1969 *ret = 0;
1970 int srclen = strlen(src);
1971 if (*src == '\'') {
1972 if (0 == strncmp(src, "'''", 3)) {
1973 const char* sp = src + 3;
1974 const char* sq = src + srclen - 3;
1975 /* last 3 chars in src must be ''' */
1976 if (! (sp <= sq && 0 == strcmp(sq, "'''")))
1977 return -1;
1978
1979 /* skip first new line right after ''' */
1980 if (*sp == '\n')
1981 sp++;
1982 else if (sp[0] == '\r' && sp[1] == '\n')
1983 sp += 2;
1984
1985 *ret = kill_line_ending_backslash(strndup(sp, sq - sp));
1986 } else {
1987 const char* sp = src + 1;
1988 const char* sq = src + srclen - 1;
1989 /* last char in src must be ' */
1990 if (! (sp <= sq && *sq == '\''))
1991 return -1;
1992 /* copy from sp to p */
1993 *ret = strndup(sp, sq - sp);
1994 }
1995 return *ret ? 0 : -1;
1996 }
1997
1998 const char* sp;
1999 const char* sq;
2000 if (0 == strncmp(src, "\"\"\"", 3)) {
2001 sp = src + 3;
2002 sq = src + srclen - 3;
2003 if (! (sp <= sq && 0 == strcmp(sq, "\"\"\"")))
2004 return -1;
2005
2006 /* skip first new line right after """ */
2007 if (*sp == '\n')
2008 sp++;
2009 else if (sp[0] == '\r' && sp[1] == '\n')
2010 sp += 2;
2011 } else {
2012 sp = src + 1;
2013 sq = src + srclen - 1;
2014 if (! (sp <= sq && *sq == '"'))
2015 return -1;
2016 }
2017
2018 char dummy_errbuf[1];
2019 *ret = normalize_string(sp, sq - sp,
2020 1, // flag kill_line_ending_backslash
2021 dummy_errbuf, sizeof(dummy_errbuf));
2022 return *ret ? 0 : -1;
2023 }