BaseXMLParser.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. * This source file is part of libRocket, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://www.librocket.com
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. *
  26. */
  27. #include "precompiled.h"
  28. #include "../../Include/Rocket/Core/BaseXMLParser.h"
  29. namespace Rocket {
  30. namespace Core {
  31. // Most file layers cache 4k.
  32. const int DEFAULT_BUFFER_SIZE = 4096;
  33. BaseXMLParser::BaseXMLParser()
  34. {
  35. read = NULL;
  36. buffer = NULL;
  37. buffer_used = 0;
  38. buffer_size = 0;
  39. open_tag_depth = 0;
  40. }
  41. BaseXMLParser::~BaseXMLParser()
  42. {
  43. }
  44. // Registers a tag as containing general character data.
  45. void BaseXMLParser::RegisterCDATATag(const String& tag)
  46. {
  47. if (!tag.empty())
  48. cdata_tags.insert(ToLower(tag));
  49. }
  50. // Parses the given stream as an XML file, and calls the handlers when
  51. // interesting phenomenon are encountered.
  52. void BaseXMLParser::Parse(Stream* stream)
  53. {
  54. xml_source = stream;
  55. buffer_size = DEFAULT_BUFFER_SIZE;
  56. buffer = (unsigned char*) malloc(buffer_size);
  57. read = buffer;
  58. line_number = 1;
  59. FillBuffer();
  60. // Read (er ... skip) the header, if one exists.
  61. ReadHeader();
  62. // Read the XML body.
  63. ReadBody();
  64. free(buffer);
  65. }
  66. // Get the current file line number
  67. int BaseXMLParser::GetLineNumber()
  68. {
  69. return line_number;
  70. }
  71. // Called when the parser finds the beginning of an element tag.
  72. void BaseXMLParser::HandleElementStart(const String& ROCKET_UNUSED_PARAMETER(name), const XMLAttributes& ROCKET_UNUSED_PARAMETER(attributes))
  73. {
  74. ROCKET_UNUSED(name);
  75. ROCKET_UNUSED(attributes);
  76. }
  77. // Called when the parser finds the end of an element tag.
  78. void BaseXMLParser::HandleElementEnd(const String& ROCKET_UNUSED_PARAMETER(name))
  79. {
  80. ROCKET_UNUSED(name);
  81. }
  82. // Called when the parser encounters data.
  83. void BaseXMLParser::HandleData(const String& ROCKET_UNUSED_PARAMETER(data))
  84. {
  85. ROCKET_UNUSED(data);
  86. }
  87. void BaseXMLParser::ReadHeader()
  88. {
  89. if (PeekString((unsigned char*) "<?"))
  90. {
  91. String temp;
  92. FindString((unsigned char*) ">", temp);
  93. }
  94. }
  95. void BaseXMLParser::ReadBody()
  96. {
  97. open_tag_depth = 0;
  98. for(;;)
  99. {
  100. // Find the next open tag.
  101. if (!FindString((unsigned char*) "<", data))
  102. break;
  103. // Check what kind of tag this is.
  104. if (PeekString((const unsigned char*) "!--"))
  105. {
  106. // Comment.
  107. String temp;
  108. if (!FindString((const unsigned char*) "-->", temp))
  109. break;
  110. }
  111. else if (PeekString((const unsigned char*) "![CDATA["))
  112. {
  113. // CDATA tag; read everything (including markup) until the ending
  114. // CDATA tag.
  115. if (!ReadCDATA())
  116. break;
  117. }
  118. else if (PeekString((const unsigned char*) "/"))
  119. {
  120. if (!ReadCloseTag())
  121. break;
  122. // Bail if we've hit the end of the XML data.
  123. if (open_tag_depth == 0)
  124. {
  125. xml_source->Seek((long)((read - buffer) - buffer_used), SEEK_CUR);
  126. break;
  127. }
  128. }
  129. else
  130. {
  131. if (!ReadOpenTag())
  132. break;
  133. }
  134. }
  135. // Check for error conditions
  136. if (open_tag_depth > 0)
  137. {
  138. Log::Message(Log::LT_WARNING, "XML parse error on line %d of %s.", GetLineNumber(), xml_source->GetSourceURL().GetURL().c_str());
  139. }
  140. }
  141. bool BaseXMLParser::ReadOpenTag()
  142. {
  143. // Increase the open depth
  144. open_tag_depth++;
  145. // Opening tag; send data immediately and open the tag.
  146. if (!data.empty())
  147. {
  148. HandleData(data);
  149. data.clear();
  150. }
  151. String tag_name;
  152. if (!FindWord(tag_name, "/>"))
  153. return false;
  154. bool section_opened = false;
  155. if (PeekString((const unsigned char*) ">"))
  156. {
  157. // Simple open tag.
  158. HandleElementStart(tag_name, XMLAttributes());
  159. section_opened = true;
  160. }
  161. else if (PeekString((const unsigned char*) "/") &&
  162. PeekString((const unsigned char*) ">"))
  163. {
  164. // Empty open tag.
  165. HandleElementStart(tag_name, XMLAttributes());
  166. HandleElementEnd(tag_name);
  167. // Tag immediately closed, reduce count
  168. open_tag_depth--;
  169. }
  170. else
  171. {
  172. // It appears we have some attributes. Let's parse them.
  173. XMLAttributes attributes;
  174. if (!ReadAttributes(attributes))
  175. return false;
  176. if (PeekString((const unsigned char*) ">"))
  177. {
  178. HandleElementStart(tag_name, attributes);
  179. section_opened = true;
  180. }
  181. else if (PeekString((const unsigned char*) "/") &&
  182. PeekString((const unsigned char*) ">"))
  183. {
  184. HandleElementStart(tag_name, attributes);
  185. HandleElementEnd(tag_name);
  186. // Tag immediately closed, reduce count
  187. open_tag_depth--;
  188. }
  189. else
  190. {
  191. return false;
  192. }
  193. }
  194. // Check if this tag needs to processed as CDATA.
  195. if (section_opened)
  196. {
  197. String lcase_tag_name = ToLower(tag_name);
  198. if (cdata_tags.find(lcase_tag_name) != cdata_tags.end())
  199. {
  200. if (ReadCDATA(lcase_tag_name.c_str()))
  201. {
  202. open_tag_depth--;
  203. if (!data.empty())
  204. {
  205. HandleData(data);
  206. data.clear();
  207. }
  208. HandleElementEnd(tag_name);
  209. return true;
  210. }
  211. return false;
  212. }
  213. }
  214. return true;
  215. }
  216. bool BaseXMLParser::ReadCloseTag()
  217. {
  218. // Closing tag; send data immediately and close the tag.
  219. if (!data.empty())
  220. {
  221. HandleData(data);
  222. data.clear();
  223. }
  224. String tag_name;
  225. if (!FindString((const unsigned char*) ">", tag_name))
  226. return false;
  227. HandleElementEnd(StringUtilities::StripWhitespace(tag_name));
  228. // Tag closed, reduce count
  229. open_tag_depth--;
  230. return true;
  231. }
  232. bool BaseXMLParser::ReadAttributes(XMLAttributes& attributes)
  233. {
  234. for (;;)
  235. {
  236. String attribute;
  237. String value;
  238. // Get the attribute name
  239. if (!FindWord(attribute, "=/>"))
  240. {
  241. return false;
  242. }
  243. // Check if theres an assigned value
  244. if (PeekString((const unsigned char*)"="))
  245. {
  246. if (PeekString((const unsigned char*) "\""))
  247. {
  248. if (!FindString((const unsigned char*) "\"", value))
  249. return false;
  250. }
  251. else if (PeekString((const unsigned char*) "'"))
  252. {
  253. if (!FindString((const unsigned char*) "'", value))
  254. return false;
  255. }
  256. else if (!FindWord(value, "/>"))
  257. {
  258. return false;
  259. }
  260. }
  261. attributes.emplace(attribute, value);
  262. // Check for the end of the tag.
  263. if (PeekString((const unsigned char*) "/", false) ||
  264. PeekString((const unsigned char*) ">", false))
  265. return true;
  266. }
  267. }
  268. bool BaseXMLParser::ReadCDATA(const char* terminator)
  269. {
  270. String cdata;
  271. if (terminator == NULL)
  272. {
  273. FindString((const unsigned char*) "]]>", cdata);
  274. data += cdata;
  275. return true;
  276. }
  277. else
  278. {
  279. for (;;)
  280. {
  281. // Search for the next tag opening.
  282. if (!FindString((const unsigned char*) "<", cdata))
  283. return false;
  284. if (PeekString((const unsigned char*) "/", false))
  285. {
  286. String tag;
  287. if (FindString((const unsigned char*) ">", tag))
  288. {
  289. size_t slash_pos = tag.find('/');
  290. String tag_name = StringUtilities::StripWhitespace(slash_pos == String::npos ? tag : tag.substr(slash_pos + 1));
  291. if (ToLower(tag_name) == terminator)
  292. {
  293. data += cdata;
  294. return true;
  295. }
  296. else
  297. {
  298. cdata += "<";
  299. cdata += tag;
  300. cdata += ">";
  301. }
  302. }
  303. else
  304. cdata += "<";
  305. }
  306. else
  307. cdata += "<";
  308. }
  309. }
  310. }
  311. // Reads from the stream until a complete word is found.
  312. bool BaseXMLParser::FindWord(String& word, const char* terminators)
  313. {
  314. for (;;)
  315. {
  316. if (read >= buffer + buffer_used)
  317. {
  318. if (!FillBuffer())
  319. return false;
  320. }
  321. // Ignore white space
  322. if (StringUtilities::IsWhitespace(*read))
  323. {
  324. if (word.empty())
  325. {
  326. read++;
  327. continue;
  328. }
  329. else
  330. return true;
  331. }
  332. // Check for termination condition
  333. if (terminators && strchr(terminators, *read))
  334. {
  335. return !word.empty();
  336. }
  337. word += *read;
  338. read++;
  339. }
  340. }
  341. // Reads from the stream until the given character set is found.
  342. bool BaseXMLParser::FindString(const unsigned char* string, String& data)
  343. {
  344. int index = 0;
  345. while (string[index])
  346. {
  347. if (read >= buffer + buffer_used)
  348. {
  349. if (!FillBuffer())
  350. return false;
  351. }
  352. // Count line numbers
  353. if (*read == '\n')
  354. {
  355. line_number++;
  356. }
  357. if (*read == string[index])
  358. {
  359. index += 1;
  360. }
  361. else
  362. {
  363. if (index > 0)
  364. {
  365. data += String((const char*)string, index);
  366. index = 0;
  367. }
  368. data += *read;
  369. }
  370. read++;
  371. }
  372. return true;
  373. }
  374. // Returns true if the next sequence of characters in the stream matches the
  375. // given string.
  376. bool BaseXMLParser::PeekString(const unsigned char* string, bool consume)
  377. {
  378. unsigned char* peek_read = read;
  379. int i = 0;
  380. while (string[i])
  381. {
  382. // If we're about to read past the end of the buffer, read into the
  383. // overflow buffer.
  384. if ((peek_read - buffer) + i >= buffer_used)
  385. {
  386. int peek_offset = (int)(peek_read - read);
  387. FillBuffer();
  388. peek_read = read + peek_offset;
  389. if (peek_read - buffer + i >= buffer_used)
  390. {
  391. // Wierd, seems our buffer is too small, realloc it bigger.
  392. buffer_size *= 2;
  393. int read_offset = (int)(read - buffer);
  394. unsigned char* new_buffer = (unsigned char*) realloc(buffer, buffer_size);
  395. ROCKET_ASSERTMSG(new_buffer != NULL, "Unable to allocate larger buffer for Peek() call");
  396. if(new_buffer == NULL)
  397. {
  398. return false;
  399. }
  400. buffer = new_buffer;
  401. // Restore the read pointers.
  402. read = buffer + read_offset;
  403. peek_read = read + peek_offset;
  404. // Attempt to fill our new buffer size.
  405. if (!FillBuffer())
  406. return false;
  407. }
  408. }
  409. // Seek past all the whitespace if we haven't hit the initial character yet.
  410. if (i == 0 && StringUtilities::IsWhitespace(*peek_read))
  411. {
  412. peek_read++;
  413. }
  414. else
  415. {
  416. if (*peek_read != string[i])
  417. return false;
  418. i++;
  419. peek_read++;
  420. }
  421. }
  422. // Set the read pointer to the end of the peek.
  423. if (consume)
  424. {
  425. read = peek_read;
  426. }
  427. return true;
  428. }
  429. // Fill the buffer as much as possible, without removing any content that is still pending
  430. bool BaseXMLParser::FillBuffer()
  431. {
  432. int bytes_free = buffer_size;
  433. int bytes_remaining = Math::Max((int)(buffer_used - (read - buffer)), 0);
  434. // If theres any data still in the buffer, shift it down, and fill it again
  435. if (bytes_remaining > 0)
  436. {
  437. memmove(buffer, read, bytes_remaining);
  438. bytes_free = buffer_size - bytes_remaining;
  439. }
  440. read = buffer;
  441. size_t bytes_read = xml_source->Read(&buffer[bytes_remaining], bytes_free);
  442. buffer_used = (int)(bytes_read + bytes_remaining);
  443. return bytes_read > 0;
  444. }
  445. }
  446. }