HTMLParser.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. { "&copy;", "©" },
  207. { "&reg;", "®" },
  208. { "&szlig;", "ß" },
  209. { "&auml;", "ä" },
  210. { "&euml;", "ë" },
  211. { "&iuml;", "ï" },
  212. { "&ouml;", "ö" },
  213. { "&uuml;", "ü" },
  214. { "&yuml;", "ÿ" },
  215. { "&Auml;", "Ä" },
  216. { "&Euml;", "Ë" },
  217. { "&Iuml;", "Ï" },
  218. { "&Ouml;", "Ö" },
  219. { "&Uuml;", "Ü" },
  220. { "&Yuml;", "Ÿ" },
  221. };
  222. auto rest_of_html = html.substring_view(i, html.length() - i);
  223. bool found = false;
  224. for (auto& escape : escapes) {
  225. if (rest_of_html.starts_with(escape.code)) {
  226. text_buffer.append(escape.value);
  227. found = true;
  228. i += strlen(escape.code) - 1;
  229. break;
  230. }
  231. }
  232. if (!found) {
  233. char num_sign = html[i + 1];
  234. if (num_sign && num_sign == '#') {
  235. int j = 2; // spip '&#' and search for ';'
  236. while (html[i + j] != ';' && j < 7) {
  237. j++;
  238. }
  239. if (j < 7) { // We found ; char
  240. bool ok;
  241. u32 codepoint;
  242. String str_code_point = html.substring_view(i + 2, j - 2);
  243. if (str_code_point.starts_with('x')) {
  244. String str = str_code_point.substring(1, str_code_point.length() - 1);
  245. codepoint = AK::StringUtils::convert_to_uint_from_hex(str, ok);
  246. } else {
  247. codepoint = str_code_point.to_uint(ok);
  248. }
  249. if (ok) {
  250. Vector<char> bytes = codepoint_to_bytes(codepoint);
  251. if (bytes.size() > 0) {
  252. for (size_t i = 0; i < bytes.size(); i++) {
  253. text_buffer.append(bytes.at(i));
  254. }
  255. found = true;
  256. i = i + j;
  257. }
  258. }
  259. }
  260. }
  261. }
  262. if (!found) {
  263. dbg() << "Unhandled escape sequence:" << html.substring_view(i, min((size_t)5, html.length()));
  264. }
  265. }
  266. break;
  267. case State::BeforeTagName:
  268. if (ch == '/') {
  269. is_slash_tag = true;
  270. break;
  271. }
  272. if (ch == '!') {
  273. if (toupper(peek(1)) == 'D'
  274. && toupper(peek(2)) == 'O'
  275. && toupper(peek(3)) == 'C'
  276. && toupper(peek(4)) == 'T'
  277. && toupper(peek(5)) == 'Y'
  278. && toupper(peek(6)) == 'P'
  279. && toupper(peek(7)) == 'E') {
  280. i += 7;
  281. move_to_state(State::InDoctype);
  282. break;
  283. }
  284. if (peek(1) == '-' && peek(2) == '-') {
  285. i += 2;
  286. move_to_state(State::InComment);
  287. break;
  288. }
  289. break;
  290. }
  291. if (ch == '>') {
  292. move_to_state(State::Free);
  293. break;
  294. }
  295. if (!isalpha(ch))
  296. break;
  297. move_to_state(State::InTagName);
  298. [[fallthrough]];
  299. case State::InTagName:
  300. if (isspace(ch)) {
  301. move_to_state(State::InAttributeList);
  302. break;
  303. }
  304. if (ch == '/' && peek(1) == '>') {
  305. open_tag();
  306. close_tag();
  307. i += 1;
  308. move_to_state(State::Free);
  309. break;
  310. }
  311. if (ch == '>') {
  312. commit_tag();
  313. move_to_state(State::Free);
  314. break;
  315. }
  316. tag_name_buffer.append(ch);
  317. break;
  318. case State::InDoctype:
  319. if (ch == '>') {
  320. commit_doctype();
  321. move_to_state(State::Free);
  322. break;
  323. }
  324. break;
  325. case State::InComment:
  326. if (ch == '-' && peek(1) == '-' && peek(2) == '>') {
  327. commit_comment();
  328. i += 2;
  329. move_to_state(State::Free);
  330. break;
  331. }
  332. text_buffer.append(ch);
  333. break;
  334. case State::InAttributeList:
  335. if (ch == '>') {
  336. commit_tag();
  337. move_to_state(State::Free);
  338. break;
  339. }
  340. if (!isalpha(ch))
  341. break;
  342. move_to_state(State::InAttributeName);
  343. [[fallthrough]];
  344. case State::InAttributeName:
  345. if (is_valid_in_attribute_name(ch)) {
  346. attribute_name_buffer.append(ch);
  347. break;
  348. }
  349. if (isspace(ch)) {
  350. commit_attribute();
  351. break;
  352. }
  353. if (ch == '>') {
  354. commit_attribute();
  355. commit_tag();
  356. move_to_state(State::Free);
  357. break;
  358. }
  359. if (ch == '=') {
  360. move_to_state(State::BeforeAttributeValue);
  361. break;
  362. }
  363. break;
  364. case State::BeforeAttributeValue:
  365. if (ch == '\'') {
  366. move_to_state(State::InAttributeValueSingleQuote);
  367. break;
  368. }
  369. if (ch == '"') {
  370. move_to_state(State::InAttributeValueDoubleQuote);
  371. break;
  372. }
  373. if (ch == '>') {
  374. commit_tag();
  375. move_to_state(State::Free);
  376. break;
  377. }
  378. if (isspace(ch)) {
  379. commit_attribute();
  380. move_to_state(State::InAttributeList);
  381. break;
  382. }
  383. move_to_state(State::InAttributeValueNoQuote);
  384. [[fallthrough]];
  385. case State::InAttributeValueNoQuote:
  386. if (isspace(ch)) {
  387. commit_attribute();
  388. move_to_state(State::InAttributeList);
  389. break;
  390. }
  391. if (ch == '>') {
  392. commit_attribute();
  393. commit_tag();
  394. move_to_state(State::Free);
  395. break;
  396. }
  397. attribute_value_buffer.append(ch);
  398. break;
  399. case State::InAttributeValueSingleQuote:
  400. if (ch == '\'') {
  401. commit_attribute();
  402. move_to_state(State::InAttributeList);
  403. break;
  404. }
  405. attribute_value_buffer.append(ch);
  406. break;
  407. case State::InAttributeValueDoubleQuote:
  408. if (ch == '"') {
  409. commit_attribute();
  410. move_to_state(State::InAttributeList);
  411. break;
  412. }
  413. attribute_value_buffer.append(ch);
  414. break;
  415. default:
  416. fprintf(stderr, "Unhandled state %d\n", (int)state);
  417. ASSERT_NOT_REACHED();
  418. }
  419. }
  420. if (!text_buffer.is_empty())
  421. commit_text_node();
  422. return true;
  423. }
  424. String to_utf8(const StringView& input, const String& encoding)
  425. {
  426. auto* decoder = TextCodec::decoder_for(encoding);
  427. ASSERT(decoder);
  428. return decoder->to_utf8(input);
  429. }
  430. RefPtr<DocumentFragment> parse_html_fragment(Document& document, const StringView& raw_html, const String& encoding)
  431. {
  432. auto fragment = adopt(*new DocumentFragment(document));
  433. if (!parse_html_document(to_utf8(raw_html, encoding), document, *fragment))
  434. return nullptr;
  435. return fragment;
  436. }
  437. RefPtr<Document> parse_html_document(const StringView& raw_html, const URL& url, const String& encoding)
  438. {
  439. String html = to_utf8(raw_html, encoding);
  440. auto document = adopt(*new Document(url));
  441. document->set_source(html);
  442. if (!parse_html_document(html, *document, *document))
  443. return nullptr;
  444. document->fixup();
  445. #if 0
  446. Function<void(Node&)> fire_insertion_callbacks = [&](Node& node) {
  447. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  448. fire_insertion_callbacks(*child);
  449. }
  450. if (node.parent())
  451. node.inserted_into(*node.parent());
  452. };
  453. fire_insertion_callbacks(document);
  454. #endif
  455. document->dispatch_event(Event::create("DOMContentLoaded"));
  456. return document;
  457. }
  458. }