Parser.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. /*
  2. * Copyright (c) 2022, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibXML/DOM/Document.h>
  7. #include <LibXML/Parser/Parser.h>
  8. struct Range {
  9. consteval Range(u32 start, u32 end)
  10. : start(start)
  11. , end(end)
  12. {
  13. }
  14. u32 start;
  15. u32 end;
  16. };
  17. template<auto... ranges>
  18. struct ranges_for_search {
  19. auto contains(u32 value) const
  20. {
  21. return ((value >= ranges.start && value <= ranges.end) || ...);
  22. }
  23. bool operator()(u32 value) const
  24. {
  25. return contains(value);
  26. }
  27. template<auto... ranges_to_include>
  28. consteval auto with() const
  29. {
  30. return ranges_for_search<ranges..., ranges_to_include...>();
  31. }
  32. template<auto... ranges_to_include>
  33. consteval auto unify(ranges_for_search<ranges_to_include...> const&) const
  34. {
  35. return ranges_for_search<ranges..., ranges_to_include...>();
  36. }
  37. };
  38. template<size_t Count, typename Element>
  39. struct StringSet {
  40. consteval StringSet(Element const (&entries)[Count])
  41. {
  42. for (size_t i = 0; i < Count - 1; ++i)
  43. elements[i] = entries[i];
  44. }
  45. consteval auto operator[](size_t i) const { return elements[i]; }
  46. Element elements[Count - 1];
  47. };
  48. template<StringSet chars>
  49. consteval static auto set_to_search()
  50. {
  51. return ([&]<auto... Ix>(IndexSequence<Ix...>) {
  52. return ranges_for_search<Range(chars[Ix], chars[Ix])...>();
  53. }(MakeIndexSequence<array_size(chars.elements)>()));
  54. }
  55. namespace XML {
  56. size_t Parser::s_debug_indent_level { 0 };
  57. void Parser::append_node(NonnullOwnPtr<Node> node)
  58. {
  59. if (m_entered_node) {
  60. auto& entered_element = m_entered_node->content.get<Node::Element>();
  61. entered_element.children.append(move(node));
  62. enter_node(*entered_element.children.last());
  63. } else {
  64. m_root_node = move(node);
  65. enter_node(*m_root_node);
  66. }
  67. }
  68. void Parser::append_text(StringView text)
  69. {
  70. if (m_listener) {
  71. m_listener->text(text);
  72. return;
  73. }
  74. if (!m_entered_node) {
  75. Node::Text node;
  76. node.builder.append(text);
  77. m_root_node = make<Node>(move(node));
  78. return;
  79. }
  80. m_entered_node->content.visit(
  81. [&](Node::Element& node) {
  82. if (!node.children.is_empty()) {
  83. auto* text_node = node.children.last()->content.get_pointer<Node::Text>();
  84. if (text_node) {
  85. text_node->builder.append(text);
  86. return;
  87. }
  88. }
  89. Node::Text text_node;
  90. text_node.builder.append(text);
  91. node.children.append(make<Node>(move(text_node)));
  92. },
  93. [&](auto&) {
  94. // Can't enter a text or comment node.
  95. VERIFY_NOT_REACHED();
  96. });
  97. }
  98. void Parser::append_comment(StringView text)
  99. {
  100. if (m_listener) {
  101. m_listener->comment(text);
  102. return;
  103. }
  104. // If there's no node to attach this to, drop it on the floor.
  105. // This can happen to comments in the prolog.
  106. if (!m_entered_node)
  107. return;
  108. m_entered_node->content.visit(
  109. [&](Node::Element& node) {
  110. node.children.append(make<Node>(Node::Comment { text }));
  111. },
  112. [&](auto&) {
  113. // Can't enter a text or comment node.
  114. VERIFY_NOT_REACHED();
  115. });
  116. }
  117. void Parser::enter_node(Node& node)
  118. {
  119. if (m_listener) {
  120. auto& element = node.content.get<Node::Element>();
  121. m_listener->element_start(element.name, element.attributes);
  122. }
  123. if (&node != m_root_node.ptr())
  124. node.parent = m_entered_node;
  125. m_entered_node = &node;
  126. }
  127. void Parser::leave_node()
  128. {
  129. if (m_listener) {
  130. auto& element = m_entered_node->content.get<Node::Element>();
  131. m_listener->element_end(element.name);
  132. }
  133. m_entered_node = m_entered_node->parent;
  134. }
  135. ErrorOr<Document, ParseError> Parser::parse()
  136. {
  137. if (auto result = parse_internal(); result.is_error()) {
  138. if (m_parse_errors.is_empty())
  139. return result.release_error();
  140. return m_parse_errors.take_first();
  141. }
  142. return Document {
  143. m_root_node.release_nonnull(),
  144. move(m_doctype),
  145. move(m_processing_instructions),
  146. m_version,
  147. };
  148. }
  149. ErrorOr<void, ParseError> Parser::parse_with_listener(Listener& listener)
  150. {
  151. m_listener = &listener;
  152. ScopeGuard unset_listener { [this] { m_listener = nullptr; } };
  153. m_listener->set_source(m_source);
  154. m_listener->document_start();
  155. auto result = parse_internal();
  156. if (result.is_error())
  157. m_listener->error(result.error());
  158. m_listener->document_end();
  159. m_root_node.clear();
  160. return result;
  161. }
  162. // 2.3.3. S, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-S
  163. ErrorOr<void, ParseError> Parser::skip_whitespace(Required required)
  164. {
  165. auto rollback = rollback_point();
  166. auto rule = enter_rule();
  167. // S ::= (#x20 | #x9 | #xD | #xA)+
  168. auto matched = m_lexer.consume_while(is_any_of("\x20\x09\x0d\x0a"sv));
  169. if (required == Required::Yes && matched.is_empty())
  170. return parse_error(m_lexer.tell(), "Expected whitespace");
  171. rollback.disarm();
  172. return {};
  173. }
  174. // 2.2.a. RestrictedChar, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-RestrictedChar
  175. constexpr static auto s_restricted_characters = ranges_for_search<Range(0x1, 0x8), Range(0xb, 0xc), Range(0xe, 0x1f), Range(0x7f, 0x84), Range(0x86, 0x9f)>();
  176. // 2.1.1. Document, https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-well-formed
  177. ErrorOr<void, ParseError> Parser::parse_internal()
  178. {
  179. auto rule = enter_rule();
  180. // document ::= ( prolog element Misc* ) - ( Char* RestrictedChar Char* )
  181. TRY(parse_prolog());
  182. TRY(parse_element());
  183. while (true) {
  184. if (auto result = parse_misc(); result.is_error())
  185. break;
  186. }
  187. auto matched_source = m_source.substring_view(0, m_lexer.tell());
  188. if (auto it = find_if(matched_source.begin(), matched_source.end(), s_restricted_characters); !it.is_end()) {
  189. return parse_error(
  190. it.index(),
  191. DeprecatedString::formatted("Invalid character #{:x} used in document", *it));
  192. }
  193. if (!m_lexer.is_eof())
  194. return parse_error(m_lexer.tell(), "Garbage after document");
  195. return {};
  196. }
  197. ErrorOr<void, ParseError> Parser::expect(StringView expected)
  198. {
  199. auto rollback = rollback_point();
  200. if (!m_lexer.consume_specific(expected)) {
  201. if (m_options.treat_errors_as_fatal)
  202. return parse_error(m_lexer.tell(), DeprecatedString::formatted("Expected '{}'", expected));
  203. }
  204. rollback.disarm();
  205. return {};
  206. }
  207. template<typename Pred>
  208. requires(IsCallableWithArguments<Pred, bool, char>) ErrorOr<StringView, ParseError> Parser::expect(Pred predicate, StringView description)
  209. {
  210. auto rollback = rollback_point();
  211. auto start = m_lexer.tell();
  212. if (!m_lexer.next_is(predicate)) {
  213. if (m_options.treat_errors_as_fatal)
  214. return parse_error(m_lexer.tell(), DeprecatedString::formatted("Expected {}", description));
  215. }
  216. m_lexer.ignore();
  217. rollback.disarm();
  218. return m_source.substring_view(start, m_lexer.tell() - start);
  219. }
  220. template<typename Pred>
  221. requires(IsCallableWithArguments<Pred, bool, char>) ErrorOr<StringView, ParseError> Parser::expect_many(Pred predicate, StringView description)
  222. {
  223. auto rollback = rollback_point();
  224. auto start = m_lexer.tell();
  225. while (m_lexer.next_is(predicate)) {
  226. if (m_lexer.is_eof())
  227. break;
  228. m_lexer.ignore();
  229. }
  230. if (m_lexer.tell() == start) {
  231. if (m_options.treat_errors_as_fatal) {
  232. return parse_error(m_lexer.tell(), DeprecatedString::formatted("Expected {}", description));
  233. }
  234. }
  235. rollback.disarm();
  236. return m_source.substring_view(start, m_lexer.tell() - start);
  237. }
  238. // 2.8.22. Prolog, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-prolog
  239. ErrorOr<void, ParseError> Parser::parse_prolog()
  240. {
  241. auto rollback = rollback_point();
  242. auto rule = enter_rule();
  243. // prolog ::= XMLDecl Misc* (doctypedecl Misc*)?
  244. // The following is valid in XML 1.0.
  245. // prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
  246. if (auto result = parse_xml_decl(); result.is_error()) {
  247. m_version = Version::Version10;
  248. m_in_compatibility_mode = true;
  249. }
  250. auto accept = accept_rule();
  251. while (true) {
  252. if (auto result = parse_misc(); result.is_error())
  253. break;
  254. }
  255. if (auto result = parse_doctype_decl(); !result.is_error()) {
  256. while (true) {
  257. if (auto result = parse_misc(); result.is_error())
  258. break;
  259. }
  260. }
  261. rollback.disarm();
  262. return {};
  263. }
  264. // 2.8.23. XMLDecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-XMLDecl
  265. ErrorOr<void, ParseError> Parser::parse_xml_decl()
  266. {
  267. auto rollback = rollback_point();
  268. auto rule = enter_rule();
  269. // XMLDecl::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
  270. TRY(expect("<?xml"sv));
  271. auto accept = accept_rule();
  272. TRY(parse_version_info());
  273. (void)parse_encoding_decl();
  274. (void)parse_standalone_document_decl();
  275. TRY(skip_whitespace());
  276. TRY(expect("?>"sv));
  277. rollback.disarm();
  278. return {};
  279. }
  280. // 2.8.24. VersionInfo, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-VersionInfo
  281. ErrorOr<void, ParseError> Parser::parse_version_info()
  282. {
  283. auto rollback = rollback_point();
  284. auto rule = enter_rule();
  285. // VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
  286. TRY(skip_whitespace(Required::Yes));
  287. TRY(expect("version"sv));
  288. auto accept = accept_rule();
  289. TRY(parse_eq());
  290. TRY(expect(is_any_of("'\""sv), "one of ' or \""sv));
  291. m_lexer.retreat();
  292. auto version_string = m_lexer.consume_quoted_string();
  293. if (version_string == "1.0") {
  294. // FIXME: Compatibility mode, figure out which rules are different in XML 1.0.
  295. m_version = Version::Version10;
  296. m_in_compatibility_mode = true;
  297. } else {
  298. if (version_string != "1.1" && m_options.treat_errors_as_fatal)
  299. return parse_error(m_lexer.tell(), DeprecatedString::formatted("Expected '1.1', found '{}'", version_string));
  300. }
  301. m_version = Version::Version11;
  302. rollback.disarm();
  303. return {};
  304. }
  305. // 2.8.25. Eq, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-Eq
  306. ErrorOr<void, ParseError> Parser::parse_eq()
  307. {
  308. auto rollback = rollback_point();
  309. auto rule = enter_rule();
  310. // Eq ::= S? '=' S?
  311. auto accept = accept_rule();
  312. TRY(skip_whitespace());
  313. TRY(expect("="sv));
  314. TRY(skip_whitespace());
  315. rollback.disarm();
  316. return {};
  317. }
  318. // 4.3.3.80. EncodingDecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
  319. ErrorOr<void, ParseError> Parser::parse_encoding_decl()
  320. {
  321. auto rollback = rollback_point();
  322. auto rule = enter_rule();
  323. // EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
  324. TRY(skip_whitespace(Required::Yes));
  325. TRY(expect("encoding"sv));
  326. auto accept = accept_rule();
  327. TRY(parse_eq());
  328. TRY(expect(is_any_of("'\""sv), "one of ' or \""sv));
  329. m_lexer.retreat();
  330. // FIXME: Actually do something with this encoding.
  331. m_encoding = m_lexer.consume_quoted_string();
  332. rollback.disarm();
  333. return {};
  334. }
  335. // 2.9.32 SDDecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-rmd
  336. ErrorOr<void, ParseError> Parser::parse_standalone_document_decl()
  337. {
  338. auto rollback = rollback_point();
  339. auto rule = enter_rule();
  340. // SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))
  341. TRY(skip_whitespace(Required::Yes));
  342. TRY(expect("standalone"sv));
  343. auto accept = accept_rule();
  344. TRY(parse_eq());
  345. TRY(expect(is_any_of("'\""sv), "one of ' or \""sv));
  346. m_lexer.retreat();
  347. auto value = m_lexer.consume_quoted_string();
  348. if (!value.is_one_of("yes", "no"))
  349. return parse_error(m_lexer.tell() - value.length(), "Expected one of 'yes' or 'no'");
  350. m_standalone = value == "yes";
  351. rollback.disarm();
  352. return {};
  353. }
  354. // 2.8.27. Misc, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-Misc
  355. ErrorOr<void, ParseError> Parser::parse_misc()
  356. {
  357. auto rollback = rollback_point();
  358. auto rule = enter_rule();
  359. // Misc ::= Comment | PI | S
  360. if (auto result = parse_comment(); !result.is_error()) {
  361. rollback.disarm();
  362. return {};
  363. }
  364. if (auto result = parse_processing_instruction(); !result.is_error()) {
  365. rollback.disarm();
  366. return {};
  367. }
  368. if (auto result = skip_whitespace(Required::Yes); !result.is_error()) {
  369. rollback.disarm();
  370. return {};
  371. }
  372. return parse_error(m_lexer.tell(), "Expected a match for 'Misc', but found none");
  373. }
  374. // 2.5.15 Comment, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-Comment
  375. ErrorOr<void, ParseError> Parser::parse_comment()
  376. {
  377. auto rollback = rollback_point();
  378. auto rule = enter_rule();
  379. // Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
  380. TRY(expect("<!--"sv));
  381. auto accept = accept_rule();
  382. bool last_seen_a_dash = false;
  383. // FIXME: This should disallow surrogate blocks
  384. auto text = m_lexer.consume_while([&](auto ch) {
  385. if (ch != '-') {
  386. last_seen_a_dash = false;
  387. return true;
  388. }
  389. if (last_seen_a_dash)
  390. return false;
  391. last_seen_a_dash = true;
  392. return true;
  393. });
  394. if (last_seen_a_dash) {
  395. m_lexer.retreat();
  396. text = text.substring_view(0, text.length() - 1);
  397. }
  398. TRY(expect("-->"sv));
  399. if (m_options.preserve_comments)
  400. append_comment(text);
  401. rollback.disarm();
  402. return {};
  403. }
  404. // 2.6.16 PI, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-PI
  405. ErrorOr<void, ParseError> Parser::parse_processing_instruction()
  406. {
  407. auto rollback = rollback_point();
  408. auto rule = enter_rule();
  409. // PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
  410. TRY(expect("<?"sv));
  411. auto accept = accept_rule();
  412. auto target = TRY(parse_processing_instruction_target());
  413. DeprecatedString data;
  414. if (auto result = skip_whitespace(Required::Yes); !result.is_error())
  415. data = m_lexer.consume_until("?>");
  416. TRY(expect("?>"sv));
  417. m_processing_instructions.set(target, data);
  418. rollback.disarm();
  419. return {};
  420. }
  421. // 2.6.17. PITarget, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-PITarget
  422. ErrorOr<Name, ParseError> Parser::parse_processing_instruction_target()
  423. {
  424. auto rollback = rollback_point();
  425. auto rule = enter_rule();
  426. // PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
  427. auto target = TRY(parse_name());
  428. auto accept = accept_rule();
  429. if (target.equals_ignoring_ascii_case("xml"sv) && m_options.treat_errors_as_fatal) {
  430. return parse_error(
  431. m_lexer.tell() - target.length(),
  432. "Use of the reserved 'xml' name for processing instruction target name is disallowed");
  433. }
  434. rollback.disarm();
  435. return target;
  436. }
  437. // NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  438. constexpr static auto s_name_start_characters = ranges_for_search<Range(':', ':'), Range('A', 'Z'), Range('_', '_'), Range('a', 'z'), Range(0xc0, 0xd6), Range(0xd8, 0xf6), Range(0xf8, 0x2ff), Range(0x370, 0x37d), Range(0x37f, 0x1fff), Range(0x200c, 0x200d), Range(0x2070, 0x218f), Range(0x2c00, 0x2fef), Range(0x3001, 0xd7ff), Range(0xf900, 0xfdcf), Range(0xfdf0, 0xfffd), Range(0x10000, 0xeffff)> {};
  439. // NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  440. constexpr static auto s_name_characters = s_name_start_characters.with<Range('-', '-'), Range('.', '.'), Range('0', '9'), Range(0xb7, 0xb7), Range(0x0300, 0x036f), Range(0x203f, 0x2040)>();
  441. // 2.3.5. Name, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-Name
  442. ErrorOr<Name, ParseError> Parser::parse_name()
  443. {
  444. auto rollback = rollback_point();
  445. auto rule = enter_rule();
  446. // Name ::= NameStartChar (NameChar)*
  447. auto start = TRY(expect(s_name_start_characters, "a NameStartChar"sv));
  448. auto accept = accept_rule();
  449. auto rest = m_lexer.consume_while(s_name_characters);
  450. StringBuilder builder;
  451. builder.append(start);
  452. builder.append(rest);
  453. rollback.disarm();
  454. return builder.to_deprecated_string();
  455. }
  456. // 2.8.28. doctypedecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-doctypedecl
  457. ErrorOr<void, ParseError> Parser::parse_doctype_decl()
  458. {
  459. auto rollback = rollback_point();
  460. auto rule = enter_rule();
  461. Doctype doctype;
  462. // doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? ('[' intSubset ']' S?)? '>'
  463. TRY(expect("<!DOCTYPE"sv));
  464. auto accept = accept_rule();
  465. TRY(skip_whitespace(Required::Yes));
  466. doctype.type = TRY(parse_name());
  467. if (auto result = skip_whitespace(Required::Yes); !result.is_error()) {
  468. auto id_start = m_lexer.tell();
  469. if (auto id_result = parse_external_id(); !id_result.is_error()) {
  470. doctype.external_id = id_result.release_value();
  471. if (m_options.resolve_external_resource) {
  472. auto resource_result = m_options.resolve_external_resource(doctype.external_id->system_id, doctype.external_id->public_id);
  473. if (resource_result.is_error()) {
  474. return parse_error(
  475. id_start,
  476. DeprecatedString::formatted("Failed to resolve external subset '{}': {}", doctype.external_id->system_id.system_literal, resource_result.error()));
  477. }
  478. StringView resolved_source = resource_result.value();
  479. TemporaryChange source { m_source, resolved_source };
  480. TemporaryChange lexer { m_lexer, GenericLexer(m_source) };
  481. auto declarations = TRY(parse_external_subset());
  482. if (!m_lexer.is_eof()) {
  483. return parse_error(
  484. m_lexer.tell(),
  485. DeprecatedString::formatted("Failed to resolve external subset '{}': garbage after declarations", doctype.external_id->system_id.system_literal));
  486. }
  487. doctype.markup_declarations.extend(move(declarations));
  488. }
  489. }
  490. }
  491. TRY(skip_whitespace(Required::No));
  492. if (m_lexer.consume_specific('[')) {
  493. auto internal_subset = TRY(parse_internal_subset());
  494. TRY(expect("]"sv));
  495. TRY(skip_whitespace());
  496. doctype.markup_declarations.extend(internal_subset);
  497. }
  498. TRY(expect(">"sv));
  499. rollback.disarm();
  500. m_doctype = move(doctype);
  501. return {};
  502. }
  503. // 3.39. element, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-element
  504. ErrorOr<void, ParseError> Parser::parse_element()
  505. {
  506. auto rollback = rollback_point();
  507. auto rule = enter_rule();
  508. // element ::= EmptyElemTag
  509. // | STag content ETag
  510. if (auto result = parse_empty_element_tag(); !result.is_error()) {
  511. append_node(result.release_value());
  512. leave_node();
  513. rollback.disarm();
  514. return {};
  515. }
  516. auto start_tag = TRY(parse_start_tag());
  517. auto& node = *start_tag;
  518. auto& tag = node.content.get<Node::Element>();
  519. append_node(move(start_tag));
  520. ScopeGuard quit {
  521. [&] {
  522. leave_node();
  523. }
  524. };
  525. TRY(parse_content());
  526. auto tag_location = m_lexer.tell();
  527. auto closing_name = TRY(parse_end_tag());
  528. // Well-formedness constraint: The Name in an element's end-tag MUST match the element type in the start-tag.
  529. if (m_options.treat_errors_as_fatal && closing_name != tag.name)
  530. return parse_error(tag_location, "Invalid closing tag");
  531. rollback.disarm();
  532. return {};
  533. }
  534. // 3.1.44. EmptyElemTag, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EmptyElemTag
  535. ErrorOr<NonnullOwnPtr<Node>, ParseError> Parser::parse_empty_element_tag()
  536. {
  537. auto rollback = rollback_point();
  538. auto rule = enter_rule();
  539. // EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
  540. TRY(expect("<"sv));
  541. auto accept = accept_rule();
  542. auto name = TRY(parse_name());
  543. HashMap<Name, DeprecatedString> attributes;
  544. while (true) {
  545. if (auto result = skip_whitespace(Required::Yes); result.is_error())
  546. break;
  547. if (auto result = parse_attribute(); !result.is_error()) {
  548. auto attribute = result.release_value();
  549. attributes.set(move(attribute.name), move(attribute.value));
  550. } else {
  551. break;
  552. }
  553. }
  554. TRY(skip_whitespace());
  555. TRY(expect("/>"sv));
  556. rollback.disarm();
  557. return make<Node>(Node::Element { move(name), move(attributes), {} });
  558. }
  559. // 3.1.41. Attribute, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-Attribute
  560. ErrorOr<Attribute, ParseError> Parser::parse_attribute()
  561. {
  562. auto rollback = rollback_point();
  563. auto rule = enter_rule();
  564. // Attribute ::= Name Eq AttValue
  565. auto name = TRY(parse_name());
  566. auto accept = accept_rule();
  567. TRY(parse_eq());
  568. auto value = TRY(parse_attribute_value());
  569. rollback.disarm();
  570. return Attribute {
  571. move(name),
  572. move(value),
  573. };
  574. }
  575. // 2.3.10. AttValue, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-AttValue
  576. ErrorOr<DeprecatedString, ParseError> Parser::parse_attribute_value()
  577. {
  578. auto rollback = rollback_point();
  579. auto rule = enter_rule();
  580. // AttValue ::= '"' ([^<&"] | Reference)* '"'
  581. // | "'" ([^<&'] | Reference)* "'"
  582. auto quote = TRY(expect(is_any_of("'\""sv), "one of ' or \""sv));
  583. auto accept = accept_rule();
  584. auto text = TRY(parse_attribute_value_inner(quote));
  585. TRY(expect(quote));
  586. rollback.disarm();
  587. return text;
  588. }
  589. ErrorOr<DeprecatedString, ParseError> Parser::parse_attribute_value_inner(StringView disallow)
  590. {
  591. StringBuilder builder;
  592. while (true) {
  593. if (m_lexer.next_is(is_any_of(disallow)) || m_lexer.is_eof())
  594. break;
  595. if (m_lexer.next_is('<')) {
  596. // Not allowed, return a nice error to make it easier to debug.
  597. return parse_error(m_lexer.tell(), "Unescaped '<' not allowed in attribute values");
  598. }
  599. if (m_lexer.next_is('&')) {
  600. auto reference = TRY(parse_reference());
  601. if (auto* char_reference = reference.get_pointer<DeprecatedString>())
  602. builder.append(*char_reference);
  603. else
  604. builder.append(TRY(resolve_reference(reference.get<EntityReference>(), ReferencePlacement::AttributeValue)));
  605. } else {
  606. builder.append(m_lexer.consume());
  607. }
  608. }
  609. return builder.to_deprecated_string();
  610. }
  611. // Char ::= [#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
  612. constexpr static auto s_characters = ranges_for_search<Range(0x1, 0xd7ff), Range(0xe000, 0xfffd), Range(0x10000, 0x10ffff)>();
  613. // 4.1.67. Reference, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-Reference
  614. ErrorOr<Variant<Parser::EntityReference, DeprecatedString>, ParseError> Parser::parse_reference()
  615. {
  616. auto rollback = rollback_point();
  617. auto rule = enter_rule();
  618. // Reference ::= EntityRef | CharRef
  619. // 4.1.68. EntityRef
  620. // EntityRef ::= '&' Name ';'
  621. // 4.1.66. CharRef
  622. // CharRef ::= '&#' [0-9]+ ';'
  623. // | '&#x' [0-9a-fA-F]+ ';'
  624. auto reference_start = m_lexer.tell();
  625. TRY(expect("&"sv));
  626. auto accept = accept_rule();
  627. auto name_result = parse_name();
  628. if (name_result.is_error()) {
  629. TRY(expect("#"sv));
  630. Optional<u32> code_point;
  631. if (m_lexer.consume_specific('x')) {
  632. auto hex = TRY(expect_many(
  633. ranges_for_search<Range('0', '9'), Range('a', 'f'), Range('A', 'F')>(),
  634. "any of [0-9a-fA-F]"sv));
  635. code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(hex);
  636. } else {
  637. auto decimal = TRY(expect_many(
  638. ranges_for_search<Range('0', '9')>(),
  639. "any of [0-9]"sv));
  640. code_point = decimal.to_uint<u32>();
  641. }
  642. if (!code_point.has_value() || !s_characters.contains(*code_point))
  643. return parse_error(reference_start, "Invalid character reference");
  644. TRY(expect(";"sv));
  645. StringBuilder builder;
  646. builder.append_code_point(*code_point);
  647. rollback.disarm();
  648. return builder.to_deprecated_string();
  649. }
  650. auto name = name_result.release_value();
  651. TRY(expect(";"sv));
  652. rollback.disarm();
  653. return EntityReference { move(name) };
  654. }
  655. // 3.1.40 STag, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-STag
  656. ErrorOr<NonnullOwnPtr<Node>, ParseError> Parser::parse_start_tag()
  657. {
  658. auto rollback = rollback_point();
  659. auto rule = enter_rule();
  660. // STag ::= '<' Name (S Attribute)* S? '>'
  661. TRY(expect("<"sv));
  662. auto accept = accept_rule();
  663. auto name = TRY(parse_name());
  664. HashMap<Name, DeprecatedString> attributes;
  665. while (true) {
  666. if (auto result = skip_whitespace(Required::Yes); result.is_error())
  667. break;
  668. if (auto result = parse_attribute(); !result.is_error()) {
  669. auto attribute = result.release_value();
  670. attributes.set(move(attribute.name), move(attribute.value));
  671. } else {
  672. break;
  673. }
  674. }
  675. TRY(skip_whitespace());
  676. TRY(expect(">"sv));
  677. rollback.disarm();
  678. return make<Node>(Node::Element { move(name), move(attributes), {} });
  679. }
  680. // 3.1.42 ETag, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-ETag
  681. ErrorOr<Name, ParseError> Parser::parse_end_tag()
  682. {
  683. auto rollback = rollback_point();
  684. auto rule = enter_rule();
  685. // ETag ::= '</' Name S? '>'
  686. TRY(expect("</"sv));
  687. auto accept = accept_rule();
  688. auto name = TRY(parse_name());
  689. TRY(skip_whitespace());
  690. TRY(expect(">"sv));
  691. rollback.disarm();
  692. return name;
  693. }
  694. // 3.1.42 content, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-content
  695. ErrorOr<void, ParseError> Parser::parse_content()
  696. {
  697. auto rollback = rollback_point();
  698. auto rule = enter_rule();
  699. // content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*
  700. if (auto result = parse_char_data(); !result.is_error())
  701. append_text(result.release_value());
  702. while (true) {
  703. if (auto result = parse_element(); !result.is_error())
  704. goto try_char_data;
  705. if (auto result = parse_reference(); !result.is_error()) {
  706. auto reference = result.release_value();
  707. if (auto char_reference = reference.get_pointer<DeprecatedString>())
  708. append_text(*char_reference);
  709. else
  710. TRY(resolve_reference(reference.get<EntityReference>(), ReferencePlacement::Content));
  711. goto try_char_data;
  712. }
  713. if (auto result = parse_cdata_section(); !result.is_error()) {
  714. if (m_options.preserve_cdata)
  715. append_text(result.release_value());
  716. goto try_char_data;
  717. }
  718. if (auto result = parse_processing_instruction(); !result.is_error())
  719. goto try_char_data;
  720. if (auto result = parse_comment(); !result.is_error())
  721. goto try_char_data;
  722. break;
  723. try_char_data:;
  724. if (auto result = parse_char_data(); !result.is_error())
  725. append_text(result.release_value());
  726. }
  727. rollback.disarm();
  728. return {};
  729. }
  730. // 2.4.14 CharData, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-CharData
  731. ErrorOr<StringView, ParseError> Parser::parse_char_data()
  732. {
  733. auto rollback = rollback_point();
  734. auto rule = enter_rule();
  735. // CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
  736. auto cend_state = 0; // 1: ], 2: ], 3: >
  737. auto text = m_lexer.consume_while([&](auto ch) {
  738. if (ch == '<' || ch == '&' || cend_state == 3)
  739. return false;
  740. switch (cend_state) {
  741. case 0:
  742. case 1:
  743. if (ch == ']')
  744. cend_state++;
  745. else
  746. cend_state = 0;
  747. return true;
  748. case 2:
  749. if (ch == '>') {
  750. cend_state++;
  751. return true;
  752. }
  753. cend_state = 0;
  754. return true;
  755. default:
  756. VERIFY_NOT_REACHED();
  757. }
  758. });
  759. if (cend_state == 3) {
  760. m_lexer.retreat(3);
  761. text = text.substring_view(0, text.length() - 3);
  762. }
  763. rollback.disarm();
  764. return text;
  765. }
  766. // 2.8.28b intSubset, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-intSubset
  767. ErrorOr<Vector<MarkupDeclaration>, ParseError> Parser::parse_internal_subset()
  768. {
  769. auto rollback = rollback_point();
  770. auto rule = enter_rule();
  771. Vector<MarkupDeclaration> declarations;
  772. // intSubset ::= (markupdecl | DeclSep)*
  773. while (true) {
  774. if (auto result = parse_markup_declaration(); !result.is_error()) {
  775. auto maybe_declaration = result.release_value();
  776. if (maybe_declaration.has_value())
  777. declarations.append(maybe_declaration.release_value());
  778. continue;
  779. }
  780. if (auto result = parse_declaration_separator(); !result.is_error()) {
  781. // The markup declarations may be made up in whole or in part of the replacement text of parameter entities.
  782. // The replacement text of a parameter entity reference in a DeclSep MUST match the production extSubsetDecl.
  783. auto maybe_replacement_text = result.release_value();
  784. if (maybe_replacement_text.has_value()) {
  785. TemporaryChange<StringView> source { m_source, maybe_replacement_text.value() };
  786. TemporaryChange lexer { m_lexer, GenericLexer { m_source } };
  787. auto contained_declarations = TRY(parse_external_subset_declaration());
  788. declarations.extend(move(contained_declarations));
  789. }
  790. continue;
  791. }
  792. break;
  793. }
  794. rollback.disarm();
  795. return declarations;
  796. }
  797. // 2.8.29 markupdecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-markupdecl
  798. ErrorOr<Optional<MarkupDeclaration>, ParseError> Parser::parse_markup_declaration()
  799. {
  800. auto rollback = rollback_point();
  801. auto rule = enter_rule();
  802. // markupdecl ::= elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment
  803. if (auto result = parse_element_declaration(); !result.is_error()) {
  804. rollback.disarm();
  805. return MarkupDeclaration { result.release_value() };
  806. }
  807. if (auto result = parse_attribute_list_declaration(); !result.is_error()) {
  808. rollback.disarm();
  809. return MarkupDeclaration { result.release_value() };
  810. }
  811. if (auto result = parse_entity_declaration(); !result.is_error()) {
  812. rollback.disarm();
  813. return MarkupDeclaration { result.release_value() };
  814. }
  815. if (auto result = parse_notation_declaration(); !result.is_error()) {
  816. rollback.disarm();
  817. return MarkupDeclaration { result.release_value() };
  818. }
  819. if (auto result = parse_processing_instruction(); !result.is_error()) {
  820. rollback.disarm();
  821. return Optional<MarkupDeclaration> {};
  822. }
  823. if (auto result = parse_comment(); !result.is_error()) {
  824. rollback.disarm();
  825. return Optional<MarkupDeclaration> {};
  826. }
  827. return parse_error(m_lexer.tell(), "Expected one of elementdecl, attlistdecl, entitydecl, notationdecl, PI or comment");
  828. }
  829. // 2.8.28a DeclSep, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-DeclSep
  830. ErrorOr<Optional<DeprecatedString>, ParseError> Parser::parse_declaration_separator()
  831. {
  832. auto rollback = rollback_point();
  833. auto rule = enter_rule();
  834. // DeclSep ::= PEReference | S
  835. if (auto name = parse_parameter_entity_reference(); !name.is_error()) {
  836. rollback.disarm();
  837. // FIXME: Resolve this PEReference.
  838. return "";
  839. }
  840. if (auto result = skip_whitespace(Required::Yes); !result.is_error()) {
  841. rollback.disarm();
  842. return Optional<DeprecatedString> {};
  843. }
  844. return parse_error(m_lexer.tell(), "Expected either whitespace, or a PEReference");
  845. }
  846. // 4.1.69 PEReference, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-PEReference
  847. ErrorOr<Name, ParseError> Parser::parse_parameter_entity_reference()
  848. {
  849. auto rollback = rollback_point();
  850. auto rule = enter_rule();
  851. // PEReference ::= '%' Name ';'
  852. TRY(expect("%"sv));
  853. auto accept = accept_rule();
  854. auto name = TRY(parse_name());
  855. TRY(expect(";"sv));
  856. rollback.disarm();
  857. return name;
  858. }
  859. // 3.2.46 elementdecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-elementdecl
  860. ErrorOr<ElementDeclaration, ParseError> Parser::parse_element_declaration()
  861. {
  862. auto rollback = rollback_point();
  863. auto rule = enter_rule();
  864. // FIXME: Apparently both name _and_ contentspec here are allowed to be PEReferences,
  865. // but the grammar does not allow that, figure this out.
  866. // elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
  867. TRY(expect("<!ELEMENT"sv));
  868. auto accept = accept_rule();
  869. TRY(skip_whitespace(Required::Yes));
  870. auto name = TRY(parse_name());
  871. TRY(skip_whitespace(Required::Yes));
  872. auto spec = TRY(parse_content_spec());
  873. TRY(expect(">"sv));
  874. rollback.disarm();
  875. return ElementDeclaration {
  876. move(name),
  877. move(spec),
  878. };
  879. }
  880. // 3.3.52 AttlistDecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-AttlistDecl
  881. ErrorOr<AttributeListDeclaration, ParseError> Parser::parse_attribute_list_declaration()
  882. {
  883. auto rollback = rollback_point();
  884. auto rule = enter_rule();
  885. AttributeListDeclaration declaration;
  886. // AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
  887. TRY(expect("<!ATTLIST"sv));
  888. auto accept = accept_rule();
  889. TRY(skip_whitespace(Required::Yes));
  890. declaration.type = TRY(parse_name());
  891. while (true) {
  892. if (auto result = parse_attribute_definition(); !result.is_error())
  893. declaration.attributes.append(result.release_value());
  894. else
  895. break;
  896. }
  897. TRY(skip_whitespace());
  898. TRY(expect(">"sv));
  899. rollback.disarm();
  900. return declaration;
  901. }
  902. // 3.3.53 AttDef, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-AttDef
  903. ErrorOr<AttributeListDeclaration::Definition, ParseError> Parser::parse_attribute_definition()
  904. {
  905. auto rollback = rollback_point();
  906. auto rule = enter_rule();
  907. Optional<AttributeListDeclaration::Type> type;
  908. Optional<AttributeListDeclaration::Default> default_;
  909. // AttDef ::= S Name S AttType S DefaultDecl
  910. TRY(skip_whitespace(Required::Yes));
  911. auto name = TRY(parse_name());
  912. auto accept = accept_rule();
  913. TRY(skip_whitespace(Required::Yes));
  914. // AttType ::= StringType | TokenizedType | EnumeratedType
  915. // StringType ::= 'CDATA'
  916. // TokenizedType ::= 'ID'
  917. // | 'IDREF'
  918. // | 'IDREFS'
  919. // | 'ENTITY'
  920. // | 'ENTITIES'
  921. // | 'NMTOKEN'
  922. // | 'NMTOKENS'
  923. // EnumeratedType ::= NotationType | Enumeration
  924. // NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
  925. // Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
  926. if (m_lexer.consume_specific("CDATA")) {
  927. type = AttributeListDeclaration::StringType::CData;
  928. } else if (m_lexer.consume_specific("IDREFS")) {
  929. type = AttributeListDeclaration::TokenizedType::IDRefs;
  930. } else if (m_lexer.consume_specific("IDREF")) {
  931. type = AttributeListDeclaration::TokenizedType::IDRef;
  932. } else if (m_lexer.consume_specific("ID")) {
  933. type = AttributeListDeclaration::TokenizedType::ID;
  934. } else if (m_lexer.consume_specific("ENTITIES")) {
  935. type = AttributeListDeclaration::TokenizedType::Entities;
  936. } else if (m_lexer.consume_specific("ENTITY")) {
  937. type = AttributeListDeclaration::TokenizedType::Entity;
  938. } else if (m_lexer.consume_specific("NMTOKENS")) {
  939. type = AttributeListDeclaration::TokenizedType::NMTokens;
  940. } else if (m_lexer.consume_specific("NMTOKEN")) {
  941. type = AttributeListDeclaration::TokenizedType::NMToken;
  942. } else if (m_lexer.consume_specific("NOTATION")) {
  943. HashTable<Name> names;
  944. TRY(skip_whitespace(Required::Yes));
  945. TRY(expect("("sv));
  946. TRY(skip_whitespace());
  947. names.set(TRY(parse_name()));
  948. while (true) {
  949. TRY(skip_whitespace());
  950. if (auto result = expect("|"sv); result.is_error())
  951. break;
  952. TRY(skip_whitespace());
  953. names.set(TRY(parse_name()));
  954. }
  955. TRY(skip_whitespace());
  956. TRY(expect(")"sv));
  957. type = AttributeListDeclaration::NotationType { move(names) };
  958. } else {
  959. HashTable<DeprecatedString> names;
  960. TRY(expect("("sv));
  961. TRY(skip_whitespace());
  962. names.set(TRY(parse_nm_token()));
  963. while (true) {
  964. TRY(skip_whitespace());
  965. if (auto result = expect("|"sv); result.is_error())
  966. break;
  967. TRY(skip_whitespace());
  968. names.set(TRY(parse_nm_token()));
  969. }
  970. TRY(skip_whitespace());
  971. TRY(expect(")"sv));
  972. type = AttributeListDeclaration::Enumeration { move(names) };
  973. }
  974. TRY(skip_whitespace(Required::Yes));
  975. // DefaultDecl ::= '#REQUIRED' | '#IMPLIED'
  976. // | (('#FIXED' S)? AttValue)
  977. if (m_lexer.consume_specific("#REQUIRED")) {
  978. default_ = AttributeListDeclaration::Required {};
  979. } else if (m_lexer.consume_specific("#IMPLIED")) {
  980. default_ = AttributeListDeclaration::Implied {};
  981. } else {
  982. bool fixed = false;
  983. if (m_lexer.consume_specific("#FIXED")) {
  984. TRY(skip_whitespace(Required::Yes));
  985. fixed = true;
  986. }
  987. auto value = TRY(parse_attribute_value());
  988. if (fixed)
  989. default_ = AttributeListDeclaration::Fixed { move(value) };
  990. else
  991. default_ = AttributeListDeclaration::DefaultValue { move(value) };
  992. }
  993. rollback.disarm();
  994. return AttributeListDeclaration::Definition {
  995. move(name),
  996. type.release_value(),
  997. default_.release_value(),
  998. };
  999. }
  1000. // 2.3.7 Nmtoken, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-Nmtoken
  1001. ErrorOr<StringView, ParseError> Parser::parse_nm_token()
  1002. {
  1003. auto rollback = rollback_point();
  1004. auto rule = enter_rule();
  1005. // Nmtoken ::= (NameChar)+
  1006. auto token = TRY(expect_many(s_name_characters, "a NameChar"sv));
  1007. rollback.disarm();
  1008. return token;
  1009. }
  1010. // 4.7.82 NotationDecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#Notations
  1011. ErrorOr<NotationDeclaration, ParseError> Parser::parse_notation_declaration()
  1012. {
  1013. auto rollback = rollback_point();
  1014. auto rule = enter_rule();
  1015. Variant<ExternalID, PublicID, Empty> notation;
  1016. // NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
  1017. TRY(expect("<!NOTATION"sv));
  1018. auto accept = accept_rule();
  1019. TRY(skip_whitespace(Required::Yes));
  1020. auto name = TRY(parse_name());
  1021. TRY(skip_whitespace(Required::Yes));
  1022. if (auto result = parse_external_id(); !result.is_error())
  1023. notation = result.release_value();
  1024. else
  1025. notation = TRY(parse_public_id());
  1026. TRY(expect(">"sv));
  1027. rollback.disarm();
  1028. return NotationDeclaration {
  1029. move(name),
  1030. move(notation).downcast<ExternalID, PublicID>(),
  1031. };
  1032. }
  1033. // 3.2.46 contentspec, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-contentspec
  1034. ErrorOr<ElementDeclaration::ContentSpec, ParseError> Parser::parse_content_spec()
  1035. {
  1036. auto rollback = rollback_point();
  1037. auto rule = enter_rule();
  1038. Optional<ElementDeclaration::ContentSpec> content_spec;
  1039. // contentspec ::= 'EMPTY' | 'ANY' | Mixed | children
  1040. if (m_lexer.consume_specific("EMPTY")) {
  1041. content_spec = ElementDeclaration::Empty {};
  1042. } else if (m_lexer.consume_specific("ANY")) {
  1043. content_spec = ElementDeclaration::Any {};
  1044. } else {
  1045. TRY(expect("("sv));
  1046. TRY(skip_whitespace());
  1047. if (m_lexer.consume_specific("#PCDATA")) {
  1048. HashTable<Name> names;
  1049. // Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*'
  1050. // | '(' S? '#PCDATA' S? ')'
  1051. TRY(skip_whitespace());
  1052. if (m_lexer.consume_specific(")*")) {
  1053. content_spec = ElementDeclaration::Mixed { .types = {}, .many = true };
  1054. } else if (m_lexer.consume_specific(')')) {
  1055. content_spec = ElementDeclaration::Mixed { .types = {}, .many = false };
  1056. } else {
  1057. while (true) {
  1058. TRY(skip_whitespace());
  1059. if (!m_lexer.consume_specific('|'))
  1060. break;
  1061. TRY(skip_whitespace());
  1062. if (auto result = parse_name(); !result.is_error())
  1063. names.set(result.release_value());
  1064. else
  1065. return parse_error(m_lexer.tell(), "Expected a Name");
  1066. }
  1067. TRY(skip_whitespace());
  1068. TRY(expect(")*"sv));
  1069. content_spec = ElementDeclaration::Mixed { .types = move(names), .many = true };
  1070. }
  1071. } else {
  1072. while (!m_lexer.next_is('('))
  1073. m_lexer.retreat();
  1074. // children ::= (choice | seq) ('?' | '*' | '+')?
  1075. // cp ::= (Name | choice | seq) ('?' | '*' | '+')?
  1076. // choice ::= '(' S? cp ( S? '|' S? cp )+ S? ')'
  1077. // seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
  1078. Function<ErrorOr<ElementDeclaration::Children::Choice, ParseError>()> parse_choice;
  1079. Function<ErrorOr<ElementDeclaration::Children::Sequence, ParseError>()> parse_sequence;
  1080. auto parse_cp_init = [&]() -> ErrorOr<Variant<Name, ElementDeclaration::Children::Choice, ElementDeclaration::Children::Sequence>, ParseError> {
  1081. if (auto result = parse_name(); !result.is_error())
  1082. return result.release_value();
  1083. if (auto result = parse_choice(); !result.is_error())
  1084. return result.release_value();
  1085. return TRY(parse_sequence());
  1086. };
  1087. auto parse_qualifier = [&]() -> ElementDeclaration::Children::Qualifier {
  1088. ElementDeclaration::Children::Qualifier qualifier { ElementDeclaration::Children::Qualifier::ExactlyOnce };
  1089. if (m_lexer.consume_specific('?'))
  1090. qualifier = ElementDeclaration::Children::Qualifier::Optional;
  1091. else if (m_lexer.consume_specific('*'))
  1092. qualifier = ElementDeclaration::Children::Qualifier::Any;
  1093. else if (m_lexer.consume_specific('+'))
  1094. qualifier = ElementDeclaration::Children::Qualifier::OneOrMore;
  1095. return qualifier;
  1096. };
  1097. auto parse_cp = [&]() -> ErrorOr<ElementDeclaration::Children::Entry, ParseError> {
  1098. auto sub_entry = TRY(parse_cp_init());
  1099. auto qualifier = parse_qualifier();
  1100. return ElementDeclaration::Children::Entry {
  1101. move(sub_entry),
  1102. qualifier,
  1103. };
  1104. };
  1105. parse_choice = [&]() -> ErrorOr<ElementDeclaration::Children::Choice, ParseError> {
  1106. auto rollback = rollback_point();
  1107. auto rule = enter_rule();
  1108. TRY(expect("("sv));
  1109. auto accept = accept_rule();
  1110. TRY(skip_whitespace());
  1111. Vector<ElementDeclaration::Children::Entry> choices;
  1112. choices.append(TRY(parse_cp()));
  1113. while (true) {
  1114. TRY(skip_whitespace());
  1115. if (!m_lexer.consume_specific('|'))
  1116. break;
  1117. TRY(skip_whitespace());
  1118. choices.append(TRY(parse_cp()));
  1119. }
  1120. TRY(expect(")"sv));
  1121. if (choices.size() < 2)
  1122. return parse_error(m_lexer.tell(), "Expected more than one choice");
  1123. TRY(skip_whitespace());
  1124. auto qualifier = parse_qualifier();
  1125. rollback.disarm();
  1126. return ElementDeclaration::Children::Choice {
  1127. move(choices),
  1128. qualifier,
  1129. };
  1130. };
  1131. parse_sequence = [&]() -> ErrorOr<ElementDeclaration::Children::Sequence, ParseError> {
  1132. auto rollback = rollback_point();
  1133. auto rule = enter_rule();
  1134. TRY(expect("("sv));
  1135. auto accept = accept_rule();
  1136. TRY(skip_whitespace());
  1137. Vector<ElementDeclaration::Children::Entry> entries;
  1138. entries.append(TRY(parse_cp()));
  1139. while (true) {
  1140. TRY(skip_whitespace());
  1141. if (!m_lexer.consume_specific(','))
  1142. break;
  1143. TRY(skip_whitespace());
  1144. entries.append(TRY(parse_cp()));
  1145. }
  1146. TRY(expect(")"sv));
  1147. TRY(skip_whitespace());
  1148. auto qualifier = parse_qualifier();
  1149. rollback.disarm();
  1150. return ElementDeclaration::Children::Sequence {
  1151. move(entries),
  1152. qualifier,
  1153. };
  1154. };
  1155. if (auto result = parse_choice(); !result.is_error()) {
  1156. auto qualifier = parse_qualifier();
  1157. content_spec = ElementDeclaration::Children {
  1158. result.release_value(),
  1159. qualifier,
  1160. };
  1161. } else {
  1162. auto sequence = TRY(parse_sequence());
  1163. auto qualifier = parse_qualifier();
  1164. content_spec = ElementDeclaration::Children {
  1165. move(sequence),
  1166. qualifier,
  1167. };
  1168. }
  1169. }
  1170. }
  1171. rollback.disarm();
  1172. return content_spec.release_value();
  1173. }
  1174. // 2.8.31 extSubsetDecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-extSubsetDecl
  1175. ErrorOr<Vector<MarkupDeclaration>, ParseError> Parser::parse_external_subset_declaration()
  1176. {
  1177. auto rollback = rollback_point();
  1178. auto rule = enter_rule();
  1179. Vector<MarkupDeclaration> declarations;
  1180. // extSubsetDecl ::= ( markupdecl | conditionalSect | DeclSep )*
  1181. while (true) {
  1182. if (auto result = parse_markup_declaration(); !result.is_error()) {
  1183. if (result.value().has_value())
  1184. declarations.append(result.release_value().release_value());
  1185. continue;
  1186. }
  1187. // FIXME: conditionalSect
  1188. if (auto result = parse_declaration_separator(); !result.is_error())
  1189. continue;
  1190. break;
  1191. }
  1192. rollback.disarm();
  1193. return declarations;
  1194. }
  1195. // 4.2.70 EntityDecl, https://www.w3.org/TR/xml/#NT-EntityDecl
  1196. ErrorOr<EntityDeclaration, ParseError> Parser::parse_entity_declaration()
  1197. {
  1198. // EntityDecl ::= GEDecl | PEDecl
  1199. if (auto result = parse_general_entity_declaration(); !result.is_error())
  1200. return result;
  1201. return parse_parameter_entity_declaration();
  1202. }
  1203. // 4.2.71 GEDecl, https://www.w3.org/TR/xml/#NT-GEDecl
  1204. ErrorOr<EntityDeclaration, ParseError> Parser::parse_general_entity_declaration()
  1205. {
  1206. auto rollback = rollback_point();
  1207. auto rule = enter_rule();
  1208. Variant<DeprecatedString, EntityDefinition, Empty> definition;
  1209. // GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
  1210. TRY(expect("<!ENTITY"sv));
  1211. auto accept = accept_rule();
  1212. TRY(skip_whitespace(Required::Yes));
  1213. auto name = TRY(parse_name());
  1214. TRY(skip_whitespace(Required::Yes));
  1215. // EntityDef ::= EntityValue | (ExternalID NDataDecl?)
  1216. if (auto result = parse_entity_value(); !result.is_error()) {
  1217. definition = result.release_value();
  1218. } else {
  1219. auto external_id = TRY(parse_external_id());
  1220. Optional<Name> notation;
  1221. if (auto notation_result = parse_notation_data_declaration(); !notation_result.is_error())
  1222. notation = notation_result.release_value();
  1223. definition = EntityDefinition {
  1224. move(external_id),
  1225. move(notation),
  1226. };
  1227. }
  1228. TRY(skip_whitespace());
  1229. TRY(expect(">"sv));
  1230. rollback.disarm();
  1231. return GEDeclaration {
  1232. move(name),
  1233. move(definition).downcast<DeprecatedString, EntityDefinition>(),
  1234. };
  1235. }
  1236. // 4.2.72 PEDecl, https://www.w3.org/TR/xml/#NT-PEDecl
  1237. ErrorOr<EntityDeclaration, ParseError> Parser::parse_parameter_entity_declaration()
  1238. {
  1239. auto rollback = rollback_point();
  1240. auto rule = enter_rule();
  1241. Variant<DeprecatedString, ExternalID, Empty> definition;
  1242. // PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
  1243. TRY(expect("<!ENTITY"sv));
  1244. auto accept = accept_rule();
  1245. TRY(skip_whitespace(Required::Yes));
  1246. TRY(expect("%"sv));
  1247. TRY(skip_whitespace(Required::Yes));
  1248. auto name = TRY(parse_name());
  1249. TRY(skip_whitespace(Required::Yes));
  1250. // PEDef ::= EntityValue | ExternalID
  1251. if (auto result = parse_entity_value(); !result.is_error())
  1252. definition = result.release_value();
  1253. else
  1254. definition = TRY(parse_external_id());
  1255. TRY(skip_whitespace());
  1256. TRY(expect(">"sv));
  1257. rollback.disarm();
  1258. return PEDeclaration {
  1259. move(name),
  1260. move(definition).downcast<DeprecatedString, ExternalID>(),
  1261. };
  1262. }
  1263. // 4.7.83 PublicID, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-PublicID
  1264. ErrorOr<PublicID, ParseError> Parser::parse_public_id()
  1265. {
  1266. auto rollback = rollback_point();
  1267. auto rule = enter_rule();
  1268. // PublicID ::= 'PUBLIC' S PubidLiteral
  1269. TRY(expect("PUBLIC"sv));
  1270. auto accept = accept_rule();
  1271. TRY(skip_whitespace(Required::Yes));
  1272. auto text = TRY(parse_public_id_literal());
  1273. rollback.disarm();
  1274. return PublicID {
  1275. text,
  1276. };
  1277. }
  1278. constexpr static auto s_public_id_characters = set_to_search<StringSet("\x20\x0d\x0a-'()+,./:=?;!*#@$_%")>().unify(ranges_for_search<Range('a', 'z'), Range('A', 'Z'), Range('0', '9')>());
  1279. // 2.3.12, PubidLiteral, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-PubidLiteral
  1280. ErrorOr<StringView, ParseError> Parser::parse_public_id_literal()
  1281. {
  1282. auto rollback = rollback_point();
  1283. auto rule = enter_rule();
  1284. // PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
  1285. auto quote = TRY(expect(is_any_of("'\""sv), "any of ' or \""sv));
  1286. auto accept = accept_rule();
  1287. auto id = TRY(expect_many(
  1288. [q = quote[0]](auto x) {
  1289. return (q == '\'' ? x != '\'' : true) && s_public_id_characters.contains(x);
  1290. },
  1291. "a PubidChar"sv));
  1292. TRY(expect(quote));
  1293. rollback.disarm();
  1294. return id;
  1295. }
  1296. // 2.3.11 SystemLiteral, https://www.w3.org/TR/xml/#NT-SystemLiteral
  1297. ErrorOr<StringView, ParseError> Parser::parse_system_id_literal()
  1298. {
  1299. auto rollback = rollback_point();
  1300. auto rule = enter_rule();
  1301. // SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
  1302. auto quote = TRY(expect(is_any_of("'\""sv), "any of ' or \""sv));
  1303. auto accept = accept_rule();
  1304. auto id = TRY(expect_many(is_not_any_of(quote), "not a quote"sv));
  1305. TRY(expect(quote));
  1306. rollback.disarm();
  1307. return id;
  1308. }
  1309. // 4.2.75 ExternalID, https://www.w3.org/TR/xml/#NT-ExternalID
  1310. ErrorOr<ExternalID, ParseError> Parser::parse_external_id()
  1311. {
  1312. auto rollback = rollback_point();
  1313. auto rule = enter_rule();
  1314. // ExternalID ::= 'SYSTEM' S SystemLiteral
  1315. // | 'PUBLIC' S PubidLiteral S SystemLiteral
  1316. Optional<PublicID> public_id;
  1317. SystemID system_id;
  1318. if (m_lexer.consume_specific("SYSTEM")) {
  1319. auto accept = accept_rule();
  1320. TRY(skip_whitespace(Required::Yes));
  1321. system_id = SystemID { TRY(parse_system_id_literal()) };
  1322. } else {
  1323. TRY(expect("PUBLIC"sv));
  1324. auto accept = accept_rule();
  1325. TRY(skip_whitespace(Required::Yes));
  1326. public_id = PublicID { TRY(parse_public_id_literal()) };
  1327. TRY(skip_whitespace(Required::Yes));
  1328. system_id = SystemID { TRY(parse_system_id_literal()) };
  1329. }
  1330. rollback.disarm();
  1331. return ExternalID {
  1332. move(public_id),
  1333. move(system_id),
  1334. };
  1335. }
  1336. // 4.2.2.76 NDataDecl, https://www.w3.org/TR/xml/#NT-NDataDecl
  1337. ErrorOr<Name, ParseError> Parser::parse_notation_data_declaration()
  1338. {
  1339. auto rollback = rollback_point();
  1340. auto rule = enter_rule();
  1341. // NDataDecl ::= S 'NDATA' S Name
  1342. TRY(skip_whitespace(Required::Yes));
  1343. auto accept = accept_rule();
  1344. TRY(expect("NDATA"sv));
  1345. TRY(skip_whitespace(Required::Yes));
  1346. auto name = TRY(parse_name());
  1347. rollback.disarm();
  1348. return name;
  1349. }
  1350. // 2.3.9 EntityValue, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EntityValue
  1351. ErrorOr<DeprecatedString, ParseError> Parser::parse_entity_value()
  1352. {
  1353. auto rollback = rollback_point();
  1354. auto rule = enter_rule();
  1355. StringBuilder builder;
  1356. // EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
  1357. // | "'" ([^%&'] | PEReference | Reference)* "'"
  1358. auto quote = TRY(expect(is_any_of("'\""sv), "any of ' or \""sv));
  1359. auto accept = accept_rule();
  1360. while (true) {
  1361. if (m_lexer.is_eof())
  1362. break;
  1363. if (m_lexer.next_is(quote))
  1364. break;
  1365. if (m_lexer.next_is('%')) {
  1366. auto start = m_lexer.tell();
  1367. TRY(parse_parameter_entity_reference());
  1368. builder.append(m_source.substring_view(start, m_lexer.tell() - start));
  1369. continue;
  1370. }
  1371. if (m_lexer.next_is('&')) {
  1372. auto start = m_lexer.tell();
  1373. TRY(parse_reference());
  1374. builder.append(m_source.substring_view(start, m_lexer.tell() - start));
  1375. continue;
  1376. }
  1377. builder.append(m_lexer.consume());
  1378. }
  1379. TRY(expect(quote));
  1380. rollback.disarm();
  1381. return builder.to_deprecated_string();
  1382. }
  1383. // 2.7.18 CDSect, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-CDSect
  1384. ErrorOr<StringView, ParseError> Parser::parse_cdata_section()
  1385. {
  1386. auto rollback = rollback_point();
  1387. auto rule = enter_rule();
  1388. // CDSect ::= CDStart CData CDEnd
  1389. // CDStart ::= '<![CDATA['
  1390. // CData ::= (Char* - (Char* ']]>' Char*))
  1391. // CDEnd ::= ']]>'
  1392. TRY(expect("<![CDATA["sv));
  1393. auto accept = accept_rule();
  1394. auto section_start = m_lexer.tell();
  1395. while (!m_lexer.next_is("]]>")) {
  1396. if (m_lexer.is_eof())
  1397. break;
  1398. m_lexer.ignore();
  1399. }
  1400. auto section_end = m_lexer.tell();
  1401. TRY(expect("]]>"sv));
  1402. rollback.disarm();
  1403. return m_source.substring_view(section_start, section_end - section_start);
  1404. }
  1405. // 2.8.30 extSubset, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-extSubset
  1406. ErrorOr<Vector<MarkupDeclaration>, ParseError> Parser::parse_external_subset()
  1407. {
  1408. auto rollback = rollback_point();
  1409. auto rule = enter_rule();
  1410. // extSubset ::= TextDecl? extSubsetDecl
  1411. (void)parse_text_declaration();
  1412. auto result = TRY(parse_external_subset_declaration());
  1413. rollback.disarm();
  1414. return result;
  1415. }
  1416. // 4.3.1.77 TextDecl, https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-TextDecl
  1417. ErrorOr<void, ParseError> Parser::parse_text_declaration()
  1418. {
  1419. auto rollback = rollback_point();
  1420. auto rule = enter_rule();
  1421. // TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'
  1422. TRY(expect("<?xml"sv));
  1423. auto accept = accept_rule();
  1424. (void)parse_version_info();
  1425. TRY(parse_encoding_decl());
  1426. TRY(skip_whitespace());
  1427. TRY(expect("?>"sv));
  1428. rollback.disarm();
  1429. return {};
  1430. }
  1431. ErrorOr<DeprecatedString, ParseError> Parser::resolve_reference(EntityReference const& reference, ReferencePlacement placement)
  1432. {
  1433. static HashTable<Name> reference_lookup {};
  1434. if (reference_lookup.contains(reference.name))
  1435. return parse_error(m_lexer.tell(), DeprecatedString::formatted("Invalid recursive definition for '{}'", reference.name));
  1436. reference_lookup.set(reference.name);
  1437. ScopeGuard remove_lookup {
  1438. [&] {
  1439. reference_lookup.remove(reference.name);
  1440. }
  1441. };
  1442. Optional<DeprecatedString> resolved;
  1443. if (m_doctype.has_value()) {
  1444. // FIXME: Split these up and resolve them ahead of time.
  1445. for (auto& declaration : m_doctype->markup_declarations) {
  1446. auto entity = declaration.get_pointer<EntityDeclaration>();
  1447. if (!entity)
  1448. continue;
  1449. auto ge_declaration = entity->get_pointer<GEDeclaration>();
  1450. if (!ge_declaration)
  1451. continue;
  1452. if (ge_declaration->name != reference.name)
  1453. continue;
  1454. TRY(ge_declaration->definition.visit(
  1455. [&](DeprecatedString const& definition) -> ErrorOr<void, ParseError> {
  1456. resolved = definition;
  1457. return {};
  1458. },
  1459. [&](EntityDefinition const& definition) -> ErrorOr<void, ParseError> {
  1460. if (placement == ReferencePlacement::AttributeValue)
  1461. return parse_error(m_lexer.tell(), DeprecatedString::formatted("Attribute references external entity '{}'", reference.name));
  1462. if (definition.notation.has_value())
  1463. return parse_error(0u, DeprecatedString::formatted("Entity reference to unparsed entity '{}'", reference.name));
  1464. if (!m_options.resolve_external_resource)
  1465. return parse_error(0u, DeprecatedString::formatted("Failed to resolve external entity '{}'", reference.name));
  1466. auto result = m_options.resolve_external_resource(definition.id.system_id, definition.id.public_id);
  1467. if (result.is_error())
  1468. return parse_error(0u, DeprecatedString::formatted("Failed to resolve external entity '{}': {}", reference.name, result.error()));
  1469. resolved = result.release_value();
  1470. return {};
  1471. }));
  1472. break;
  1473. }
  1474. }
  1475. if (!resolved.has_value()) {
  1476. if (reference.name == "amp")
  1477. return "&";
  1478. if (reference.name == "lt")
  1479. return "<";
  1480. if (reference.name == "gt")
  1481. return ">";
  1482. if (reference.name == "apos")
  1483. return "'";
  1484. if (reference.name == "quot")
  1485. return "\"";
  1486. return parse_error(0u, DeprecatedString::formatted("Reference to undeclared entity '{}'", reference.name));
  1487. }
  1488. StringView resolved_source = *resolved;
  1489. TemporaryChange source { m_source, resolved_source };
  1490. TemporaryChange lexer { m_lexer, GenericLexer(m_source) };
  1491. switch (placement) {
  1492. case ReferencePlacement::AttributeValue:
  1493. return TRY(parse_attribute_value_inner(""sv));
  1494. case ReferencePlacement::Content:
  1495. TRY(parse_content());
  1496. return "";
  1497. default:
  1498. VERIFY_NOT_REACHED();
  1499. }
  1500. }
  1501. }