]> mj.ucw.cz Git - libucw.git/blob - sherlock/xml/parse.c
572b6b96b77a0136d6a4259a6569e7b51232080c
[libucw.git] / sherlock / xml / parse.c
1 /*
2  *      Sherlock Library -- A simple XML parser
3  *
4  *      (c) 2007--2008 Pavel Charvat <pchar@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "sherlock/sherlock.h"
13 #include "sherlock/xml/xml.h"
14 #include "sherlock/xml/dtd.h"
15 #include "sherlock/xml/internals.h"
16 #include "lib/fastbuf.h"
17 #include "lib/ff-unicode.h"
18 #include "lib/unicode.h"
19 #include "lib/chartype.h"
20 #include "lib/hashfunc.h"
21
22 #include <setjmp.h>
23
24 /*** Basic parsing ***/
25
26 void NONRET
27 xml_fatal_expected(struct xml_context *ctx, uns c)
28 {
29   if (c >= 32 && c < 128)
30     xml_fatal(ctx, "Expected '%c'", c);
31   else
32     xml_fatal(ctx, "Expected U+%04x", c);
33 }
34
35 void NONRET
36 xml_fatal_expected_white(struct xml_context *ctx)
37 {
38   xml_fatal(ctx, "Expected a white space");
39 }
40
41 void NONRET
42 xml_fatal_expected_quot(struct xml_context *ctx)
43 {
44   xml_fatal(ctx, "Expected a quotation mark");
45 }
46
47 void
48 xml_parse_eq(struct xml_context *ctx)
49 {
50   /* Eq ::= S? '=' S? */
51   xml_parse_white(ctx, 0);
52   xml_parse_char(ctx, '=');
53   xml_parse_white(ctx, 0);
54 }
55
56 /*** Names and nmtokens ***/
57
58 static char *
59 xml_parse_string(struct xml_context *ctx, struct mempool *pool, uns first_cat, uns next_cat, char *err)
60 {
61   char *p = mp_start_noalign(pool, 1);
62   if (unlikely(!(xml_peek_cat(ctx) & first_cat)))
63     xml_fatal(ctx, "%s", err);
64   do
65     {
66       p = mp_spread(pool, p, 5);
67       p = utf8_32_put(p, xml_skip_char(ctx));
68     }
69   while (xml_peek_cat(ctx) & next_cat);
70   *p++ = 0;
71   return mp_end(pool, p);
72 }
73
74 static void
75 xml_skip_string(struct xml_context *ctx, uns first_cat, uns next_cat, char *err)
76 {
77   if (unlikely(!(xml_get_cat(ctx) & first_cat)))
78     xml_fatal(ctx, "%s", err);
79   while (xml_peek_cat(ctx) & next_cat)
80     xml_skip_char(ctx);
81 }
82
83 char *
84 xml_parse_name(struct xml_context *ctx, struct mempool *pool)
85 {
86   /* Name ::= NameStartChar (NameChar)* */
87   return xml_parse_string(ctx, pool, ctx->cat_sname, ctx->cat_name, "Expected a name");
88 }
89
90 void
91 xml_skip_name(struct xml_context *ctx)
92 {
93   xml_skip_string(ctx, ctx->cat_sname, ctx->cat_name, "Expected a name");
94 }
95
96 char *
97 xml_parse_nmtoken(struct xml_context *ctx, struct mempool *pool)
98 {
99   /* Nmtoken ::= (NameChar)+ */
100   return xml_parse_string(ctx, pool, ctx->cat_name, ctx->cat_name, "Expected a nmtoken");
101 }
102
103 /*** Simple literals ***/
104
105 char *
106 xml_parse_system_literal(struct xml_context *ctx, struct mempool *pool)
107 {
108   /* SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'") */
109   char *p = mp_start_noalign(pool, 1);
110   uns q = xml_parse_quote(ctx), c;
111   while ((c = xml_get_char(ctx)) != q)
112     {
113       p = mp_spread(pool, p, 5);
114       p = utf8_32_put(p, c);
115     }
116   *p++ = 0;
117   return mp_end(pool, p);
118 }
119
120 char *
121 xml_parse_pubid_literal(struct xml_context *ctx, struct mempool *pool)
122 {
123   /* PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" */
124   char *p = mp_start_noalign(pool, 1);
125   uns q = xml_parse_quote(ctx), c;
126   while ((c = xml_get_char(ctx)) != q)
127     {
128       if (unlikely(!(xml_last_cat(ctx) & XML_CHAR_PUBID)))
129         xml_fatal(ctx, "Expected a pubid character");
130       p = mp_spread(pool, p, 2);
131       *p++ = c;
132     }
133   *p++ = 0;
134   return mp_end(pool, p);
135 }
136
137 /*** Comments ***/
138
139 void
140 xml_push_comment(struct xml_context *ctx)
141 {
142   TRACE(ctx, "push_comment");
143   /* Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
144    * Already parsed: '<!-' */
145   xml_parse_char(ctx, '-');
146   struct xml_node *n = xml_push_dom(ctx, NULL);
147   n->type = XML_NODE_COMMENT;
148   char *p = mp_start_noalign(ctx->pool, 6);
149   while (1)
150     {
151       if (xml_get_char(ctx) == '-')
152         if (xml_get_char(ctx) == '-')
153           break;
154         else
155           *p++ = '-';
156       p = utf8_32_put(p, xml_last_char(ctx));
157       p = mp_spread(ctx->pool, p, 6);
158     }
159   xml_parse_char(ctx, '>');
160   *p = 0;
161   n->len = p - (char *)mp_ptr(ctx->pool);
162   n->text = mp_end(ctx->pool, p + 1);
163   if ((ctx->flags & XML_REPORT_COMMENTS) && ctx->h_comment)
164     ctx->h_comment(ctx);
165 }
166
167 void
168 xml_pop_comment(struct xml_context *ctx)
169 {
170   xml_pop_dom(ctx, !(ctx->flags & XML_ALLOC_COMMENTS));
171   xml_dec(ctx);
172   TRACE(ctx, "pop_comment");
173 }
174
175 void
176 xml_skip_comment(struct xml_context *ctx)
177 {
178   TRACE(ctx, "skip_comment");
179   xml_parse_char(ctx, '-');
180   while (xml_get_char(ctx) != '-' || xml_get_char(ctx) != '-');
181   xml_parse_char(ctx, '>');
182   xml_dec(ctx);
183 }
184
185 /*** Processing instructions ***/
186
187 void
188 xml_push_pi(struct xml_context *ctx)
189 {
190   TRACE(ctx, "push_pi");
191   /* Parses a PI to ctx->value and ctx->name:
192    *   PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
193    *   PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
194    * Already parsed: '<?' */
195   struct xml_node *n = xml_push_dom(ctx, NULL);
196   n->type = XML_NODE_PI;
197   n->name = xml_parse_name(ctx, ctx->pool);
198   if (unlikely(!strcasecmp(n->name, "xml")))
199     xml_error(ctx, "Reserved PI target");
200   char *p = mp_start_noalign(ctx->pool, 5);
201   if (!xml_parse_white(ctx, 0))
202     xml_parse_seq(ctx, "?>");
203   else
204     while (1)
205       {
206         if (xml_get_char(ctx) == '?')
207           if (xml_peek_char(ctx) == '>')
208             {
209               xml_skip_char(ctx);
210               break;
211             }
212           else
213             *p++ = '?';
214         else
215           p = utf8_32_put(p, xml_last_char(ctx));
216         p = mp_spread(ctx->pool, p, 5);
217       }
218   *p = 0;
219   n->len = p - (char *)mp_ptr(ctx->pool);
220   n->text = mp_end(ctx->pool, p + 1);
221   if ((ctx->flags & XML_REPORT_PIS) && ctx->h_pi)
222     ctx->h_pi(ctx);
223 }
224
225 void
226 xml_pop_pi(struct xml_context *ctx)
227 {
228   xml_pop_dom(ctx, !(ctx->flags & XML_ALLOC_PIS));
229   xml_dec(ctx);
230   TRACE(ctx, "pop_pi");
231 }
232
233 void
234 xml_skip_pi(struct xml_context *ctx)
235 {
236   TRACE(ctx, "skip_pi");
237   if (ctx->flags & XML_VALIDATING)
238     {
239       struct mempool_state state;
240       mp_save(ctx->stack, &state);
241       if (unlikely(!strcasecmp(xml_parse_name(ctx, ctx->stack), "xml")))
242         xml_error(ctx, "Reserved PI target");
243       mp_restore(ctx->stack, &state);
244       if (!xml_parse_white(ctx, 0))
245         {
246           xml_parse_seq(ctx, "?>");
247           xml_dec(ctx);
248           return;
249         }
250     }
251   while (1)
252     if (xml_get_char(ctx) == '?')
253       if (xml_peek_char(ctx) == '>')
254         break;
255   xml_skip_char(ctx);
256   xml_dec(ctx);
257 }
258
259 /*** Character references ***/
260
261 uns
262 xml_parse_char_ref(struct xml_context *ctx)
263 {
264   TRACE(ctx, "parse_char_ref");
265   /* CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
266    * Already parsed: '&#' */
267   uns v = 0;
268   if (xml_get_char(ctx) == 'x')
269     {
270       if (!(xml_get_cat(ctx) & XML_CHAR_XDIGIT))
271         {
272           xml_error(ctx, "Expected a hexadecimal value of character reference");
273           goto recover;
274         }
275       do
276         {
277           v = (v << 4) + Cxvalue(xml_last_char(ctx));
278         }
279       while (v < 0x110000 && (xml_get_cat(ctx) & XML_CHAR_XDIGIT));
280     }
281   else
282     {
283       if (!(xml_last_cat(ctx) & XML_CHAR_DIGIT))
284         {
285           xml_error(ctx, "Expected a numeric value of character reference");
286           goto recover;
287         }
288       do
289         {
290           v = v * 10 + xml_last_char(ctx) - '0';
291         }
292       while (v < 0x110000 && (xml_get_cat(ctx) & XML_CHAR_DIGIT));
293     }
294   uns cat = xml_char_cat(v);
295   if (!(cat & ctx->cat_unrestricted))
296     {
297       xml_error(ctx, "Character reference out of range");
298       goto recover;
299     }
300   if (xml_last_char(ctx) == ';')
301     {
302       xml_dec(ctx);
303       return v;
304     }
305   xml_error(ctx, "Expected ';'");
306 recover:
307   while (xml_last_char(ctx) != ';')
308     xml_get_char(ctx);
309   xml_dec(ctx);
310   return UNI_REPLACEMENT;
311 }
312
313 /*** References to general entities ***/
314
315 static void
316 xml_parse_ref(struct xml_context *ctx)
317 {
318   /* Reference ::= EntityRef | CharRef
319    * EntityRef ::= '&' Name ';'
320    * Already parsed: '&' */
321   struct fastbuf *out = &ctx->chars;
322   if (xml_peek_char(ctx) == '#')
323     {
324       xml_skip_char(ctx);
325       bput_utf8_32(out, xml_parse_char_ref(ctx));
326     }
327   else
328     {
329       TRACE(ctx, "parse_ge_ref");
330       struct mempool_state state;
331       mp_save(ctx->stack, &state);
332       char *name = xml_parse_name(ctx, ctx->stack);
333       xml_parse_char(ctx, ';');
334       struct xml_dtd_entity *ent = xml_dtd_find_entity(ctx, name);
335       if (!ent)
336         {
337           xml_error(ctx, "Unknown entity &%s;", name);
338           bputc(out, '&');
339           bputs(out, name);
340           bputc(out, ';');
341         }
342       else if (ent->flags & XML_DTD_ENTITY_TRIVIAL)
343         {
344           TRACE(ctx, "Trivial entity &%s;", name);
345           bputs(out, ent->text);
346         }
347       else
348         {
349           TRACE(ctx, "Pushed entity &%s;", name);
350           mp_restore(ctx->stack, &state);
351           xml_dec(ctx);
352           xml_push_entity(ctx, ent);
353           return;
354         }
355       mp_restore(ctx->stack, &state);
356       xml_dec(ctx);
357     }
358 }
359
360 /*** Character data ***/
361
362 void
363 xml_spout_chars(struct fastbuf *fb)
364 {
365   if (fb->bptr < fb->bufend)
366     return;
367   struct xml_context *ctx = SKIP_BACK(struct xml_context, chars, fb);
368   struct mempool *pool = ctx->pool;
369   if (fb->bufend != fb->buffer)
370     {
371       TRACE(ctx, "growing chars");
372       uns len = fb->bufend - fb->buffer;
373       uns reported = fb->bstop - fb->buffer;
374       fb->buffer = mp_expand(pool);
375       fb->bufend = fb->buffer + mp_avail(pool);
376       fb->bptr = fb->buffer + len;
377       fb->bstop = fb->buffer + reported;
378     }
379   else
380     {
381       TRACE(ctx, "starting chars");
382       mp_save(pool, &ctx->chars_state);
383       fb->bptr = fb->buffer = fb->bstop = mp_start_noalign(pool, 2);
384       fb->bufend = fb->buffer + mp_avail(pool) - 1;
385     }
386 }
387
388 static inline uns
389 xml_end_chars(struct xml_context *ctx, char **out)
390 {
391   struct fastbuf *fb = &ctx->chars;
392   uns len = fb->bptr - fb->buffer;
393   if (len)
394     {
395       TRACE(ctx, "ending chars");
396       *fb->bptr = 0;
397       *out = mp_end(ctx->pool, fb->bptr + 1);
398       fb->bufend = fb->bstop = fb->bptr = fb->buffer;
399     }
400   return len;
401 }
402
403 static inline uns
404 xml_report_chars(struct xml_context *ctx, char **out)
405 {
406   struct fastbuf *fb = &ctx->chars;
407   uns len = fb->bptr - fb->buffer;
408   if (len)
409     {
410       *fb->bptr = 0;
411       *out = fb->bstop;
412       fb->bstop = fb->bptr;
413     }
414   return len;
415 }
416
417 static inline uns
418 xml_flush_chars(struct xml_context *ctx)
419 {
420   char *text, *rtext;
421   uns len = xml_end_chars(ctx, &text), rlen;
422   if (len)
423     {
424       if ((ctx->flags & XML_REPORT_CHARS) && ctx->h_block && (rlen = xml_report_chars(ctx, &rtext)))
425         ctx->h_block(ctx, rtext, rlen);
426       if (!(ctx->flags & XML_ALLOC_CHARS) && (!(ctx->flags & XML_REPORT_CHARS) || !ctx->h_chars))
427         {
428           mp_restore(ctx->pool, &ctx->chars_state);
429           return 0;
430         }
431       struct xml_node *n = xml_push_dom(ctx, &ctx->chars_state);
432       n->type = XML_NODE_CHARS;
433       n->text = text;
434       n->len = len;
435       if ((ctx->flags & XML_REPORT_CHARS) && ctx->h_chars)
436         ctx->h_chars(ctx);
437     }
438   return len;
439 }
440
441 static inline void
442 xml_pop_chars(struct xml_context *ctx)
443 {
444   xml_pop_dom(ctx, !(ctx->flags & XML_ALLOC_CHARS));
445   TRACE(ctx, "pop_chars");
446 }
447
448 static inline void
449 xml_append_chars(struct xml_context *ctx)
450 {
451   TRACE(ctx, "append_chars");
452   struct fastbuf *out = &ctx->chars;
453   while (xml_get_char(ctx) != '<')
454     if (xml_last_char(ctx) == '&')
455       {
456         xml_inc(ctx);
457         xml_parse_ref(ctx);
458       }
459     else
460       bput_utf8_32(out, xml_last_char(ctx));
461   xml_unget_char(ctx);
462 }
463
464 /*** CDATA sections ***/
465
466 static void
467 xml_append_cdata(struct xml_context *ctx)
468 {
469   /* CDSect :== '<![CDATA[' (Char* - (Char* ']]>' Char*)) ']]>'
470    * Already parsed: '<![' */
471   TRACE(ctx, "append_cdata");
472   xml_parse_seq(ctx, "CDATA[");
473   struct fastbuf *out = &ctx->chars;
474   uns rlen;
475   char *rtext;
476   if ((ctx->flags & XML_REPORT_CHARS) && ctx->h_block && (rlen = xml_report_chars(ctx, &rtext)))
477     ctx->h_block(ctx, rtext, rlen);
478   while (1)
479     {
480       if (xml_get_char(ctx) == ']')
481         {
482           if (xml_get_char(ctx) == ']')
483             if (xml_get_char(ctx) == '>')
484               break;
485             else
486               bputc(out, ']');
487           bputc(out, ']');
488         }
489       bput_utf8_32(out, xml_last_char(ctx));
490     }
491   if ((ctx->flags & XML_REPORT_CHARS) && ctx->h_cdata && (rlen = xml_report_chars(ctx, &rtext)))
492     ctx->h_cdata(ctx, rtext, rlen);
493   xml_dec(ctx);
494 }
495
496 static void UNUSED
497 xml_skip_cdata(struct xml_context *ctx)
498 {
499   TRACE(ctx, "skip_cdata");
500   xml_parse_seq(ctx, "CDATA[");
501   while (xml_get_char(ctx) != ']' || xml_get_char(ctx) != ']' || xml_get_char(ctx) != '>');
502   xml_dec(ctx);
503 }
504
505 /*** Attribute values ***/
506
507 char *
508 xml_parse_attr_value(struct xml_context *ctx, struct xml_dtd_attr *attr UNUSED)
509 {
510   TRACE(ctx, "parse_attr_value");
511   /* AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'" */
512   /* FIXME: -- check value constrains / normalize leading/trailing WS and repeated WS */
513   struct mempool_state state;
514   uns quote = xml_parse_quote(ctx);
515   mp_save(ctx->stack, &state);
516   struct fastbuf *out = &ctx->chars;
517   struct xml_source *src = ctx->src;
518   while (1)
519     {
520       uns c = xml_get_char(ctx);
521       if (c == '&')
522         {
523           xml_inc(ctx);
524           xml_parse_ref(ctx);
525         }
526       else if (c == quote && src == ctx->src)
527         break;
528       else if (c == '<')
529         xml_error(ctx, "Attribute value must not contain '<'");
530       else if (xml_last_cat(ctx) & XML_CHAR_WHITE)
531         bputc(out, ' ');
532       else
533         bput_utf8_32(out, c);
534     }
535   mp_restore(ctx->stack, &state);
536   char *text;
537   return xml_end_chars(ctx, &text) ? text : "";
538 }
539
540 uns
541 xml_normalize_white(struct xml_context *ctx UNUSED, char *text)
542 {
543   char *s = text, *d = text;
544   while (*s == 0x20)
545     s++;
546   while (1)
547     {
548       while (*s & ~0x20)
549         *d++ = *s++;
550       if (!*s)
551         break;
552       while (*++s == 0x20);
553       *d++ = 0x20;
554     }
555   if (d != text && d[-1] == 0x20)
556     d--;
557   *d = 0;
558   return d - text;
559 }
560
561 /*** Attributes ***/
562
563 struct xml_attrs_table;
564
565 static inline uns
566 xml_attrs_hash(struct xml_attrs_table *t UNUSED, struct xml_node *e, char *n)
567 {
568   return hash_pointer(e) ^ hash_string(n);
569 }
570
571 static inline int
572 xml_attrs_eq(struct xml_attrs_table *t UNUSED, struct xml_node *e1, char *n1, struct xml_node *e2, char *n2)
573 {
574   return (e1 == e2) && !strcmp(n1, n2);
575 }
576
577 static inline void
578 xml_attrs_init_key(struct xml_attrs_table *t UNUSED, struct xml_attr *a, struct xml_node *e, char *name)
579 {
580   a->elem = e;
581   a->name = name;
582   a->val = NULL;
583   a->user = NULL;
584   slist_add_tail(&e->attrs, &a->n);
585 }
586
587 #define HASH_PREFIX(x) xml_attrs_##x
588 #define HASH_NODE struct xml_attr
589 #define HASH_KEY_COMPLEX(x) x elem, x name
590 #define HASH_KEY_DECL struct xml_node *elem, char *name
591 #define HASH_TABLE_DYNAMIC
592 #define HASH_GIVE_EQ
593 #define HASH_GIVE_HASHFN
594 #define HASH_GIVE_INIT_KEY
595 #define HASH_WANT_CLEANUP
596 #define HASH_WANT_REMOVE
597 #define HASH_WANT_LOOKUP
598 #define HASH_WANT_FIND
599 #define HASH_GIVE_ALLOC
600 XML_HASH_GIVE_ALLOC
601 #include "lib/hashtable.h"
602
603 static void
604 xml_parse_attr(struct xml_context *ctx)
605 {
606   TRACE(ctx, "parse_attr");
607   /* Attribute ::= Name Eq AttValue */
608   struct xml_node *e = ctx->node;
609   char *n = xml_parse_name(ctx, ctx->pool);
610   struct xml_attr *a = xml_attrs_lookup(ctx->tab_attrs, e, n);
611   xml_parse_eq(ctx);
612   char *v = xml_parse_attr_value(ctx, NULL);
613   if (a->val)
614     {
615       xml_error(ctx, "Attribute %s is not unique in element <%s>", n, e->name);
616       return;
617     }
618   a->val = v;
619   if (!e->dtd)
620     a->dtd = NULL;
621   else if (!(a->dtd = xml_dtd_find_attr(ctx, e->dtd, a->name)))
622     xml_error(ctx, "Undefined attribute %s in element <%s>", n, e->name);
623   else
624     xml_validate_attr(ctx, a->dtd, a->val);
625 }
626
627 struct xml_attr *
628 xml_attr_find(struct xml_context *ctx, struct xml_node *node, char *name)
629 {
630   return xml_attrs_find(ctx->tab_attrs, node, name);
631 }
632
633 void
634 xml_attrs_table_init(struct xml_context *ctx)
635 {
636   xml_attrs_init(ctx->tab_attrs = xml_hash_new(ctx->pool, sizeof(struct xml_attrs_table)));
637 }
638
639 void
640 xml_attrs_table_cleanup(struct xml_context *ctx)
641 {
642   xml_attrs_cleanup(ctx->tab_attrs);
643 }
644
645 /*** Elements ***/
646
647 static void
648 xml_push_element(struct xml_context *ctx)
649 {
650   TRACE(ctx, "push_element");
651   /* EmptyElemTag | STag
652    * EmptyElemTag ::= '<' Name (S  Attribute)* S? '/>'
653    * STag ::= '<' Name (S  Attribute)* S? '>'
654    * Already parsed: '<' */
655   struct xml_node *e = xml_push_dom(ctx, NULL);
656   clist_init(&e->sons);
657   e->type = XML_NODE_ELEM;
658   e->name = xml_parse_name(ctx, ctx->pool);
659   slist_init(&e->attrs);
660   if (!e->parent)
661     {
662       ctx->dom = e;
663       if (ctx->doctype && strcmp(e->name, ctx->doctype))
664         xml_error(ctx, "The root element <%s> does not match the document type <%s>", e->name, ctx->doctype);
665     }
666   if (!ctx->dtd)
667     e->dtd = NULL;
668   else if (!(e->dtd = xml_dtd_find_elem(ctx, e->name)))
669     xml_error(ctx, "Undefined element <%s>", e->name);
670   else
671     {
672       // FIXME: validate regular expressions
673     }
674   while (1)
675     {
676       uns white = xml_parse_white(ctx, 0);
677       uns c = xml_get_char(ctx);
678       if (c == '/')
679         {
680           xml_parse_char(ctx, '>');
681           ctx->flags |= XML_EMPTY_ELEM_TAG;
682           break;
683         }
684       else if (c == '>')
685         break;
686       else if (!white)
687         xml_fatal_expected_white(ctx);
688       xml_unget_char(ctx);
689       xml_parse_attr(ctx);
690     }
691   if ((ctx->flags & XML_REPORT_TAGS) && ctx->h_stag)
692     ctx->h_stag(ctx);
693 }
694
695 static void
696 xml_pop_element(struct xml_context *ctx)
697 {
698   TRACE(ctx, "pop_element");
699   if ((ctx->flags & XML_REPORT_TAGS) && ctx->h_etag)
700     ctx->h_etag(ctx);
701   struct xml_node *e = ctx->node;
702   uns free = !(ctx->flags & XML_ALLOC_TAGS);
703   if (free)
704     {
705       if (!e->parent)
706         ctx->dom = NULL;
707       /* Restore hash table of attributes */
708       SLIST_FOR_EACH(struct xml_attr *, a, e->attrs)
709         xml_attrs_remove(ctx->tab_attrs, a);
710       struct xml_node *n;
711       while (n = clist_head(&e->sons))
712         {
713           if (n->type == XML_NODE_ELEM)
714             {
715               SLIST_FOR_EACH(struct xml_attr *, a, n->attrs)
716                 xml_attrs_remove(ctx->tab_attrs, a);
717               clist_insert_list_after(&n->sons, &n->n);
718             }
719           clist_remove(&n->n);
720         }
721     }
722   xml_pop_dom(ctx, free);
723   xml_dec(ctx);
724 }
725
726 static void
727 xml_parse_etag(struct xml_context *ctx)
728 {
729  /* ETag ::= '</' Name S? '>'
730   * Already parsed: '<' */
731   struct xml_node *e = ctx->node;
732   ASSERT(e);
733   char *n = e->name;
734   while (*n)
735     {
736       uns c;
737       n = utf8_32_get(n, &c);
738       if (xml_get_char(ctx) != c)
739         goto recover;
740     }
741   xml_parse_white(ctx, 0);
742   if (xml_get_char(ctx) != '>')
743     {
744 recover:
745       xml_error(ctx, "Invalid ETag, expected </%s>", e->name);
746       while (xml_get_char(ctx) != '>');
747     }
748   xml_dec(ctx);
749 }
750
751 /*** Document type declaration ***/
752
753 static void
754 xml_parse_doctype_decl(struct xml_context *ctx)
755 {
756   TRACE(ctx, "parse_doctype_decl");
757   /* doctypedecl ::= '<!DOCTYPE' S  Name (S  ExternalID)? S? ('[' intSubset ']' S?)? '>'
758    * Already parsed: '<!'
759    * Terminated before '[' or '>' */
760   if (ctx->doctype)
761     xml_fatal(ctx, "Multiple document types not allowed");
762   xml_parse_seq(ctx, "DOCTYPE");
763   xml_parse_white(ctx, 1);
764   ctx->doctype = xml_parse_name(ctx, ctx->pool);
765   TRACE(ctx, "doctype=%s", ctx->doctype);
766   uns c;
767   if (xml_parse_white(ctx, 0) && ((c = xml_peek_char(ctx)) == 'S' || c == 'P'))
768     {
769       if (c == 'S')
770         {
771           xml_parse_seq(ctx, "SYSTEM");
772           xml_parse_white(ctx, 1);
773           ctx->system_id = xml_parse_system_literal(ctx, ctx->pool);
774         }
775       else
776         {
777           xml_parse_seq(ctx, "PUBLIC");
778           xml_parse_white(ctx, 1);
779           ctx->public_id = xml_parse_pubid_literal(ctx, ctx->pool);
780           xml_parse_white(ctx, 1);
781           ctx->system_id = xml_parse_system_literal(ctx, ctx->pool);
782         }
783       xml_parse_white(ctx, 0);
784       ctx->flags |= XML_HAS_EXTERNAL_SUBSET;
785     }
786   if (xml_peek_char(ctx) == '[')
787     ctx->flags |= XML_HAS_INTERNAL_SUBSET;
788   if (ctx->h_doctype_decl)
789     ctx->h_doctype_decl(ctx);
790 }
791
792
793
794 ///////////////////////////////////////////////////////////////////////////////////////////////////////////
795
796 /* DTD: Internal subset */
797
798 static void
799 xml_parse_internal_subset(struct xml_context *ctx)
800 {
801   // FIXME: comments/pi have no parent
802   /* '[' intSubset ']'
803    * intSubset :== (markupdecl | DeclSep)
804    * Already parsed: ']' */
805   while (1)
806     {
807       xml_parse_white(ctx, 0);
808       uns c = xml_get_char(ctx);
809       xml_inc(ctx);
810       if (c == '<')
811         if ((c = xml_get_char(ctx)) == '!')
812           switch (c = xml_get_char(ctx))
813             {
814               case '-':
815                 xml_push_comment(ctx);
816                 xml_pop_comment(ctx);
817                 break;
818               case 'N':
819                 xml_parse_seq(ctx, "OTATION");
820                 xml_parse_notation_decl(ctx);
821                 break;
822               case 'E':
823                 if ((c = xml_get_char(ctx)) == 'N')
824                   {
825                     xml_parse_seq(ctx, "TITY");
826                     xml_parse_entity_decl(ctx);
827                   }
828                 else if (c == 'L')
829                   {
830                     xml_parse_seq(ctx, "EMENT");
831                     xml_parse_element_decl(ctx);
832                   }
833                 else
834                   goto invalid_markup;
835                 break;
836               case 'A':
837                 xml_parse_seq(ctx, "TTLIST");
838                 xml_parse_attr_list_decl(ctx);
839                 break;
840               default:
841                 goto invalid_markup;
842             }
843         else if (c == '?')
844           {
845             xml_push_pi(ctx);
846             xml_pop_pi(ctx);
847           }
848         else
849           goto invalid_markup;
850       else if (c == '%')
851         xml_parse_pe_ref(ctx);
852       else if (c == ']')
853         break;
854       else
855         goto invalid_markup;
856     }
857   xml_dec(ctx);
858   xml_dec(ctx);
859   return;
860 invalid_markup:
861   xml_fatal(ctx, "Invalid markup in the internal subset");
862 }
863
864 /*** The State Machine ***/
865
866 uns
867 xml_next(struct xml_context *ctx)
868 {
869   /* A nasty state machine */
870
871 #define PULL(x) do { if (ctx->pull & XML_PULL_##x) return ctx->state = XML_STATE_##x; case XML_STATE_##x: ; } while (0)
872 #define PULL_STATE(x, s) do { if (ctx->pull & XML_PULL_##x) return ctx->state = XML_STATE_##s, XML_STATE_##x; case XML_STATE_##s: ; } while (0)
873
874   TRACE(ctx, "xml_next (state=%u)", ctx->state);
875   jmp_buf throw_buf;
876   ctx->throw_buf = &throw_buf;
877   if (setjmp(throw_buf))
878     {
879 error:
880       if (ctx->err_code == XML_ERR_EOF && ctx->h_fatal)
881         ctx->h_fatal(ctx);
882       TRACE(ctx, "raised fatal error");
883       return ctx->state = XML_STATE_EOF;
884     }
885   uns c;
886   switch (ctx->state)
887     {
888       case XML_STATE_START:
889         TRACE(ctx, "entering prolog");
890         ctx->flags |= XML_SRC_DOCUMENT | XML_SRC_EXPECTED_DECL;
891         if (ctx->h_document_start)
892           ctx->h_document_start(ctx);
893         /* XMLDecl */
894         xml_refill(ctx);
895         if (ctx->h_xml_decl)
896           ctx->h_xml_decl(ctx);
897         PULL(XML_DECL);
898
899         /* Misc* (doctypedecl Misc*)? */
900         while (1)
901           {
902             xml_parse_white(ctx, 0);
903             xml_parse_char(ctx, '<');
904             xml_inc(ctx);
905             if ((c = xml_get_char(ctx)) == '?')
906               /* Processing intruction */
907               if (!(ctx->flags & XML_REPORT_PIS))
908                 xml_skip_pi(ctx);
909               else
910                 {
911                   xml_push_pi(ctx);
912                   PULL_STATE(PI, PROLOG_PI);
913                   xml_pop_pi(ctx);
914                 }
915             else if (c != '!')
916               {
917                 /* Found the root tag */
918                 xml_unget_char(ctx);
919                 goto first_tag;
920               }
921             else if (xml_get_char(ctx) == '-')
922               if (!(ctx->flags & XML_REPORT_COMMENTS))
923                 xml_skip_comment(ctx);
924               else
925                 {
926                   xml_push_comment(ctx);
927                   PULL_STATE(COMMENT, PROLOG_COMMENT);
928                   xml_pop_comment(ctx);
929                 }
930             else
931               {
932                 /* DocTypeDecl */
933                 xml_unget_char(ctx);
934                 xml_parse_doctype_decl(ctx);
935                 PULL(DOCTYPE_DECL);
936                 if (xml_peek_char(ctx) == '[')
937                   {
938                     xml_skip_char(ctx);
939                     xml_inc(ctx);
940                     if (ctx->flags & XML_PARSE_DTD)
941                       {
942                         xml_dtd_init(ctx);
943                         if (ctx->h_dtd_start)
944                           ctx->h_dtd_start(ctx);
945                         // FIXME: pull iface?
946                         xml_parse_internal_subset(ctx);
947                         // FIXME: external subset
948                         if (ctx->h_dtd_end)
949                           ctx->h_dtd_end(ctx);
950                       }
951                     else
952                       xml_skip_internal_subset(ctx);
953                   }
954                 xml_parse_white(ctx, 0);
955                 xml_parse_char(ctx, '>');
956                 xml_dec(ctx);
957               }
958           }
959
960       case XML_STATE_CHARS:
961
962         while (1)
963           {
964             if (xml_peek_char(ctx) != '<')
965               {
966                 /* CharData */
967                 xml_append_chars(ctx);
968                 continue;
969               }
970             else
971               xml_skip_char(ctx);
972             xml_inc(ctx);
973 first_tag:
974
975             if ((c = xml_get_char(ctx)) == '?')
976               {
977                 /* PI */
978                 if (!(ctx->flags & (XML_REPORT_PIS | XML_ALLOC_PIS)))
979                   xml_skip_pi(ctx);
980                 else
981                   {
982                     if (xml_flush_chars(ctx))
983                       {
984                         PULL_STATE(CHARS, CHARS_BEFORE_PI);
985                         xml_pop_chars(ctx);
986                       }
987                     xml_push_pi(ctx);
988                     PULL(PI);
989                     xml_pop_pi(ctx);
990                   }
991               }
992
993             else if (c == '!')
994               if ((c = xml_get_char(ctx)) == '-')
995                 {
996                   /* Comment */
997                   if (!(ctx->flags & (XML_REPORT_COMMENTS | XML_ALLOC_COMMENTS)))
998                     xml_skip_comment(ctx);
999                   else
1000                     {
1001                       if (xml_flush_chars(ctx))
1002                         {
1003                           PULL_STATE(CHARS, CHARS_BEFORE_COMMENT);
1004                           xml_pop_chars(ctx);
1005                         }
1006                       xml_push_comment(ctx);
1007                       PULL(COMMENT);
1008                       xml_pop_comment(ctx);
1009                     }
1010                 }
1011               else if (c == '[')
1012                 {
1013                   /* CDATA */
1014                   xml_append_cdata(ctx);
1015                 }
1016               else
1017                 xml_fatal(ctx, "Unexpected character after '<!'");
1018
1019             else if (c != '/')
1020               {
1021                 /* STag | EmptyElemTag */
1022                 xml_unget_char(ctx);
1023                 if (xml_flush_chars(ctx))
1024                   {
1025                     PULL_STATE(CHARS, CHARS_BEFORE_STAG);
1026                     xml_pop_chars(ctx);
1027                   }
1028
1029                 xml_push_element(ctx);
1030                 PULL(STAG);
1031                 if (ctx->flags & XML_EMPTY_ELEM_TAG)
1032                   goto pop_element;
1033               }
1034
1035             else
1036               {
1037                 /* ETag */
1038                 if (xml_flush_chars(ctx))
1039                   {
1040                     PULL_STATE(CHARS, CHARS_BEFORE_ETAG);
1041                     xml_pop_chars(ctx);
1042                   }
1043
1044                 xml_parse_etag(ctx);
1045 pop_element:
1046                 PULL(ETAG);
1047                 xml_pop_element(ctx);
1048                 if (!ctx->node)
1049                   goto epilog;
1050               }
1051           }
1052
1053 epilog:
1054         /* Misc* */
1055         TRACE(ctx, "entering epilog");
1056         while (1)
1057           {
1058             /* Epilog whitespace is the only place, where a valid document can reach EOF */
1059             if (setjmp(throw_buf))
1060               if (ctx->err_code == XML_ERR_EOF)
1061                 {
1062                   TRACE(ctx, "reached EOF");
1063                   ctx->state = XML_STATE_EOF;
1064                   if (ctx->h_document_end)
1065                     ctx->h_document_end(ctx);
1066       case XML_STATE_EOF:
1067                   ctx->err_code = 0;
1068                   ctx->err_msg = NULL;
1069                   return XML_STATE_EOF;
1070                 }
1071               else
1072                 goto error;
1073             xml_parse_white(ctx, 0);
1074             if (setjmp(throw_buf))
1075               goto error;
1076
1077             /* Misc */
1078             xml_parse_char(ctx, '<');
1079             xml_inc(ctx);
1080             if ((c = xml_get_char(ctx)) == '?')
1081               /* Processing instruction */
1082               if (!(ctx->flags & XML_REPORT_PIS))
1083                 xml_skip_pi(ctx);
1084               else
1085                 {
1086                   xml_push_pi(ctx);
1087                   PULL_STATE(PI, EPILOG_PI);
1088                   xml_pop_pi(ctx);
1089                 }
1090             else if (c == '!')
1091               {
1092                 xml_parse_char(ctx, '-');
1093                 /* Comment */
1094                 if (!(ctx->flags & XML_REPORT_COMMENTS))
1095                   xml_skip_comment(ctx);
1096                 else
1097                   {
1098                     xml_push_comment(ctx);
1099                     PULL_STATE(COMMENT, EPILOG_COMMENT);
1100                     xml_pop_comment(ctx);
1101                   }
1102               }
1103             else
1104               xml_fatal(ctx, "Syntax error in the epilog");
1105           }
1106
1107     }
1108   ASSERT(0);
1109 }
1110
1111 uns
1112 xml_parse(struct xml_context *ctx)
1113 {
1114   /* This cycle shoud run only once unless the user overrides the value of ctx->pull in a SAX handler */
1115   do
1116     {
1117       ctx->pull = 0;
1118     }
1119   while (xml_next(ctx));
1120   return ctx->err_code;
1121 }