BaseXMLParser.cpp 12 KB

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