HTMLParser.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Function.h>
  27. #include <AK/NonnullRefPtrVector.h>
  28. #include <AK/StringBuilder.h>
  29. #include <AK/StringUtils.h>
  30. #include <LibTextCodec/Decoder.h>
  31. #include <LibWeb/DOM/Comment.h>
  32. #include <LibWeb/DOM/DocumentFragment.h>
  33. #include <LibWeb/DOM/DocumentType.h>
  34. #include <LibWeb/DOM/Element.h>
  35. #include <LibWeb/DOM/ElementFactory.h>
  36. #include <LibWeb/DOM/Event.h>
  37. #include <LibWeb/DOM/Text.h>
  38. #include <LibWeb/Parser/HTMLParser.h>
  39. #include <ctype.h>
  40. #include <stdio.h>
  41. namespace Web {
  42. static bool is_valid_in_attribute_name(char ch)
  43. {
  44. return isalnum(ch) || ch == '_' || ch == '-';
  45. }
  46. static bool is_void_element(const StringView& tag_name)
  47. {
  48. return tag_name == "area"
  49. || tag_name == "base"
  50. || tag_name == "br"
  51. || tag_name == "col"
  52. || tag_name == "embed"
  53. || tag_name == "hr"
  54. || tag_name == "img"
  55. || tag_name == "input"
  56. || tag_name == "link"
  57. || tag_name == "meta"
  58. || tag_name == "param"
  59. || tag_name == "source"
  60. || tag_name == "track"
  61. || tag_name == "wbr";
  62. }
  63. static Vector<char> codepoint_to_bytes(const u32 codepoint)
  64. {
  65. Vector<char, 0> bytes;
  66. if (codepoint < 0x80) {
  67. bytes.insert(0, (char)codepoint);
  68. } else if (codepoint < 0x800) {
  69. char b2 = (codepoint & 0x3F) + 0x80;
  70. char b1 = ((codepoint >> 6) & 0x1F) + +0xC0;
  71. bytes.insert(0, b1);
  72. bytes.insert(1, b2);
  73. }
  74. return bytes;
  75. }
  76. static bool parse_html_document(const StringView& html, Document& document, ParentNode& root)
  77. {
  78. NonnullRefPtrVector<ParentNode> node_stack;
  79. node_stack.append(root);
  80. enum class State {
  81. Free = 0,
  82. BeforeTagName,
  83. InTagName,
  84. InDoctype,
  85. InComment,
  86. InAttributeList,
  87. InAttributeName,
  88. BeforeAttributeValue,
  89. InAttributeValueNoQuote,
  90. InAttributeValueSingleQuote,
  91. InAttributeValueDoubleQuote,
  92. };
  93. auto state = State::Free;
  94. StringBuilder text_buffer;
  95. Vector<char, 32> tag_name_buffer;
  96. Vector<Attribute> attributes;
  97. Vector<char, 256> attribute_name_buffer;
  98. Vector<char, 256> attribute_value_buffer;
  99. bool is_slash_tag = false;
  100. bool is_exclamation_tag = false;
  101. auto commit_text_node = [&] {
  102. auto text_node = adopt(*new Text(document, text_buffer.to_string()));
  103. node_stack.last().append_child(text_node);
  104. text_buffer.clear();
  105. };
  106. auto move_to_state = [&](State new_state) {
  107. if (new_state == State::BeforeTagName) {
  108. is_slash_tag = false;
  109. is_exclamation_tag = false;
  110. tag_name_buffer.clear();
  111. attributes.clear();
  112. }
  113. if (new_state == State::InAttributeName)
  114. attribute_name_buffer.clear();
  115. if (new_state == State::BeforeAttributeValue)
  116. attribute_value_buffer.clear();
  117. if (state == State::Free && !text_buffer.is_empty()) {
  118. commit_text_node();
  119. }
  120. state = new_state;
  121. text_buffer.clear();
  122. };
  123. auto close_tag = [&] {
  124. if (node_stack.size() > 1)
  125. node_stack.take_last();
  126. };
  127. auto open_tag = [&] {
  128. auto new_element = create_element(document, String::copy(tag_name_buffer));
  129. tag_name_buffer.clear();
  130. new_element->set_attributes(move(attributes));
  131. node_stack.append(new_element);
  132. if (node_stack.size() != 1) {
  133. node_stack[node_stack.size() - 2].append_child(new_element);
  134. }
  135. if (is_void_element(new_element->tag_name()))
  136. close_tag();
  137. };
  138. auto commit_doctype = [&] {
  139. node_stack.last().append_child(adopt(*new DocumentType(document)));
  140. };
  141. auto commit_comment = [&] {
  142. node_stack.last().append_child(adopt(*new Comment(document, text_buffer.to_string())));
  143. };
  144. auto commit_tag = [&] {
  145. if (is_slash_tag)
  146. close_tag();
  147. else
  148. open_tag();
  149. };
  150. auto commit_attribute = [&] {
  151. if (!attribute_name_buffer.is_empty()) {
  152. auto name = String::copy(attribute_name_buffer);
  153. String value;
  154. if (attribute_value_buffer.is_empty())
  155. value = String::empty();
  156. else
  157. value = String::copy(attribute_value_buffer);
  158. attributes.empend(name, value);
  159. }
  160. };
  161. for (size_t i = 0; i < html.length(); ++i) {
  162. auto peek = [&](size_t offset) -> char {
  163. if (i + offset >= html.length())
  164. return '\0';
  165. return html[i + offset];
  166. };
  167. char ch = html[i];
  168. switch (state) {
  169. case State::Free:
  170. if (ch == '<') {
  171. bool should_treat_as_text = false;
  172. if (node_stack.last().tag_name() == "script") {
  173. bool is_script_close_tag = peek(1) == '/'
  174. && tolower(peek(2)) == 's'
  175. && tolower(peek(3)) == 'c'
  176. && tolower(peek(4)) == 'r'
  177. && tolower(peek(5)) == 'i'
  178. && tolower(peek(6)) == 'p'
  179. && tolower(peek(7)) == 't'
  180. && tolower(peek(8)) == '>';
  181. if (!is_script_close_tag)
  182. should_treat_as_text = true;
  183. }
  184. if (!should_treat_as_text) {
  185. is_slash_tag = false;
  186. move_to_state(State::BeforeTagName);
  187. break;
  188. }
  189. }
  190. if (ch != '&') {
  191. text_buffer.append(ch);
  192. } else {
  193. struct Escape {
  194. const char* code;
  195. const char* value;
  196. };
  197. static Escape escapes[] = {
  198. { "&lt;", "<" },
  199. { "&gt;", ">" },
  200. { "&amp;", "&" },
  201. { "&mdash;", "-" },
  202. { "&nbsp;", " " }, // FIXME: Should actually be *non-breaking*
  203. { "&quot;", "\"" },
  204. { "&raquo;", ">>" },
  205. { "&laquo;", "<<" },
  206. };
  207. auto rest_of_html = html.substring_view(i, html.length() - i);
  208. bool found = false;
  209. for (auto& escape : escapes) {
  210. if (rest_of_html.starts_with(escape.code)) {
  211. text_buffer.append(escape.value);
  212. found = true;
  213. i += strlen(escape.code) - 1;
  214. break;
  215. }
  216. }
  217. if (!found) {
  218. char num_sign = html[i + 1];
  219. if (num_sign && num_sign == '#') {
  220. int j = 2; // spip '&#' and search for ';'
  221. while (html[i + j] != ';' && j < 7) {
  222. j++;
  223. }
  224. if (j < 7) { // We found ; char
  225. bool ok;
  226. u32 codepoint;
  227. String str_code_point = html.substring_view(i + 2, j - 2);
  228. if (str_code_point.starts_with('x')) {
  229. String str = str_code_point.substring(1, str_code_point.length() - 1);
  230. codepoint = AK::StringUtils::convert_to_uint_from_hex(str, ok);
  231. } else {
  232. codepoint = str_code_point.to_uint(ok);
  233. }
  234. if (ok) {
  235. Vector<char> bytes = codepoint_to_bytes(codepoint);
  236. if (bytes.size() > 0) {
  237. for (size_t i = 0; i < bytes.size(); i++) {
  238. text_buffer.append(bytes.at(i));
  239. }
  240. found = true;
  241. i = i + j;
  242. }
  243. }
  244. }
  245. }
  246. }
  247. if (!found) {
  248. dbg() << "Unhandled escape sequence:" << html.substring_view(i, min((size_t)5, html.length()));
  249. }
  250. }
  251. break;
  252. case State::BeforeTagName:
  253. if (ch == '/') {
  254. is_slash_tag = true;
  255. break;
  256. }
  257. if (ch == '!') {
  258. if (toupper(peek(1)) == 'D'
  259. && toupper(peek(2)) == 'O'
  260. && toupper(peek(3)) == 'C'
  261. && toupper(peek(4)) == 'T'
  262. && toupper(peek(5)) == 'Y'
  263. && toupper(peek(6)) == 'P'
  264. && toupper(peek(7)) == 'E') {
  265. i += 7;
  266. move_to_state(State::InDoctype);
  267. break;
  268. }
  269. if (peek(1) == '-' && peek(2) == '-') {
  270. i += 2;
  271. move_to_state(State::InComment);
  272. break;
  273. }
  274. break;
  275. }
  276. if (ch == '>') {
  277. move_to_state(State::Free);
  278. break;
  279. }
  280. if (!isalpha(ch))
  281. break;
  282. move_to_state(State::InTagName);
  283. [[fallthrough]];
  284. case State::InTagName:
  285. if (isspace(ch)) {
  286. move_to_state(State::InAttributeList);
  287. break;
  288. }
  289. if (ch == '/' && peek(1) == '>') {
  290. open_tag();
  291. close_tag();
  292. i += 1;
  293. move_to_state(State::Free);
  294. break;
  295. }
  296. if (ch == '>') {
  297. commit_tag();
  298. move_to_state(State::Free);
  299. break;
  300. }
  301. tag_name_buffer.append(ch);
  302. break;
  303. case State::InDoctype:
  304. if (ch == '>') {
  305. commit_doctype();
  306. move_to_state(State::Free);
  307. break;
  308. }
  309. break;
  310. case State::InComment:
  311. if (ch == '-' && peek(1) == '-' && peek(2) == '>') {
  312. commit_comment();
  313. i += 2;
  314. move_to_state(State::Free);
  315. break;
  316. }
  317. text_buffer.append(ch);
  318. break;
  319. case State::InAttributeList:
  320. if (ch == '>') {
  321. commit_tag();
  322. move_to_state(State::Free);
  323. break;
  324. }
  325. if (!isalpha(ch))
  326. break;
  327. move_to_state(State::InAttributeName);
  328. [[fallthrough]];
  329. case State::InAttributeName:
  330. if (is_valid_in_attribute_name(ch)) {
  331. attribute_name_buffer.append(ch);
  332. break;
  333. }
  334. if (isspace(ch)) {
  335. commit_attribute();
  336. break;
  337. }
  338. if (ch == '>') {
  339. commit_attribute();
  340. commit_tag();
  341. move_to_state(State::Free);
  342. break;
  343. }
  344. if (ch == '=') {
  345. move_to_state(State::BeforeAttributeValue);
  346. break;
  347. }
  348. break;
  349. case State::BeforeAttributeValue:
  350. if (ch == '\'') {
  351. move_to_state(State::InAttributeValueSingleQuote);
  352. break;
  353. }
  354. if (ch == '"') {
  355. move_to_state(State::InAttributeValueDoubleQuote);
  356. break;
  357. }
  358. if (ch == '>') {
  359. commit_tag();
  360. move_to_state(State::Free);
  361. break;
  362. }
  363. if (isspace(ch)) {
  364. commit_attribute();
  365. move_to_state(State::InAttributeList);
  366. break;
  367. }
  368. move_to_state(State::InAttributeValueNoQuote);
  369. [[fallthrough]];
  370. case State::InAttributeValueNoQuote:
  371. if (isspace(ch)) {
  372. commit_attribute();
  373. move_to_state(State::InAttributeList);
  374. break;
  375. }
  376. if (ch == '>') {
  377. commit_attribute();
  378. commit_tag();
  379. move_to_state(State::Free);
  380. break;
  381. }
  382. attribute_value_buffer.append(ch);
  383. break;
  384. case State::InAttributeValueSingleQuote:
  385. if (ch == '\'') {
  386. commit_attribute();
  387. move_to_state(State::InAttributeList);
  388. break;
  389. }
  390. attribute_value_buffer.append(ch);
  391. break;
  392. case State::InAttributeValueDoubleQuote:
  393. if (ch == '"') {
  394. commit_attribute();
  395. move_to_state(State::InAttributeList);
  396. break;
  397. }
  398. attribute_value_buffer.append(ch);
  399. break;
  400. default:
  401. fprintf(stderr, "Unhandled state %d\n", (int)state);
  402. ASSERT_NOT_REACHED();
  403. }
  404. }
  405. if (!text_buffer.is_empty())
  406. commit_text_node();
  407. return true;
  408. }
  409. String to_utf8(const StringView& input, const String& encoding)
  410. {
  411. auto* decoder = TextCodec::decoder_for(encoding);
  412. ASSERT(decoder);
  413. return decoder->to_utf8(input);
  414. }
  415. RefPtr<DocumentFragment> parse_html_fragment(Document& document, const StringView& raw_html, const String& encoding)
  416. {
  417. auto fragment = adopt(*new DocumentFragment(document));
  418. if (!parse_html_document(to_utf8(raw_html, encoding), document, *fragment))
  419. return nullptr;
  420. return fragment;
  421. }
  422. RefPtr<Document> parse_html_document(const StringView& raw_html, const URL& url, const String& encoding)
  423. {
  424. String html = to_utf8(raw_html, encoding);
  425. auto document = adopt(*new Document(url));
  426. document->set_source(html);
  427. if (!parse_html_document(html, *document, *document))
  428. return nullptr;
  429. document->fixup();
  430. #if 0
  431. Function<void(Node&)> fire_insertion_callbacks = [&](Node& node) {
  432. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  433. fire_insertion_callbacks(*child);
  434. }
  435. if (node.parent())
  436. node.inserted_into(*node.parent());
  437. };
  438. fire_insertion_callbacks(document);
  439. #endif
  440. document->dispatch_event(Event::create("DOMContentLoaded"));
  441. return document;
  442. }
  443. }