Debian Codegraph @

cutl/xml/parser.cxx

raw
1 // file : cutl/xml/parser.cxx
2 // copyright : Copyright (c) 2009-2013 Code Synthesis Tools CC
3 // license : MIT; see accompanying LICENSE file
4
5 #include <new> // std::bad_alloc
6 #include <cassert>
7 #include <cstring> // std::strchr
8 #include <istream>
9 #include <ostream>
10 #include <sstream>
11
12 #include <cutl/xml/parser.hxx>
13
14 using namespace std;
15
16 namespace cutl
17 {
18 namespace xml
19 {
20 // parsing
21 //
22 parsing::
23 ~parsing () throw () {}
24
25 parsing::
26 parsing (const string& n,
27 unsigned long long l,
28 unsigned long long c,
29 const string& d)
30 : name_ (n), line_ (l), column_ (c), description_ (d)
31 {
32 init ();
33 }
34
35 parsing::
36 parsing (const parser& p, const std::string& d)
37 : name_ (p.input_name ()),
38 line_ (p.line ()),
39 column_ (p.column ()),
40 description_ (d)
41 {
42 init ();
43 }
44
45 void parsing::
46 init ()
47 {
48 ostringstream os;
49 if (!name_.empty ())
50 os << name_ << ':';
51 os << line_ << ':' << column_ << ": error: " << description_;
52 what_ = os.str ();
53 }
54
55 char const* parsing::
56 what () const throw ()
57 {
58 return what_.c_str ();
59 }
60
61 // parser::event_type
62 //
63 static const char* parser_event_str[] =
64 {
65 "start element",
66 "end element",
67 "start attribute",
68 "end attribute",
69 "characters",
70 "start namespace declaration",
71 "end namespace declaration",
72 "end of file"
73 };
74
75 ostream&
76 operator<< (ostream& os, parser::event_type e)
77 {
78 return os << parser_event_str[e];
79 }
80
81 // parser
82 //
83 parser::
84 ~parser ()
85 {
86 if (p_ != 0)
87 XML_ParserFree (p_);
88 }
89
90 parser::
91 parser (istream& is, const string& iname, feature_type f)
92 : is_ (is), iname_ (iname), feature_ (f),
93 depth_ (0), state_ (state_next), event_ (eof), queue_ (eof),
94 pqname_ (&qname_), pvalue_ (&value_),
95 attr_i_ (0), start_ns_i_ (0), end_ns_i_ (0)
96 {
97 if ((feature_ & receive_attributes_map) != 0 &&
98 (feature_ & receive_attributes_event) != 0)
99 feature_ &= ~receive_attributes_map;
100
101 // Allocate the parser. Make sure nothing else can throw after
102 // this call since otherwise we will leak it.
103 //
104 p_ = XML_ParserCreateNS (0, XML_Char (' '));
105
106 if (p_ == 0)
107 throw bad_alloc ();
108
109 // Get prefixes in addition to namespaces and local names.
110 //
111 XML_SetReturnNSTriplet (p_, true);
112
113 // Set handlers.
114 //
115 XML_SetUserData(p_, this);
116
117 if ((f & receive_elements) != 0)
118 {
119 XML_SetStartElementHandler (p_, &start_element_);
120 XML_SetEndElementHandler (p_, &end_element_);
121 }
122
123 if ((f & receive_characters) != 0)
124 XML_SetCharacterDataHandler (p_, &characters_);
125
126 if ((f & receive_namespace_decls) != 0)
127 XML_SetNamespaceDeclHandler (p_,
128 &start_namespace_decl_,
129 &end_namespace_decl_);
130 }
131
132 void parser::
133 handle_error ()
134 {
135 XML_Error e (XML_GetErrorCode (p_));
136
137 if (e == XML_ERROR_ABORTED)
138 {
139 // For now we only abort the parser in the characters_() handler.
140 //
141 switch (content ())
142 {
143 case empty:
144 throw parsing (*this, "character in empty content");
145 case complex:
146 throw parsing (*this, "character in complex content");
147 default:
148 assert (false);
149 }
150 }
151 else
152 throw parsing (iname_,
153 XML_GetCurrentLineNumber (p_),
154 XML_GetCurrentColumnNumber (p_),
155 XML_ErrorString (e));
156 }
157
158 struct stream_exception_controller
159 {
160 ~stream_exception_controller ()
161 {
162 istream::iostate s = is_.rdstate ();
163 s &= ~istream::failbit;
164
165 // If our error state (sans failbit) intersects with the
166 // exception state then that means we have an active
167 // exception and changing error/exception state will
168 // cause another to be thrown.
169 //
170 if (!(old_state_ & s))
171 {
172 // Clear failbit if it was caused by eof.
173 //
174 if (is_.fail () && is_.eof ())
175 is_.clear (s);
176
177 is_.exceptions (old_state_);
178 }
179 }
180
181 stream_exception_controller (istream& is)
182 : is_ (is), old_state_ (is_.exceptions ())
183 {
184 is_.exceptions (old_state_ & ~istream::failbit);
185 }
186
187 private:
188 stream_exception_controller (const stream_exception_controller&);
189
190 stream_exception_controller&
191 operator= (const stream_exception_controller&);
192
193 private:
194 istream& is_;
195 istream::iostate old_state_;
196 };
197
198 const string& parser::
199 attribute (const qname_type& qn) const
200 {
201 if (const element_entry* e = get_element ())
202 {
203 attribute_map_type::const_iterator i (e->attr_map_.find (qn));
204
205 if (i != e->attr_map_.end ())
206 {
207 if (!i->second.handled)
208 {
209 i->second.handled = true;
210 e->attr_unhandled_--;
211 }
212 return i->second.value;
213 }
214 }
215
216 throw parsing (*this, "attribute '" + qn.string () + "' expected");
217 }
218
219 string parser::
220 attribute (const qname_type& qn, const string& dv) const
221 {
222 if (const element_entry* e = get_element ())
223 {
224 attribute_map_type::const_iterator i (e->attr_map_.find (qn));
225
226 if (i != e->attr_map_.end ())
227 {
228 if (!i->second.handled)
229 {
230 i->second.handled = true;
231 e->attr_unhandled_--;
232 }
233 return i->second.value;
234 }
235 }
236
237 return dv;
238 }
239
240 bool parser::
241 attribute_present (const qname_type& qn) const
242 {
243 if (const element_entry* e = get_element ())
244 {
245 attribute_map_type::const_iterator i (e->attr_map_.find (qn));
246
247 if (i != e->attr_map_.end ())
248 {
249 if (!i->second.handled)
250 {
251 i->second.handled = true;
252 e->attr_unhandled_--;
253 }
254 return true;
255 }
256 }
257
258 return false;
259 }
260
261 void parser::
262 next_expect (event_type e)
263 {
264 if (next () != e)
265 throw parsing (*this, string (parser_event_str[e]) + " expected");
266 }
267
268 void parser::
269 next_expect (event_type e, const string& ns, const string& n)
270 {
271 if (next () != e || namespace_ () != ns || name () != n)
272 throw parsing (*this,
273 string (parser_event_str[e]) + " '" +
274 qname_type (ns, n).string () + "' expected");
275 }
276
277 const parser::element_entry* parser::
278 get_element () const
279 {
280 // The start_element_() Expat handler may have already provisioned
281 // an entry in the element stack. In this case, we need to get the
282 // one before it, if any.
283 //
284 const element_entry* r (0);
285 element_state::size_type n (element_state_.size ());
286 if (n != 0)
287 {
288 n--;
289 if (element_state_[n].depth == depth_)
290 r = &element_state_[n];
291 else if (n != 0 && element_state_[n].depth > depth_)
292 {
293 n--;
294 if (element_state_[n].depth == depth_)
295 r = &element_state_[n];
296 }
297 }
298 return r;
299 }
300
301 void parser::
302 pop_element ()
303 {
304 // Make sure there are no unhandled attributes left.
305 //
306 const element_entry& e (element_state_.back ());
307 if (e.attr_unhandled_ != 0)
308 {
309 // Find the first unhandled attribute and report it.
310 //
311 for (attribute_map_type::const_iterator i (e.attr_map_.begin ());
312 i != e.attr_map_.end (); ++i)
313 {
314 if (!i->second.handled)
315 throw parsing (
316 *this, "unexpected attribute '" + i->first.string () + "'");
317 }
318 assert (false);
319 }
320
321 element_state_.pop_back ();
322 }
323
324 parser::event_type parser::
325 next_ (bool peek)
326 {
327 event_type e (next_body ());
328
329 // Content-specific processing. Note that we handle characters in the
330 // characters_() Expat handler for two reasons. Firstly, it is faster
331 // to ignore the whitespaces at the source. Secondly, this allows us
332 // to distinguish between element and attribute characters. We can
333 // move this processing to the handler because the characters event
334 // is never queued.
335 //
336 switch (e)
337 {
338 case end_element:
339 {
340 // If this is a peek, then avoid popping the stack just yet.
341 // This way, the attribute map will still be valid until we
342 // call next().
343 //
344 if (!peek)
345 {
346 if (!element_state_.empty () &&
347 element_state_.back ().depth == depth_)
348 pop_element ();
349
350 depth_--;
351 }
352 break;
353 }
354 case start_element:
355 {
356 const element_entry* e (get_element ());
357 switch (e != 0 ? e->content : mixed)
358 {
359 case empty:
360 throw parsing (*this, "element in empty content");
361 case simple:
362 throw parsing (*this, "element in simple content");
363 default:
364 break;
365 }
366
367 // If this is a peek, then delay adjusting the depth.
368 //
369 if (!peek)
370 depth_++;
371
372 break;
373 }
374 default:
375 break;
376 }
377
378 return e;
379 }
380
381 parser::event_type parser::
382 next_body ()
383 {
384 // See if we have any start namespace declarations we need to return.
385 //
386 if (start_ns_i_ < start_ns_.size ())
387 {
388 // Based on the previous event determine what's the next one must be.
389 //
390 switch (event_)
391 {
392 case start_namespace_decl:
393 {
394 if (++start_ns_i_ == start_ns_.size ())
395 {
396 start_ns_i_ = 0;
397 start_ns_.clear ();
398 pqname_ = &qname_;
399 break; // No more declarations.
400 }
401 // Fall through.
402 }
403 case start_element:
404 {
405 event_ = start_namespace_decl;
406 pqname_ = &start_ns_[start_ns_i_];
407 return event_;
408 }
409 default:
410 {
411 assert (false);
412 return event_ = eof;
413 }
414 }
415 }
416
417 // See if we have any attributes we need to return as events.
418 //
419 if (attr_i_ < attr_.size ())
420 {
421 // Based on the previous event determine what's the next one must be.
422 //
423 switch (event_)
424 {
425 case start_attribute:
426 {
427 event_ = characters;
428 pvalue_ = &attr_[attr_i_].value;
429 return event_;
430 }
431 case characters:
432 {
433 event_ = end_attribute; // Name is already set.
434 return event_;
435 }
436 case end_attribute:
437 {
438 if (++attr_i_ == attr_.size ())
439 {
440 attr_i_ = 0;
441 attr_.clear ();
442 pqname_ = &qname_;
443 pvalue_ = &value_;
444 break; // No more attributes.
445 }
446 // Fall through.
447 }
448 case start_element:
449 case start_namespace_decl:
450 {
451 event_ = start_attribute;
452 pqname_ = &attr_[attr_i_].qname;
453 return event_;
454 }
455 default:
456 {
457 assert (false);
458 return event_ = eof;
459 }
460 }
461 }
462
463 // See if we have any end namespace declarations we need to return.
464 //
465 if (end_ns_i_ < end_ns_.size ())
466 {
467 // Based on the previous event determine what's the next one must be.
468 //
469 switch (event_)
470 {
471 case end_namespace_decl:
472 {
473 if (++end_ns_i_ == end_ns_.size ())
474 {
475 end_ns_i_ = 0;
476 end_ns_.clear ();
477 pqname_ = &qname_;
478 break; // No more declarations.
479 }
480 // Fall through.
481 }
482 // The end namespace declaration comes before the end element
483 // which means it can follow pretty much any other event.
484 //
485 default:
486 {
487 event_ = end_namespace_decl;
488 pqname_ = &end_ns_[end_ns_i_];
489 return event_;
490 }
491 }
492 }
493
494 // Check the queue.
495 //
496 if (queue_ != eof)
497 {
498 event_ = queue_;
499 queue_ = eof;
500 return event_;
501 }
502
503 XML_ParsingStatus ps;
504 XML_GetParsingStatus (p_, &ps);
505
506 switch (ps.parsing)
507 {
508 case XML_INITIALIZED:
509 {
510 // As if we finished the previous chunk.
511 break;
512 }
513 case XML_PARSING:
514 {
515 assert (false);
516 return event_ = eof;
517 }
518 case XML_FINISHED:
519 {
520 return event_ = eof;
521 }
522 case XML_SUSPENDED:
523 {
524 switch (XML_ResumeParser (p_))
525 {
526 case XML_STATUS_SUSPENDED:
527 {
528 // If the parser is again in the suspended state, then
529 // that means we have the next event.
530 //
531 return event_;
532 }
533 case XML_STATUS_OK:
534 {
535 // Otherwise, we need to get and parse the next chunk of data
536 // unless this was the last chunk, in which case this is eof.
537 //
538 if (ps.finalBuffer)
539 return event_ = eof;
540
541 break;
542 }
543 case XML_STATUS_ERROR:
544 handle_error ();
545 }
546
547 break;
548 }
549 }
550
551 // Get and parse the next chunk of data until we get the next event
552 // or reach eof.
553 //
554 event_ = eof;
555 XML_Status s;
556 do
557 {
558 const size_t cap (4096);
559
560 char* b (static_cast<char*> (XML_GetBuffer (p_, cap)));
561 if (b == 0)
562 throw bad_alloc ();
563
564 // Temporarily unset the exception failbit. Also clear the fail bit
565 // when we reset the old state if it was caused by eof.
566 //
567 {
568 stream_exception_controller sec (is_);
569 is_.read (b, static_cast<streamsize> (cap));
570 }
571
572 s = XML_ParseBuffer (p_, static_cast<int> (is_.gcount ()), is_.eof ());
573
574 if (s == XML_STATUS_ERROR)
575 handle_error ();
576
577 } while (s != XML_STATUS_SUSPENDED && !is_.eof ());
578
579 return event_;
580 }
581
582 static void
583 split_name (const XML_Char* s, qname& qn)
584 {
585 string& ns (qn.namespace_ ());
586 string& name (qn.name ());
587 string& prefix (qn.prefix ());
588
589 const char* p (strchr (s, ' '));
590
591 if (p == 0)
592 {
593 ns.clear ();
594 name = s;
595 prefix.clear ();
596 }
597 else
598 {
599 ns.assign (s, 0, p - s);
600
601 s = p + 1;
602 p = strchr (s, ' ');
603
604 if (p == 0)
605 {
606 name = s;
607 prefix.clear ();
608 }
609 else
610 {
611 name.assign (s, 0, p - s);
612 prefix = p + 1;
613 }
614 }
615 }
616
617 void XMLCALL parser::
618 start_element_ (void* v, const XML_Char* name, const XML_Char** atts)
619 {
620 parser& p (*static_cast<parser*> (v));
621
622 XML_ParsingStatus ps;
623 XML_GetParsingStatus (p.p_, &ps);
624
625 // Expat has a (mis)-feature of a possibily calling handlers even
626 // after the non-resumable XML_StopParser call.
627 //
628 if (ps.parsing == XML_FINISHED)
629 return;
630
631 // Cannot be a followup event.
632 //
633 assert (ps.parsing == XML_PARSING);
634
635 p.event_ = start_element;
636 split_name (name, p.qname_);
637
638 p.line_ = XML_GetCurrentLineNumber (p.p_);
639 p.column_ = XML_GetCurrentColumnNumber (p.p_);
640
641 // Handle attributes.
642 //
643 if (*atts != 0)
644 {
645 bool am ((p.feature_ & receive_attributes_map) != 0);
646 bool ae ((p.feature_ & receive_attributes_event) != 0);
647
648 // Provision an entry for this element.
649 //
650 element_entry* pe (0);
651 if (am)
652 {
653 p.element_state_.push_back (element_entry (p.depth_ + 1));
654 pe = &p.element_state_.back ();
655 }
656
657 if (am || ae)
658 {
659 for (; *atts != 0; atts += 2)
660 {
661 if (am)
662 {
663 qname_type qn;
664 split_name (*atts, qn);
665 attribute_map_type::value_type v (qn, attribute_value_type ());
666 v.second.value = *(atts + 1);
667 v.second.handled = false;
668 pe->attr_map_.insert (v);
669 }
670 else
671 {
672 p.attr_.push_back (attribute_type ());
673 split_name (*atts, p.attr_.back ().qname);
674 p.attr_.back ().value = *(atts + 1);
675 }
676 }
677
678 if (am)
679 pe->attr_unhandled_ = pe->attr_map_.size ();
680 }
681 }
682
683 XML_StopParser (p.p_, true);
684 }
685
686 void XMLCALL parser::
687 end_element_ (void* v, const XML_Char* name)
688 {
689 parser& p (*static_cast<parser*> (v));
690
691 XML_ParsingStatus ps;
692 XML_GetParsingStatus (p.p_, &ps);
693
694 // Expat has a (mis)-feature of a possibily calling handlers even
695 // after the non-resumable XML_StopParser call.
696 //
697 if (ps.parsing == XML_FINISHED)
698 return;
699
700 // This can be a followup event for empty elements (<foo/>). In this
701 // case the element name is already set.
702 //
703 if (ps.parsing != XML_PARSING)
704 p.queue_ = end_element;
705 else
706 {
707 // We may also have the end namespace declaration events which
708 // should come before the end element. If that's the case, then
709 // queue the end element and return the end namespace as the next
710 // event.
711 //
712 if (p.end_ns_i_ < p.end_ns_.size ())
713 {
714 p.event_ = end_namespace_decl;
715 p.queue_ = end_element;
716 }
717 else
718 p.event_ = end_element;
719
720 split_name (name, p.qname_);
721
722 p.line_ = XML_GetCurrentLineNumber (p.p_);
723 p.column_ = XML_GetCurrentColumnNumber (p.p_);
724
725 XML_StopParser (p.p_, true);
726 }
727 }
728
729 void XMLCALL parser::
730 characters_ (void* v, const XML_Char* s, int n)
731 {
732 parser& p (*static_cast<parser*> (v));
733
734 XML_ParsingStatus ps;
735 XML_GetParsingStatus (p.p_, &ps);
736
737 // Expat has a (mis)-feature of a possibily calling handlers even
738 // after the non-resumable XML_StopParser call.
739 //
740 if (ps.parsing == XML_FINISHED)
741 return;
742
743 // If this is empty or complex content, see if these are whitespaces.
744 //
745 switch (p.content ())
746 {
747 case empty:
748 case complex:
749 {
750 for (int i (0); i != n; ++i)
751 {
752 char c (s[i]);
753 if (c == 0x20 || c == 0x0A || c == 0x0D || c == 0x09)
754 continue;
755
756 // It would have been easier to throw the exception directly,
757 // however, the Expat code is most likely not exception safe.
758 //
759 p.line_ = XML_GetCurrentLineNumber (p.p_);
760 p.column_ = XML_GetCurrentColumnNumber (p.p_);
761 XML_StopParser (p.p_, false);
762 break;
763 }
764 return;
765 }
766 default:
767 break;
768 }
769
770 // This can be a followup event for another character event. In
771 // this case simply append the data.
772 //
773 if (ps.parsing != XML_PARSING)
774 {
775 assert (p.event_ == characters);
776 p.value_.append (s, n);
777 }
778 else
779 {
780 p.event_ = characters;
781 p.value_.assign (s, n);
782
783 p.line_ = XML_GetCurrentLineNumber (p.p_);
784 p.column_ = XML_GetCurrentColumnNumber (p.p_);
785
786 XML_StopParser (p.p_, true);
787 }
788 }
789
790 void XMLCALL parser::
791 start_namespace_decl_ (void* v, const XML_Char* prefix, const XML_Char* ns)
792 {
793 parser& p (*static_cast<parser*> (v));
794
795 XML_ParsingStatus ps;
796 XML_GetParsingStatus (p.p_, &ps);
797
798 // Expat has a (mis)-feature of a possibily calling handlers even
799 // after the non-resumable XML_StopParser call.
800 //
801 if (ps.parsing == XML_FINISHED)
802 return;
803
804 p.start_ns_.push_back (qname_type ());
805 p.start_ns_.back ().prefix () = (prefix != 0 ? prefix : "");
806 p.start_ns_.back ().namespace_ () = (ns != 0 ? ns : "");
807 }
808
809 void XMLCALL parser::
810 end_namespace_decl_ (void* v, const XML_Char* prefix)
811 {
812 parser& p (*static_cast<parser*> (v));
813
814 XML_ParsingStatus ps;
815 XML_GetParsingStatus (p.p_, &ps);
816
817 // Expat has a (mis)-feature of a possibily calling handlers even
818 // after the non-resumable XML_StopParser call.
819 //
820 if (ps.parsing == XML_FINISHED)
821 return;
822
823 p.end_ns_.push_back (qname_type ());
824 p.end_ns_.back ().prefix () = (prefix != 0 ? prefix : "");
825 }
826 }
827 }