Parser.cpp 44 KB

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