-
Notifications
You must be signed in to change notification settings - Fork 2
/
tc_xml.h
1395 lines (1192 loc) · 43 KB
/
tc_xml.h
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
/*
* tc_xml.h: XML file parser.
*
* DEPENDS:
* VERSION: 0.1.0 (2024-08-01)
* LICENSE: CC0 & Boost (dual-licensed)
* AUTHOR: Tim Čas
* URL: https://github.com/darkuranium/tclib
*
* VERSION HISTORY:
* 0.1.0 initial public release
*
* TODOS:
* - Ensure full compliance with XML spec (for non-validating parsers)
* - Introduce a node-based / DOM-like API
* - Add an XPath-like parser to it (but might be a separate lib)
* - [maybe] Introduce various helper flags (like TCXML_CONCAT_CDATA)
* - Full C++-compilation-mode support
*/
#ifndef TC_XML_H_
#define TC_XML_H_
#include <stdint.h>
#include <stdbool.h>
typedef struct tcxml_string
{
size_t len;
char* ptr;
} tcxml_string_t;
typedef struct tcxml_error
{
size_t offset, line, column;
const char* message;
} tcxml_error_t;
#define TCXML_ERROR_IS_OK(error) !(error).message
// Utility functions; used internally, but provided here as they may be useful.
// Convert UTF-32 to UTF-8, returning the number of characters written into `utf8` (or 0 on error).
size_t tcxml_utf8_from_utf32(char utf8[4], uint32_t utf32);
// Convert UTF-8 to UTF-32, returning the number of characters read from `utf8` (or 0 on error).
// `utf32` may be NULL, in which case this simply counts bytes that make up 1 UTF-32 character.
size_t tcxml_utf32_from_utf8(uint32_t* utf32, const char* utf8, size_t utf8len);
typedef struct tcxml_sax_callbacks
{
// start of parse
void (*start)(void* udata);
// end of parse
void (*end)(void* udata);
// <?xml ...?>
void (*xml_decl)(tcxml_string_t version, tcxml_string_t encoding, bool* standalone, void* udata);
// cdata
void (*cdata)(tcxml_string_t data, void* udata);
// basic text
void (*text)(tcxml_string_t text, size_t body_head, size_t body_tail, void* udata);
// element start, e.g. <foo>
void (*element_start)(tcxml_string_t tag, tcxml_string_t* attrs, size_t nattrs, void* udata);
// element end, e.g. </foo>
void (*element_end)(tcxml_string_t tag, void* udata);
// processing instruction, e.g. <?foo ... ?>
void (*processing_instruction)(tcxml_string_t target, tcxml_string_t body, void* udata);
// comment, e.g. <!-- ... -->
void (*comment)(tcxml_string_t text, void* udata);
// unknown entity reference, e.g. &foo;
// note that this is *not* triggered for & < > ' "
// should return the replacement text in `replacement` (defaults to `&<ref>;`, i.e. no-op), and a boolean on whether we want to continue parse (true), or abort with error (false)
bool (*unknown_entity_reference)(tcxml_string_t* replacement, tcxml_string_t ref, void* udata);
// whitespace that can be ignored, e.g. <x>[here]<y/>[here]</x>
//void (*ignorable_whitespace)(tcxml_string_t text, void* udata);
// handle missing start & end elements; `stack` can be inspected & modified to help resolve the problem
// should return whether we should continue parsing (true), or abort (false)
//bool (*error_element_start_missing)(char* tag, char** stack, size_t* stack_top, void* udata);
//bool (*error_element_end_missing)(char* tag, char** stack, size_t* stack_top, void* udata);
} tcxml_sax_callbacks_t;
/// A streaming parser context, in order to reuse memory allocations.
typedef struct tcxml_sax_buffers
{
// allocated strings, this is reused between callback calls
struct
{
size_t maxlen; // used so that we know how many subarrays to free
size_t mem, len;
struct
{
size_t mem, len;
char* ptr;
}* ptr;
} data_buf;
// text buffer, contains already-converted text (e.g. `they're` => `they're`)
struct
{
size_t mem, len;
char* ptr;
} text_buf;
// element attribute list, passed to callback
struct
{
size_t mem, len;
tcxml_string_t* ptr;
} attrs;
// element tag name stack
/*struct
{
size_t mem, len;
tcxml_string_t* ptr;
} stack;*/
} tcxml_sax_buffers_t;
tcxml_sax_buffers_t* tcxml_sax_buffers_init(tcxml_sax_buffers_t* bufs);
void tcxml_sax_buffers_deinit(const tcxml_sax_buffers_t* bufs);
/// `bufs` is optional. If NULL, will allocate a temporary context.
tcxml_error_t tcxml_sax_process(tcxml_sax_buffers_t* bufs, const char* src, const tcxml_sax_callbacks_t* cbs, void* udata);
/*
#define TCXML_CONCAT_CDATA 0x01 // concatenate neighbouring cdata, e.g. `<![CDATA[foo]]><![CDATA[bar]]>` into `foobar`
#define TCXML_ALLOW_HTML_LIKE_ATTRIBS 0x02 // allow HTML-like attributes (`<x foo=bar baz/>` --- no quotes and attribs without values)
#define TCXML_ALLOW_NONCOMPLIANT_COMMENTS 0x04 // allow non-compliant comments, i.e. comments containing `--`
#define TCXML_INSERT_MISSING_START 0x08 // insert missing start elements (this prevents `error_element_start_missing` from being called)
#define TCXML_INSERT_MISSING_END 0x10 // insert missing end elements (this prevents `error_element_end_missing` from being called)
#define TCXML_NODE_XML_DECL 0 // <?xml ...?>
#define TCXML_NODE_CDATA 1 // <![CDATA[...]]>
#define TCXML_NODE_TEXT 2 // plain text
#define TCXML_NODE_ELEMENT 3 // <foo>...</foo> <bar/>
#define TCXML_NODE_PROCESSING_INSTRUCTION 4 // <?foo ...?>
#define TCXML_NODE_COMMENT 5 // <!-- ... -->
*/
typedef struct tcxml_node
{
uint8_t type;
// VALID IN: all
char* whitespace_pre; // preceding ignorable whitespace
char* whitespace_post; // following ignorable whitespace
// VALID IN: xml_decl (always "xml"), element, processing_instruction
char* tag;
// VALID IN: cdata, text, processing_instruction, comment
tcxml_string_t text; // text contents
// VALID IN: xml_decl, element
tcxml_string_t const* args;
// VALID IN: element
size_t nchildren;
struct tcxml_node* children;
} tcxml_node_t;
#endif /* TC_XML_H_ */
#ifdef TC_XML_IMPLEMENTATION
#undef TC_XML_IMPLEMENTATION
#include <stdlib.h>
#include <string.h>
#include <assert.h>
//#include <errno.h> // for ERANGE, as triggered by strtoul
#ifdef __cplusplus
#if defined(_MSC_VER) || defined(__GNUC__)
#define restrict __restrict
#else
#define restrict
#endif
//#define TC__RESTRICT(T) T restrict
#endif
size_t tcxml_utf8_from_utf32(char utf8[4], uint32_t utf32)
{
if(utf32 <= 0x7F)
{
utf8[0] = utf32; // 0xxxxxxx
return 1;
}
if(utf32 <= 0x7FF)
{
utf8[0] = 0xC0 | (utf32 >> 6); // 110xxxxx
utf8[1] = 0x80 | (utf32 & 0x3F); // 10xxxxxx
return 2;
}
if(utf32 <= 0xFFFF)
{
utf8[0] = 0xE0 | (utf32 >> 12); // 1110xxxx
utf8[1] = 0x80 | ((utf32 >> 6) & 0x3F); // 10xxxxxx
utf8[2] = 0x80 | (utf32 & 0x3F); // 10xxxxxx
return 3;
}
if(utf32 <= 0x10FFFF)
{
utf8[0] = 0xF0 | (utf32 >> 18); // 11110xxx
utf8[1] = 0x80 | ((utf32 >> 12) & 0x3F);// 10xxxxxx
utf8[1] = 0x80 | ((utf32 >> 6) & 0x3F); // 10xxxxxx
utf8[2] = 0x80 | (utf32 & 0x3F); // 10xxxxxx
return 4;
}
return 0; // invalid
}
// TODO performance: Optimize
size_t tcxml_utf32_from_utf8(uint32_t* utf32, const char* utf8, size_t utf8len)
{
// to simplify logic below (avoid `if` conditions for NULL)
uint32_t utf32_tmp;
if(!utf32) utf32 = &utf32_tmp;
*utf32 = UINT32_MAX; // for invalid UTF-8, we'll simply store an invalid UTF-32 character
if(!utf8len)
return 0;
if(!(utf8[0] & 0x80)) // 0xxxxxxx
{
*utf32 = utf8[0];
return 1;
}
else if(utf8len < 2)
return 0; // truncated UTF-8
if((utf8[0] & 0xE0) == 0xC0 // 110xxxxx
&& (utf8[1] & 0xC0) == 0x80) // 10xxxxxx
{
*utf32 = (utf8[0] & 0x1F) << 6
| (utf8[1] & 0x3F);
return 2;
}
else if(utf8len < 3)
return 0; // truncated UTF-8
if((utf8[0] & 0xF0) == 0xE0 // 1110xxxx
&& (utf8[1] & 0xC0) == 0x80 // 10xxxxxx
&& (utf8[2] & 0xC0) == 0x80) // 10xxxxxx
{
*utf32 = (utf8[0] & 0x0F) << 12
| (utf8[1] & 0x3F) << 6
| (utf8[2] & 0x3F);
return 3;
}
else if(utf8len < 4)
return 0;
if((utf8[0] & 0xF8) == 0xF0 // 11110xxx
&& (utf8[1] & 0xC0) == 0x80 // 10xxxxxx
&& (utf8[2] & 0xC0) == 0x80 // 10xxxxxx
&& (utf8[3] & 0xC0) == 0x80) // 10xxxxxx
{
*utf32 = (utf8[0] & 0x0F) << 18
| (utf8[1] & 0x3F) << 12
| (utf8[2] & 0x3F) << 6
| (utf8[3] & 0x3F);
return 4;
}
//could use `else if(utf8len < 5)` if we wanted to extend UTF-8 support to up to 0x7FFFFFFF / 6 bytes (but we don't)
return 0; // invalid UTF-8
}
tcxml_sax_buffers_t* tcxml_sax_buffers_init(tcxml_sax_buffers_t* bufs)
{
if(!bufs) return NULL;
*bufs = (tcxml_sax_buffers_t){ {0} };
return bufs;
}
void tcxml_sax_buffers_deinit(const tcxml_sax_buffers_t* bufs)
{
if(!bufs) return;
tcxml_sax_buffers_t mbufs = *bufs;
for(size_t i = 0; i < mbufs.data_buf.maxlen; i++)
free(mbufs.data_buf.ptr[i].ptr);
free(mbufs.data_buf.ptr);
free(mbufs.text_buf.ptr);
free(mbufs.attrs.ptr);
//free(mbufs.stack.ptr);
}
// https://www.w3.org/TR/xml/#sec-documents
struct tcxml_parse_context_
{
tcxml_sax_buffers_t* bufs;
const tcxml_sax_callbacks_t* cbs;
void* udata;
tcxml_error_t error;
// non-`const` for convenience (to avoid tons of casts for tcxml_string_t), but actually never modified
char* str;
char* ptr;
// a temporary used by various functions
tcxml_string_t capture;
};
static size_t tcxml_next_pow_2_(size_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
#if SIZE_MAX >= UINT64_MAX
v |= v >> 32;
#endif
v++;
return v;
}
static void tcxml_arr_ensuremem_impl_(void** ptr, size_t size, size_t* mem, size_t len)
{
if(*mem < len)
{
*mem = len < 8 ? 8 : tcxml_next_pow_2_(len);
*ptr = realloc(*ptr, *mem * size);
}
}
//#define TCXML_ARR_ENSUREMEM_(arr) tcxml_arr_ensuremem_impl_(&(arr)->ptr, sizeof(*(arr)->ptr), &(arr)->mem, (arr)->len)
#define TCXML_ARR_APPENDN_(arr, n) (tcxml_arr_ensuremem_impl_((void**)&(arr)->ptr, sizeof(*(arr)->ptr), &(arr)->mem, ((arr)->len += (n))), &(arr)->ptr[(arr)->len - (n)])
//#define TCXML_ARR_PUSH_(arr, item) (*TCXML_ARR_APPENDN_(arr, 1) = (item))
//#define TCXML_ARR_POP_(arr) (assert((arr)->len), (arr)->ptr[--(arr)->len])
static void tcxml_data_reset_(tcxml_sax_buffers_t* restrict bufs)
{
bufs->data_buf.len = 0;
}
static tcxml_string_t tcxml_data_push_(tcxml_sax_buffers_t* restrict bufs, tcxml_string_t str)
{
size_t index = bufs->data_buf.len;
// reserve a data slot
TCXML_ARR_APPENDN_(&bufs->data_buf, 1);
if(bufs->data_buf.maxlen < bufs->data_buf.len)
{
assert(bufs->data_buf.maxlen + 1 == bufs->data_buf.len);
bufs->data_buf.maxlen = bufs->data_buf.len;
// first time reaching this far, ensure value is initialized
bufs->data_buf.ptr[index].mem = 0; // (`len` is reset below anyway)
bufs->data_buf.ptr[index].ptr = NULL;
}
// populate the slot (note that we need to do this even if str.ptr == NULL, so that popn_ works correctly)
bufs->data_buf.ptr[index].len = 0;
if(!str.ptr)
return (tcxml_string_t){ 0, NULL };
TCXML_ARR_APPENDN_(&bufs->data_buf.ptr[index], str.len + 1);
memcpy(bufs->data_buf.ptr[index].ptr, str.ptr, str.len);
bufs->data_buf.ptr[index].ptr[str.len] = 0;
return (tcxml_string_t){
str.len,
bufs->data_buf.ptr[index].ptr,
};
}
static tcxml_string_t tcxml_data_pushpp_(tcxml_sax_buffers_t* restrict bufs, const char* head, const char* tail)
{
return tcxml_data_push_(bufs, (tcxml_string_t){ tail - head, (char*)head });
}
static tcxml_string_t tcxml_data_pushpn_(tcxml_sax_buffers_t* restrict bufs, const char* str, size_t len)
{
return tcxml_data_push_(bufs, (tcxml_string_t){ len, (char*)str });
}
// Guaranteed to *not* free memory.
static void tcxml_data_popn_(tcxml_sax_buffers_t* restrict bufs, size_t n)
{
assert(bufs->data_buf.len >= n);
bufs->data_buf.len -= n;
}
static void tcxml_text_reset_(tcxml_sax_buffers_t* restrict bufs)
{
bufs->text_buf.len = 0;
}
static void tcxml_text_append_(tcxml_sax_buffers_t* restrict bufs, tcxml_string_t str, bool normalize_eol)
{
size_t olen = bufs->text_buf.len;
char* ptr = TCXML_ARR_APPENDN_(&bufs->text_buf, str.len);
if(str.len)
{
if(!normalize_eol)
memcpy(ptr, str.ptr, str.len);
else
{
// normalize line endings as we copy; this may reduce the string length, so we fix that up at the end
size_t pos = 0;
for(;;)
{
const char* cr = memchr(&str.ptr[pos], '\r', str.len - pos);
if(!cr)
break;
// found a CR, first simply copy over everything until that
size_t nleading = (cr - str.ptr) - pos;
memcpy(&ptr[olen], &str.ptr[pos], nleading);
olen += nleading;
// emit a LF and adjust `pos` to one beyond it (so that next search doesn't find the same thing)
ptr[olen++] = '\n';
pos = cr - str.ptr + 1;
// check for CRLF
if(pos < str.len && str.ptr[pos] == '\n')
++pos; // skip LF in CRLF (since this should count as *one* newline)
}
// copy any final (trailing) data, after last CR
memcpy(&ptr[olen], &str.ptr[pos], str.len - pos);
olen += str.len - pos;
// finally, adjust the length to actual length
assert(olen <= bufs->text_buf.len && "Output length out of bounds");
bufs->text_buf.len = olen;
}
}
}
static void tcxml_text_appendpp_(tcxml_sax_buffers_t* restrict bufs, const char* head, const char* tail, bool normalize_eol)
{
tcxml_text_append_(bufs, (tcxml_string_t){ tail - head, (char*)head }, normalize_eol);
}
static void tcxml_text_appendpn_(tcxml_sax_buffers_t* restrict bufs, const char* str, size_t len, bool normalize_eol)
{
tcxml_text_append_(bufs, (tcxml_string_t){ len, (char*)str }, normalize_eol);
}
static tcxml_string_t tcxml_text_finish_(tcxml_sax_buffers_t* restrict bufs)
{
tcxml_string_t str = {bufs->text_buf.len, bufs->text_buf.ptr};
*TCXML_ARR_APPENDN_(&bufs->text_buf, 1) = 0;
return str;
}
// compare `str1` with a 0-terminated `str2`
static int tcxml_string_cmpz_(tcxml_string_t str1, const char* str2)
{
size_t str2_len = strlen(str2);
if(str1.len < str2_len)
return -1;
if(str1.len > str2_len)
return +1;
return memcmp(str1.ptr, str2, str1.len);
}
static bool tcxml_starts_with_(const char* str, const char* start)
{
return !memcmp(str, start, strlen(start));
}
static void tcxml_advance_line_col_(const char* head, const char* tail, tcxml_error_t* error)
{
while(head < tail)
{
size_t u8chars;
switch(head[0])
{
case '\r':
if(head + 1 < tail && head[1] == '\n')
++head; // skip over next `head`
/* (fallthrough) */
case '\n':
++error->line;
error->column = 0;
++head;
break;
default:
u8chars = tcxml_utf32_from_utf8(NULL, head, tail - head);
if(!u8chars) u8chars = 1; // in case of invalid UTF-8, we assume 1 char
error->column += u8chars;
head += u8chars;
break;
}
}
}
static tcxml_error_t tcxml_make_error_(struct tcxml_parse_context_* restrict ctx, const char* message)
{
tcxml_error_t error = {
.offset = ctx->ptr - ctx->str,
.message = message,
};
//tcxml_advance_line_col_(ctx->str + ctx->bom_skip, ctx->ptr, &error);
return error;
}
static bool tcxml_match_(const char* str, struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_starts_with_(ctx->ptr, str))
return false;
ctx->ptr += strlen(str);
return true;
}
#define TCXML_WSPACE_CHARS_ " \t\r\n"
static size_t tcxml_measure_wspace_left_(tcxml_string_t str)
{
size_t i;
for(i = 0; i < str.len; i++)
if(!strchr(TCXML_WSPACE_CHARS_, str.ptr[i]))
break;
return i;
}
static size_t tcxml_measure_wspace_right_(tcxml_string_t str)
{
size_t i;
for(i = str.len; i > 0; i--)
if(!strchr(TCXML_WSPACE_CHARS_, str.ptr[i-1]))
break;
return str.len - i;
}
#define TCXML_ERROR_(MESSAGE) (ctx->error = tcxml_make_error_(ctx, MESSAGE), false)
#define TCXML_CAPTURE_(HEAD,TAIL) (ctx->capture = (tcxml_string_t){ (TAIL) - (HEAD), (HEAD) }, true)
static bool tcxml_px_prolog_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_px_Misc_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_px_CDSect_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_p_SDDecl_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_px_element_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_p_STag_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_p_ETag_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_px_content_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_p_EmptyElemTag_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_p_Reference_(struct tcxml_parse_context_* restrict ctx);
static bool tcxml_p_EncodingDecl_(struct tcxml_parse_context_* restrict ctx);
/*
document ::= prolog element Misc*
*/
static bool tcxml_px_document_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_px_prolog_(ctx))
return false; // forward error
if(!tcxml_px_element_(ctx))
return false; // forward error
char* ptr;
do
{
ptr = ctx->ptr;
}
while(tcxml_px_Misc_(ctx));
ctx->ptr = ptr; // undo last, partial tcxml_p_Misc_
return true; // no capture
}
/*
==SKIP==
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
-- NOTE: simplified to allow all Unicode except #x0 --
*/
/*
S ::= (#x20 | #x9 | #xD | #xA)+
*/
static bool tcxml_p_S_(struct tcxml_parse_context_* restrict ctx)
{
char* head = ctx->ptr;
ctx->ptr += strspn(ctx->ptr, " \t\r\n");
if(head == ctx->ptr)
return TCXML_ERROR_("Expected whitespace");
return TCXML_CAPTURE_(head, ctx->ptr);
}
/*
NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] |
[#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] |
[#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] |
[#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
[#x10000-#xEFFFF]
NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] |
[#x203F-#x2040]
Name ::= NameStartChar (NameChar)*
*/
static bool tcxml_p_NameStartChar_(struct tcxml_parse_context_* restrict ctx)
{
// $$$ TODO: Handle UTF-8
if(*ctx->ptr == ':'
|| ('A' <= *ctx->ptr && *ctx->ptr <= 'Z')
|| *ctx->ptr == '_'
|| ('a' <= *ctx->ptr && *ctx->ptr <= 'z'))
{
char* head = ctx->ptr++;
return TCXML_CAPTURE_(head, ctx->ptr);
}
return TCXML_ERROR_("Expected start of XML name character");
}
static bool tcxml_p_NameChar_(struct tcxml_parse_context_* restrict ctx)
{
if(tcxml_p_NameStartChar_(ctx))
return true;
// $$$ TODO: Handle UTF-8
if(*ctx->ptr == '-'
|| *ctx->ptr == '.'
|| ('0' <= *ctx->ptr && *ctx->ptr <= '9'))
{
char* head = ctx->ptr++;
return TCXML_CAPTURE_(head, ctx->ptr);
}
return TCXML_ERROR_("Expected XML name character");
}
static bool tcxml_p_Name_(struct tcxml_parse_context_* restrict ctx)
{
char* head = ctx->ptr;
if(!tcxml_p_NameStartChar_(ctx))
return TCXML_ERROR_("Expected XML name");
while(tcxml_p_NameChar_(ctx)) { /* nothing to do */ }
return TCXML_CAPTURE_(head, ctx->ptr);
}
/*
==SKIP==
Names ::= Name (#x20 Name)*
Nmtoken ::= (NameChar)+
Nmtokens ::= Nmtoken (#20 Nmtoken)*
EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' |
"'" ([^%&'] | PEReference | Reference)* "'"
*/
/*
AttValue ::= '"' ([^<&"] | Reference)* '"' |
"'" ([^<&'] | Reference)* "'"
*/
static bool tcxml_p_AttValue_(struct tcxml_parse_context_* restrict ctx)
{
char quot = *ctx->ptr;
if(quot != '"' && quot != '\'')
return TCXML_ERROR_("Expected `\"` or `'` to start attribute value");
++ctx->ptr; // quot
tcxml_text_reset_(ctx->bufs);
while(*ctx->ptr && *ctx->ptr != quot)
{
size_t span = strcspn(ctx->ptr, quot == '"' ? "<&\"" : "<&'");
if(span)
{
tcxml_text_appendpn_(ctx->bufs, ctx->ptr, span, true);
ctx->ptr += span;
}
else if(!tcxml_p_Reference_(ctx))
return TCXML_ERROR_("Invalid attribute value contents");
}
if(*ctx->ptr != quot)
return TCXML_ERROR_("Expected end of attribute value quoted string");
++ctx->ptr; // quot
return true; // forward capture
}
/*
SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
*/
/*
CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
-- NOTE: simplified to [^<&]* --
*/
static bool tcxml_p_CharData_(struct tcxml_parse_context_* restrict ctx)
{
char* head = ctx->ptr;
ctx->ptr += strcspn(ctx->ptr, "<&");
tcxml_text_appendpp_(ctx->bufs, head, ctx->ptr, false);
return true; // CharData always succeeds, as it can be empty
}
/*
Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
*/
static bool tcxml_px_Comment_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_match_("<!--", ctx))
return TCXML_ERROR_("Expected start of a comment");
char* chead = ctx->ptr;
while(ctx->ptr[0] && (ctx->ptr[0] != '-' || ctx->ptr[1] != '-'))
++ctx->ptr;
char* ctail = ctx->ptr;
if(!tcxml_match_("-->", ctx))
return TCXML_ERROR_("Expected end of a comment");
if(ctx->cbs->comment)
{
tcxml_string_t text = tcxml_data_pushpp_(ctx->bufs, chead, ctail);
ctx->cbs->comment(text, ctx->udata);
tcxml_data_popn_(ctx->bufs, 1);
}
return true;
}
/*
PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
*/
static bool tcxml_p_PITarget_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_p_Name_(ctx))
return TCXML_ERROR_("Expected processing instruction target name");
if(ctx->capture.len == 3
&& strchr("Xx", ctx->capture.ptr[0])
&& strchr("Mm", ctx->capture.ptr[1])
&& strchr("Ll", ctx->capture.ptr[2]))
return TCXML_ERROR_("Processing instruction target `xml` is reserved");
return true; // return Name
}
static bool tcxml_px_PI_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_match_("<?", ctx))
return TCXML_ERROR_("Expected start of processing instruction");
if(!tcxml_p_PITarget_(ctx))
return false; // forward error
tcxml_string_t target = ctx->capture;
tcxml_string_t body;
if(tcxml_p_S_(ctx))
{
char* bhead = ctx->ptr;
while(ctx->ptr[0] && (ctx->ptr[0] != '?' || ctx->ptr[1] != '>'))
++ctx->ptr;
char* btail = ctx->ptr;
body = (tcxml_string_t){ btail - bhead, bhead };
}
else
body = (tcxml_string_t){ 0, NULL }; // no body => no capture
if(!tcxml_match_("?>", ctx))
return TCXML_ERROR_("Expected end of processing instruction");
if(ctx->cbs->processing_instruction)
{
target = tcxml_data_push_(ctx->bufs, target);
body = tcxml_data_push_(ctx->bufs, body);
ctx->cbs->processing_instruction(target, body, ctx->udata);
tcxml_data_popn_(ctx->bufs, 2);
}
return true;
}
/*
CDSect ::= CDStart CData CDEnd
CDStart ::= '<![CDATA['
CData ::= (Char* - (Char* ']]>' Char*))
CDEnd ::= ']]>'
*/
static bool tcxml_p_CDStart_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_match_("<![CDATA[", ctx))
return TCXML_ERROR_("Expected CDATA start");
return true;
}
static bool tcxml_p_CData_(struct tcxml_parse_context_* restrict ctx)
{
char* dhead = ctx->ptr;
while(ctx->ptr[0] && (ctx->ptr[0] != ']' || ctx->ptr[1] != ']' || ctx->ptr[2] != '>'))
++ctx->ptr;
char* dtail = ctx->ptr;
tcxml_text_appendpp_(ctx->bufs, dhead, dtail, true);
return true; // result in text_buf
}
static bool tcxml_p_CDEnd_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_match_("]]>", ctx))
return TCXML_ERROR_("Expected CDATA end");
return true;
}
static bool tcxml_px_CDSect_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_p_CDStart_(ctx))
return false; // forward error
tcxml_text_reset_(ctx->bufs);
if(!tcxml_p_CData_(ctx))
return false; // forward error
if(!tcxml_p_CDEnd_(ctx))
return false; // forward error
if(ctx->cbs->cdata)
{
tcxml_string_t cdata = tcxml_text_finish_(ctx->bufs);
ctx->cbs->cdata(cdata, ctx->udata);
}
return true;
}
/*
prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
Eq ::= S? '=' S?
VersionNum ::= '1.' [0-9]+
Misc ::= Comment | PI | S
-- NOTE: simplified by removing doctypedecl --
*/
static bool tcxml_p_Eq_(struct tcxml_parse_context_* restrict ctx)
{
tcxml_p_S_(ctx);
if(!tcxml_match_("=", ctx))
return TCXML_ERROR_("Expected '=' sign");
tcxml_p_S_(ctx);
return true; // ctx->capture irrelevant
}
static bool tcxml_p_VersionNum_(struct tcxml_parse_context_* restrict ctx)
{
char* vhead = ctx->ptr;
if(!tcxml_match_("1.", ctx))
return TCXML_ERROR_("Invalid XML version: expected '1.x'");
char* head = ctx->ptr;
ctx->ptr += strspn(ctx->ptr, "0123456789");
if(head == ctx->ptr)
return TCXML_ERROR_("Invalid XML version: expected digits after '1.'");
return TCXML_CAPTURE_(vhead, ctx->ptr);
}
static bool tcxml_p_VersionInfo_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_p_S_(ctx))
return false; // forward error
if(!tcxml_match_("version", ctx))
return TCXML_ERROR_("Expected `version` declaration attribute");
if(!tcxml_p_Eq_(ctx))
return false; // forward error
char quot = *ctx->ptr;
if(quot != '\'' && quot != '"')
return TCXML_ERROR_("Expected start of quoted string");
++ctx->ptr; // quot
if(!tcxml_p_VersionNum_(ctx))
return false; // forward error
if(*ctx->ptr != quot)
return TCXML_ERROR_("Expected end of quoted string");
++ctx->ptr; // quot
return true; // forward `capture` from VersionNum
}
static bool tcxml_px_XMLDecl_(struct tcxml_parse_context_* restrict ctx)
{
char* ptr;
if(!tcxml_match_("<?xml", ctx))
return TCXML_ERROR_("Expected XML declaration");
if(!tcxml_p_VersionInfo_(ctx))
return false; // forward error
tcxml_string_t version = ctx->capture;
tcxml_string_t encoding;
ptr = ctx->ptr;
if(tcxml_p_EncodingDecl_(ctx))
encoding = ctx->capture;
else
{
encoding = (tcxml_string_t){ 0, NULL };
ctx->ptr = ptr;
}
int standalone;
ptr = ctx->ptr;
if(tcxml_p_SDDecl_(ctx))
standalone = ctx->capture.ptr[0] == 'y';
else
{
standalone = -1;
ctx->ptr = ptr;
}
tcxml_p_S_(ctx);
if(!tcxml_match_("?>", ctx))
return TCXML_ERROR_("Expected end of XML declaration");
if(ctx->cbs->xml_decl)
{
version = tcxml_data_push_(ctx->bufs, version);
encoding = tcxml_data_push_(ctx->bufs, encoding);
bool standalone_bool = standalone;
ctx->cbs->xml_decl(version, encoding, standalone != -1 ? &standalone_bool : NULL, ctx->udata);
tcxml_data_popn_(ctx->bufs, 2);
}
return true;
}
static bool tcxml_px_prolog_(struct tcxml_parse_context_* restrict ctx)
{
char* ptr;
ptr = ctx->ptr;
if(!tcxml_px_XMLDecl_(ctx))
ctx->ptr = ptr;
do
{
ptr = ctx->ptr;
}
while(tcxml_px_Misc_(ctx));
ctx->ptr = ptr; // undo last, partial tcxml_px_Misc_
return true;
}
static bool tcxml_px_Misc_(struct tcxml_parse_context_* restrict ctx)
{
char* ptr = ctx->ptr;
if(tcxml_px_Comment_(ctx))
return true;
ctx->ptr = ptr;
if(tcxml_px_PI_(ctx))
return true;
ctx->ptr = ptr;
if(tcxml_p_S_(ctx))
{
/*if(ctx->cbs->ignorable_whitespace)
{
tcxml_string_t text = tcxml_data_push_(ctx, ctx->capture);
ctx->cbs->ignorable_whitespace(text, ctx->udata);
tcxml_data_popn_(ctx, 1);
}*/
return true;
}
//ctx->ptr = ptr;
return TCXML_ERROR_("Expected comment, processing instruction, or whitespace");
}
/*
SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))
*/
static bool tcxml_p_SDDecl_(struct tcxml_parse_context_* restrict ctx)
{
if(!tcxml_p_S_(ctx))
return false; // forward error
if(!tcxml_match_("standalone", ctx))
return TCXML_ERROR_("Expected `standalone=...` declaration attribute");
if(!tcxml_p_Eq_(ctx))
return false; // forward error
char quot = *ctx->ptr;
if(quot != '\'' && quot != '"')
return TCXML_ERROR_("Expected start of quoted string");
++ctx->ptr; // quot
char* head = ctx->ptr;
if(!tcxml_match_("yes", ctx)
&& !tcxml_match_("no", ctx))
return TCXML_ERROR_("Expected 'yes' or 'no' for `standalone=...` declaration attribute");
char* tail = ctx->ptr;
if(*ctx->ptr != quot)
return TCXML_ERROR_("Expected end of quoted string");
++ctx->ptr; // quot
return TCXML_CAPTURE_(head,tail);
}
/*
element ::= EmptyElemTag |
STag content ETag
*/
static bool tcxml_px_element_(struct tcxml_parse_context_* restrict ctx)
{
char* ptr;
ptr = ctx->ptr;
if(tcxml_p_EmptyElemTag_(ctx))
{
if(ctx->cbs->element_start || ctx->cbs->element_end)
{
assert((ctx->bufs->attrs.len & 1) == 0 && "Expected an even number of attribute elements");
tcxml_string_t tag = tcxml_data_push_(ctx->bufs, ctx->capture);
if(ctx->cbs->element_start)
ctx->cbs->element_start(tag, ctx->bufs->attrs.ptr, ctx->bufs->attrs.len / 2, ctx->udata);
if(ctx->cbs->element_end)
ctx->cbs->element_end(tag, ctx->udata);
tcxml_data_popn_(ctx->bufs, 1);
}
tcxml_data_reset_(ctx->bufs); // (optional)
return true; // don't care about capture (we've already invoked events)
}