HTMLParser.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 <LibWeb/DOM/Comment.h>
  30. #include <LibWeb/DOM/DocumentFragment.h>
  31. #include <LibWeb/DOM/DocumentType.h>
  32. #include <LibWeb/DOM/Element.h>
  33. #include <LibWeb/DOM/ElementFactory.h>
  34. #include <LibWeb/DOM/Text.h>
  35. #include <LibWeb/Parser/HTMLParser.h>
  36. #include <ctype.h>
  37. #include <stdio.h>
  38. namespace Web {
  39. static bool is_valid_in_attribute_name(char ch)
  40. {
  41. return isalnum(ch) || ch == '_' || ch == '-';
  42. }
  43. static bool is_self_closing_tag(const StringView& tag_name)
  44. {
  45. return tag_name == "area"
  46. || tag_name == "base"
  47. || tag_name == "br"
  48. || tag_name == "col"
  49. || tag_name == "embed"
  50. || tag_name == "hr"
  51. || tag_name == "img"
  52. || tag_name == "input"
  53. || tag_name == "link"
  54. || tag_name == "meta"
  55. || tag_name == "param"
  56. || tag_name == "source"
  57. || tag_name == "track"
  58. || tag_name == "wbr";
  59. }
  60. static bool parse_html_document(const StringView& html, Document& document, ParentNode& root)
  61. {
  62. NonnullRefPtrVector<ParentNode> node_stack;
  63. node_stack.append(root);
  64. enum class State {
  65. Free = 0,
  66. BeforeTagName,
  67. InTagName,
  68. InDoctype,
  69. InComment,
  70. InAttributeList,
  71. InAttributeName,
  72. BeforeAttributeValue,
  73. InAttributeValueNoQuote,
  74. InAttributeValueSingleQuote,
  75. InAttributeValueDoubleQuote,
  76. };
  77. auto state = State::Free;
  78. StringBuilder text_buffer;
  79. Vector<char, 32> tag_name_buffer;
  80. Vector<Attribute> attributes;
  81. Vector<char, 256> attribute_name_buffer;
  82. Vector<char, 256> attribute_value_buffer;
  83. bool is_slash_tag = false;
  84. bool is_exclamation_tag = false;
  85. auto move_to_state = [&](State new_state) {
  86. if (new_state == State::BeforeTagName) {
  87. is_slash_tag = false;
  88. is_exclamation_tag = false;
  89. tag_name_buffer.clear();
  90. attributes.clear();
  91. }
  92. if (new_state == State::InAttributeName)
  93. attribute_name_buffer.clear();
  94. if (new_state == State::BeforeAttributeValue)
  95. attribute_value_buffer.clear();
  96. if (state == State::Free && !text_buffer.string_view().is_empty()) {
  97. auto text_node = adopt(*new Text(document, text_buffer.to_string()));
  98. node_stack.last().append_child(text_node, false);
  99. }
  100. state = new_state;
  101. text_buffer.clear();
  102. };
  103. auto close_tag = [&] {
  104. if (node_stack.size() > 1)
  105. node_stack.take_last();
  106. };
  107. auto open_tag = [&] {
  108. auto new_element = create_element(document, String::copy(tag_name_buffer));
  109. tag_name_buffer.clear();
  110. new_element->set_attributes(move(attributes));
  111. node_stack.append(new_element);
  112. if (node_stack.size() != 1)
  113. node_stack[node_stack.size() - 2].append_child(new_element, false);
  114. if (is_self_closing_tag(new_element->tag_name()))
  115. close_tag();
  116. };
  117. auto commit_doctype = [&] {
  118. node_stack.last().append_child(adopt(*new DocumentType(document)), false);
  119. };
  120. auto commit_comment = [&] {
  121. node_stack.last().append_child(adopt(*new Comment(document, text_buffer.to_string())), false);
  122. };
  123. auto commit_tag = [&] {
  124. if (is_slash_tag)
  125. close_tag();
  126. else
  127. open_tag();
  128. };
  129. auto commit_attribute = [&] {
  130. if (!attribute_name_buffer.is_empty()) {
  131. auto name = String::copy(attribute_name_buffer);
  132. String value;
  133. if (attribute_value_buffer.is_empty())
  134. value = String::empty();
  135. else
  136. value = String::copy(attribute_value_buffer);
  137. attributes.empend(name, value);
  138. }
  139. };
  140. for (size_t i = 0; i < html.length(); ++i) {
  141. auto peek = [&](size_t offset) -> char {
  142. if (i + offset >= html.length())
  143. return '\0';
  144. return html[i + offset];
  145. };
  146. char ch = html[i];
  147. switch (state) {
  148. case State::Free:
  149. if (ch == '<') {
  150. is_slash_tag = false;
  151. move_to_state(State::BeforeTagName);
  152. break;
  153. }
  154. if (ch != '&') {
  155. text_buffer.append(ch);
  156. } else {
  157. struct Escape {
  158. const char* code;
  159. const char* value;
  160. };
  161. static Escape escapes[] = {
  162. { "&lt;", "<" },
  163. { "&gt;", ">" },
  164. { "&amp;", "&" },
  165. { "&mdash;", "-" },
  166. };
  167. auto rest_of_html = html.substring_view(i, html.length() - i);
  168. bool found = false;
  169. for (auto& escape : escapes) {
  170. if (rest_of_html.starts_with(escape.code)) {
  171. text_buffer.append(escape.value);
  172. found = true;
  173. i += strlen(escape.code) - 1;
  174. break;
  175. }
  176. }
  177. if (!found)
  178. dbg() << "Unhandled escape sequence";
  179. }
  180. break;
  181. case State::BeforeTagName:
  182. if (ch == '/') {
  183. is_slash_tag = true;
  184. break;
  185. }
  186. if (ch == '!') {
  187. if (toupper(peek(1)) == 'D'
  188. && toupper(peek(2)) == 'O'
  189. && toupper(peek(3)) == 'C'
  190. && toupper(peek(4)) == 'T'
  191. && toupper(peek(5)) == 'Y'
  192. && toupper(peek(6)) == 'P'
  193. && toupper(peek(7)) == 'E') {
  194. i += 7;
  195. move_to_state(State::InDoctype);
  196. break;
  197. }
  198. if (peek(1) == '-' && peek(2) == '-') {
  199. i += 2;
  200. move_to_state(State::InComment);
  201. break;
  202. }
  203. break;
  204. }
  205. if (ch == '>') {
  206. move_to_state(State::Free);
  207. break;
  208. }
  209. if (!isalpha(ch))
  210. break;
  211. move_to_state(State::InTagName);
  212. [[fallthrough]];
  213. case State::InTagName:
  214. if (isspace(ch)) {
  215. move_to_state(State::InAttributeList);
  216. break;
  217. }
  218. if (ch == '>') {
  219. commit_tag();
  220. move_to_state(State::Free);
  221. break;
  222. }
  223. tag_name_buffer.append(ch);
  224. break;
  225. case State::InDoctype:
  226. if (ch == '>') {
  227. commit_doctype();
  228. move_to_state(State::Free);
  229. break;
  230. }
  231. break;
  232. case State::InComment:
  233. if (ch == '-' && peek(1) == '-' && peek(2) == '>') {
  234. commit_comment();
  235. i += 2;
  236. move_to_state(State::Free);
  237. break;
  238. }
  239. text_buffer.append(ch);
  240. break;
  241. case State::InAttributeList:
  242. if (ch == '>') {
  243. commit_tag();
  244. move_to_state(State::Free);
  245. break;
  246. }
  247. if (!isalpha(ch))
  248. break;
  249. move_to_state(State::InAttributeName);
  250. [[fallthrough]];
  251. case State::InAttributeName:
  252. if (is_valid_in_attribute_name(ch)) {
  253. attribute_name_buffer.append(ch);
  254. break;
  255. }
  256. if (isspace(ch)) {
  257. commit_attribute();
  258. break;
  259. }
  260. if (ch == '>') {
  261. commit_attribute();
  262. commit_tag();
  263. move_to_state(State::Free);
  264. break;
  265. }
  266. if (ch == '=') {
  267. move_to_state(State::BeforeAttributeValue);
  268. break;
  269. }
  270. break;
  271. case State::BeforeAttributeValue:
  272. if (ch == '\'') {
  273. move_to_state(State::InAttributeValueSingleQuote);
  274. break;
  275. }
  276. if (ch == '"') {
  277. move_to_state(State::InAttributeValueDoubleQuote);
  278. break;
  279. }
  280. if (ch == '>') {
  281. commit_tag();
  282. move_to_state(State::Free);
  283. break;
  284. }
  285. if (isspace(ch)) {
  286. commit_attribute();
  287. move_to_state(State::InAttributeList);
  288. break;
  289. }
  290. move_to_state(State::InAttributeValueNoQuote);
  291. [[fallthrough]];
  292. case State::InAttributeValueNoQuote:
  293. if (isspace(ch)) {
  294. commit_attribute();
  295. move_to_state(State::InAttributeList);
  296. break;
  297. }
  298. if (ch == '>') {
  299. commit_attribute();
  300. commit_tag();
  301. move_to_state(State::Free);
  302. break;
  303. }
  304. attribute_value_buffer.append(ch);
  305. break;
  306. case State::InAttributeValueSingleQuote:
  307. if (ch == '\'') {
  308. commit_attribute();
  309. move_to_state(State::InAttributeList);
  310. break;
  311. }
  312. attribute_value_buffer.append(ch);
  313. break;
  314. case State::InAttributeValueDoubleQuote:
  315. if (ch == '"') {
  316. commit_attribute();
  317. move_to_state(State::InAttributeList);
  318. break;
  319. }
  320. attribute_value_buffer.append(ch);
  321. break;
  322. default:
  323. fprintf(stderr, "Unhandled state %d\n", (int)state);
  324. ASSERT_NOT_REACHED();
  325. }
  326. }
  327. return true;
  328. }
  329. RefPtr<DocumentFragment> parse_html_fragment(Document& document, const StringView& html)
  330. {
  331. auto fragment = adopt(*new DocumentFragment(document));
  332. if (!parse_html_document(html, document, *fragment))
  333. return nullptr;
  334. return fragment;
  335. }
  336. RefPtr<Document> parse_html_document(const StringView& html, const URL& url)
  337. {
  338. auto document = adopt(*new Document);
  339. document->set_url(url);
  340. document->set_source(html);
  341. if (!parse_html_document(html, *document, *document))
  342. return nullptr;
  343. document->fixup();
  344. Function<void(Node&)> fire_insertion_callbacks = [&](Node& node) {
  345. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  346. fire_insertion_callbacks(*child);
  347. }
  348. if (node.parent())
  349. node.inserted_into(*node.parent());
  350. };
  351. fire_insertion_callbacks(document);
  352. document->dispatch_event("DOMContentLoaded");
  353. return document;
  354. }
  355. }