BaseXMLParser.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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 <string.h>
  32. namespace Rml {
  33. namespace Core {
  34. BaseXMLParser::BaseXMLParser()
  35. {
  36. open_tag_depth = 0;
  37. treat_content_as_cdata = false;
  38. }
  39. BaseXMLParser::~BaseXMLParser()
  40. {
  41. }
  42. // Registers a tag as containing general character data.
  43. void BaseXMLParser::RegisterCDATATag(const String& tag)
  44. {
  45. if (!tag.empty())
  46. cdata_tags.insert(StringUtilities::ToLower(tag));
  47. }
  48. // Parses the given stream as an XML file, and calls the handlers when
  49. // interesting phenomenon are encountered.
  50. void BaseXMLParser::Parse(Stream* stream)
  51. {
  52. source_url = &stream->GetSourceURL();
  53. xml_source.clear();
  54. const size_t source_size = stream->Length();
  55. const size_t read_size = stream->Read(xml_source, source_size);
  56. RMLUI_ASSERT(source_size == read_size);
  57. xml_index = 0;
  58. line_number = 1;
  59. treat_content_as_cdata = false;
  60. // Read (er ... skip) the header, if one exists.
  61. ReadHeader();
  62. // Read the XML body.
  63. ReadBody();
  64. xml_source.clear();
  65. source_url = nullptr;
  66. }
  67. // Get the current file line number
  68. int BaseXMLParser::GetLineNumber() const
  69. {
  70. return line_number;
  71. }
  72. int BaseXMLParser::GetLineNumberOpenTag() const
  73. {
  74. return line_number_open_tag;
  75. }
  76. // Called when the parser finds the beginning of an element tag.
  77. void BaseXMLParser::HandleElementStart(const String& RMLUI_UNUSED_PARAMETER(name), const XMLAttributes& RMLUI_UNUSED_PARAMETER(attributes))
  78. {
  79. RMLUI_UNUSED(name);
  80. RMLUI_UNUSED(attributes);
  81. }
  82. // Called when the parser finds the end of an element tag.
  83. void BaseXMLParser::HandleElementEnd(const String& RMLUI_UNUSED_PARAMETER(name))
  84. {
  85. RMLUI_UNUSED(name);
  86. }
  87. // Called when the parser encounters data.
  88. void BaseXMLParser::HandleData(const String& RMLUI_UNUSED_PARAMETER(data))
  89. {
  90. RMLUI_UNUSED(data);
  91. }
  92. /// Returns the source URL of this parse. Only valid during parsing.
  93. const URL& BaseXMLParser::GetSourceURL() const
  94. {
  95. RMLUI_ASSERT(source_url);
  96. return *source_url;
  97. }
  98. void BaseXMLParser::TreatElementContentAsCDATA()
  99. {
  100. treat_content_as_cdata = true;
  101. }
  102. void BaseXMLParser::Next() {
  103. xml_index += 1;
  104. }
  105. bool BaseXMLParser::AtEnd() const {
  106. return xml_index >= xml_source.size();
  107. }
  108. char BaseXMLParser::Look() const {
  109. RMLUI_ASSERT(!AtEnd());
  110. return xml_source[xml_index];
  111. }
  112. void BaseXMLParser::ReadHeader()
  113. {
  114. if (PeekString("<?"))
  115. {
  116. String temp;
  117. FindString(">", temp);
  118. }
  119. }
  120. void BaseXMLParser::ReadBody()
  121. {
  122. RMLUI_ZoneScoped;
  123. open_tag_depth = 0;
  124. line_number_open_tag = 0;
  125. for(;;)
  126. {
  127. // Find the next open tag.
  128. if (!FindString("<", data, true))
  129. break;
  130. // Check what kind of tag this is.
  131. if (PeekString("!--"))
  132. {
  133. // Comment.
  134. String temp;
  135. if (!FindString("-->", temp))
  136. break;
  137. }
  138. else if (PeekString("![CDATA["))
  139. {
  140. // CDATA tag; read everything (including markup) until the ending
  141. // CDATA tag.
  142. if (!ReadCDATA())
  143. break;
  144. }
  145. else if (PeekString("/"))
  146. {
  147. if (!ReadCloseTag())
  148. break;
  149. // Bail if we've hit the end of the XML data.
  150. if (open_tag_depth == 0)
  151. break;
  152. }
  153. else
  154. {
  155. if (ReadOpenTag())
  156. line_number_open_tag = line_number;
  157. else
  158. break;
  159. }
  160. }
  161. // Check for error conditions
  162. if (open_tag_depth > 0)
  163. {
  164. Log::Message(Log::LT_WARNING, "XML parse error on line %d of %s.", GetLineNumber(), source_url->GetURL().c_str());
  165. }
  166. }
  167. bool BaseXMLParser::ReadOpenTag()
  168. {
  169. // Increase the open depth
  170. open_tag_depth++;
  171. treat_content_as_cdata = false;
  172. // Opening tag; send data immediately and open the tag.
  173. if (!data.empty())
  174. {
  175. HandleData(data);
  176. data.clear();
  177. }
  178. String tag_name;
  179. if (!FindWord(tag_name, "/>"))
  180. return false;
  181. bool section_opened = false;
  182. if (PeekString(">"))
  183. {
  184. // Simple open tag.
  185. HandleElementStart(tag_name, XMLAttributes());
  186. section_opened = true;
  187. }
  188. else if (PeekString("/") &&
  189. PeekString(">"))
  190. {
  191. // Empty open tag.
  192. HandleElementStart(tag_name, XMLAttributes());
  193. HandleElementEnd(tag_name);
  194. // Tag immediately closed, reduce count
  195. open_tag_depth--;
  196. }
  197. else
  198. {
  199. // It appears we have some attributes. Let's parse them.
  200. XMLAttributes attributes;
  201. if (!ReadAttributes(attributes))
  202. return false;
  203. if (PeekString(">"))
  204. {
  205. HandleElementStart(tag_name, attributes);
  206. section_opened = true;
  207. }
  208. else if (PeekString("/") &&
  209. PeekString(">"))
  210. {
  211. HandleElementStart(tag_name, attributes);
  212. HandleElementEnd(tag_name);
  213. // Tag immediately closed, reduce count
  214. open_tag_depth--;
  215. }
  216. else
  217. {
  218. return false;
  219. }
  220. }
  221. // Check if this tag needs to be processed as CDATA.
  222. if (section_opened)
  223. {
  224. String lcase_tag_name = StringUtilities::ToLower(tag_name);
  225. bool is_cdata_tag = (cdata_tags.find(lcase_tag_name) != cdata_tags.end());
  226. if (treat_content_as_cdata || is_cdata_tag)
  227. {
  228. if (ReadCDATA(lcase_tag_name.c_str(), !is_cdata_tag))
  229. {
  230. open_tag_depth--;
  231. if (!data.empty())
  232. {
  233. HandleData(data);
  234. data.clear();
  235. }
  236. HandleElementEnd(tag_name);
  237. return true;
  238. }
  239. return false;
  240. }
  241. }
  242. return true;
  243. }
  244. bool BaseXMLParser::ReadCloseTag()
  245. {
  246. // Closing tag; send data immediately and close the tag.
  247. if (!data.empty())
  248. {
  249. HandleData(data);
  250. data.clear();
  251. }
  252. String tag_name;
  253. if (!FindString(">", tag_name))
  254. return false;
  255. HandleElementEnd(StringUtilities::StripWhitespace(tag_name));
  256. // Tag closed, reduce count
  257. open_tag_depth--;
  258. return true;
  259. }
  260. bool BaseXMLParser::ReadAttributes(XMLAttributes& attributes)
  261. {
  262. for (;;)
  263. {
  264. String attribute;
  265. String value;
  266. // Get the attribute name
  267. if (!FindWord(attribute, "=/>"))
  268. {
  269. return false;
  270. }
  271. // Check if theres an assigned value
  272. if (PeekString("="))
  273. {
  274. if (PeekString("\""))
  275. {
  276. if (!FindString("\"", value))
  277. return false;
  278. }
  279. else if (PeekString("'"))
  280. {
  281. if (!FindString("'", value))
  282. return false;
  283. }
  284. else if (!FindWord(value, "/>"))
  285. {
  286. return false;
  287. }
  288. }
  289. attributes[attribute] = value;
  290. // Check for the end of the tag.
  291. if (PeekString("/", false) ||
  292. PeekString(">", false))
  293. return true;
  294. }
  295. }
  296. bool BaseXMLParser::ReadCDATA(const char* tag_terminator, bool only_terminate_at_same_xml_depth)
  297. {
  298. String cdata;
  299. if (tag_terminator == nullptr)
  300. {
  301. FindString("]]>", cdata);
  302. data += cdata;
  303. return true;
  304. }
  305. else
  306. {
  307. int tag_depth = 1;
  308. // TODO: This doesn't properly handle comments and double brackets,
  309. // should probably find a way to use the normal parsing flow instead.
  310. for (;;)
  311. {
  312. // Search for the next tag opening.
  313. if (!FindString("<", cdata))
  314. return false;
  315. String node_raw;
  316. if (!FindString(">", node_raw))
  317. return false;
  318. String node_stripped = StringUtilities::StripWhitespace(node_raw);
  319. bool close_begin = false;
  320. bool close_end = false;
  321. if (!node_stripped.empty())
  322. {
  323. if (node_stripped.front() == '/')
  324. close_begin = true;
  325. else if (node_stripped.back() == '/')
  326. close_end = true;
  327. }
  328. if (!close_begin && !close_end)
  329. tag_depth += 1;
  330. else if (close_begin && !close_end)
  331. tag_depth -= 1;
  332. if (close_begin && !close_end && (!only_terminate_at_same_xml_depth || tag_depth == 0))
  333. {
  334. String tag_name = StringUtilities::StripWhitespace(node_stripped.substr(1));
  335. if (StringUtilities::ToLower(tag_name) == tag_terminator)
  336. {
  337. data += cdata;
  338. return true;
  339. }
  340. }
  341. if (only_terminate_at_same_xml_depth && tag_depth <= 0)
  342. {
  343. return false;
  344. }
  345. cdata += '<' + node_raw + '>';
  346. }
  347. }
  348. }
  349. // Reads from the stream until a complete word is found.
  350. bool BaseXMLParser::FindWord(String& word, const char* terminators)
  351. {
  352. while (!AtEnd())
  353. {
  354. char c = Look();
  355. // Ignore white space
  356. if (StringUtilities::IsWhitespace(c))
  357. {
  358. if (word.empty())
  359. {
  360. Next();
  361. continue;
  362. }
  363. else
  364. return true;
  365. }
  366. // Check for termination condition
  367. if (terminators && strchr(terminators, c))
  368. {
  369. return !word.empty();
  370. }
  371. word += c;
  372. Next();
  373. }
  374. return false;
  375. }
  376. // Reads from the stream until the given character set is found.
  377. bool BaseXMLParser::FindString(const char* string, String& data, bool escape_brackets)
  378. {
  379. int index = 0;
  380. bool in_brackets = false;
  381. char previous = 0;
  382. while (string[index])
  383. {
  384. if (AtEnd())
  385. return false;
  386. const char c = Look();
  387. // Count line numbers
  388. if (c == '\n')
  389. {
  390. line_number++;
  391. }
  392. if(escape_brackets)
  393. {
  394. if (c == '{' && previous == '{')
  395. in_brackets = true;
  396. else if (c == '}' && previous == '}')
  397. in_brackets = false;
  398. }
  399. if (c == string[index] && !in_brackets)
  400. {
  401. index += 1;
  402. }
  403. else
  404. {
  405. if (index > 0)
  406. {
  407. data += String(string, index);
  408. index = 0;
  409. }
  410. data += c;
  411. }
  412. previous = c;
  413. Next();
  414. }
  415. return true;
  416. }
  417. // Returns true if the next sequence of characters in the stream matches the
  418. // given string.
  419. bool BaseXMLParser::PeekString(const char* string, bool consume)
  420. {
  421. const size_t start_index = xml_index;
  422. bool success = true;
  423. int i = 0;
  424. while (string[i])
  425. {
  426. if (AtEnd())
  427. {
  428. success = false;
  429. break;
  430. }
  431. const char c = Look();
  432. // Seek past all the whitespace if we haven't hit the initial character yet.
  433. if (i == 0 && StringUtilities::IsWhitespace(c))
  434. {
  435. Next();
  436. }
  437. else
  438. {
  439. if (c != string[i])
  440. {
  441. success = false;
  442. break;
  443. }
  444. i++;
  445. Next();
  446. }
  447. }
  448. // Set the index to the start index unless we are consuming.
  449. if (!consume || !success)
  450. xml_index = start_index;
  451. return success;
  452. }
  453. }
  454. }