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
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef INCLUDED_ORCUS_SAX_PARSER_HPP
#define INCLUDED_ORCUS_SAX_PARSER_HPP
#include "sax_parser_base.hpp"
#include <string_view>
#include <cstdint>
namespace orcus {
struct sax_parser_default_config
{
/**
* An integer value representing a baseline XML version. A value of 10
* corresponds with version 1.0 whereas a value of 11 corresponds with
* version 1.1.
*/
static constexpr uint8_t baseline_version = 10;
};
class sax_handler
{
public:
/**
* Called when a doctype declaration <!DOCTYPE ... > is encountered.
*
* @param dtd struct containing doctype declaration data.
*/
void doctype(const orcus::sax::doctype_declaration& dtd)
{
(void)dtd;
}
/**
* Called when <?... is encountered, where the '...' may be an
* arbitraray dentifier. One common declaration is <?xml which is
* typically given at the start of an XML stream.
*
* @param decl name of the identifier.
*/
void start_declaration(std::string_view decl)
{
(void)decl;
}
/**
* Called when the closing tag (>) of a <?... ?> is encountered.
*
* @param decl name of the identifier.
*/
void end_declaration(std::string_view decl)
{
(void)decl;
}
/**
* Called at the start of each element.
*
* @param elem information of the element being parsed.
*/
void start_element(const orcus::sax::parser_element& elem)
{
(void)elem;
}
/**
* Called at the end of each element.
*
* @param elem information of the element being parsed.
*/
void end_element(const orcus::sax::parser_element& elem)
{
(void)elem;
}
/**
* Called when a segment of a text content is parsed. Each text content
* is a direct child of an element, which may have multiple child contents
* when the element also has a child element that are direct sibling to
* the text contents or the text contents are splitted by a comment.
*
* @param val value of the text content.
* @param transient when true, the text content has been converted and is
* stored in a temporary buffer due to presence of one or
* more encoded characters, in which case <em>the passed
* text value needs to be either immediately converted to
* a non-text value or be interned within the scope of
* the callback</em>.
*/
void characters(std::string_view val, bool transient)
{
(void)val; (void)transient;
}
/**
* Called upon parsing of an attribute of an element. Note that <em>when
* the attribute's transient flag is set, the attribute value is stored in
* a temporary buffer due to presence of one or more encoded characters,
* and must be processed within the scope of the callback</em>.
*
* @param attr struct containing attribute information.
*/
void attribute(const orcus::sax::parser_attribute& attr)
{
(void)attr;
}
};
/**
* SAX parser for XML documents.
*
* This parser is barebone in that it only parses the document and picks up
* all encountered elements and attributes without checking proper element
* pairs. The user is responsible for checking whether or not the document is
* well-formed in terms of element scopes.
*
* This parser additionally records the begin and end offset positions of each
* element.
*
* @tparam HandlerT Handler type with member functions for event callbacks.
* Refer to @ref sax_handler.
* @tparam ConfigT Parser configuration.
*/
template<typename HandlerT, typename ConfigT = sax_parser_default_config>
class sax_parser : public sax::parser_base
{
public:
typedef HandlerT handler_type;
typedef ConfigT config_type;
sax_parser(std::string_view content, handler_type& handler);
~sax_parser() = default;
void parse();
private:
/**
* Parse XML header that occurs at the beginning of every XML stream i.e.
* <?xml version="..." encoding="..." ?>
*/
void header();
void body();
void element();
void element_open(std::ptrdiff_t begin_pos);
void element_close(std::ptrdiff_t begin_pos);
void special_tag();
void declaration(const char* name_check);
void cdata();
void doctype();
void characters();
void attribute();
private:
handler_type& m_handler;
};
template<typename HandlerT, typename ConfigT>
sax_parser<HandlerT,ConfigT>::sax_parser(std::string_view content, handler_type& handler) :
sax::parser_base(content.data(), content.size()),
m_handler(handler)
{
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::parse()
{
m_nest_level = 0;
mp_char = mp_begin;
header();
skip_space_and_control();
body();
assert(m_buffer_pos == 0);
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::header()
{
// we don't handle multi byte encodings so we can just skip bom entry if exists.
skip_bom();
// Allow leading whitespace in the XML stream.
// TODO : Make this configurable since strictly speaking such an XML
// sttream is invalid.
skip_space_and_control();
if (!has_char() || cur_char() != '<')
throw malformed_xml_error("xml file must begin with '<'.", offset());
if (config_type::baseline_version >= 11)
{
// XML version 1.1 requires a header declaration whereas in 1.0 it's
// optional.
if (next_char_checked() != '?')
throw malformed_xml_error("xml file must begin with '<?'.", offset());
declaration("xml");
}
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::body()
{
while (has_char())
{
if (cur_char() == '<')
{
element();
if (!m_root_elem_open)
// Root element closed. Stop parsing.
return;
}
else if (m_nest_level)
// Call characters only when in xml hierarchy.
characters();
else
next();
}
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::element()
{
assert(cur_char() == '<');
std::ptrdiff_t pos = offset();
char c = next_char_checked();
switch (c)
{
case '/':
element_close(pos);
return;
case '!':
special_tag();
return;
case '?':
declaration(nullptr);
return;
}
element_open(pos);
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::element_open(std::ptrdiff_t begin_pos)
{
sax::parser_element elem;
element_name(elem, begin_pos);
while (true)
{
skip_space_and_control();
char c = cur_char_checked();
if (c == '/')
{
// Self-closing element: <element/>
if (next_and_char() != '>')
throw malformed_xml_error("expected '/>' to self-close the element.", offset());
next();
elem.end_pos = offset();
m_handler.start_element(elem);
reset_buffer_pos();
m_handler.end_element(elem);
if (!m_nest_level)
m_root_elem_open = false;
#if ORCUS_DEBUG_SAX_PARSER
cout << "element_open: ns='" << elem.ns << "', name='" << elem.name << "' (self-closing)" << endl;
#endif
return;
}
else if (c == '>')
{
// End of opening element: <element>
next();
elem.end_pos = offset();
nest_up();
m_handler.start_element(elem);
reset_buffer_pos();
#if ORCUS_DEBUG_SAX_PARSER
cout << "element_open: ns='" << elem.ns << "', name='" << elem.name << "'" << endl;
#endif
return;
}
else
attribute();
}
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::element_close(std::ptrdiff_t begin_pos)
{
assert(cur_char() == '/');
nest_down();
next_check();
sax::parser_element elem;
element_name(elem, begin_pos);
if (cur_char() != '>')
throw malformed_xml_error("expected '>' to close the element.", offset());
next();
elem.end_pos = offset();
m_handler.end_element(elem);
#if ORCUS_DEBUG_SAX_PARSER
cout << "element_close: ns='" << elem.ns << "', name='" << elem.name << "'" << endl;
#endif
if (!m_nest_level)
m_root_elem_open = false;
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::special_tag()
{
assert(cur_char() == '!');
// This can be either <![CDATA, <!--, or <!DOCTYPE.
size_t len = available_size();
if (len < 2)
throw malformed_xml_error("special tag too short.", offset());
switch (next_and_char())
{
case '-':
{
// Possibly comment.
if (next_and_char() != '-')
throw malformed_xml_error("comment expected.", offset());
len -= 2;
if (len < 3)
throw malformed_xml_error("malformed comment.", offset());
next();
comment();
}
break;
case '[':
{
// Possibly a CDATA.
expects_next("CDATA[", 6);
if (has_char())
cdata();
}
break;
case 'D':
{
// check if this is a DOCTYPE.
expects_next("OCTYPE", 6);
skip_space_and_control();
if (has_char())
doctype();
}
break;
default:
throw malformed_xml_error("failed to parse special tag.", offset());
}
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::declaration(const char* name_check)
{
assert(cur_char() == '?');
next_check();
// Get the declaration name first.
std::string_view decl_name;
name(decl_name);
#if ORCUS_DEBUG_SAX_PARSER
cout << "sax_parser::declaration: start name='" << decl_name << "'" << endl;
#endif
if (name_check && decl_name != name_check)
{
std::ostringstream os;
os << "declaration name of '" << name_check << "' was expected, but '" << decl_name << "' was found instead.";
throw malformed_xml_error(os.str(), offset());
}
m_handler.start_declaration(decl_name);
skip_space_and_control();
// Parse the attributes.
while (cur_char_checked() != '?')
{
attribute();
skip_space_and_control();
}
if (next_char_checked() != '>')
throw malformed_xml_error("declaration must end with '?>'.", offset());
m_handler.end_declaration(decl_name);
reset_buffer_pos();
next();
#if ORCUS_DEBUG_SAX_PARSER
cout << "sax_parser::declaration: end name='" << decl_name << "'" << endl;
#endif
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::cdata()
{
size_t len = available_size();
assert(len > 3);
// Parse until we reach ']]>'.
const char* p0 = mp_char;
size_t i = 0, match = 0;
for (char c = cur_char(); i < len; ++i, c = next_and_char())
{
if (c == ']')
{
// Be aware that we may encounter a series of more than two ']'
// characters, in which case we'll only count the last two.
if (match == 0)
// First ']'
++match;
else if (match == 1)
// Second ']'
++match;
}
else if (c == '>' && match == 2)
{
// Found ']]>'.
size_t cdata_len = i - 2;
m_handler.characters(std::string_view(p0, cdata_len), false);
next();
return;
}
else
match = 0;
}
throw malformed_xml_error("malformed CDATA section.", offset());
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::doctype()
{
// Parse the root element first.
sax::doctype_declaration param;
name(param.root_element);
skip_space_and_control();
// Either PUBLIC or SYSTEM.
size_t len = available_size();
if (len < 6)
throw malformed_xml_error("DOCTYPE section too short.", offset());
param.keyword = sax::doctype_declaration::keyword_type::dtd_private;
char c = cur_char();
if (c == 'P')
{
if (next_and_char() != 'U' || next_and_char() != 'B' || next_and_char() != 'L' || next_and_char() != 'I' || next_and_char() != 'C')
throw malformed_xml_error("malformed DOCTYPE section.", offset());
param.keyword = sax::doctype_declaration::keyword_type::dtd_public;
}
else if (c == 'S')
{
if (next_and_char() != 'Y' || next_and_char() != 'S' || next_and_char() != 'T' || next_and_char() != 'E' || next_and_char() != 'M')
throw malformed_xml_error("malformed DOCTYPE section.", offset());
}
next_check();
skip_space_and_control();
// Parse FPI.
value(param.fpi, false);
has_char_throw("DOCTYPE section too short.");
skip_space_and_control();
has_char_throw("DOCTYPE section too short.");
if (cur_char() == '>')
{
// Optional URI not given. Exit.
#if ORCUS_DEBUG_SAX_PARSER
cout << "sax_parser::doctype: root='" << param.root_element << "', fpi='" << param.fpi << "'" << endl;
#endif
m_handler.doctype(param);
next();
return;
}
// Parse optional URI.
value(param.uri, false);
has_char_throw("DOCTYPE section too short.");
skip_space_and_control();
has_char_throw("DOCTYPE section too short.");
if (cur_char() != '>')
throw malformed_xml_error("malformed DOCTYPE section - closing '>' expected but not found.", offset());
#if ORCUS_DEBUG_SAX_PARSER
cout << "sax_parser::doctype: root='" << param.root_element << "', fpi='" << param.fpi << "' uri='" << param.uri << "'" << endl;
#endif
m_handler.doctype(param);
next();
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::characters()
{
const char* p0 = mp_char;
for (; has_char(); next())
{
if (cur_char() == '<')
break;
if (cur_char() == '&')
{
// Text span with one or more encoded characters. Parse using cell buffer.
cell_buffer& buf = get_cell_buffer();
buf.reset();
buf.append(p0, mp_char-p0);
characters_with_encoded_char(buf);
if (buf.empty())
m_handler.characters(std::string_view{}, false);
else
m_handler.characters(buf.str(), true);
return;
}
}
if (mp_char > p0)
{
std::string_view val(p0, mp_char-p0);
m_handler.characters(val, false);
}
}
template<typename HandlerT, typename ConfigT>
void sax_parser<HandlerT,ConfigT>::attribute()
{
sax::parser_attribute attr;
attribute_name(attr.ns, attr.name);
#if ORCUS_DEBUG_SAX_PARSER
cout << "sax_parser::attribute: ns='" << attr.ns << "', name='" << attr.name << "'" << endl;
#endif
skip_space_and_control();
char c = cur_char_checked();
if (c != '=')
{
std::ostringstream os;
os << "Attribute must begin with 'name=..'. (ns='" << attr.ns << "', name='" << attr.name << "')";
throw malformed_xml_error(os.str(), offset());
}
next_check(); // skip the '='.
skip_space_and_control();
attr.transient = value(attr.value, true);
if (attr.transient)
// Value is stored in a temporary buffer. Push a new buffer.
inc_buffer_pos();
#if ORCUS_DEBUG_SAX_PARSER
cout << "sax_parser::attribute: value='" << attr.value << "'" << endl;
#endif
m_handler.attribute(attr);
}
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|