HTMLParser.cpp 13 KB

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