Parser.cpp 45 KB

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