Parser.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. * Copyright (c) 2021, Sam Atkins <atkinssj@gmail.com>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/NonnullRefPtrVector.h>
  9. #include <AK/SourceLocation.h>
  10. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  11. #include <LibWeb/CSS/CSSStyleRule.h>
  12. #include <LibWeb/CSS/CSSStyleSheet.h>
  13. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  14. #include <LibWeb/CSS/Parser/Parser.h>
  15. #include <LibWeb/CSS/Parser/StyleBlockRule.h>
  16. #include <LibWeb/CSS/Parser/StyleComponentValueRule.h>
  17. #include <LibWeb/CSS/Parser/StyleFunctionRule.h>
  18. #include <LibWeb/CSS/Parser/StyleRule.h>
  19. #include <LibWeb/CSS/Selector.h>
  20. #include <LibWeb/DOM/Document.h>
  21. #include <LibWeb/Dump.h>
  22. #define CSS_PARSER_TRACE 1
  23. static void log_parse_error(const SourceLocation& location = SourceLocation::current())
  24. {
  25. dbgln_if(CSS_PARSER_TRACE, "Parse error (CSS) {}", location);
  26. }
  27. namespace Web::CSS {
  28. ParsingContext::ParsingContext()
  29. {
  30. }
  31. ParsingContext::ParsingContext(DOM::Document const& document)
  32. : m_document(&document)
  33. {
  34. }
  35. ParsingContext::ParsingContext(DOM::ParentNode const& parent_node)
  36. : m_document(&parent_node.document())
  37. {
  38. }
  39. bool ParsingContext::in_quirks_mode() const
  40. {
  41. return m_document ? m_document->in_quirks_mode() : false;
  42. }
  43. URL ParsingContext::complete_url(String const& addr) const
  44. {
  45. return m_document ? m_document->url().complete_url(addr) : URL::create_with_url_or_path(addr);
  46. }
  47. template<typename T>
  48. TokenStream<T>::TokenStream(Vector<T> const& tokens)
  49. : m_tokens(tokens)
  50. , m_eof(make_eof())
  51. {
  52. }
  53. template<typename T>
  54. TokenStream<T>::~TokenStream()
  55. {
  56. }
  57. template<typename T>
  58. bool TokenStream<T>::has_next_token()
  59. {
  60. return (size_t)(m_iterator_offset + 1) < m_tokens.size();
  61. }
  62. template<typename T>
  63. T const& TokenStream<T>::peek_token()
  64. {
  65. if (!has_next_token())
  66. return m_eof;
  67. return m_tokens.at(m_iterator_offset + 1);
  68. }
  69. template<typename T>
  70. T const& TokenStream<T>::next_token()
  71. {
  72. if (!has_next_token())
  73. return m_eof;
  74. ++m_iterator_offset;
  75. return m_tokens.at(m_iterator_offset);
  76. }
  77. template<typename T>
  78. T const& TokenStream<T>::current_token()
  79. {
  80. if ((size_t)m_iterator_offset >= m_tokens.size())
  81. return m_eof;
  82. return m_tokens.at(m_iterator_offset);
  83. }
  84. template<typename T>
  85. void TokenStream<T>::reconsume_current_input_token()
  86. {
  87. VERIFY(m_iterator_offset >= 0);
  88. --m_iterator_offset;
  89. }
  90. template<typename T>
  91. void TokenStream<T>::skip_whitespace()
  92. {
  93. while (peek_token().is(Token::Type::Whitespace))
  94. next_token();
  95. }
  96. template<>
  97. Token TokenStream<Token>::make_eof()
  98. {
  99. return Tokenizer::create_eof_token();
  100. }
  101. template<>
  102. StyleComponentValueRule TokenStream<StyleComponentValueRule>::make_eof()
  103. {
  104. return StyleComponentValueRule(Tokenizer::create_eof_token());
  105. }
  106. template<typename T>
  107. void TokenStream<T>::dump_all_tokens()
  108. {
  109. dbgln("Dumping all tokens:");
  110. for (auto& token : m_tokens)
  111. dbgln("{}", token.to_debug_string());
  112. }
  113. Parser::Parser(ParsingContext const& context, StringView const& input, String const& encoding)
  114. : m_context(context)
  115. , m_tokenizer(input, encoding)
  116. , m_tokens(m_tokenizer.parse())
  117. , m_token_stream(TokenStream(m_tokens))
  118. {
  119. }
  120. Parser::~Parser()
  121. {
  122. }
  123. NonnullRefPtr<CSSStyleSheet> Parser::parse_as_stylesheet()
  124. {
  125. return parse_as_stylesheet(m_token_stream);
  126. }
  127. template<typename T>
  128. NonnullRefPtr<CSSStyleSheet> Parser::parse_as_stylesheet(TokenStream<T>& tokens)
  129. {
  130. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_stylesheet");
  131. auto parser_rules = consume_a_list_of_rules(tokens, true);
  132. NonnullRefPtrVector<CSSRule> rules;
  133. for (auto& raw_rule : parser_rules) {
  134. auto rule = convert_to_rule(raw_rule);
  135. if (rule)
  136. rules.append(*rule);
  137. }
  138. auto stylesheet = CSSStyleSheet::create(rules);
  139. dump_sheet(stylesheet);
  140. return stylesheet;
  141. }
  142. Vector<Selector> Parser::parse_a_selector()
  143. {
  144. return parse_a_selector(m_token_stream);
  145. }
  146. template<typename T>
  147. Vector<Selector> Parser::parse_a_selector(TokenStream<T>& tokens)
  148. {
  149. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_a_selector");
  150. auto comma_separated_lists = parse_as_comma_separated_list_of_component_values(tokens);
  151. Vector<Selector> selectors;
  152. for (auto& selector_parts : comma_separated_lists) {
  153. auto stream = TokenStream(selector_parts);
  154. auto selector = parse_single_selector(stream);
  155. if (selector.has_value())
  156. selectors.append(selector.value());
  157. }
  158. return selectors;
  159. }
  160. Vector<Selector> Parser::parse_a_relative_selector()
  161. {
  162. return parse_a_relative_selector(m_token_stream);
  163. }
  164. template<typename T>
  165. Vector<Selector> Parser::parse_a_relative_selector(TokenStream<T>& tokens)
  166. {
  167. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_a_relative_selector");
  168. auto comma_separated_lists = parse_as_comma_separated_list_of_component_values(tokens);
  169. Vector<Selector> selectors;
  170. for (auto& selector_parts : comma_separated_lists) {
  171. auto stream = TokenStream(selector_parts);
  172. auto selector = parse_single_selector(stream, true);
  173. if (selector.has_value())
  174. selectors.append(selector.value());
  175. }
  176. return selectors;
  177. }
  178. template<typename T>
  179. Optional<Selector> Parser::parse_single_selector(TokenStream<T>& tokens, bool is_relative)
  180. {
  181. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_single_selector");
  182. // FIXME: Bring this all in line with the spec. https://www.w3.org/TR/selectors-4/
  183. Vector<Selector::ComplexSelector> selectors;
  184. auto check_for_eof_or_whitespace = [&](T& current_value) -> bool {
  185. if (current_value.is(Token::Type::EndOfFile))
  186. return true;
  187. if (current_value.is(Token::Type::Whitespace)) {
  188. tokens.reconsume_current_input_token();
  189. return true;
  190. }
  191. return false;
  192. };
  193. auto parse_simple_selector = [&]() -> Optional<Selector::SimpleSelector> {
  194. auto current_value = tokens.next_token();
  195. if (check_for_eof_or_whitespace(current_value))
  196. return {};
  197. Selector::SimpleSelector::Type type;
  198. String value;
  199. // FIXME: Handle namespace prefixes.
  200. if (current_value.is(Token::Type::Delim) && ((Token)current_value).delim() == "*") {
  201. // FIXME: Handle selectors like `*.foo`.
  202. type = Selector::SimpleSelector::Type::Universal;
  203. Selector::SimpleSelector result;
  204. result.type = type;
  205. return result;
  206. }
  207. if (current_value.is(Token::Type::Hash)) {
  208. if (((Token)current_value).m_hash_type != Token::HashType::Id) {
  209. dbgln("Selector contains hash token that is not an id: {}", current_value.to_debug_string());
  210. return {};
  211. }
  212. type = Selector::SimpleSelector::Type::Id;
  213. value = ((Token)current_value).m_value.to_string();
  214. } else if (current_value.is(Token::Type::Delim) && ((Token)current_value).delim() == ".") {
  215. current_value = tokens.next_token();
  216. if (check_for_eof_or_whitespace(current_value))
  217. return {};
  218. if (!current_value.is(Token::Type::Ident)) {
  219. dbgln("Expected an ident after '.', got: {}", current_value.to_debug_string());
  220. return {};
  221. }
  222. type = Selector::SimpleSelector::Type::Class;
  223. value = current_value.token().ident().to_lowercase_string();
  224. } else if (current_value.is(Token::Type::Delim) && current_value.token().delim() == "*") {
  225. type = Selector::SimpleSelector::Type::Universal;
  226. } else if (current_value.is(Token::Type::Ident)) {
  227. type = Selector::SimpleSelector::Type::TagName;
  228. value = current_value.token().ident().to_lowercase_string();
  229. } else if ((current_value.is(Token::Type::Delim) && current_value.token().delim() == ":")
  230. || (current_value.is_block() && current_value.block().is_square())) {
  231. // FIXME: This is a temporary hack until we make the Selector::SimpleSelector::Type changes.
  232. type = Selector::SimpleSelector::Type::Universal;
  233. tokens.reconsume_current_input_token();
  234. } else {
  235. dbgln("Invalid simple selector!");
  236. return {};
  237. }
  238. Selector::SimpleSelector simple_selector;
  239. simple_selector.type = type;
  240. simple_selector.value = value;
  241. current_value = tokens.next_token();
  242. if (check_for_eof_or_whitespace(current_value))
  243. return simple_selector;
  244. // FIXME: Attribute selectors want to be their own Selector::SimpleSelector::Type according to the spec.
  245. if (current_value.is_block() && current_value.block().is_square()) {
  246. Vector<StyleComponentValueRule> const& attribute_parts = current_value.block().values();
  247. if (attribute_parts.is_empty()) {
  248. dbgln("CSS attribute selector is empty!");
  249. return {};
  250. }
  251. // FIXME: Handle namespace prefix for attribute name.
  252. auto& attribute_part = attribute_parts.first();
  253. if (!attribute_part.is(Token::Type::Ident)) {
  254. dbgln("Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  255. return {};
  256. }
  257. simple_selector.attribute_match_type = Selector::SimpleSelector::AttributeMatchType::HasAttribute;
  258. simple_selector.attribute_name = attribute_part.token().ident();
  259. if (attribute_parts.size() == 1)
  260. return simple_selector;
  261. size_t attribute_index = 1;
  262. auto& delim_part = attribute_parts.at(attribute_index);
  263. if (!delim_part.is(Token::Type::Delim)) {
  264. dbgln("Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  265. return {};
  266. }
  267. if (delim_part.token().delim() == "=") {
  268. simple_selector.attribute_match_type = Selector::SimpleSelector::AttributeMatchType::ExactValueMatch;
  269. attribute_index++;
  270. } else {
  271. attribute_index++;
  272. if (attribute_index >= attribute_parts.size()) {
  273. dbgln("Attribute selector ended part way through a match type.");
  274. return {};
  275. }
  276. auto& delim_second_part = attribute_parts.at(attribute_index);
  277. if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == "=")) {
  278. dbgln("Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  279. return {};
  280. }
  281. if (delim_part.token().delim() == "~") {
  282. simple_selector.attribute_match_type = Selector::SimpleSelector::AttributeMatchType::ContainsWord;
  283. attribute_index++;
  284. } else if (delim_part.token().delim() == "*") {
  285. simple_selector.attribute_match_type = Selector::SimpleSelector::AttributeMatchType::ContainsString;
  286. attribute_index++;
  287. } else if (delim_part.token().delim() == "|") {
  288. simple_selector.attribute_match_type = Selector::SimpleSelector::AttributeMatchType::StartsWithSegment;
  289. attribute_index++;
  290. } else if (delim_part.token().delim() == "^") {
  291. simple_selector.attribute_match_type = Selector::SimpleSelector::AttributeMatchType::StartsWithString;
  292. attribute_index++;
  293. } else if (delim_part.token().delim() == "$") {
  294. simple_selector.attribute_match_type = Selector::SimpleSelector::AttributeMatchType::EndsWithString;
  295. attribute_index++;
  296. }
  297. }
  298. if (attribute_index >= attribute_parts.size()) {
  299. dbgln("Attribute selector ended without a value to match.");
  300. return {};
  301. }
  302. auto& value_part = attribute_parts.at(attribute_index);
  303. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  304. dbgln("Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  305. return {};
  306. }
  307. simple_selector.attribute_value = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  308. // FIXME: Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  309. return simple_selector;
  310. }
  311. // FIXME: Pseudo-class selectors want to be their own Selector::SimpleSelector::Type according to the spec.
  312. if (current_value.is(Token::Type::Colon)) {
  313. bool is_pseudo = false;
  314. current_value = tokens.next_token();
  315. if (check_for_eof_or_whitespace(current_value))
  316. return {};
  317. if (current_value.is(Token::Type::Colon)) {
  318. is_pseudo = true;
  319. current_value = tokens.next_token();
  320. if (check_for_eof_or_whitespace(current_value))
  321. return {};
  322. }
  323. // Ignore for now, otherwise we produce a "false positive" selector
  324. // and apply styles to the element itself, not its pseudo element
  325. if (is_pseudo)
  326. return {};
  327. current_value = tokens.next_token();
  328. if (check_for_eof_or_whitespace(current_value))
  329. return simple_selector;
  330. if (current_value.is(Token::Type::Ident)) {
  331. auto pseudo_name = ((Token)current_value).ident();
  332. if (pseudo_name.equals_ignoring_case("link")) {
  333. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Link;
  334. } else if (pseudo_name.equals_ignoring_case("visited")) {
  335. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Visited;
  336. } else if (pseudo_name.equals_ignoring_case("active")) {
  337. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Active;
  338. } else if (pseudo_name.equals_ignoring_case("hover")) {
  339. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Hover;
  340. } else if (pseudo_name.equals_ignoring_case("focus")) {
  341. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Focus;
  342. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  343. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::FirstChild;
  344. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  345. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::LastChild;
  346. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  347. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::OnlyChild;
  348. } else if (pseudo_name.equals_ignoring_case("empty")) {
  349. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Empty;
  350. } else if (pseudo_name.equals_ignoring_case("root")) {
  351. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Root;
  352. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  353. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::FirstOfType;
  354. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  355. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::LastOfType;
  356. } else if (pseudo_name.equals_ignoring_case("before")) {
  357. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  358. } else if (pseudo_name.equals_ignoring_case("after")) {
  359. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  360. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  361. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Disabled;
  362. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  363. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Enabled;
  364. } else if (pseudo_name.equals_ignoring_case("checked")) {
  365. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Checked;
  366. } else {
  367. dbgln("Unknown pseudo class: '{}'", pseudo_name);
  368. return simple_selector;
  369. }
  370. } else if (current_value.is(Token::Type::Function)) {
  371. auto& pseudo_function = current_value.function();
  372. if (pseudo_function.name().equals_ignoring_case("nth-child")) {
  373. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::NthChild;
  374. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  375. auto nth_child_pattern = parse_nth_child_pattern(function_values);
  376. if (nth_child_pattern.has_value()) {
  377. simple_selector.nth_child_pattern = nth_child_pattern.value();
  378. } else {
  379. dbgln("Invalid nth-child format");
  380. return {};
  381. }
  382. } else if (pseudo_function.name().equals_ignoring_case("nth-last-child")) {
  383. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::NthLastChild;
  384. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  385. auto nth_child_pattern = parse_nth_child_pattern(function_values);
  386. if (nth_child_pattern.has_value()) {
  387. simple_selector.nth_child_pattern = nth_child_pattern.value();
  388. } else {
  389. dbgln("Invalid nth-child format");
  390. return {};
  391. }
  392. } else if (pseudo_function.name().equals_ignoring_case("not")) {
  393. simple_selector.pseudo_class = Selector::SimpleSelector::PseudoClass::Not;
  394. simple_selector.not_selector = pseudo_function.values_as_string();
  395. } else {
  396. dbgln("Unknown pseudo class: '{}'()", pseudo_function.name());
  397. return {};
  398. }
  399. } else {
  400. dbgln("Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", current_value.to_debug_string());
  401. return {};
  402. }
  403. }
  404. tokens.reconsume_current_input_token();
  405. return simple_selector;
  406. };
  407. auto parse_complex_selector = [&]() -> Optional<Selector::ComplexSelector> {
  408. auto relation = Selector::ComplexSelector::Relation::Descendant;
  409. tokens.skip_whitespace();
  410. auto current_value = tokens.peek_token();
  411. if (current_value.is(Token::Type::Delim)) {
  412. auto delim = ((Token)current_value).delim();
  413. if (delim == ">") {
  414. relation = Selector::ComplexSelector::Relation::ImmediateChild;
  415. tokens.next_token();
  416. } else if (delim == "+") {
  417. relation = Selector::ComplexSelector::Relation::AdjacentSibling;
  418. tokens.next_token();
  419. } else if (delim == "~") {
  420. relation = Selector::ComplexSelector::Relation::GeneralSibling;
  421. tokens.next_token();
  422. } else if (delim == "|") {
  423. tokens.next_token();
  424. auto next = tokens.peek_token();
  425. if (next.is(Token::Type::EndOfFile))
  426. return {};
  427. if (next.is(Token::Type::Delim) && next.token().delim() == "|") {
  428. relation = Selector::ComplexSelector::Relation::Column;
  429. tokens.next_token();
  430. }
  431. }
  432. }
  433. tokens.skip_whitespace();
  434. Vector<Selector::SimpleSelector> simple_selectors;
  435. for (;;) {
  436. auto current_value = tokens.peek_token();
  437. if (current_value.is(Token::Type::EndOfFile) || current_value.is(Token::Type::Whitespace))
  438. break;
  439. auto component = parse_simple_selector();
  440. if (!component.has_value())
  441. break;
  442. simple_selectors.append(component.value());
  443. }
  444. if (simple_selectors.is_empty())
  445. return {};
  446. return Selector::ComplexSelector { relation, move(simple_selectors) };
  447. };
  448. for (;;) {
  449. auto current_value = tokens.peek_token();
  450. if (current_value.is(Token::Type::EndOfFile))
  451. break;
  452. auto complex = parse_complex_selector();
  453. if (complex.has_value())
  454. selectors.append(complex.value());
  455. }
  456. if (selectors.is_empty())
  457. return {};
  458. if (!is_relative)
  459. selectors.first().relation = Selector::ComplexSelector::Relation::None;
  460. return Selector(move(selectors));
  461. }
  462. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(bool top_level)
  463. {
  464. return consume_a_list_of_rules(m_token_stream, top_level);
  465. }
  466. template<typename T>
  467. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  468. {
  469. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_list_of_rules");
  470. NonnullRefPtrVector<StyleRule> rules;
  471. for (;;) {
  472. auto token = tokens.next_token();
  473. if (token.is(Token::Type::Whitespace)) {
  474. continue;
  475. }
  476. if (token.is(Token::Type::EndOfFile)) {
  477. break;
  478. }
  479. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  480. if (top_level) {
  481. continue;
  482. }
  483. tokens.reconsume_current_input_token();
  484. auto maybe_qualified = consume_a_qualified_rule(tokens);
  485. if (maybe_qualified) {
  486. rules.append(maybe_qualified.release_nonnull());
  487. }
  488. continue;
  489. }
  490. if (token.is(Token::Type::AtKeyword)) {
  491. tokens.reconsume_current_input_token();
  492. rules.append(consume_an_at_rule(tokens));
  493. continue;
  494. }
  495. tokens.reconsume_current_input_token();
  496. auto maybe_qualified = consume_a_qualified_rule(tokens);
  497. if (maybe_qualified) {
  498. rules.append(maybe_qualified.release_nonnull());
  499. }
  500. }
  501. return rules;
  502. }
  503. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule()
  504. {
  505. return consume_an_at_rule(m_token_stream);
  506. }
  507. template<typename T>
  508. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  509. {
  510. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_an_at_rule");
  511. auto name_ident = tokens.next_token();
  512. VERIFY(name_ident.is(Token::Type::Ident));
  513. NonnullRefPtr<StyleRule> rule = create<StyleRule>(StyleRule::Type::At);
  514. rule->m_name = ((Token)name_ident).ident();
  515. for (;;) {
  516. auto token = tokens.next_token();
  517. if (token.is(Token::Type::Semicolon)) {
  518. return rule;
  519. }
  520. if (token.is(Token::Type::EndOfFile)) {
  521. log_parse_error();
  522. return rule;
  523. }
  524. if (token.is(Token::Type::OpenCurly)) {
  525. rule->m_block = consume_a_simple_block(tokens);
  526. return rule;
  527. }
  528. // how is "simple block with an associated token of <{-token>" a valid token?
  529. tokens.reconsume_current_input_token();
  530. auto value = consume_a_component_value(tokens);
  531. rule->m_prelude.append(value);
  532. }
  533. }
  534. RefPtr<StyleRule> Parser::consume_a_qualified_rule()
  535. {
  536. return consume_a_qualified_rule(m_token_stream);
  537. }
  538. template<typename T>
  539. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  540. {
  541. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_qualified_rule");
  542. NonnullRefPtr<StyleRule> rule = create<StyleRule>(StyleRule::Type::Qualified);
  543. for (;;) {
  544. auto token = tokens.next_token();
  545. if (token.is(Token::Type::EndOfFile)) {
  546. log_parse_error();
  547. return {};
  548. }
  549. if (token.is(Token::Type::OpenCurly)) {
  550. rule->m_block = consume_a_simple_block(tokens);
  551. return rule;
  552. }
  553. // how is "simple block with an associated token of <{-token>" a valid token?
  554. tokens.reconsume_current_input_token();
  555. auto value = consume_a_component_value(tokens);
  556. rule->m_prelude.append(value);
  557. }
  558. return rule;
  559. }
  560. template<>
  561. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  562. {
  563. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_component_value - shortcut: '{}'", tokens.peek_token().to_debug_string());
  564. return tokens.next_token();
  565. }
  566. template<typename T>
  567. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  568. {
  569. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_component_value");
  570. auto token = tokens.next_token();
  571. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  572. return StyleComponentValueRule(consume_a_simple_block(tokens));
  573. if (token.is(Token::Type::Function))
  574. return StyleComponentValueRule(consume_a_function(tokens));
  575. return StyleComponentValueRule(token);
  576. }
  577. StyleComponentValueRule Parser::consume_a_component_value()
  578. {
  579. return consume_a_component_value(m_token_stream);
  580. }
  581. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block()
  582. {
  583. return consume_a_simple_block(m_token_stream);
  584. }
  585. template<typename T>
  586. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  587. {
  588. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_simple_block");
  589. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  590. NonnullRefPtr<StyleBlockRule> block = create<StyleBlockRule>();
  591. block->m_token = tokens.current_token();
  592. for (;;) {
  593. auto token = tokens.next_token();
  594. if (token.is(ending_token)) {
  595. return block;
  596. }
  597. if (token.is(Token::Type::EndOfFile)) {
  598. log_parse_error();
  599. return block;
  600. }
  601. tokens.reconsume_current_input_token();
  602. auto value = consume_a_component_value(tokens);
  603. block->m_values.append(value);
  604. }
  605. }
  606. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function()
  607. {
  608. return consume_a_function(m_token_stream);
  609. }
  610. template<typename T>
  611. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  612. {
  613. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_function");
  614. auto name_ident = tokens.current_token();
  615. VERIFY(name_ident.is(Token::Type::Function));
  616. NonnullRefPtr<StyleFunctionRule> function = create<StyleFunctionRule>(((Token)name_ident).m_value.to_string());
  617. for (;;) {
  618. auto token = tokens.next_token();
  619. if (token.is(Token::Type::CloseParen)) {
  620. return function;
  621. }
  622. if (token.is(Token::Type::EndOfFile)) {
  623. log_parse_error();
  624. return function;
  625. }
  626. tokens.reconsume_current_input_token();
  627. auto value = consume_a_component_value(tokens);
  628. function->m_values.append(value);
  629. }
  630. return function;
  631. }
  632. Optional<StyleDeclarationRule> Parser::consume_a_declaration()
  633. {
  634. return consume_a_declaration(m_token_stream);
  635. }
  636. template<typename T>
  637. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  638. {
  639. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_declaration");
  640. auto token = tokens.next_token();
  641. StyleDeclarationRule declaration;
  642. VERIFY(token.is(Token::Type::Ident));
  643. declaration.m_name = ((Token)token).ident();
  644. tokens.skip_whitespace();
  645. auto colon = tokens.next_token();
  646. if (!colon.is(Token::Type::Colon)) {
  647. log_parse_error();
  648. return {};
  649. }
  650. tokens.skip_whitespace();
  651. for (;;) {
  652. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  653. break;
  654. }
  655. declaration.m_values.append(consume_a_component_value(tokens));
  656. }
  657. if (declaration.m_values.size() >= 2) {
  658. auto second_last = declaration.m_values.at(declaration.m_values.size() - 2);
  659. auto last = declaration.m_values.at(declaration.m_values.size() - 1);
  660. if (second_last.m_type == StyleComponentValueRule::ComponentType::Token && last.m_type == StyleComponentValueRule::ComponentType::Token) {
  661. auto last_token = last.m_token;
  662. auto second_last_token = second_last.m_token;
  663. if (second_last_token.is(Token::Type::Delim) && second_last_token.m_value.to_string().equals_ignoring_case("!")) {
  664. if (last_token.is(Token::Type::Ident) && last_token.m_value.to_string().equals_ignoring_case("important")) {
  665. declaration.m_values.remove(declaration.m_values.size() - 2);
  666. declaration.m_values.remove(declaration.m_values.size() - 1);
  667. declaration.m_important = true;
  668. }
  669. }
  670. }
  671. }
  672. while (!declaration.m_values.is_empty()) {
  673. auto maybe_whitespace = declaration.m_values.last();
  674. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  675. break;
  676. }
  677. declaration.m_values.take_last();
  678. }
  679. return declaration;
  680. }
  681. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations()
  682. {
  683. return consume_a_list_of_declarations(m_token_stream);
  684. }
  685. template<typename T>
  686. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  687. {
  688. dbgln_if(CSS_PARSER_TRACE, "Parser::consume_a_list_of_declarations");
  689. Vector<DeclarationOrAtRule> list;
  690. for (;;) {
  691. auto token = tokens.next_token();
  692. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  693. continue;
  694. }
  695. if (token.is(Token::Type::EndOfFile)) {
  696. return list;
  697. }
  698. if (token.is(Token::Type::AtKeyword)) {
  699. tokens.reconsume_current_input_token();
  700. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  701. continue;
  702. }
  703. if (token.is(Token::Type::Ident)) {
  704. Vector<StyleComponentValueRule> temp;
  705. temp.append(token);
  706. for (;;) {
  707. auto peek = tokens.peek_token();
  708. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  709. break;
  710. }
  711. temp.append(consume_a_component_value(tokens));
  712. }
  713. auto token_stream = TokenStream(temp);
  714. auto maybe_declaration = consume_a_declaration(token_stream);
  715. if (maybe_declaration.has_value()) {
  716. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  717. }
  718. continue;
  719. }
  720. log_parse_error();
  721. tokens.reconsume_current_input_token();
  722. auto peek = tokens.peek_token();
  723. if (!(peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))) {
  724. (void)consume_a_component_value(tokens);
  725. }
  726. }
  727. return list;
  728. }
  729. RefPtr<CSSRule> Parser::parse_as_rule()
  730. {
  731. return parse_as_rule(m_token_stream);
  732. }
  733. template<typename T>
  734. RefPtr<CSSRule> Parser::parse_as_rule(TokenStream<T>& tokens)
  735. {
  736. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_rule");
  737. RefPtr<CSSRule> rule;
  738. tokens.skip_whitespace();
  739. auto token = tokens.peek_token();
  740. if (token.is(Token::Type::EndOfFile)) {
  741. return {};
  742. } else if (token.is(Token::Type::AtKeyword)) {
  743. auto at_rule = consume_an_at_rule();
  744. rule = convert_to_rule(at_rule);
  745. } else {
  746. auto qualified_rule = consume_a_qualified_rule(tokens);
  747. if (!qualified_rule)
  748. return {};
  749. rule = convert_to_rule(*qualified_rule);
  750. }
  751. tokens.skip_whitespace();
  752. auto maybe_eof = tokens.peek_token();
  753. if (maybe_eof.is(Token::Type::EndOfFile)) {
  754. return rule;
  755. }
  756. return {};
  757. }
  758. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  759. {
  760. return parse_as_list_of_rules(m_token_stream);
  761. }
  762. template<typename T>
  763. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules(TokenStream<T>& tokens)
  764. {
  765. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_list_of_rules");
  766. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  767. NonnullRefPtrVector<CSSRule> rules;
  768. for (auto& rule : parsed_rules) {
  769. auto converted_rule = convert_to_rule(rule);
  770. if (converted_rule)
  771. rules.append(*converted_rule);
  772. }
  773. return rules;
  774. }
  775. Optional<StyleProperty> Parser::parse_as_declaration()
  776. {
  777. return parse_as_declaration(m_token_stream);
  778. }
  779. template<typename T>
  780. Optional<StyleProperty> Parser::parse_as_declaration(TokenStream<T>& tokens)
  781. {
  782. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_declaration");
  783. tokens.skip_whitespace();
  784. auto token = tokens.peek_token();
  785. if (!token.is(Token::Type::Ident)) {
  786. return {};
  787. }
  788. auto declaration = consume_a_declaration(tokens);
  789. if (declaration.has_value())
  790. return convert_to_style_property(declaration.value());
  791. return {};
  792. }
  793. RefPtr<CSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  794. {
  795. return parse_as_list_of_declarations(m_token_stream);
  796. }
  797. template<typename T>
  798. RefPtr<CSSStyleDeclaration> Parser::parse_as_list_of_declarations(TokenStream<T>& tokens)
  799. {
  800. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_list_of_declarations");
  801. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  802. Vector<StyleProperty> properties;
  803. HashMap<String, StyleProperty> custom_properties;
  804. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  805. if (declaration_or_at_rule.is_at_rule()) {
  806. dbgln("Parser::parse_as_list_of_declarations(): At-rule is not allowed here!");
  807. continue;
  808. }
  809. auto& declaration = declaration_or_at_rule.m_declaration;
  810. auto maybe_property = convert_to_style_property(declaration);
  811. if (maybe_property.has_value()) {
  812. auto property = maybe_property.value();
  813. if (property.property_id == PropertyID::Custom) {
  814. custom_properties.set(property.custom_name, property);
  815. } else {
  816. properties.append(property);
  817. }
  818. }
  819. }
  820. return CSSStyleDeclaration::create(move(properties), move(custom_properties));
  821. }
  822. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  823. {
  824. return parse_as_component_value(m_token_stream);
  825. }
  826. template<typename T>
  827. Optional<StyleComponentValueRule> Parser::parse_as_component_value(TokenStream<T>& tokens)
  828. {
  829. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_component_value");
  830. tokens.skip_whitespace();
  831. auto token = tokens.peek_token();
  832. if (token.is(Token::Type::EndOfFile)) {
  833. return {};
  834. }
  835. auto value = consume_a_component_value(tokens);
  836. tokens.skip_whitespace();
  837. auto maybe_eof = tokens.peek_token();
  838. if (maybe_eof.is(Token::Type::EndOfFile)) {
  839. return value;
  840. }
  841. return {};
  842. }
  843. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  844. {
  845. return parse_as_list_of_component_values(m_token_stream);
  846. }
  847. template<typename T>
  848. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values(TokenStream<T>& tokens)
  849. {
  850. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_list_of_component_values");
  851. Vector<StyleComponentValueRule> rules;
  852. for (;;) {
  853. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  854. break;
  855. }
  856. rules.append(consume_a_component_value(tokens));
  857. }
  858. return rules;
  859. }
  860. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  861. {
  862. return parse_as_comma_separated_list_of_component_values(m_token_stream);
  863. }
  864. template<typename T>
  865. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  866. {
  867. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_as_comma_separated_list_of_component_values");
  868. Vector<Vector<StyleComponentValueRule>> lists;
  869. lists.append({});
  870. for (;;) {
  871. auto next = tokens.next_token();
  872. if (next.is(Token::Type::Comma)) {
  873. lists.append({});
  874. continue;
  875. } else if (next.is(Token::Type::EndOfFile)) {
  876. break;
  877. }
  878. tokens.reconsume_current_input_token();
  879. auto component_value = consume_a_component_value(tokens);
  880. lists.last().append(component_value);
  881. }
  882. return lists;
  883. }
  884. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  885. {
  886. dbgln_if(CSS_PARSER_TRACE, "Parser::convert_to_rule");
  887. if (rule->m_type == StyleRule::Type::At) {
  888. if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  889. Optional<String> url;
  890. auto url_token = rule->prelude().first();
  891. if (url_token.is_function()) {
  892. auto& function = url_token.function();
  893. if (function.name().equals_ignoring_case("url"sv) && !function.values().is_empty()) {
  894. auto& argument_token = url_token.function().values().first();
  895. if (argument_token.is(Token::Type::String))
  896. url = argument_token.token().string();
  897. else
  898. dbgln("First argument to url() was not a string: '{}'", argument_token.to_debug_string());
  899. }
  900. }
  901. if (url_token.is(Token::Type::String))
  902. url = url_token.token().string();
  903. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  904. if (url.has_value())
  905. return CSSImportRule::create(m_context.complete_url(url.value()));
  906. } else {
  907. dbgln("Unrecognized CSS at-rule: {}", rule->m_name);
  908. }
  909. // FIXME: More at rules!
  910. } else {
  911. auto prelude_stream = TokenStream(rule->m_prelude);
  912. Vector<Selector> selectors = parse_a_selector(prelude_stream);
  913. auto declaration = convert_to_declaration(*rule->m_block);
  914. if (declaration && !selectors.is_empty())
  915. return CSSStyleRule::create(move(selectors), move(*declaration));
  916. else
  917. dbgln("Discarding invalid/unsupported style rule: '{}'", rule->to_string());
  918. }
  919. return {};
  920. }
  921. RefPtr<CSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  922. {
  923. dbgln_if(CSS_PARSER_TRACE, "Parser::convert_to_declaration");
  924. if (!block->is_curly())
  925. return {};
  926. auto stream = TokenStream(block->m_values);
  927. return parse_as_list_of_declarations(stream);
  928. }
  929. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule& declaration)
  930. {
  931. dbgln_if(CSS_PARSER_TRACE, "Parser::convert_to_style_property");
  932. auto& property_name = declaration.m_name;
  933. auto property_id = property_id_from_string(property_name);
  934. if (property_id == PropertyID::Invalid && property_name.starts_with("--"))
  935. property_id = PropertyID::Custom;
  936. if (property_id == PropertyID::Invalid && !property_name.starts_with("-")) {
  937. dbgln("Parser::convert_to_style_property(): Unrecognized property '{}'", property_name);
  938. return {};
  939. }
  940. auto value_token_stream = TokenStream(declaration.m_values);
  941. auto value = parse_css_value(property_id, value_token_stream);
  942. if (!value) {
  943. dbgln("Parser::convert_to_style_property(): Property '{}' has no value.", property_name);
  944. return {};
  945. }
  946. if (property_id == PropertyID::Custom) {
  947. return StyleProperty { property_id, value.release_nonnull(), declaration.m_name, declaration.m_important };
  948. } else {
  949. return StyleProperty { property_id, value.release_nonnull(), {}, declaration.m_important };
  950. }
  951. }
  952. Optional<float> Parser::try_parse_float(StringView string)
  953. {
  954. // FIXME: This is copied from DeprecatedCSSParser, so may not be to spec.
  955. const char* str = string.characters_without_null_termination();
  956. size_t len = string.length();
  957. size_t weight = 1;
  958. int exp_val = 0;
  959. float value = 0.0f;
  960. float fraction = 0.0f;
  961. bool has_sign = false;
  962. bool is_negative = false;
  963. bool is_fractional = false;
  964. bool is_scientific = false;
  965. if (str[0] == '-') {
  966. is_negative = true;
  967. has_sign = true;
  968. }
  969. if (str[0] == '+') {
  970. has_sign = true;
  971. }
  972. for (size_t i = has_sign; i < len; i++) {
  973. // Looks like we're about to start working on the fractional part
  974. if (str[i] == '.') {
  975. is_fractional = true;
  976. continue;
  977. }
  978. if (str[i] == 'e' || str[i] == 'E') {
  979. if (str[i + 1] == '-' || str[i + 1] == '+')
  980. exp_val = atoi(str + i + 2);
  981. else
  982. exp_val = atoi(str + i + 1);
  983. is_scientific = true;
  984. continue;
  985. }
  986. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  987. return {};
  988. continue;
  989. }
  990. if (is_fractional) {
  991. fraction *= 10;
  992. fraction += str[i] - '0';
  993. weight *= 10;
  994. } else {
  995. value = value * 10;
  996. value += str[i] - '0';
  997. }
  998. }
  999. fraction /= weight;
  1000. value += fraction;
  1001. if (is_scientific) {
  1002. bool divide = exp_val < 0;
  1003. if (divide)
  1004. exp_val *= -1;
  1005. for (int i = 0; i < exp_val; i++) {
  1006. if (divide)
  1007. value /= 10;
  1008. else
  1009. value *= 10;
  1010. }
  1011. }
  1012. return is_negative ? -value : value;
  1013. }
  1014. RefPtr<StyleValue> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  1015. {
  1016. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_css_value");
  1017. // FIXME: This is mostly copied from the old, deprecated parser. It is probably not to spec.
  1018. auto takes_integer_value = [](PropertyID property_id) -> bool {
  1019. return property_id == PropertyID::ZIndex
  1020. || property_id == PropertyID::FontWeight
  1021. || property_id == PropertyID::Custom;
  1022. };
  1023. auto parse_length = [&]() -> Optional<Length> {
  1024. Length::Type type = Length::Type::Undefined;
  1025. Optional<float> numeric_value;
  1026. auto token = tokens.next_token();
  1027. if (token.is(Token::Type::Dimension)) {
  1028. auto length_string = token.token().m_value.string_view();
  1029. auto unit_string = token.token().m_unit.string_view();
  1030. if (unit_string.equals_ignoring_case("%")) {
  1031. type = Length::Type::Percentage;
  1032. } else if (unit_string.equals_ignoring_case("px")) {
  1033. type = Length::Type::Px;
  1034. } else if (unit_string.equals_ignoring_case("pt")) {
  1035. type = Length::Type::Pt;
  1036. } else if (unit_string.equals_ignoring_case("pc")) {
  1037. type = Length::Type::Pc;
  1038. } else if (unit_string.equals_ignoring_case("mm")) {
  1039. type = Length::Type::Mm;
  1040. } else if (unit_string.equals_ignoring_case("rem")) {
  1041. type = Length::Type::Rem;
  1042. } else if (unit_string.equals_ignoring_case("em")) {
  1043. type = Length::Type::Em;
  1044. } else if (unit_string.equals_ignoring_case("ex")) {
  1045. type = Length::Type::Ex;
  1046. } else if (unit_string.equals_ignoring_case("vw")) {
  1047. type = Length::Type::Vw;
  1048. } else if (unit_string.equals_ignoring_case("vh")) {
  1049. type = Length::Type::Vh;
  1050. } else if (unit_string.equals_ignoring_case("vmax")) {
  1051. type = Length::Type::Vmax;
  1052. } else if (unit_string.equals_ignoring_case("vmin")) {
  1053. type = Length::Type::Vmin;
  1054. } else if (unit_string.equals_ignoring_case("cm")) {
  1055. type = Length::Type::Cm;
  1056. } else if (unit_string.equals_ignoring_case("in")) {
  1057. type = Length::Type::In;
  1058. } else if (unit_string.equals_ignoring_case("Q")) {
  1059. type = Length::Type::Q;
  1060. } else if (m_context.in_quirks_mode()) {
  1061. type = Length::Type::Px;
  1062. }
  1063. numeric_value = try_parse_float(length_string);
  1064. } else if (token.is(Token::Type::Number)) {
  1065. auto value_string = token.token().m_value.string_view();
  1066. if (value_string == "0") {
  1067. type = Length::Type::Px;
  1068. numeric_value = 0;
  1069. } else if (m_context.in_quirks_mode()) {
  1070. type = Length::Type::Px;
  1071. numeric_value = try_parse_float(value_string);
  1072. }
  1073. }
  1074. if (!numeric_value.has_value())
  1075. return {};
  1076. return Length(numeric_value.value(), type);
  1077. };
  1078. auto token = tokens.next_token();
  1079. if (takes_integer_value(property_id) && token.is(Token::Type::Number)) {
  1080. auto number = token.token();
  1081. if (number.m_number_type == Token::NumberType::Integer) {
  1082. return LengthStyleValue::create(Length::make_px(number.integer()));
  1083. }
  1084. }
  1085. if (token.is(Token::Type::Dimension) || token.is(Token::Type::Number)) {
  1086. tokens.reconsume_current_input_token();
  1087. auto length = parse_length();
  1088. if (length.has_value())
  1089. return LengthStyleValue::create(length.value());
  1090. auto value_string = token.token().m_value.string_view();
  1091. auto float_number = try_parse_float(value_string);
  1092. if (float_number.has_value())
  1093. return NumericStyleValue::create(float_number.value());
  1094. return nullptr;
  1095. }
  1096. if (token.is(Token::Type::Ident)) {
  1097. auto ident = token.token().ident();
  1098. if (ident.equals_ignoring_case("inherit"))
  1099. return InheritStyleValue::create();
  1100. if (ident.equals_ignoring_case("initial"))
  1101. return InitialStyleValue::create();
  1102. if (ident.equals_ignoring_case("auto"))
  1103. return LengthStyleValue::create(Length::make_auto());
  1104. }
  1105. if (token.is_function() && token.function().name().equals_ignoring_case("var")) {
  1106. // FIXME: Handle fallback value as second parameter
  1107. // https://www.w3.org/TR/css-variables-1/#using-variables
  1108. if (!token.function().values().is_empty()) {
  1109. auto& property_name_token = token.function().values().first();
  1110. if (property_name_token.is(Token::Type::Ident))
  1111. return CustomStyleValue::create(property_name_token.token().ident());
  1112. else
  1113. dbgln("First argument to var() function was not an ident: '{}'", property_name_token.to_debug_string());
  1114. }
  1115. }
  1116. if (token.is(Token::Type::Ident)) {
  1117. auto value_id = value_id_from_string(token.token().ident());
  1118. if (value_id != ValueID::Invalid)
  1119. return IdentifierStyleValue::create(value_id);
  1120. }
  1121. auto parse_css_color = [&]() -> Optional<Color> {
  1122. if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_case("transparent"))
  1123. return Color::from_rgba(0x00000000);
  1124. // FIXME: Handle all the different color notations.
  1125. // https://www.w3.org/TR/css-color-3/
  1126. // Right now, this uses non-CSS-specific parsing, and assumes the whole color value is one token,
  1127. // which is isn't if it's a function-style syntax.
  1128. auto color = Color::from_string(token.token().m_value.to_string().to_lowercase());
  1129. if (color.has_value())
  1130. return color;
  1131. return {};
  1132. };
  1133. auto color = parse_css_color();
  1134. if (color.has_value())
  1135. return ColorStyleValue::create(color.value());
  1136. if (token.is(Token::Type::String))
  1137. return StringStyleValue::create(token.token().string());
  1138. return {};
  1139. }
  1140. Optional<Selector::SimpleSelector::NthChildPattern> Parser::parse_nth_child_pattern(TokenStream<StyleComponentValueRule>& values)
  1141. {
  1142. dbgln_if(CSS_PARSER_TRACE, "Parser::parse_nth_child_pattern");
  1143. Selector::SimpleSelector::NthChildPattern pattern;
  1144. auto current_value = values.next_token();
  1145. if (current_value.is(Token::Type::Ident)) {
  1146. auto ident = current_value.token().ident();
  1147. if (ident.equals_ignoring_case("odd")) {
  1148. pattern.step_size = 2;
  1149. pattern.offset = 1;
  1150. return pattern;
  1151. } else if (ident.equals_ignoring_case("even")) {
  1152. pattern.step_size = 2;
  1153. return pattern;
  1154. }
  1155. }
  1156. // Try to match any of following patterns:
  1157. // 1. An+B
  1158. // 2. An
  1159. // 3. B
  1160. // ...where "A" is "step_size", "B" is "offset" and rest are literals.
  1161. // "A" can be omitted, in that case "A" = 1.
  1162. // "A" may have "+" or "-" sign, "B" always must be predated by sign for pattern (1).
  1163. auto is_n = [](StyleComponentValueRule value) -> bool {
  1164. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n");
  1165. };
  1166. auto is_delim = [](StyleComponentValueRule value, StringView delim) -> bool {
  1167. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  1168. };
  1169. int step_size_or_offset = 0;
  1170. // "When a=1, or a=-1, the 1 may be omitted from the rule."
  1171. if (is_n(current_value)) {
  1172. step_size_or_offset = +1;
  1173. } else if (is_delim(current_value, "+"sv) && is_n(values.peek_token())) {
  1174. step_size_or_offset = +1;
  1175. values.next_token();
  1176. } else if (is_delim(current_value, "-"sv) && is_n(values.peek_token())) {
  1177. step_size_or_offset = -1;
  1178. values.next_token();
  1179. } else if (current_value.is(Token::Type::Number)) {
  1180. step_size_or_offset = current_value.token().integer();
  1181. } else {
  1182. values.reconsume_current_input_token();
  1183. }
  1184. current_value = values.next_token();
  1185. if (is_n(current_value)) {
  1186. values.skip_whitespace();
  1187. auto next_value = values.peek_token();
  1188. if (is_delim(next_value, "+") || is_delim(next_value, "-")) {
  1189. const auto sign = is_delim(next_value, "+") ? 1 : -1;
  1190. values.next_token();
  1191. values.skip_whitespace();
  1192. // "An+B" pattern
  1193. auto number = values.next_token();
  1194. if (!number.is(Token::Type::Number))
  1195. return {};
  1196. pattern.step_size = step_size_or_offset;
  1197. pattern.offset = sign * number.token().integer();
  1198. } else {
  1199. // "An" pattern
  1200. pattern.step_size = step_size_or_offset;
  1201. }
  1202. } else {
  1203. // "B" pattern
  1204. pattern.offset = step_size_or_offset;
  1205. }
  1206. if (values.has_next_token())
  1207. return {};
  1208. return pattern;
  1209. }
  1210. }