BaseXMLParser.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/BaseXMLParser.h"
  29. #include "../../Include/RmlUi/Core/Profiling.h"
  30. #include "../../Include/RmlUi/Core/Stream.h"
  31. #include "XMLParseTools.h"
  32. #include <string.h>
  33. namespace Rml {
  34. namespace Core {
  35. BaseXMLParser::BaseXMLParser()
  36. {}
  37. BaseXMLParser::~BaseXMLParser()
  38. {}
  39. // Registers a tag as containing general character data.
  40. void BaseXMLParser::RegisterCDATATag(const String& tag)
  41. {
  42. if (!tag.empty())
  43. cdata_tags.insert(StringUtilities::ToLower(tag));
  44. }
  45. void BaseXMLParser::RegisterInnerXMLAttribute(const String& attribute_name)
  46. {
  47. attributes_for_inner_xml_data.insert(attribute_name);
  48. }
  49. // Parses the given stream as an XML file, and calls the handlers when
  50. // interesting phenomenon are encountered.
  51. void BaseXMLParser::Parse(Stream* stream)
  52. {
  53. source_url = &stream->GetSourceURL();
  54. xml_source.clear();
  55. // We read in the whole XML file here.
  56. // TODO: It doesn't look like the Stream interface is used for anything useful. We
  57. // might as well just use a span or StringView, and get completely rid of it.
  58. // @performance Otherwise, use the temporary allocator.
  59. const size_t source_size = stream->Length();
  60. stream->Read(xml_source, source_size);
  61. xml_index = 0;
  62. line_number = 1;
  63. line_number_open_tag = 1;
  64. inner_xml_data = false;
  65. inner_xml_data_terminate_depth = 0;
  66. inner_xml_data_index_begin = 0;
  67. // Read (er ... skip) the header, if one exists.
  68. ReadHeader();
  69. // Read the XML body.
  70. ReadBody();
  71. xml_source.clear();
  72. source_url = nullptr;
  73. }
  74. // Get the current file line number
  75. int BaseXMLParser::GetLineNumber() const
  76. {
  77. return line_number;
  78. }
  79. int BaseXMLParser::GetLineNumberOpenTag() const
  80. {
  81. return line_number_open_tag;
  82. }
  83. // Called when the parser finds the beginning of an element tag.
  84. void BaseXMLParser::HandleElementStart(const String& RMLUI_UNUSED_PARAMETER(name), const XMLAttributes& RMLUI_UNUSED_PARAMETER(attributes))
  85. {
  86. RMLUI_UNUSED(name);
  87. RMLUI_UNUSED(attributes);
  88. }
  89. // Called when the parser finds the end of an element tag.
  90. void BaseXMLParser::HandleElementEnd(const String& RMLUI_UNUSED_PARAMETER(name))
  91. {
  92. RMLUI_UNUSED(name);
  93. }
  94. // Called when the parser encounters data.
  95. void BaseXMLParser::HandleData(const String& RMLUI_UNUSED_PARAMETER(data), XMLDataType RMLUI_UNUSED_PARAMETER(type))
  96. {
  97. RMLUI_UNUSED(data);
  98. RMLUI_UNUSED(type);
  99. }
  100. /// Returns the source URL of this parse. Only valid during parsing.
  101. const URL* BaseXMLParser::GetSourceURLPtr() const
  102. {
  103. return source_url;
  104. }
  105. void BaseXMLParser::Next() {
  106. xml_index += 1;
  107. }
  108. bool BaseXMLParser::AtEnd() const {
  109. return xml_index >= xml_source.size();
  110. }
  111. char BaseXMLParser::Look() const {
  112. RMLUI_ASSERT(!AtEnd());
  113. return xml_source[xml_index];
  114. }
  115. void BaseXMLParser::HandleElementStartInternal(const String& name, const XMLAttributes& attributes)
  116. {
  117. if (!inner_xml_data)
  118. HandleElementStart(name, attributes);
  119. }
  120. void BaseXMLParser::HandleElementEndInternal(const String& name)
  121. {
  122. if (!inner_xml_data)
  123. HandleElementEnd(name);
  124. }
  125. void BaseXMLParser::HandleDataInternal(const String& data, XMLDataType type)
  126. {
  127. if (!inner_xml_data)
  128. HandleData(data, type);
  129. }
  130. void BaseXMLParser::ReadHeader()
  131. {
  132. if (PeekString("<?"))
  133. {
  134. String temp;
  135. FindString(">", temp);
  136. }
  137. }
  138. void BaseXMLParser::ReadBody()
  139. {
  140. RMLUI_ZoneScoped;
  141. open_tag_depth = 0;
  142. line_number_open_tag = 0;
  143. for(;;)
  144. {
  145. // Find the next open tag.
  146. if (!FindString("<", data, true))
  147. break;
  148. const size_t xml_index_tag = xml_index - 1;
  149. // Check what kind of tag this is.
  150. if (PeekString("!--"))
  151. {
  152. // Comment.
  153. String temp;
  154. if (!FindString("-->", temp))
  155. break;
  156. }
  157. else if (PeekString("![CDATA["))
  158. {
  159. // CDATA tag; read everything (including markup) until the ending
  160. // CDATA tag.
  161. if (!ReadCDATA())
  162. break;
  163. }
  164. else if (PeekString("/"))
  165. {
  166. if (!ReadCloseTag(xml_index_tag))
  167. break;
  168. // Bail if we've hit the end of the XML data.
  169. if (open_tag_depth == 0)
  170. break;
  171. }
  172. else
  173. {
  174. if (ReadOpenTag())
  175. line_number_open_tag = line_number;
  176. else
  177. break;
  178. }
  179. }
  180. // Check for error conditions
  181. if (open_tag_depth > 0)
  182. {
  183. Log::Message(Log::LT_WARNING, "XML parse error on line %d of %s.", GetLineNumber(), source_url->GetURL().c_str());
  184. }
  185. }
  186. bool BaseXMLParser::ReadOpenTag()
  187. {
  188. // Increase the open depth
  189. open_tag_depth++;
  190. // Opening tag; send data immediately and open the tag.
  191. if (!data.empty())
  192. {
  193. HandleDataInternal(data, XMLDataType::Text);
  194. data.clear();
  195. }
  196. String tag_name;
  197. if (!FindWord(tag_name, "/>"))
  198. return false;
  199. bool section_opened = false;
  200. if (PeekString(">"))
  201. {
  202. // Simple open tag.
  203. HandleElementStartInternal(tag_name, XMLAttributes());
  204. section_opened = true;
  205. }
  206. else if (PeekString("/") &&
  207. PeekString(">"))
  208. {
  209. // Empty open tag.
  210. HandleElementStartInternal(tag_name, XMLAttributes());
  211. HandleElementEndInternal(tag_name);
  212. // Tag immediately closed, reduce count
  213. open_tag_depth--;
  214. }
  215. else
  216. {
  217. // It appears we have some attributes. Let's parse them.
  218. bool parse_inner_xml_as_data = false;
  219. XMLAttributes attributes;
  220. if (!ReadAttributes(attributes, parse_inner_xml_as_data))
  221. return false;
  222. if (PeekString(">"))
  223. {
  224. HandleElementStartInternal(tag_name, attributes);
  225. section_opened = true;
  226. }
  227. else if (PeekString("/") &&
  228. PeekString(">"))
  229. {
  230. HandleElementStartInternal(tag_name, attributes);
  231. HandleElementEndInternal(tag_name);
  232. // Tag immediately closed, reduce count
  233. open_tag_depth--;
  234. }
  235. else
  236. {
  237. return false;
  238. }
  239. if (section_opened && parse_inner_xml_as_data && !inner_xml_data)
  240. {
  241. inner_xml_data = true;
  242. inner_xml_data_terminate_depth = open_tag_depth;
  243. inner_xml_data_index_begin = xml_index;
  244. }
  245. }
  246. // Check if this tag needs to be processed as CDATA.
  247. if (section_opened)
  248. {
  249. const String lcase_tag_name = StringUtilities::ToLower(tag_name);
  250. bool is_cdata_tag = (cdata_tags.find(lcase_tag_name) != cdata_tags.end());
  251. if (is_cdata_tag)
  252. {
  253. if (ReadCDATA(lcase_tag_name.c_str()))
  254. {
  255. open_tag_depth--;
  256. if (!data.empty())
  257. {
  258. HandleDataInternal(data, XMLDataType::CData);
  259. data.clear();
  260. }
  261. HandleElementEndInternal(tag_name);
  262. return true;
  263. }
  264. return false;
  265. }
  266. }
  267. return true;
  268. }
  269. bool BaseXMLParser::ReadCloseTag(const size_t xml_index_tag)
  270. {
  271. if (inner_xml_data && open_tag_depth == inner_xml_data_terminate_depth)
  272. {
  273. // Closing the tag that initiated the inner xml data parsing. Set all its contents as Data to be
  274. // submitted next, and disable the mode to resume normal parsing behavior.
  275. RMLUI_ASSERT(inner_xml_data_index_begin <= xml_index_tag);
  276. inner_xml_data = false;
  277. data = xml_source.substr(inner_xml_data_index_begin, xml_index_tag - inner_xml_data_index_begin);
  278. HandleDataInternal(data, XMLDataType::InnerXML);
  279. data.clear();
  280. }
  281. // Closing tag; send data immediately and close the tag.
  282. if (!data.empty())
  283. {
  284. HandleDataInternal(data, XMLDataType::Text);
  285. data.clear();
  286. }
  287. String tag_name;
  288. if (!FindString(">", tag_name))
  289. return false;
  290. HandleElementEndInternal(StringUtilities::StripWhitespace(tag_name));
  291. // Tag closed, reduce count
  292. open_tag_depth--;
  293. return true;
  294. }
  295. bool BaseXMLParser::ReadAttributes(XMLAttributes& attributes, bool& parse_raw_xml_content)
  296. {
  297. for (;;)
  298. {
  299. String attribute;
  300. String value;
  301. // Get the attribute name
  302. if (!FindWord(attribute, "=/>"))
  303. {
  304. return false;
  305. }
  306. // Check if theres an assigned value
  307. if (PeekString("="))
  308. {
  309. if (PeekString("\""))
  310. {
  311. if (!FindString("\"", value))
  312. return false;
  313. }
  314. else if (PeekString("'"))
  315. {
  316. if (!FindString("'", value))
  317. return false;
  318. }
  319. else if (!FindWord(value, "/>"))
  320. {
  321. return false;
  322. }
  323. }
  324. if (attributes_for_inner_xml_data.count(attribute) == 1)
  325. parse_raw_xml_content = true;
  326. attributes[attribute] = value;
  327. // Check for the end of the tag.
  328. if (PeekString("/", false) || PeekString(">", false))
  329. return true;
  330. }
  331. }
  332. bool BaseXMLParser::ReadCDATA(const char* tag_terminator)
  333. {
  334. String cdata;
  335. if (tag_terminator == nullptr)
  336. {
  337. FindString("]]>", cdata);
  338. data += cdata;
  339. return true;
  340. }
  341. else
  342. {
  343. for (;;)
  344. {
  345. // Search for the next tag opening.
  346. if (!FindString("<", cdata))
  347. return false;
  348. if (PeekString("/", false))
  349. {
  350. String tag;
  351. if (FindString(">", tag))
  352. {
  353. size_t slash_pos = tag.find('/');
  354. String tag_name = StringUtilities::StripWhitespace(slash_pos == String::npos ? tag : tag.substr(slash_pos + 1));
  355. if (StringUtilities::ToLower(tag_name) == tag_terminator)
  356. {
  357. data += cdata;
  358. return true;
  359. }
  360. else
  361. {
  362. cdata += '<' + tag + '>';
  363. }
  364. }
  365. else
  366. cdata += "<";
  367. }
  368. else
  369. cdata += "<";
  370. }
  371. }
  372. }
  373. // Reads from the stream until a complete word is found.
  374. bool BaseXMLParser::FindWord(String& word, const char* terminators)
  375. {
  376. while (!AtEnd())
  377. {
  378. char c = Look();
  379. // Ignore white space
  380. if (StringUtilities::IsWhitespace(c))
  381. {
  382. if (word.empty())
  383. {
  384. Next();
  385. continue;
  386. }
  387. else
  388. return true;
  389. }
  390. // Check for termination condition
  391. if (terminators && strchr(terminators, c))
  392. {
  393. return !word.empty();
  394. }
  395. word += c;
  396. Next();
  397. }
  398. return false;
  399. }
  400. // Reads from the stream until the given character set is found.
  401. bool BaseXMLParser::FindString(const char* string, String& data, bool escape_brackets)
  402. {
  403. int index = 0;
  404. bool in_brackets = false;
  405. char previous = 0;
  406. while (string[index])
  407. {
  408. if (AtEnd())
  409. return false;
  410. const char c = Look();
  411. // Count line numbers
  412. if (c == '\n')
  413. {
  414. line_number++;
  415. }
  416. if(escape_brackets)
  417. {
  418. const char* error_str = XMLParseTools::ParseDataBrackets(in_brackets, c, previous);
  419. if (error_str)
  420. {
  421. Log::Message(Log::LT_WARNING, "XML parse error. %s", error_str);
  422. return false;
  423. }
  424. }
  425. if (c == string[index] && !in_brackets)
  426. {
  427. index += 1;
  428. }
  429. else
  430. {
  431. if (index > 0)
  432. {
  433. data += String(string, index);
  434. index = 0;
  435. }
  436. data += c;
  437. }
  438. previous = c;
  439. Next();
  440. }
  441. return true;
  442. }
  443. // Returns true if the next sequence of characters in the stream matches the
  444. // given string.
  445. bool BaseXMLParser::PeekString(const char* string, bool consume)
  446. {
  447. const size_t start_index = xml_index;
  448. bool success = true;
  449. int i = 0;
  450. while (string[i])
  451. {
  452. if (AtEnd())
  453. {
  454. success = false;
  455. break;
  456. }
  457. const char c = Look();
  458. // Seek past all the whitespace if we haven't hit the initial character yet.
  459. if (i == 0 && StringUtilities::IsWhitespace(c))
  460. {
  461. Next();
  462. }
  463. else
  464. {
  465. if (c != string[i])
  466. {
  467. success = false;
  468. break;
  469. }
  470. i++;
  471. Next();
  472. }
  473. }
  474. // Set the index to the start index unless we are consuming.
  475. if (!consume || !success)
  476. xml_index = start_index;
  477. return success;
  478. }
  479. }
  480. }