Parser.cpp 45 KB

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