Parser.cpp 50 KB

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