]> mj.ucw.cz Git - libucw.git/blob - sherlock/xml/parse.c
25ab84cbddaed0ba5bf5da4565cb18f79d34661b
[libucw.git] / sherlock / xml / parse.c
1 /*
2  *      Sherlock Library -- A simple XML parser
3  *
4  *      (c) 2007 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/common.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);
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);
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 data ***/
260
261 static inline uns
262 xml_flush_chars(struct xml_context *ctx)
263 {
264   struct fastbuf *fb = &ctx->chars;
265   if (fb->bufend == fb->buffer)
266     return 0;
267   TRACE(ctx, "flush_chars");
268   struct xml_node *n = ctx->node;
269   n->text = xml_end_chars(ctx, &n->len);
270   n->len = fb->bufend - fb->buffer;
271   if ((ctx->flags & XML_REPORT_CHARS) && ctx->h_chars)
272     ctx->h_chars(ctx);
273   return 1;
274 }
275
276 static inline void
277 xml_pop_chars(struct xml_context *ctx)
278 {
279   xml_pop_dom(ctx, !(ctx->flags & XML_ALLOC_CHARS));
280   TRACE(ctx, "pop_chars");
281 }
282
283 static inline void
284 xml_append_chars(struct xml_context *ctx)
285 {
286   TRACE(ctx, "append_chars");
287   struct fastbuf *out = &ctx->chars;
288   while (xml_get_char(ctx) != '<')
289     if (xml_last_char(ctx) == '&')
290       {
291         xml_inc(ctx);
292         xml_parse_ref(ctx);
293       }
294     else
295       bput_utf8_32(out, xml_last_char(ctx));
296   xml_unget_char(ctx);
297 }
298
299 /*** CDATA sections ***/
300
301 static void
302 xml_push_cdata(struct xml_context *ctx)
303 {
304   TRACE(ctx, "push_cdata");
305   /* CDSect :== '<![CDATA[' (Char* - (Char* ']]>' Char*)) ']]>'
306    * Already parsed: '<![' */
307   xml_parse_seq(ctx, "CDATA[");
308   struct xml_node *n = xml_push_dom(ctx);
309   n->type = XML_NODE_CHARS;
310   char *p = mp_start_noalign(ctx->pool, 7);
311   while (1)
312     {
313       if (xml_get_char(ctx) == ']')
314         {
315           if (xml_get_char(ctx) == ']')
316             if (xml_get_char(ctx) == '>')
317               break;
318             else
319               *p++ = ']';
320           *p++ = ']';
321         }
322       p = utf8_32_put(p, xml_last_char(ctx));
323       p = mp_spread(ctx->pool, p, 7);
324     }
325   *p = 0;
326   n->len = p - (char *)mp_ptr(ctx->pool);
327   n->text = mp_end(ctx->pool, p + 1);
328   if ((ctx->flags & XML_REPORT_CHARS) && ctx->h_cdata)
329     ctx->h_cdata(ctx);
330 }
331
332 static void
333 xml_pop_cdata(struct xml_context *ctx)
334 {
335   xml_pop_dom(ctx, !(ctx->flags & XML_ALLOC_CHARS));
336   xml_dec(ctx);
337   TRACE(ctx, "pop_cdata");
338 }
339
340 static void
341 xml_append_cdata(struct xml_context *ctx)
342 {
343   TRACE(ctx, "append_cdata");
344   xml_parse_seq(ctx, "CDATA[");
345   struct fastbuf *out = &ctx->chars;
346   while (1)
347     {
348       if (xml_get_char(ctx) == ']')
349         {
350           if (xml_get_char(ctx) == ']')
351             if (xml_get_char(ctx) == '>')
352               break;
353             else
354               bputc(out, ']');
355           bputc(out, ']');
356         }
357       bput_utf8_32(out, xml_last_char(ctx));
358     }
359   xml_dec(ctx);
360 }
361
362 static void UNUSED
363 xml_skip_cdata(struct xml_context *ctx)
364 {
365   TRACE(ctx, "skip_cdata");
366   xml_parse_seq(ctx, "CDATA[");
367   while (xml_get_char(ctx) != ']' || xml_get_char(ctx) != ']' || xml_get_char(ctx) != '>');
368   xml_dec(ctx);
369 }
370
371 /*** Character references ***/
372
373 uns
374 xml_parse_char_ref(struct xml_context *ctx)
375 {
376   TRACE(ctx, "parse_char_ref");
377   /* CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
378    * Already parsed: '&#' */
379   uns v = 0;
380   if (xml_get_char(ctx) == 'x')
381     {
382       if (!(xml_get_cat(ctx) & XML_CHAR_XDIGIT))
383         {
384           xml_error(ctx, "Expected a hexadecimal value of character reference");
385           goto recover;
386         }
387       do
388         {
389           v = (v << 4) + Cxvalue(xml_last_char(ctx));
390         }
391       while (v < 0x110000 && (xml_get_cat(ctx) & XML_CHAR_XDIGIT));
392     }
393   else
394     {
395       if (!(xml_last_cat(ctx) & XML_CHAR_DIGIT))
396         {
397           xml_error(ctx, "Expected a numeric value of character reference");
398           goto recover;
399         }
400       do
401         {
402           v = v * 10 + xml_last_char(ctx) - '0';
403         }
404       while (v < 0x110000 && (xml_get_cat(ctx) & XML_CHAR_DIGIT));
405     }
406   uns cat = xml_char_cat(v);
407   if (!(cat & ctx->cat_unrestricted))
408     {
409       xml_error(ctx, "Character reference out of range");
410       goto recover;
411     }
412   if (xml_last_char(ctx) == ';')
413     {
414       xml_dec(ctx);
415       return v;
416     }
417   xml_error(ctx, "Expected ';'");
418 recover:
419   while (xml_last_char(ctx) != ';')
420     xml_get_char(ctx);
421   xml_dec(ctx);
422   return UNI_REPLACEMENT;
423 }
424
425 /*** References to general entities ***/
426
427 void
428 xml_parse_ref(struct xml_context *ctx)
429 {
430   /* Reference ::= EntityRef | CharRef
431    * EntityRef ::= '&' Name ';'
432    * Already parsed: '&' */
433   struct fastbuf *out = &ctx->chars;
434   if (xml_peek_char(ctx) == '#')
435     {
436       xml_skip_char(ctx);
437       bput_utf8_32(out, xml_parse_char_ref(ctx));
438     }
439   else
440     {
441       TRACE(ctx, "parse_ge_ref");
442       struct mempool_state state;
443       mp_save(ctx->stack, &state);
444       char *name = xml_parse_name(ctx, ctx->stack);
445       xml_parse_char(ctx, ';');
446       struct xml_dtd_ent *ent = xml_dtd_find_ent(ctx, name);
447       if (!ent)
448         {
449           xml_error(ctx, "Unknown entity &%s;", name);
450           bputc(out, '&');
451           bputs(out, name);
452           bputc(out, ';');
453         }
454       else if (ent->flags & XML_DTD_ENT_TRIVIAL)
455         {
456           TRACE(ctx, "Trivial entity &%s;", name);
457           bwrite(out, ent->text, ent->len);
458         }
459       else
460         {
461           TRACE(ctx, "Pushed entity &%s;", name);
462           mp_restore(ctx->stack, &state);
463           xml_dec(ctx);
464           xml_push_entity(ctx, ent);
465           return;
466         }
467       mp_restore(ctx->stack, &state);
468       xml_dec(ctx);
469     }
470 }
471
472 /*** Attribute values ***/
473
474 char *
475 xml_parse_attr_value(struct xml_context *ctx, struct xml_dtd_attr *attr UNUSED)
476 {
477   TRACE(ctx, "parse_attr_value");
478   /* AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'" */
479   /* FIXME:
480    * -- copying from ctx->chars to ctx->pool is not necessary, we could directly write to ctx->pool
481    * -- berare quotes inside parased entities
482    * -- check value constrains / normalize value */
483   struct mempool_state state;
484   uns quote = xml_parse_quote(ctx);
485   mp_save(ctx->stack, &state);
486   xml_start_chars(ctx);
487   struct fastbuf *out = &ctx->chars;
488   while (1)
489     {
490       uns c = xml_get_char(ctx);
491       if (c == '&')
492         {
493           xml_inc(ctx);
494           xml_parse_ref(ctx);
495         }
496       else if (c == quote) // FIXME: beware quotes inside parsed entities
497         break;
498       else if (c == '<')
499         xml_error(ctx, "Attribute value must not contain '<'");
500       else if (xml_last_cat(ctx) & XML_CHAR_WHITE)
501         bputc(out, ' ');
502       else
503         bput_utf8_32(out, c);
504     }
505   mp_restore(ctx->stack, &state);
506   uns len;
507   return xml_end_chars(ctx, &len);
508 }
509
510 /*** Attributes ***/
511
512 struct xml_attrs_table;
513
514 static inline uns
515 xml_attrs_hash(struct xml_attrs_table *t UNUSED, struct xml_node *e, char *n)
516 {
517   return hash_pointer(e) ^ hash_string(n);
518 }
519
520 static inline int
521 xml_attrs_eq(struct xml_attrs_table *t UNUSED, struct xml_node *e1, char *n1, struct xml_node *e2, char *n2)
522 {
523   return (e1 == e2) && !strcmp(n1, n2);
524 }
525
526 static inline void
527 xml_attrs_init_key(struct xml_attrs_table *t UNUSED, struct xml_attr *a, struct xml_node *e, char *name)
528 {
529   a->elem = e;
530   a->name = name;
531   a->val = NULL;
532   slist_add_tail(&e->attrs, &a->n);
533 }
534
535 #define HASH_PREFIX(x) xml_attrs_##x
536 #define HASH_NODE struct xml_attr
537 #define HASH_KEY_COMPLEX(x) x elem, x name
538 #define HASH_KEY_DECL struct xml_node *elem, char *name
539 #define HASH_TABLE_DYNAMIC
540 #define HASH_GIVE_EQ
541 #define HASH_GIVE_HASHFN
542 #define HASH_GIVE_INIT_KEY
543 #define HASH_WANT_CLEANUP
544 #define HASH_WANT_REMOVE
545 #define HASH_WANT_LOOKUP
546 #define HASH_WANT_FIND
547 #define HASH_GIVE_ALLOC
548 XML_HASH_GIVE_ALLOC
549 #include "lib/hashtable.h"
550
551 static void
552 xml_parse_attr(struct xml_context *ctx)
553 {
554   TRACE(ctx, "parse_attr");
555   /* Attribute ::= Name Eq AttValue */
556   /* FIXME:
557    * -- memory management
558    * -- DTD */
559   struct xml_node *e = ctx->node;
560   char *n = xml_parse_name(ctx, ctx->pool);
561   struct xml_attr *a = xml_attrs_lookup(ctx->tab_attrs, e, n);
562   xml_parse_eq(ctx);
563   char *v = xml_parse_attr_value(ctx, NULL);
564   if (a->val)
565     xml_error(ctx, "Attribute %s is not unique", n);
566   else
567     a->val = v;
568 }
569
570 struct xml_attr *
571 xml_attr_find(struct xml_context *ctx, struct xml_node *node, char *name)
572 {
573   return xml_attrs_find(ctx->tab_attrs, node, name);
574 }
575
576 void
577 xml_attrs_table_init(struct xml_context *ctx)
578 {
579   xml_attrs_init(ctx->tab_attrs = xml_hash_new(ctx->pool, sizeof(struct xml_attrs_table)));
580 }
581
582 void
583 xml_attrs_table_cleanup(struct xml_context *ctx)
584 {
585   xml_attrs_cleanup(ctx->tab_attrs);
586 }
587
588 /*** Elements ***/
589
590 static void
591 xml_push_element(struct xml_context *ctx)
592 {
593   TRACE(ctx, "push_element");
594   /* EmptyElemTag | STag
595    * EmptyElemTag ::= '<' Name (S  Attribute)* S? '/>'
596    * STag ::= '<' Name (S  Attribute)* S? '>'
597    * Already parsed: '<' */
598   struct xml_node *e = xml_push_dom(ctx);
599   clist_init(&e->sons);
600   e->type = XML_NODE_ELEM;
601   e->name = xml_parse_name(ctx, ctx->pool);
602   slist_init(&e->attrs);
603   if (!e->parent)
604     {
605       ctx->root = e;
606       if (ctx->doctype && strcmp(e->name, ctx->doctype))
607         xml_error(ctx, "The root element %s does not match the document type %s", e->name, ctx->doctype);
608     }
609   while (1)
610     {
611       uns white = xml_parse_white(ctx, 0);
612       uns c = xml_get_char(ctx);
613       if (c == '/')
614         {
615           xml_parse_char(ctx, '>');
616           ctx->flags |= XML_EMPTY_ELEM_TAG;
617           break;
618         }
619       else if (c == '>')
620         break;
621       else if (!white)
622         xml_fatal_expected_white(ctx);
623       xml_unget_char(ctx);
624       xml_parse_attr(ctx);
625     }
626   if ((ctx->flags & XML_REPORT_TAGS) && ctx->h_stag)
627     ctx->h_stag(ctx);
628 }
629
630 static void
631 xml_pop_element(struct xml_context *ctx)
632 {
633   TRACE(ctx, "pop_element");
634   if ((ctx->flags & XML_REPORT_TAGS) && ctx->h_etag)
635     ctx->h_etag(ctx);
636   struct xml_node *e = ctx->node;
637   uns free = !(ctx->flags & XML_ALLOC_TAGS);
638   if (free)
639     {
640       if (!e->parent)
641         ctx->root = NULL;
642       /* Restore hash table of attributes */
643       SLIST_FOR_EACH(struct xml_attr *, a, e->attrs)
644         xml_attrs_remove(ctx->tab_attrs, a);
645       struct xml_node *n;
646       while (n = clist_head(&e->sons))
647         {
648           if (n->type == XML_NODE_ELEM)
649             {
650               SLIST_FOR_EACH(struct xml_attr *, a, n->attrs)
651                 xml_attrs_remove(ctx->tab_attrs, a);
652               clist_insert_list_after(&n->sons, &n->n);
653             }
654           clist_remove(&n->n);
655         }
656     }
657   xml_pop_dom(ctx, free);
658   xml_dec(ctx);
659 }
660
661 static void
662 xml_parse_etag(struct xml_context *ctx)
663 {
664  /* ETag ::= '</' Name S? '>'
665   * Already parsed: '<' */
666   struct xml_node *e = ctx->node;
667   ASSERT(e);
668   char *n = e->name;
669   while (*n)
670     {
671       uns c;
672       n = utf8_32_get(n, &c);
673       if (xml_get_char(ctx) != c)
674         goto recover;
675     }
676   xml_parse_white(ctx, 0);
677   if (xml_get_char(ctx) != '>')
678     {
679 recover:
680       xml_error(ctx, "Invalid ETag, expected </%s>", e->name);
681       while (xml_get_char(ctx) != '>');
682     }
683   xml_dec(ctx);
684 }
685
686 /*** Document type declaration ***/
687
688 static void
689 xml_parse_doctype_decl(struct xml_context *ctx)
690 {
691   TRACE(ctx, "parse_doctype_decl");
692   /* doctypedecl ::= '<!DOCTYPE' S  Name (S  ExternalID)? S? ('[' intSubset ']' S?)? '>'
693    * Already parsed: '<!'
694    * Terminated before '[' or '>' */
695   if (ctx->doctype)
696     xml_fatal(ctx, "Multiple document types not allowed");
697   xml_parse_seq(ctx, "DOCTYPE");
698   xml_parse_white(ctx, 1);
699   ctx->doctype = xml_parse_name(ctx, ctx->pool);
700   TRACE(ctx, "doctype=%s", ctx->doctype);
701   uns c;
702   if (xml_parse_white(ctx, 0) && ((c = xml_peek_char(ctx)) == 'S' || c == 'P'))
703     {
704       if (c == 'S')
705         {
706           xml_parse_seq(ctx, "SYSTEM");
707           xml_parse_white(ctx, 1);
708           ctx->system_id = xml_parse_system_literal(ctx, ctx->pool);
709         }
710       else
711         {
712           xml_parse_seq(ctx, "PUBLIC");
713           xml_parse_white(ctx, 1);
714           ctx->public_id = xml_parse_pubid_literal(ctx, ctx->pool);
715           xml_parse_white(ctx, 1);
716           ctx->system_id = xml_parse_system_literal(ctx, ctx->pool);
717         }
718       xml_parse_white(ctx, 0);
719       ctx->flags |= XML_HAS_EXTERNAL_SUBSET;
720     }
721   if (xml_peek_char(ctx) == '[')
722     ctx->flags |= XML_HAS_INTERNAL_SUBSET;
723   if (ctx->h_doctype_decl)
724     ctx->h_doctype_decl(ctx);
725 }
726
727
728
729 ///////////////////////////////////////////////////////////////////////////////////////////////////////////
730
731 /* DTD: Internal subset */
732
733 static void
734 xml_parse_internal_subset(struct xml_context *ctx)
735 {
736   // FIXME: comments/pi have no parent
737   /* '[' intSubset ']'
738    * intSubset :== (markupdecl | DeclSep)
739    * Already parsed: ']' */
740   while (1)
741     {
742       xml_parse_white(ctx, 0);
743       uns c = xml_get_char(ctx);
744       xml_inc(ctx);
745       if (c == '<')
746         if ((c = xml_get_char(ctx)) == '!')
747           switch (c = xml_get_char(ctx))
748             {
749               case '-':
750                 xml_push_comment(ctx);
751                 xml_pop_comment(ctx);
752                 break;
753               case 'N':
754                 xml_parse_seq(ctx, "OTATION");
755                 xml_parse_notation_decl(ctx);
756                 break;
757               case 'E':
758                 if ((c = xml_get_char(ctx)) == 'N')
759                   {
760                     xml_parse_seq(ctx, "TITY");
761                     xml_parse_entity_decl(ctx);
762                   }
763                 else if (c == 'L')
764                   {
765                     xml_parse_seq(ctx, "EMENT");
766                     xml_parse_element_decl(ctx);
767                   }
768                 else
769                   goto invalid_markup;
770                 break;
771               case 'A':
772                 xml_parse_seq(ctx, "TTLIST");
773                 xml_parse_attr_list_decl(ctx);
774                 break;
775               default:
776                 goto invalid_markup;
777             }
778         else if (c == '?')
779           {
780             xml_push_pi(ctx);
781             xml_pop_pi(ctx);
782           }
783         else
784           goto invalid_markup;
785       else if (c == '%')
786         xml_parse_pe_ref(ctx);
787       else if (c == ']')
788         break;
789       else
790         goto invalid_markup;
791     }
792   xml_dec(ctx);
793   xml_dec(ctx);
794   return;
795 invalid_markup:
796   xml_fatal(ctx, "Invalid markup in the internal subset");
797 }
798
799 /*** The State Machine ***/
800
801 uns
802 xml_next(struct xml_context *ctx)
803 {
804   /* A nasty state machine */
805
806 #define PULL(x) do { if (ctx->pull & XML_PULL_##x) return ctx->state = XML_STATE_##x; case XML_STATE_##x: ; } while (0)
807 #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)
808
809   TRACE(ctx, "xml_next (state=%u)", ctx->state);
810   jmp_buf throw_buf;
811   ctx->throw_buf = &throw_buf;
812   if (setjmp(throw_buf))
813     {
814 error:
815       if (ctx->err_code == XML_ERR_EOF && ctx->h_fatal)
816         ctx->h_fatal(ctx);
817       TRACE(ctx, "raised fatal error");
818       return ctx->state = XML_STATE_EOF;
819     }
820   uns c;
821   switch (ctx->state)
822     {
823       case XML_STATE_START:
824         TRACE(ctx, "entering prolog");
825         if (ctx->h_document_start)
826           ctx->h_document_start(ctx);
827         /* XMLDecl */
828         xml_refill(ctx);
829         if (ctx->h_xml_decl)
830           ctx->h_xml_decl(ctx);
831         PULL(XML_DECL);
832
833         /* Misc* (doctypedecl Misc*)? */
834         while (1)
835           {
836             xml_parse_white(ctx, 0);
837             xml_parse_char(ctx, '<');
838             xml_inc(ctx);
839             if ((c = xml_get_char(ctx)) == '?')
840               /* Processing intruction */
841               if (!(ctx->flags & XML_REPORT_PIS))
842                 xml_skip_pi(ctx);
843               else
844                 {
845                   xml_push_pi(ctx);
846                   PULL_STATE(PI, PROLOG_PI);
847                   xml_pop_pi(ctx);
848                 }
849             else if (c != '!')
850               {
851                 /* Found the root tag */
852                 xml_unget_char(ctx);
853                 goto first_tag;
854               }
855             else if (xml_get_char(ctx) == '-')
856               if (!(ctx->flags & XML_REPORT_COMMENTS))
857                 xml_skip_comment(ctx);
858               else
859                 {
860                   xml_push_comment(ctx);
861                   PULL_STATE(COMMENT, PROLOG_COMMENT);
862                   xml_pop_comment(ctx);
863                 }
864             else
865               {
866                 /* DocTypeDecl */
867                 xml_unget_char(ctx);
868                 xml_parse_doctype_decl(ctx);
869                 PULL(DOCTYPE_DECL);
870                 if (xml_peek_char(ctx) == '[')
871                   {
872                     xml_skip_char(ctx);
873                     xml_inc(ctx);
874                     if (ctx->flags & XML_PARSE_DTD)
875                       {
876                         xml_dtd_init(ctx);
877                         if (ctx->h_dtd_start)
878                           ctx->h_dtd_start(ctx);
879                         // FIXME: pu;; iface?
880                         xml_parse_internal_subset(ctx);
881                         // FIXME: external subset
882                         if (ctx->h_dtd_end)
883                           ctx->h_dtd_end(ctx);
884                       }
885                     else
886                       xml_skip_internal_subset(ctx);
887                   }
888                 xml_parse_white(ctx, 0);
889                 xml_parse_char(ctx, '>');
890                 xml_dec(ctx);
891               }
892           }
893
894       case XML_STATE_CHARS:
895
896         while (1)
897           {
898             if (xml_peek_char(ctx) != '<')
899               {
900                 /* CharData */
901                 xml_append_chars(ctx);
902                 continue;
903               }
904             else
905               xml_skip_char(ctx);
906             xml_inc(ctx);
907 first_tag:
908
909             if ((c = xml_get_char(ctx)) == '?')
910               {
911                 /* PI */
912                 if (!(ctx->flags & (XML_REPORT_PIS | XML_ALLOC_PIS)))
913                   xml_skip_pi(ctx);
914                 else
915                   {
916                     if (xml_flush_chars(ctx))
917                       {
918                         PULL_STATE(CHARS, CHARS_BEFORE_PI);
919                         xml_pop_chars(ctx);
920                       }
921                     xml_push_pi(ctx);
922                     PULL(PI);
923                     xml_pop_pi(ctx);
924                   }
925               }
926
927             else if (c == '!')
928               if ((c = xml_get_char(ctx)) == '-')
929                 {
930                   /* Comment */
931                   if (!(ctx->flags & (XML_REPORT_COMMENTS | XML_ALLOC_COMMENTS)))
932                     xml_skip_comment(ctx);
933                   else
934                     {
935                       if (xml_flush_chars(ctx))
936                         {
937                           PULL_STATE(CHARS, CHARS_BEFORE_COMMENT);
938                           xml_pop_chars(ctx);
939                         }
940                       xml_push_comment(ctx);
941                       PULL(COMMENT);
942                       xml_pop_comment(ctx);
943                     }
944                 }
945               else if (c == '[')
946                 {
947                   /* CDATA */
948                   if (!(ctx->flags & XML_UNFOLD_CDATA))
949                     xml_append_cdata(ctx);
950                   else
951                     {
952                       if (xml_flush_chars(ctx))
953                         {
954                           PULL_STATE(CHARS, CHARS_BEFORE_CDATA);
955                           xml_pop_chars(ctx);
956                         }
957                       xml_push_cdata(ctx);
958                       PULL(CDATA);
959                       xml_pop_cdata(ctx);
960                     }
961                 }
962               else
963                 xml_fatal(ctx, "Unexpected character after '<!'");
964
965             else if (c != '/')
966               {
967                 /* STag | EmptyElemTag */
968                 xml_unget_char(ctx);
969                 if (xml_flush_chars(ctx))
970                   {
971                     PULL_STATE(CHARS, CHARS_BEFORE_STAG);
972                     xml_pop_chars(ctx);
973                   }
974
975                 xml_push_element(ctx);
976                 PULL(STAG);
977                 if (ctx->flags & XML_EMPTY_ELEM_TAG)
978                   goto pop_element;
979               }
980
981             else
982               {
983                 /* ETag */
984                 if (xml_flush_chars(ctx))
985                   {
986                     PULL_STATE(CHARS, CHARS_BEFORE_ETAG);
987                     xml_pop_chars(ctx);
988                   }
989
990                 xml_parse_etag(ctx);
991 pop_element:
992                 PULL(ETAG);
993                 xml_pop_element(ctx);
994                 if (!ctx->node)
995                   goto epilog;
996               }
997           }
998
999 epilog:
1000         /* Misc* */
1001         TRACE(ctx, "entering epilog");
1002         while (1)
1003           {
1004             /* Epilog whitespace is the only place, where a valid document can reach EOF */
1005             if (setjmp(throw_buf))
1006               if (ctx->err_code == XML_ERR_EOF)
1007                 {
1008                   TRACE(ctx, "reached EOF");
1009                   ctx->state = XML_STATE_EOF;
1010                   if (ctx->h_document_end)
1011                     ctx->h_document_end(ctx);
1012       case XML_STATE_EOF:
1013                   ctx->err_code = 0;
1014                   ctx->err_msg = NULL;
1015                   return XML_STATE_EOF;
1016                 }
1017               else
1018                 goto error;
1019             xml_parse_white(ctx, 0);
1020             if (setjmp(throw_buf))
1021               goto error;
1022
1023             /* Misc */
1024             xml_parse_char(ctx, '<');
1025             xml_inc(ctx);
1026             if ((c = xml_get_char(ctx)) == '?')
1027               /* Processing instruction */
1028               if (!(ctx->flags & XML_REPORT_PIS))
1029                 xml_skip_pi(ctx);
1030               else
1031                 {
1032                   xml_push_pi(ctx);
1033                   PULL_STATE(PI, EPILOG_PI);
1034                   xml_pop_pi(ctx);
1035                 }
1036             else if (c == '!')
1037               {
1038                 xml_parse_char(ctx, '-');
1039                 /* Comment */
1040                 if (!(ctx->flags & XML_REPORT_COMMENTS))
1041                   xml_skip_comment(ctx);
1042                 else
1043                   {
1044                     xml_push_comment(ctx);
1045                     PULL_STATE(COMMENT, EPILOG_COMMENT);
1046                     xml_pop_comment(ctx);
1047                   }
1048               }
1049             else
1050               xml_fatal(ctx, "Syntax error in the epilog");
1051           }
1052
1053     }
1054   ASSERT(0);
1055 }
1056
1057 uns
1058 xml_parse(struct xml_context *ctx)
1059 {
1060   /* This cycle shoud run only once unless the user overrides the value of ctx->pull in a SAX handler */
1061   do
1062     {
1063       ctx->pull = 0;
1064     }
1065   while (xml_next(ctx));
1066   return ctx->err_code;
1067 }