Parser.cpp 45 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. 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_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_string());
  215. return {};
  216. }
  217. type = Selector::SimpleSelector::Type::Class;
  218. value = current_value.to_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_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_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_string(), delim_second_part.to_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_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_string());
  382. return simple_selector;
  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. } else {
  413. dbgln("Unrecognized relation delimiter: '{}'", delim);
  414. }
  415. }
  416. tokens.skip_whitespace();
  417. Vector<Selector::SimpleSelector> simple_selectors;
  418. for (;;) {
  419. auto current_value = tokens.peek_token();
  420. if (current_value.is(Token::Type::EndOfFile) || current_value.is(Token::Type::Whitespace))
  421. break;
  422. auto component = parse_simple_selector();
  423. if (!component.has_value())
  424. break;
  425. simple_selectors.append(component.value());
  426. }
  427. if (simple_selectors.is_empty())
  428. return {};
  429. return Selector::ComplexSelector { relation, move(simple_selectors) };
  430. };
  431. for (;;) {
  432. auto current_value = tokens.peek_token();
  433. if (current_value.is(Token::Type::EndOfFile))
  434. break;
  435. auto complex = parse_complex_selector();
  436. if (complex.has_value())
  437. selectors.append(complex.value());
  438. }
  439. if (selectors.is_empty())
  440. return {};
  441. if (!is_relative)
  442. selectors.first().relation = Selector::ComplexSelector::Relation::None;
  443. return Selector(move(selectors));
  444. }
  445. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(bool top_level)
  446. {
  447. return consume_a_list_of_rules(m_token_stream, top_level);
  448. }
  449. template<typename T>
  450. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  451. {
  452. NonnullRefPtrVector<StyleRule> rules;
  453. for (;;) {
  454. auto token = tokens.next_token();
  455. if (token.is(Token::Type::Whitespace)) {
  456. continue;
  457. }
  458. if (token.is(Token::Type::EndOfFile)) {
  459. break;
  460. }
  461. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  462. if (top_level) {
  463. continue;
  464. }
  465. tokens.reconsume_current_input_token();
  466. auto maybe_qualified = consume_a_qualified_rule(tokens);
  467. if (maybe_qualified) {
  468. rules.append(maybe_qualified.release_nonnull());
  469. }
  470. continue;
  471. }
  472. if (token.is(Token::Type::AtKeyword)) {
  473. tokens.reconsume_current_input_token();
  474. rules.append(consume_an_at_rule(tokens));
  475. continue;
  476. }
  477. tokens.reconsume_current_input_token();
  478. auto maybe_qualified = consume_a_qualified_rule(tokens);
  479. if (maybe_qualified) {
  480. rules.append(maybe_qualified.release_nonnull());
  481. }
  482. }
  483. return rules;
  484. }
  485. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule()
  486. {
  487. return consume_an_at_rule(m_token_stream);
  488. }
  489. template<typename T>
  490. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  491. {
  492. auto name_ident = tokens.next_token();
  493. VERIFY(name_ident.is(Token::Type::Ident));
  494. NonnullRefPtr<StyleRule> rule = create<StyleRule>(StyleRule::Type::At);
  495. rule->m_name = ((Token)name_ident).ident();
  496. for (;;) {
  497. auto token = tokens.next_token();
  498. if (token.is(Token::Type::Semicolon)) {
  499. return rule;
  500. }
  501. if (token.is(Token::Type::EndOfFile)) {
  502. log_parse_error();
  503. return rule;
  504. }
  505. if (token.is(Token::Type::OpenCurly)) {
  506. rule->m_block = consume_a_simple_block(tokens);
  507. return rule;
  508. }
  509. // how is "simple block with an associated token of <{-token>" a valid token?
  510. tokens.reconsume_current_input_token();
  511. auto value = consume_a_component_value(tokens);
  512. rule->m_prelude.append(value);
  513. }
  514. }
  515. RefPtr<StyleRule> Parser::consume_a_qualified_rule()
  516. {
  517. return consume_a_qualified_rule(m_token_stream);
  518. }
  519. template<typename T>
  520. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  521. {
  522. NonnullRefPtr<StyleRule> rule = create<StyleRule>(StyleRule::Type::Qualified);
  523. for (;;) {
  524. auto token = tokens.next_token();
  525. if (token.is(Token::Type::EndOfFile)) {
  526. log_parse_error();
  527. return {};
  528. }
  529. if (token.is(Token::Type::OpenCurly)) {
  530. rule->m_block = consume_a_simple_block(tokens);
  531. return rule;
  532. }
  533. // how is "simple block with an associated token of <{-token>" a valid token?
  534. tokens.reconsume_current_input_token();
  535. auto value = consume_a_component_value(tokens);
  536. rule->m_prelude.append(value);
  537. }
  538. return rule;
  539. }
  540. template<>
  541. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  542. {
  543. return tokens.next_token();
  544. }
  545. template<typename T>
  546. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  547. {
  548. auto token = tokens.next_token();
  549. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  550. return StyleComponentValueRule(consume_a_simple_block(tokens));
  551. if (token.is(Token::Type::Function))
  552. return StyleComponentValueRule(consume_a_function(tokens));
  553. return StyleComponentValueRule(token);
  554. }
  555. StyleComponentValueRule Parser::consume_a_component_value()
  556. {
  557. return consume_a_component_value(m_token_stream);
  558. }
  559. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block()
  560. {
  561. return consume_a_simple_block(m_token_stream);
  562. }
  563. template<typename T>
  564. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  565. {
  566. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  567. NonnullRefPtr<StyleBlockRule> block = create<StyleBlockRule>();
  568. block->m_token = tokens.current_token();
  569. for (;;) {
  570. auto token = tokens.next_token();
  571. if (token.is(ending_token)) {
  572. return block;
  573. }
  574. if (token.is(Token::Type::EndOfFile)) {
  575. log_parse_error();
  576. return block;
  577. }
  578. tokens.reconsume_current_input_token();
  579. auto value = consume_a_component_value(tokens);
  580. block->m_values.append(value);
  581. }
  582. }
  583. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function()
  584. {
  585. return consume_a_function(m_token_stream);
  586. }
  587. template<typename T>
  588. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  589. {
  590. auto name_ident = tokens.current_token();
  591. VERIFY(name_ident.is(Token::Type::Function));
  592. NonnullRefPtr<StyleFunctionRule> function = create<StyleFunctionRule>(((Token)name_ident).m_value.to_string());
  593. for (;;) {
  594. auto token = tokens.next_token();
  595. if (token.is(Token::Type::CloseParen)) {
  596. return function;
  597. }
  598. if (token.is(Token::Type::EndOfFile)) {
  599. log_parse_error();
  600. return function;
  601. }
  602. tokens.reconsume_current_input_token();
  603. auto value = consume_a_component_value(tokens);
  604. function->m_values.append(value.to_string());
  605. }
  606. return function;
  607. }
  608. Optional<StyleDeclarationRule> Parser::consume_a_declaration()
  609. {
  610. return consume_a_declaration(m_token_stream);
  611. }
  612. template<typename T>
  613. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  614. {
  615. auto token = tokens.next_token();
  616. StyleDeclarationRule declaration;
  617. VERIFY(token.is(Token::Type::Ident));
  618. declaration.m_name = ((Token)token).ident();
  619. tokens.skip_whitespace();
  620. auto colon = tokens.next_token();
  621. if (!colon.is(Token::Type::Colon)) {
  622. log_parse_error();
  623. return {};
  624. }
  625. tokens.skip_whitespace();
  626. for (;;) {
  627. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  628. break;
  629. }
  630. declaration.m_values.append(consume_a_component_value(tokens));
  631. }
  632. if (declaration.m_values.size() >= 2) {
  633. auto second_last = declaration.m_values.at(declaration.m_values.size() - 2);
  634. auto last = declaration.m_values.at(declaration.m_values.size() - 1);
  635. if (second_last.m_type == StyleComponentValueRule::ComponentType::Token && last.m_type == StyleComponentValueRule::ComponentType::Token) {
  636. auto last_token = last.m_token;
  637. auto second_last_token = second_last.m_token;
  638. if (second_last_token.is(Token::Type::Delim) && second_last_token.m_value.to_string().equals_ignoring_case("!")) {
  639. if (last_token.is(Token::Type::Ident) && last_token.m_value.to_string().equals_ignoring_case("important")) {
  640. declaration.m_values.remove(declaration.m_values.size() - 2);
  641. declaration.m_values.remove(declaration.m_values.size() - 1);
  642. declaration.m_important = true;
  643. }
  644. }
  645. }
  646. }
  647. while (!declaration.m_values.is_empty()) {
  648. auto maybe_whitespace = declaration.m_values.last();
  649. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  650. break;
  651. }
  652. declaration.m_values.take_last();
  653. }
  654. return declaration;
  655. }
  656. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations()
  657. {
  658. return consume_a_list_of_declarations(m_token_stream);
  659. }
  660. template<typename T>
  661. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  662. {
  663. Vector<DeclarationOrAtRule> list;
  664. for (;;) {
  665. auto token = tokens.next_token();
  666. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  667. continue;
  668. }
  669. if (token.is(Token::Type::EndOfFile)) {
  670. return list;
  671. }
  672. if (token.is(Token::Type::AtKeyword)) {
  673. tokens.reconsume_current_input_token();
  674. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  675. continue;
  676. }
  677. if (token.is(Token::Type::Ident)) {
  678. Vector<StyleComponentValueRule> temp;
  679. temp.append(token);
  680. for (;;) {
  681. auto peek = tokens.peek_token();
  682. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  683. break;
  684. }
  685. temp.append(consume_a_component_value(tokens));
  686. }
  687. auto token_stream = TokenStream(temp);
  688. auto maybe_declaration = consume_a_declaration(token_stream);
  689. if (maybe_declaration.has_value()) {
  690. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  691. }
  692. continue;
  693. }
  694. log_parse_error();
  695. tokens.reconsume_current_input_token();
  696. auto peek = tokens.peek_token();
  697. if (!(peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))) {
  698. (void)consume_a_component_value(tokens);
  699. }
  700. }
  701. return list;
  702. }
  703. RefPtr<CSSRule> Parser::parse_as_rule()
  704. {
  705. return parse_as_rule(m_token_stream);
  706. }
  707. template<typename T>
  708. RefPtr<CSSRule> Parser::parse_as_rule(TokenStream<T>& tokens)
  709. {
  710. RefPtr<CSSRule> rule;
  711. tokens.skip_whitespace();
  712. auto token = tokens.peek_token();
  713. if (token.is(Token::Type::EndOfFile)) {
  714. return {};
  715. } else if (token.is(Token::Type::AtKeyword)) {
  716. auto at_rule = consume_an_at_rule();
  717. rule = convert_to_rule(at_rule);
  718. } else {
  719. auto qualified_rule = consume_a_qualified_rule(tokens);
  720. if (!qualified_rule)
  721. return {};
  722. rule = convert_to_rule(*qualified_rule);
  723. }
  724. tokens.skip_whitespace();
  725. auto maybe_eof = tokens.peek_token();
  726. if (maybe_eof.is(Token::Type::EndOfFile)) {
  727. return rule;
  728. }
  729. return {};
  730. }
  731. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  732. {
  733. return parse_as_list_of_rules(m_token_stream);
  734. }
  735. template<typename T>
  736. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules(TokenStream<T>& tokens)
  737. {
  738. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  739. NonnullRefPtrVector<CSSRule> rules;
  740. for (auto& rule : parsed_rules) {
  741. auto converted_rule = convert_to_rule(rule);
  742. if (converted_rule)
  743. rules.append(*converted_rule);
  744. }
  745. return rules;
  746. }
  747. Optional<StyleProperty> Parser::parse_as_declaration()
  748. {
  749. return parse_as_declaration(m_token_stream);
  750. }
  751. template<typename T>
  752. Optional<StyleProperty> Parser::parse_as_declaration(TokenStream<T>& tokens)
  753. {
  754. tokens.skip_whitespace();
  755. auto token = tokens.peek_token();
  756. if (!token.is(Token::Type::Ident)) {
  757. return {};
  758. }
  759. auto declaration = consume_a_declaration(tokens);
  760. if (declaration.has_value())
  761. return convert_to_style_property(declaration.value());
  762. return {};
  763. }
  764. RefPtr<CSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  765. {
  766. return parse_as_list_of_declarations(m_token_stream);
  767. }
  768. template<typename T>
  769. RefPtr<CSSStyleDeclaration> Parser::parse_as_list_of_declarations(TokenStream<T>& tokens)
  770. {
  771. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  772. Vector<StyleProperty> properties;
  773. HashMap<String, StyleProperty> custom_properties;
  774. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  775. if (declaration_or_at_rule.is_at_rule()) {
  776. dbgln("Parser::parse_as_list_of_declarations(): At-rule is not allowed here!");
  777. continue;
  778. }
  779. auto& declaration = declaration_or_at_rule.m_declaration;
  780. auto maybe_property = convert_to_style_property(declaration);
  781. if (maybe_property.has_value()) {
  782. auto property = maybe_property.value();
  783. if (property.property_id == PropertyID::Custom) {
  784. custom_properties.set(property.custom_name, property);
  785. } else {
  786. properties.append(property);
  787. }
  788. }
  789. }
  790. return CSSStyleDeclaration::create(move(properties), move(custom_properties));
  791. }
  792. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  793. {
  794. return parse_as_component_value(m_token_stream);
  795. }
  796. template<typename T>
  797. Optional<StyleComponentValueRule> Parser::parse_as_component_value(TokenStream<T>& tokens)
  798. {
  799. tokens.skip_whitespace();
  800. auto token = tokens.peek_token();
  801. if (token.is(Token::Type::EndOfFile)) {
  802. return {};
  803. }
  804. auto value = consume_a_component_value(tokens);
  805. tokens.skip_whitespace();
  806. auto maybe_eof = tokens.peek_token();
  807. if (maybe_eof.is(Token::Type::EndOfFile)) {
  808. return value;
  809. }
  810. return {};
  811. }
  812. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  813. {
  814. return parse_as_list_of_component_values(m_token_stream);
  815. }
  816. template<typename T>
  817. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values(TokenStream<T>& tokens)
  818. {
  819. Vector<StyleComponentValueRule> rules;
  820. for (;;) {
  821. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  822. break;
  823. }
  824. rules.append(consume_a_component_value(tokens));
  825. }
  826. return rules;
  827. }
  828. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  829. {
  830. return parse_as_comma_separated_list_of_component_values(m_token_stream);
  831. }
  832. template<typename T>
  833. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  834. {
  835. Vector<Vector<StyleComponentValueRule>> lists;
  836. lists.append({});
  837. for (;;) {
  838. auto next = tokens.next_token();
  839. if (next.is(Token::Type::Comma)) {
  840. lists.append({});
  841. continue;
  842. } else if (next.is(Token::Type::EndOfFile)) {
  843. break;
  844. }
  845. tokens.reconsume_current_input_token();
  846. auto component_value = consume_a_component_value(tokens);
  847. lists.last().append(component_value);
  848. }
  849. return lists;
  850. }
  851. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  852. {
  853. if (rule->m_type == StyleRule::Type::At) {
  854. if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  855. Optional<String> url;
  856. auto url_token = rule->prelude().first();
  857. if (url_token.is_function()) {
  858. auto& function = url_token.function();
  859. if (function.name().equals_ignoring_case("url"sv) && !function.values().is_empty())
  860. url = url_token.function().values().first();
  861. }
  862. if (url_token.is(Token::Type::String))
  863. url = url_token.token().string();
  864. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  865. if (url.has_value())
  866. return CSSImportRule::create(m_context.complete_url(url.value()));
  867. } else {
  868. dbgln("Unrecognized CSS at-rule: {}", rule->m_name);
  869. }
  870. // FIXME: More at rules!
  871. } else {
  872. auto prelude_stream = TokenStream(rule->m_prelude);
  873. Vector<Selector> selectors = parse_a_selector(prelude_stream);
  874. auto declaration = convert_to_declaration(*rule->m_block);
  875. if (declaration && !selectors.is_empty())
  876. return CSSStyleRule::create(move(selectors), move(*declaration));
  877. else
  878. dbgln("Discarding invalid/unsupported style rule: '{}'", rule->to_string());
  879. }
  880. return {};
  881. }
  882. RefPtr<CSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  883. {
  884. if (!block->is_curly())
  885. return {};
  886. auto stream = TokenStream(block->m_values);
  887. return parse_as_list_of_declarations(stream);
  888. }
  889. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule& declaration)
  890. {
  891. auto& property_name = declaration.m_name;
  892. auto property_id = property_id_from_string(property_name);
  893. if (property_id == PropertyID::Invalid && property_name.starts_with("--"))
  894. property_id = PropertyID::Custom;
  895. if (property_id == PropertyID::Invalid && !property_name.starts_with("-")) {
  896. dbgln("Parser::convert_to_style_property(): Unrecognized property '{}'", property_name);
  897. return {};
  898. }
  899. auto value_token_stream = TokenStream(declaration.m_values);
  900. auto value = parse_css_value(property_id, value_token_stream);
  901. if (!value) {
  902. dbgln("Parser::convert_to_style_property(): Property '{}' has no value.", property_name);
  903. return {};
  904. }
  905. if (property_id == PropertyID::Custom) {
  906. return StyleProperty { property_id, value.release_nonnull(), declaration.m_name, declaration.m_important };
  907. } else {
  908. return StyleProperty { property_id, value.release_nonnull(), {}, declaration.m_important };
  909. }
  910. }
  911. Optional<float> Parser::try_parse_float(StringView string)
  912. {
  913. // FIXME: This is copied from DeprecatedCSSParser, so may not be to spec.
  914. const char* str = string.characters_without_null_termination();
  915. size_t len = string.length();
  916. size_t weight = 1;
  917. int exp_val = 0;
  918. float value = 0.0f;
  919. float fraction = 0.0f;
  920. bool has_sign = false;
  921. bool is_negative = false;
  922. bool is_fractional = false;
  923. bool is_scientific = false;
  924. if (str[0] == '-') {
  925. is_negative = true;
  926. has_sign = true;
  927. }
  928. if (str[0] == '+') {
  929. has_sign = true;
  930. }
  931. for (size_t i = has_sign; i < len; i++) {
  932. // Looks like we're about to start working on the fractional part
  933. if (str[i] == '.') {
  934. is_fractional = true;
  935. continue;
  936. }
  937. if (str[i] == 'e' || str[i] == 'E') {
  938. if (str[i + 1] == '-' || str[i + 1] == '+')
  939. exp_val = atoi(str + i + 2);
  940. else
  941. exp_val = atoi(str + i + 1);
  942. is_scientific = true;
  943. continue;
  944. }
  945. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  946. return {};
  947. continue;
  948. }
  949. if (is_fractional) {
  950. fraction *= 10;
  951. fraction += str[i] - '0';
  952. weight *= 10;
  953. } else {
  954. value = value * 10;
  955. value += str[i] - '0';
  956. }
  957. }
  958. fraction /= weight;
  959. value += fraction;
  960. if (is_scientific) {
  961. bool divide = exp_val < 0;
  962. if (divide)
  963. exp_val *= -1;
  964. for (int i = 0; i < exp_val; i++) {
  965. if (divide)
  966. value /= 10;
  967. else
  968. value *= 10;
  969. }
  970. }
  971. return is_negative ? -value : value;
  972. }
  973. RefPtr<StyleValue> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  974. {
  975. // FIXME: This is mostly copied from the old, deprecated parser. It is probably not to spec.
  976. auto takes_integer_value = [](PropertyID property_id) -> bool {
  977. return property_id == PropertyID::ZIndex
  978. || property_id == PropertyID::FontWeight
  979. || property_id == PropertyID::Custom;
  980. };
  981. auto parse_length = [&]() -> Optional<Length> {
  982. Length::Type type = Length::Type::Undefined;
  983. Optional<float> numeric_value;
  984. auto token = tokens.next_token();
  985. if (token.is(Token::Type::Dimension)) {
  986. auto length_string = token.token().m_value.string_view();
  987. auto unit_string = token.token().m_unit.string_view();
  988. if (unit_string.equals_ignoring_case("%")) {
  989. type = Length::Type::Percentage;
  990. } else if (unit_string.equals_ignoring_case("px")) {
  991. type = Length::Type::Px;
  992. } else if (unit_string.equals_ignoring_case("pt")) {
  993. type = Length::Type::Pt;
  994. } else if (unit_string.equals_ignoring_case("pc")) {
  995. type = Length::Type::Pc;
  996. } else if (unit_string.equals_ignoring_case("mm")) {
  997. type = Length::Type::Mm;
  998. } else if (unit_string.equals_ignoring_case("rem")) {
  999. type = Length::Type::Rem;
  1000. } else if (unit_string.equals_ignoring_case("em")) {
  1001. type = Length::Type::Em;
  1002. } else if (unit_string.equals_ignoring_case("ex")) {
  1003. type = Length::Type::Ex;
  1004. } else if (unit_string.equals_ignoring_case("vw")) {
  1005. type = Length::Type::Vw;
  1006. } else if (unit_string.equals_ignoring_case("vh")) {
  1007. type = Length::Type::Vh;
  1008. } else if (unit_string.equals_ignoring_case("vmax")) {
  1009. type = Length::Type::Vmax;
  1010. } else if (unit_string.equals_ignoring_case("vmin")) {
  1011. type = Length::Type::Vmin;
  1012. } else if (unit_string.equals_ignoring_case("cm")) {
  1013. type = Length::Type::Cm;
  1014. } else if (unit_string.equals_ignoring_case("in")) {
  1015. type = Length::Type::In;
  1016. } else if (unit_string.equals_ignoring_case("Q")) {
  1017. type = Length::Type::Q;
  1018. } else if (m_context.in_quirks_mode()) {
  1019. type = Length::Type::Px;
  1020. }
  1021. numeric_value = try_parse_float(length_string);
  1022. } else if (token.is(Token::Type::Number)) {
  1023. auto value_string = token.token().m_value.string_view();
  1024. if (value_string == "0") {
  1025. type = Length::Type::Px;
  1026. numeric_value = 0;
  1027. } else if (m_context.in_quirks_mode()) {
  1028. type = Length::Type::Px;
  1029. numeric_value = try_parse_float(value_string);
  1030. }
  1031. }
  1032. if (!numeric_value.has_value())
  1033. return {};
  1034. return Length(numeric_value.value(), type);
  1035. };
  1036. auto token = tokens.next_token();
  1037. if (takes_integer_value(property_id) && token.is(Token::Type::Number)) {
  1038. auto number = token.token();
  1039. if (number.m_number_type == Token::NumberType::Integer) {
  1040. return LengthStyleValue::create(Length::make_px(number.integer()));
  1041. }
  1042. }
  1043. if (token.is(Token::Type::Dimension) || token.is(Token::Type::Number)) {
  1044. tokens.reconsume_current_input_token();
  1045. auto length = parse_length();
  1046. if (length.has_value())
  1047. return LengthStyleValue::create(length.value());
  1048. auto value_string = token.token().m_value.string_view();
  1049. auto float_number = try_parse_float(value_string);
  1050. if (float_number.has_value())
  1051. return NumericStyleValue::create(float_number.value());
  1052. return nullptr;
  1053. }
  1054. if (token.is(Token::Type::Ident)) {
  1055. auto ident = token.token().ident();
  1056. if (ident.equals_ignoring_case("inherit"))
  1057. return InheritStyleValue::create();
  1058. if (ident.equals_ignoring_case("initial"))
  1059. return InitialStyleValue::create();
  1060. if (ident.equals_ignoring_case("auto"))
  1061. return LengthStyleValue::create(Length::make_auto());
  1062. }
  1063. if (token.is_function() && token.function().name().equals_ignoring_case("var")) {
  1064. // FIXME: Handle fallback value as second parameter
  1065. // https://www.w3.org/TR/css-variables-1/#using-variables
  1066. if (!token.function().values().is_empty()) {
  1067. auto& property_name = token.function().values().first();
  1068. return CustomStyleValue::create(property_name);
  1069. }
  1070. }
  1071. if (token.is(Token::Type::Ident)) {
  1072. auto value_id = value_id_from_string(token.token().ident());
  1073. if (value_id != ValueID::Invalid)
  1074. return IdentifierStyleValue::create(value_id);
  1075. }
  1076. auto parse_css_color = [&]() -> Optional<Color> {
  1077. if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_case("transparent"))
  1078. return Color::from_rgba(0x00000000);
  1079. // FIXME: Handle all the different color notations.
  1080. // https://www.w3.org/TR/css-color-3/
  1081. // Right now, this uses non-CSS-specific parsing, and assumes the whole color value is one token,
  1082. // which is isn't if it's a function-style syntax.
  1083. auto color = Color::from_string(token.to_string().to_lowercase());
  1084. if (color.has_value())
  1085. return color;
  1086. return {};
  1087. };
  1088. auto color = parse_css_color();
  1089. if (color.has_value())
  1090. return ColorStyleValue::create(color.value());
  1091. if (token.is(Token::Type::String))
  1092. return StringStyleValue::create(token.token().string());
  1093. return {};
  1094. }
  1095. }