HTMLParser.cpp 13 KB

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