HTMLParser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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_void_element(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_void_element(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 == '/' && peek(1) == '>') {
  240. open_tag();
  241. close_tag();
  242. i += 1;
  243. move_to_state(State::Free);
  244. break;
  245. }
  246. if (ch == '>') {
  247. commit_tag();
  248. move_to_state(State::Free);
  249. break;
  250. }
  251. tag_name_buffer.append(ch);
  252. break;
  253. case State::InDoctype:
  254. if (ch == '>') {
  255. commit_doctype();
  256. move_to_state(State::Free);
  257. break;
  258. }
  259. break;
  260. case State::InComment:
  261. if (ch == '-' && peek(1) == '-' && peek(2) == '>') {
  262. commit_comment();
  263. i += 2;
  264. move_to_state(State::Free);
  265. break;
  266. }
  267. text_buffer.append(ch);
  268. break;
  269. case State::InAttributeList:
  270. if (ch == '>') {
  271. commit_tag();
  272. move_to_state(State::Free);
  273. break;
  274. }
  275. if (!isalpha(ch))
  276. break;
  277. move_to_state(State::InAttributeName);
  278. [[fallthrough]];
  279. case State::InAttributeName:
  280. if (is_valid_in_attribute_name(ch)) {
  281. attribute_name_buffer.append(ch);
  282. break;
  283. }
  284. if (isspace(ch)) {
  285. commit_attribute();
  286. break;
  287. }
  288. if (ch == '>') {
  289. commit_attribute();
  290. commit_tag();
  291. move_to_state(State::Free);
  292. break;
  293. }
  294. if (ch == '=') {
  295. move_to_state(State::BeforeAttributeValue);
  296. break;
  297. }
  298. break;
  299. case State::BeforeAttributeValue:
  300. if (ch == '\'') {
  301. move_to_state(State::InAttributeValueSingleQuote);
  302. break;
  303. }
  304. if (ch == '"') {
  305. move_to_state(State::InAttributeValueDoubleQuote);
  306. break;
  307. }
  308. if (ch == '>') {
  309. commit_tag();
  310. move_to_state(State::Free);
  311. break;
  312. }
  313. if (isspace(ch)) {
  314. commit_attribute();
  315. move_to_state(State::InAttributeList);
  316. break;
  317. }
  318. move_to_state(State::InAttributeValueNoQuote);
  319. [[fallthrough]];
  320. case State::InAttributeValueNoQuote:
  321. if (isspace(ch)) {
  322. commit_attribute();
  323. move_to_state(State::InAttributeList);
  324. break;
  325. }
  326. if (ch == '>') {
  327. commit_attribute();
  328. commit_tag();
  329. move_to_state(State::Free);
  330. break;
  331. }
  332. attribute_value_buffer.append(ch);
  333. break;
  334. case State::InAttributeValueSingleQuote:
  335. if (ch == '\'') {
  336. commit_attribute();
  337. move_to_state(State::InAttributeList);
  338. break;
  339. }
  340. attribute_value_buffer.append(ch);
  341. break;
  342. case State::InAttributeValueDoubleQuote:
  343. if (ch == '"') {
  344. commit_attribute();
  345. move_to_state(State::InAttributeList);
  346. break;
  347. }
  348. attribute_value_buffer.append(ch);
  349. break;
  350. default:
  351. fprintf(stderr, "Unhandled state %d\n", (int)state);
  352. ASSERT_NOT_REACHED();
  353. }
  354. }
  355. if (!text_buffer.is_empty())
  356. commit_text_node();
  357. return true;
  358. }
  359. RefPtr<DocumentFragment> parse_html_fragment(Document& document, const StringView& html)
  360. {
  361. auto fragment = adopt(*new DocumentFragment(document));
  362. if (!parse_html_document(html, document, *fragment))
  363. return nullptr;
  364. return fragment;
  365. }
  366. RefPtr<Document> parse_html_document(const StringView& html, const URL& url)
  367. {
  368. auto document = adopt(*new Document(url));
  369. document->set_source(html);
  370. if (!parse_html_document(html, *document, *document))
  371. return nullptr;
  372. document->fixup();
  373. #if 0
  374. Function<void(Node&)> fire_insertion_callbacks = [&](Node& node) {
  375. for (auto* child = node.first_child(); child; child = child->next_sibling()) {
  376. fire_insertion_callbacks(*child);
  377. }
  378. if (node.parent())
  379. node.inserted_into(*node.parent());
  380. };
  381. fire_insertion_callbacks(document);
  382. #endif
  383. document->dispatch_event(Event::create("DOMContentLoaded"));
  384. return document;
  385. }
  386. }