Parser.cpp 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. * Copyright (c) 2021, Sam Atkins <atkinssj@gmail.com>
  5. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. #include <AK/NonnullRefPtrVector.h>
  12. #include <AK/SourceLocation.h>
  13. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  14. #include <LibWeb/CSS/CSSStyleRule.h>
  15. #include <LibWeb/CSS/CSSStyleSheet.h>
  16. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  17. #include <LibWeb/CSS/Parser/Parser.h>
  18. #include <LibWeb/CSS/Parser/StyleBlockRule.h>
  19. #include <LibWeb/CSS/Parser/StyleComponentValueRule.h>
  20. #include <LibWeb/CSS/Parser/StyleFunctionRule.h>
  21. #include <LibWeb/CSS/Parser/StyleRule.h>
  22. #include <LibWeb/CSS/Selector.h>
  23. #include <LibWeb/DOM/Document.h>
  24. #include <LibWeb/Dump.h>
  25. static void log_parse_error(const SourceLocation& location = SourceLocation::current())
  26. {
  27. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  28. }
  29. namespace Web::CSS {
  30. ParsingContext::ParsingContext()
  31. {
  32. }
  33. ParsingContext::ParsingContext(DOM::Document& document)
  34. : m_document(&document)
  35. {
  36. }
  37. ParsingContext::ParsingContext(DOM::ParentNode& parent_node)
  38. : m_document(&parent_node.document())
  39. {
  40. }
  41. bool ParsingContext::in_quirks_mode() const
  42. {
  43. return m_document ? m_document->in_quirks_mode() : false;
  44. }
  45. URL ParsingContext::complete_url(String const& addr) const
  46. {
  47. return m_document ? m_document->url().complete_url(addr) : URL::create_with_url_or_path(addr);
  48. }
  49. template<typename T>
  50. TokenStream<T>::TokenStream(Vector<T> const& tokens)
  51. : m_tokens(tokens)
  52. , m_eof(make_eof())
  53. {
  54. }
  55. template<typename T>
  56. TokenStream<T>::~TokenStream()
  57. {
  58. }
  59. template<typename T>
  60. bool TokenStream<T>::has_next_token()
  61. {
  62. return (size_t)(m_iterator_offset + 1) < m_tokens.size();
  63. }
  64. template<typename T>
  65. T const& TokenStream<T>::peek_token(int offset)
  66. {
  67. if (!has_next_token())
  68. return m_eof;
  69. return m_tokens.at(m_iterator_offset + offset + 1);
  70. }
  71. template<typename T>
  72. T const& TokenStream<T>::next_token()
  73. {
  74. if (!has_next_token())
  75. return m_eof;
  76. ++m_iterator_offset;
  77. return m_tokens.at(m_iterator_offset);
  78. }
  79. template<typename T>
  80. T const& TokenStream<T>::current_token()
  81. {
  82. if ((size_t)m_iterator_offset >= m_tokens.size())
  83. return m_eof;
  84. return m_tokens.at(m_iterator_offset);
  85. }
  86. template<typename T>
  87. void TokenStream<T>::reconsume_current_input_token()
  88. {
  89. VERIFY(m_iterator_offset >= 0);
  90. --m_iterator_offset;
  91. }
  92. template<typename T>
  93. void TokenStream<T>::skip_whitespace()
  94. {
  95. while (peek_token().is(Token::Type::Whitespace))
  96. next_token();
  97. }
  98. template<>
  99. Token TokenStream<Token>::make_eof()
  100. {
  101. return Tokenizer::create_eof_token();
  102. }
  103. template<>
  104. StyleComponentValueRule TokenStream<StyleComponentValueRule>::make_eof()
  105. {
  106. return StyleComponentValueRule(Tokenizer::create_eof_token());
  107. }
  108. template<typename T>
  109. void TokenStream<T>::dump_all_tokens()
  110. {
  111. dbgln("Dumping all tokens:");
  112. for (size_t i = 0; i < m_tokens.size(); ++i) {
  113. auto& token = m_tokens[i];
  114. if ((i - 1) == (size_t)m_iterator_offset)
  115. dbgln("-> {}", token.to_debug_string());
  116. else
  117. dbgln(" {}", token.to_debug_string());
  118. }
  119. }
  120. Parser::Parser(ParsingContext const& context, StringView const& input, String const& encoding)
  121. : m_context(context)
  122. , m_tokenizer(input, encoding)
  123. , m_tokens(m_tokenizer.parse())
  124. , m_token_stream(TokenStream(m_tokens))
  125. {
  126. }
  127. Parser::~Parser()
  128. {
  129. }
  130. NonnullRefPtr<CSSStyleSheet> Parser::parse_as_stylesheet()
  131. {
  132. return parse_a_stylesheet(m_token_stream);
  133. }
  134. template<typename T>
  135. NonnullRefPtr<CSSStyleSheet> Parser::parse_a_stylesheet(TokenStream<T>& tokens)
  136. {
  137. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_stylesheet");
  138. auto parser_rules = consume_a_list_of_rules(tokens, true);
  139. NonnullRefPtrVector<CSSRule> rules;
  140. for (auto& raw_rule : parser_rules) {
  141. auto rule = convert_to_rule(raw_rule);
  142. if (rule)
  143. rules.append(*rule);
  144. }
  145. auto stylesheet = CSSStyleSheet::create(rules);
  146. if constexpr (CSS_PARSER_DEBUG) {
  147. dump_sheet(stylesheet);
  148. }
  149. return stylesheet;
  150. }
  151. Optional<SelectorList> Parser::parse_as_selector()
  152. {
  153. return parse_a_selector(m_token_stream);
  154. }
  155. template<typename T>
  156. Optional<SelectorList> Parser::parse_a_selector(TokenStream<T>& tokens)
  157. {
  158. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_a_selector");
  159. auto selector_list = parse_a_selector_list(tokens);
  160. if (selector_list.has_value())
  161. return selector_list;
  162. return {};
  163. }
  164. Optional<SelectorList> Parser::parse_as_relative_selector()
  165. {
  166. return parse_a_relative_selector(m_token_stream);
  167. }
  168. template<typename T>
  169. Optional<SelectorList> Parser::parse_a_relative_selector(TokenStream<T>& tokens)
  170. {
  171. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_a_relative_selector");
  172. auto selector_list = parse_a_relative_selector_list(tokens);
  173. if (selector_list.has_value())
  174. return selector_list;
  175. return {};
  176. }
  177. template<typename T>
  178. Optional<SelectorList> Parser::parse_a_selector_list(TokenStream<T>& tokens)
  179. {
  180. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_a_selector_list");
  181. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  182. NonnullRefPtrVector<Selector> selectors;
  183. for (auto& selector_parts : comma_separated_lists) {
  184. auto stream = TokenStream(selector_parts);
  185. auto selector = parse_complex_selector(stream, false);
  186. if (selector)
  187. selectors.append(selector.release_nonnull());
  188. else
  189. return {};
  190. }
  191. if (selectors.is_empty())
  192. return {};
  193. return selectors;
  194. }
  195. template<typename T>
  196. Optional<SelectorList> Parser::parse_a_relative_selector_list(TokenStream<T>& tokens)
  197. {
  198. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_a_relative_selector_list");
  199. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  200. NonnullRefPtrVector<Selector> selectors;
  201. for (auto& selector_parts : comma_separated_lists) {
  202. auto stream = TokenStream(selector_parts);
  203. auto selector = parse_complex_selector(stream, true);
  204. if (selector)
  205. selectors.append(selector.release_nonnull());
  206. else
  207. return {};
  208. }
  209. if (selectors.is_empty())
  210. return {};
  211. return selectors;
  212. }
  213. RefPtr<Selector> Parser::parse_complex_selector(TokenStream<StyleComponentValueRule>& tokens, bool allow_starting_combinator)
  214. {
  215. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_complex_selector");
  216. Vector<Selector::CompoundSelector> compound_selectors;
  217. auto first_selector = parse_compound_selector(tokens);
  218. if (first_selector.is_error())
  219. return {};
  220. if (!allow_starting_combinator) {
  221. if (first_selector.value().combinator != Selector::Combinator::Descendant)
  222. return {};
  223. first_selector.value().combinator = Selector::Combinator::None;
  224. }
  225. compound_selectors.append(first_selector.value());
  226. while (tokens.has_next_token()) {
  227. auto compound_selector = parse_compound_selector(tokens);
  228. if (compound_selector.is_error()) {
  229. if (compound_selector.error() == SelectorParsingResult::Done)
  230. break;
  231. else
  232. return {};
  233. }
  234. compound_selectors.append(compound_selector.value());
  235. }
  236. if (compound_selectors.is_empty())
  237. return {};
  238. return Selector::create(move(compound_selectors));
  239. }
  240. Result<Selector::CompoundSelector, Parser::SelectorParsingResult> Parser::parse_compound_selector(TokenStream<StyleComponentValueRule>& tokens)
  241. {
  242. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_compound_selector");
  243. tokens.skip_whitespace();
  244. auto combinator = parse_selector_combinator(tokens).value_or(Selector::Combinator::Descendant);
  245. tokens.skip_whitespace();
  246. Vector<Selector::SimpleSelector> simple_selectors;
  247. while (tokens.has_next_token()) {
  248. auto component = parse_simple_selector(tokens);
  249. if (component.is_error()) {
  250. if (component.error() == SelectorParsingResult::Done)
  251. break;
  252. else
  253. return component.error();
  254. }
  255. simple_selectors.append(component.value());
  256. }
  257. if (simple_selectors.is_empty())
  258. return SelectorParsingResult::Done;
  259. return Selector::CompoundSelector { combinator, move(simple_selectors) };
  260. }
  261. Optional<Selector::Combinator> Parser::parse_selector_combinator(TokenStream<StyleComponentValueRule>& tokens)
  262. {
  263. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_selector_combinator");
  264. auto& current_value = tokens.next_token();
  265. if (current_value.is(Token::Type::Delim)) {
  266. auto delim = current_value.token().delim();
  267. if (delim == ">"sv) {
  268. return Selector::Combinator::ImmediateChild;
  269. } else if (delim == "+"sv) {
  270. return Selector::Combinator::NextSibling;
  271. } else if (delim == "~"sv) {
  272. return Selector::Combinator::SubsequentSibling;
  273. } else if (delim == "|"sv) {
  274. auto& next = tokens.peek_token();
  275. if (next.is(Token::Type::EndOfFile))
  276. return {};
  277. if (next.is(Token::Type::Delim) && next.token().delim() == "|"sv) {
  278. tokens.next_token();
  279. return Selector::Combinator::Column;
  280. }
  281. }
  282. }
  283. tokens.reconsume_current_input_token();
  284. return {};
  285. }
  286. Result<Selector::SimpleSelector, Parser::SelectorParsingResult> Parser::parse_simple_selector(TokenStream<StyleComponentValueRule>& tokens)
  287. {
  288. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_simple_selector");
  289. auto peek_token_ends_selector = [&]() -> bool {
  290. auto& value = tokens.peek_token();
  291. return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
  292. };
  293. if (peek_token_ends_selector())
  294. return SelectorParsingResult::Done;
  295. auto& first_value = tokens.next_token();
  296. if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "*"sv) {
  297. return Selector::SimpleSelector {
  298. .type = Selector::SimpleSelector::Type::Universal
  299. };
  300. } else if (first_value.is(Token::Type::Hash)) {
  301. if (first_value.token().hash_type() != Token::HashType::Id) {
  302. dbgln_if(CSS_PARSER_DEBUG, "Selector contains hash token that is not an id: {}", first_value.to_debug_string());
  303. return SelectorParsingResult::SyntaxError;
  304. }
  305. return Selector::SimpleSelector {
  306. .type = Selector::SimpleSelector::Type::Id,
  307. .value = first_value.token().hash_value()
  308. };
  309. } else if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "."sv) {
  310. if (peek_token_ends_selector())
  311. return SelectorParsingResult::SyntaxError;
  312. auto& class_name_value = tokens.next_token();
  313. if (!class_name_value.is(Token::Type::Ident)) {
  314. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident after '.', got: {}", class_name_value.to_debug_string());
  315. return SelectorParsingResult::SyntaxError;
  316. }
  317. return Selector::SimpleSelector {
  318. .type = Selector::SimpleSelector::Type::Class,
  319. .value = class_name_value.token().ident()
  320. };
  321. } else if (first_value.is(Token::Type::Ident)) {
  322. return Selector::SimpleSelector {
  323. .type = Selector::SimpleSelector::Type::TagName,
  324. .value = first_value.token().ident()
  325. };
  326. } else if (first_value.is_block() && first_value.block().is_square()) {
  327. auto& attribute_parts = first_value.block().values();
  328. if (attribute_parts.is_empty()) {
  329. dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
  330. return SelectorParsingResult::SyntaxError;
  331. }
  332. // FIXME: Handle namespace prefix for attribute name.
  333. auto& attribute_part = attribute_parts.first();
  334. if (!attribute_part.is(Token::Type::Ident)) {
  335. dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  336. return SelectorParsingResult::SyntaxError;
  337. }
  338. Selector::SimpleSelector simple_selector {
  339. .type = Selector::SimpleSelector::Type::Attribute,
  340. .attribute = {
  341. .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
  342. // FIXME: Case-sensitivity is defined by the document language.
  343. // HTML is insensitive with attribute names, and our code generally assumes
  344. // they are converted to lowercase, so we do that here too. If we want to be
  345. // correct with XML later, we'll need to keep the original case and then do
  346. // a case-insensitive compare later.
  347. .name = attribute_part.token().ident().to_lowercase_string(),
  348. }
  349. };
  350. if (attribute_parts.size() == 1)
  351. return simple_selector;
  352. size_t attribute_index = 1;
  353. auto& delim_part = attribute_parts.at(attribute_index);
  354. if (!delim_part.is(Token::Type::Delim)) {
  355. dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  356. return SelectorParsingResult::SyntaxError;
  357. }
  358. if (delim_part.token().delim() == "="sv) {
  359. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
  360. attribute_index++;
  361. } else {
  362. attribute_index++;
  363. if (attribute_index >= attribute_parts.size()) {
  364. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
  365. return SelectorParsingResult::SyntaxError;
  366. }
  367. auto& delim_second_part = attribute_parts.at(attribute_index);
  368. if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == "=")) {
  369. dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  370. return SelectorParsingResult::SyntaxError;
  371. }
  372. if (delim_part.token().delim() == "~"sv) {
  373. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
  374. attribute_index++;
  375. } else if (delim_part.token().delim() == "*"sv) {
  376. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
  377. attribute_index++;
  378. } else if (delim_part.token().delim() == "|"sv) {
  379. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
  380. attribute_index++;
  381. } else if (delim_part.token().delim() == "^"sv) {
  382. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
  383. attribute_index++;
  384. } else if (delim_part.token().delim() == "$"sv) {
  385. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
  386. attribute_index++;
  387. }
  388. }
  389. if (attribute_index >= attribute_parts.size()) {
  390. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
  391. return SelectorParsingResult::SyntaxError;
  392. }
  393. auto& value_part = attribute_parts.at(attribute_index);
  394. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  395. dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  396. return SelectorParsingResult::SyntaxError;
  397. }
  398. simple_selector.attribute.value = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  399. // FIXME: Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  400. return simple_selector;
  401. } else if (first_value.is(Token::Type::Colon)) {
  402. if (peek_token_ends_selector())
  403. return SelectorParsingResult::SyntaxError;
  404. bool is_pseudo = false;
  405. if (tokens.peek_token().is(Token::Type::Colon)) {
  406. is_pseudo = true;
  407. tokens.next_token();
  408. if (peek_token_ends_selector())
  409. return SelectorParsingResult::SyntaxError;
  410. }
  411. if (is_pseudo) {
  412. Selector::SimpleSelector simple_selector {
  413. .type = Selector::SimpleSelector::Type::PseudoElement
  414. };
  415. auto& name_token = tokens.next_token();
  416. if (!name_token.is(Token::Type::Ident)) {
  417. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
  418. return SelectorParsingResult::SyntaxError;
  419. }
  420. auto pseudo_name = name_token.token().ident();
  421. if (pseudo_name.equals_ignoring_case("after")) {
  422. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  423. } else if (pseudo_name.equals_ignoring_case("before")) {
  424. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  425. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  426. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  427. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  428. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  429. } else {
  430. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized pseudo-element: '{}'", pseudo_name);
  431. return SelectorParsingResult::SyntaxError;
  432. }
  433. return simple_selector;
  434. }
  435. if (peek_token_ends_selector())
  436. return SelectorParsingResult::SyntaxError;
  437. auto& pseudo_class_token = tokens.next_token();
  438. Selector::SimpleSelector simple_selector {
  439. .type = Selector::SimpleSelector::Type::PseudoClass
  440. };
  441. if (pseudo_class_token.is(Token::Type::Ident)) {
  442. auto pseudo_name = pseudo_class_token.token().ident();
  443. if (pseudo_name.equals_ignoring_case("active")) {
  444. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Active;
  445. } else if (pseudo_name.equals_ignoring_case("checked")) {
  446. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Checked;
  447. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  448. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Disabled;
  449. } else if (pseudo_name.equals_ignoring_case("empty")) {
  450. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Empty;
  451. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  452. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Enabled;
  453. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  454. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstChild;
  455. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  456. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstOfType;
  457. } else if (pseudo_name.equals_ignoring_case("focus")) {
  458. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Focus;
  459. } else if (pseudo_name.equals_ignoring_case("hover")) {
  460. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Hover;
  461. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  462. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastChild;
  463. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  464. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastOfType;
  465. } else if (pseudo_name.equals_ignoring_case("link")) {
  466. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Link;
  467. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  468. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::OnlyChild;
  469. } else if (pseudo_name.equals_ignoring_case("root")) {
  470. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Root;
  471. } else if (pseudo_name.equals_ignoring_case("visited")) {
  472. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Visited;
  473. } else if (pseudo_name.equals_ignoring_case("after")) {
  474. // Single-colon syntax allowed for compatibility. https://www.w3.org/TR/selectors/#pseudo-element-syntax
  475. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  476. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  477. } else if (pseudo_name.equals_ignoring_case("before")) {
  478. // See :after
  479. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  480. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  481. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  482. // See :after
  483. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  484. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  485. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  486. // See :after
  487. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  488. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  489. } else {
  490. dbgln_if(CSS_PARSER_DEBUG, "Unknown pseudo class: '{}'", pseudo_name);
  491. return SelectorParsingResult::SyntaxError;
  492. }
  493. return simple_selector;
  494. } else if (pseudo_class_token.is_function()) {
  495. auto& pseudo_function = pseudo_class_token.function();
  496. if (pseudo_function.name().equals_ignoring_case("not")) {
  497. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Not;
  498. auto function_token_stream = TokenStream(pseudo_function.values());
  499. auto not_selector = parse_a_selector(function_token_stream);
  500. if (!not_selector.has_value()) {
  501. dbgln_if(CSS_PARSER_DEBUG, "Invalid selector in :not() clause");
  502. return SelectorParsingResult::SyntaxError;
  503. }
  504. simple_selector.pseudo_class.not_selector = not_selector.value();
  505. } else if (pseudo_function.name().equals_ignoring_case("nth-child")) {
  506. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthChild;
  507. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  508. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  509. if (nth_child_pattern.has_value()) {
  510. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  511. } else {
  512. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  513. return SelectorParsingResult::SyntaxError;
  514. }
  515. } else if (pseudo_function.name().equals_ignoring_case("nth-last-child")) {
  516. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthLastChild;
  517. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  518. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  519. if (nth_child_pattern.has_value()) {
  520. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  521. } else {
  522. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  523. return SelectorParsingResult::SyntaxError;
  524. }
  525. } else {
  526. dbgln_if(CSS_PARSER_DEBUG, "Unknown pseudo class: '{}'()", pseudo_function.name());
  527. return SelectorParsingResult::SyntaxError;
  528. }
  529. return simple_selector;
  530. } else {
  531. dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
  532. return SelectorParsingResult::SyntaxError;
  533. }
  534. }
  535. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  536. return SelectorParsingResult::SyntaxError;
  537. }
  538. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(bool top_level)
  539. {
  540. return consume_a_list_of_rules(m_token_stream, top_level);
  541. }
  542. template<typename T>
  543. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  544. {
  545. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_list_of_rules");
  546. NonnullRefPtrVector<StyleRule> rules;
  547. for (;;) {
  548. auto& token = tokens.next_token();
  549. if (token.is(Token::Type::Whitespace)) {
  550. continue;
  551. }
  552. if (token.is(Token::Type::EndOfFile)) {
  553. break;
  554. }
  555. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  556. if (top_level) {
  557. continue;
  558. }
  559. tokens.reconsume_current_input_token();
  560. auto maybe_qualified = consume_a_qualified_rule(tokens);
  561. if (maybe_qualified) {
  562. rules.append(maybe_qualified.release_nonnull());
  563. }
  564. continue;
  565. }
  566. if (token.is(Token::Type::AtKeyword)) {
  567. tokens.reconsume_current_input_token();
  568. rules.append(consume_an_at_rule(tokens));
  569. continue;
  570. }
  571. tokens.reconsume_current_input_token();
  572. auto maybe_qualified = consume_a_qualified_rule(tokens);
  573. if (maybe_qualified) {
  574. rules.append(maybe_qualified.release_nonnull());
  575. }
  576. }
  577. return rules;
  578. }
  579. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule()
  580. {
  581. return consume_an_at_rule(m_token_stream);
  582. }
  583. template<typename T>
  584. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  585. {
  586. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_an_at_rule");
  587. auto& name_ident = tokens.next_token();
  588. VERIFY(name_ident.is(Token::Type::AtKeyword));
  589. NonnullRefPtr<StyleRule> rule = create<StyleRule>(StyleRule::Type::At);
  590. rule->m_name = ((Token)name_ident).at_keyword();
  591. for (;;) {
  592. auto& token = tokens.next_token();
  593. if (token.is(Token::Type::Semicolon)) {
  594. return rule;
  595. }
  596. if (token.is(Token::Type::EndOfFile)) {
  597. log_parse_error();
  598. return rule;
  599. }
  600. if (token.is(Token::Type::OpenCurly)) {
  601. rule->m_block = consume_a_simple_block(tokens);
  602. return rule;
  603. }
  604. // how is "simple block with an associated token of <{-token>" a valid token?
  605. tokens.reconsume_current_input_token();
  606. auto value = consume_a_component_value(tokens);
  607. rule->m_prelude.append(value);
  608. }
  609. }
  610. RefPtr<StyleRule> Parser::consume_a_qualified_rule()
  611. {
  612. return consume_a_qualified_rule(m_token_stream);
  613. }
  614. template<typename T>
  615. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  616. {
  617. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_qualified_rule");
  618. NonnullRefPtr<StyleRule> rule = create<StyleRule>(StyleRule::Type::Qualified);
  619. for (;;) {
  620. auto& token = tokens.next_token();
  621. if (token.is(Token::Type::EndOfFile)) {
  622. log_parse_error();
  623. return {};
  624. }
  625. if (token.is(Token::Type::OpenCurly)) {
  626. rule->m_block = consume_a_simple_block(tokens);
  627. return rule;
  628. }
  629. // how is "simple block with an associated token of <{-token>" a valid token?
  630. tokens.reconsume_current_input_token();
  631. auto value = consume_a_component_value(tokens);
  632. rule->m_prelude.append(value);
  633. }
  634. return rule;
  635. }
  636. template<>
  637. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  638. {
  639. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_component_value - shortcut: '{}'", tokens.peek_token().to_debug_string());
  640. return tokens.next_token();
  641. }
  642. template<typename T>
  643. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  644. {
  645. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_component_value");
  646. auto& token = tokens.next_token();
  647. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  648. return StyleComponentValueRule(consume_a_simple_block(tokens));
  649. if (token.is(Token::Type::Function))
  650. return StyleComponentValueRule(consume_a_function(tokens));
  651. return StyleComponentValueRule(token);
  652. }
  653. StyleComponentValueRule Parser::consume_a_component_value()
  654. {
  655. return consume_a_component_value(m_token_stream);
  656. }
  657. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block()
  658. {
  659. return consume_a_simple_block(m_token_stream);
  660. }
  661. template<typename T>
  662. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  663. {
  664. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_simple_block");
  665. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  666. NonnullRefPtr<StyleBlockRule> block = create<StyleBlockRule>();
  667. block->m_token = tokens.current_token();
  668. for (;;) {
  669. auto& token = tokens.next_token();
  670. if (token.is(ending_token)) {
  671. return block;
  672. }
  673. if (token.is(Token::Type::EndOfFile)) {
  674. log_parse_error();
  675. return block;
  676. }
  677. tokens.reconsume_current_input_token();
  678. auto value = consume_a_component_value(tokens);
  679. block->m_values.append(value);
  680. }
  681. }
  682. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function()
  683. {
  684. return consume_a_function(m_token_stream);
  685. }
  686. template<typename T>
  687. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  688. {
  689. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_function");
  690. auto name_ident = tokens.current_token();
  691. VERIFY(name_ident.is(Token::Type::Function));
  692. NonnullRefPtr<StyleFunctionRule> function = create<StyleFunctionRule>(((Token)name_ident).m_value.to_string());
  693. for (;;) {
  694. auto& token = tokens.next_token();
  695. if (token.is(Token::Type::CloseParen)) {
  696. return function;
  697. }
  698. if (token.is(Token::Type::EndOfFile)) {
  699. log_parse_error();
  700. return function;
  701. }
  702. tokens.reconsume_current_input_token();
  703. auto value = consume_a_component_value(tokens);
  704. function->m_values.append(value);
  705. }
  706. return function;
  707. }
  708. Optional<StyleDeclarationRule> Parser::consume_a_declaration()
  709. {
  710. return consume_a_declaration(m_token_stream);
  711. }
  712. template<typename T>
  713. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  714. {
  715. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_declaration");
  716. auto& token = tokens.next_token();
  717. StyleDeclarationRule declaration;
  718. VERIFY(token.is(Token::Type::Ident));
  719. declaration.m_name = ((Token)token).ident();
  720. tokens.skip_whitespace();
  721. auto& maybe_colon = tokens.next_token();
  722. if (!maybe_colon.is(Token::Type::Colon)) {
  723. log_parse_error();
  724. return {};
  725. }
  726. tokens.skip_whitespace();
  727. for (;;) {
  728. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  729. break;
  730. }
  731. declaration.m_values.append(consume_a_component_value(tokens));
  732. }
  733. if (declaration.m_values.size() >= 2) {
  734. auto second_last = declaration.m_values.at(declaration.m_values.size() - 2);
  735. auto last = declaration.m_values.at(declaration.m_values.size() - 1);
  736. if (second_last.m_type == StyleComponentValueRule::ComponentType::Token && last.m_type == StyleComponentValueRule::ComponentType::Token) {
  737. auto last_token = last.m_token;
  738. auto second_last_token = second_last.m_token;
  739. if (second_last_token.is(Token::Type::Delim) && second_last_token.m_value.to_string().equals_ignoring_case("!")) {
  740. if (last_token.is(Token::Type::Ident) && last_token.m_value.to_string().equals_ignoring_case("important")) {
  741. declaration.m_values.remove(declaration.m_values.size() - 2);
  742. declaration.m_values.remove(declaration.m_values.size() - 1);
  743. declaration.m_important = true;
  744. }
  745. }
  746. }
  747. }
  748. while (!declaration.m_values.is_empty()) {
  749. auto maybe_whitespace = declaration.m_values.last();
  750. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  751. break;
  752. }
  753. declaration.m_values.take_last();
  754. }
  755. return declaration;
  756. }
  757. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations()
  758. {
  759. return consume_a_list_of_declarations(m_token_stream);
  760. }
  761. template<typename T>
  762. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  763. {
  764. dbgln_if(CSS_PARSER_DEBUG, "Parser::consume_a_list_of_declarations");
  765. Vector<DeclarationOrAtRule> list;
  766. for (;;) {
  767. auto& token = tokens.next_token();
  768. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  769. continue;
  770. }
  771. if (token.is(Token::Type::EndOfFile)) {
  772. return list;
  773. }
  774. if (token.is(Token::Type::AtKeyword)) {
  775. tokens.reconsume_current_input_token();
  776. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  777. continue;
  778. }
  779. if (token.is(Token::Type::Ident)) {
  780. Vector<StyleComponentValueRule> temp;
  781. temp.append(token);
  782. for (;;) {
  783. auto& peek = tokens.peek_token();
  784. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  785. break;
  786. }
  787. temp.append(consume_a_component_value(tokens));
  788. }
  789. auto token_stream = TokenStream(temp);
  790. auto maybe_declaration = consume_a_declaration(token_stream);
  791. if (maybe_declaration.has_value()) {
  792. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  793. }
  794. continue;
  795. }
  796. log_parse_error();
  797. tokens.reconsume_current_input_token();
  798. for (;;) {
  799. auto& peek = tokens.peek_token();
  800. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  801. break;
  802. dbgln("Discarding token: '{}'", peek.to_debug_string());
  803. (void)consume_a_component_value(tokens);
  804. }
  805. }
  806. return list;
  807. }
  808. RefPtr<CSSRule> Parser::parse_as_rule()
  809. {
  810. return parse_a_rule(m_token_stream);
  811. }
  812. template<typename T>
  813. RefPtr<CSSRule> Parser::parse_a_rule(TokenStream<T>& tokens)
  814. {
  815. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_rule");
  816. RefPtr<CSSRule> rule;
  817. tokens.skip_whitespace();
  818. auto& token = tokens.peek_token();
  819. if (token.is(Token::Type::EndOfFile)) {
  820. return {};
  821. } else if (token.is(Token::Type::AtKeyword)) {
  822. auto at_rule = consume_an_at_rule();
  823. rule = convert_to_rule(at_rule);
  824. } else {
  825. auto qualified_rule = consume_a_qualified_rule(tokens);
  826. if (!qualified_rule)
  827. return {};
  828. rule = convert_to_rule(*qualified_rule);
  829. }
  830. tokens.skip_whitespace();
  831. auto& maybe_eof = tokens.peek_token();
  832. if (maybe_eof.is(Token::Type::EndOfFile)) {
  833. return rule;
  834. }
  835. return {};
  836. }
  837. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  838. {
  839. return parse_a_list_of_rules(m_token_stream);
  840. }
  841. template<typename T>
  842. NonnullRefPtrVector<CSSRule> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  843. {
  844. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_list_of_rules");
  845. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  846. NonnullRefPtrVector<CSSRule> rules;
  847. for (auto& rule : parsed_rules) {
  848. auto converted_rule = convert_to_rule(rule);
  849. if (converted_rule)
  850. rules.append(*converted_rule);
  851. }
  852. return rules;
  853. }
  854. Optional<StyleProperty> Parser::parse_as_declaration()
  855. {
  856. return parse_a_declaration(m_token_stream);
  857. }
  858. template<typename T>
  859. Optional<StyleProperty> Parser::parse_a_declaration(TokenStream<T>& tokens)
  860. {
  861. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_declaration");
  862. tokens.skip_whitespace();
  863. auto& token = tokens.peek_token();
  864. if (!token.is(Token::Type::Ident)) {
  865. return {};
  866. }
  867. auto declaration = consume_a_declaration(tokens);
  868. if (declaration.has_value())
  869. return convert_to_style_property(declaration.value());
  870. return {};
  871. }
  872. RefPtr<CSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  873. {
  874. return parse_a_list_of_declarations(m_token_stream);
  875. }
  876. template<typename T>
  877. RefPtr<CSSStyleDeclaration> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  878. {
  879. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_list_of_declarations");
  880. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  881. Vector<StyleProperty> properties;
  882. HashMap<String, StyleProperty> custom_properties;
  883. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  884. if (declaration_or_at_rule.is_at_rule()) {
  885. dbgln("Parser::parse_as_list_of_declarations(): At-rule is not allowed here!");
  886. continue;
  887. }
  888. auto& declaration = declaration_or_at_rule.m_declaration;
  889. auto maybe_property = convert_to_style_property(declaration);
  890. if (maybe_property.has_value()) {
  891. auto property = maybe_property.value();
  892. if (property.property_id == PropertyID::Custom) {
  893. custom_properties.set(property.custom_name, property);
  894. } else {
  895. properties.append(property);
  896. }
  897. }
  898. }
  899. return CSSStyleDeclaration::create(move(properties), move(custom_properties));
  900. }
  901. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  902. {
  903. return parse_a_component_value(m_token_stream);
  904. }
  905. template<typename T>
  906. Optional<StyleComponentValueRule> Parser::parse_a_component_value(TokenStream<T>& tokens)
  907. {
  908. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_component_value");
  909. tokens.skip_whitespace();
  910. auto& token = tokens.peek_token();
  911. if (token.is(Token::Type::EndOfFile)) {
  912. return {};
  913. }
  914. auto value = consume_a_component_value(tokens);
  915. tokens.skip_whitespace();
  916. auto& maybe_eof = tokens.peek_token();
  917. if (maybe_eof.is(Token::Type::EndOfFile)) {
  918. return value;
  919. }
  920. return {};
  921. }
  922. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  923. {
  924. return parse_a_list_of_component_values(m_token_stream);
  925. }
  926. template<typename T>
  927. Vector<StyleComponentValueRule> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  928. {
  929. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_list_of_component_values");
  930. Vector<StyleComponentValueRule> rules;
  931. for (;;) {
  932. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  933. break;
  934. }
  935. rules.append(consume_a_component_value(tokens));
  936. }
  937. return rules;
  938. }
  939. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  940. {
  941. return parse_a_comma_separated_list_of_component_values(m_token_stream);
  942. }
  943. template<typename T>
  944. Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  945. {
  946. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_as_comma_separated_list_of_component_values");
  947. Vector<Vector<StyleComponentValueRule>> lists;
  948. lists.append({});
  949. for (;;) {
  950. auto& next = tokens.next_token();
  951. if (next.is(Token::Type::Comma)) {
  952. lists.append({});
  953. continue;
  954. } else if (next.is(Token::Type::EndOfFile)) {
  955. break;
  956. }
  957. tokens.reconsume_current_input_token();
  958. auto component_value = consume_a_component_value(tokens);
  959. lists.last().append(component_value);
  960. }
  961. return lists;
  962. }
  963. Optional<URL> Parser::parse_url_function(ParsingContext const& context, StyleComponentValueRule const& component_value)
  964. {
  965. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  966. // FIXME: Handle data: urls (RFC2397)
  967. auto is_data_url = [](StringView& url_string) -> bool {
  968. return url_string.starts_with("data:", CaseSensitivity::CaseInsensitive);
  969. };
  970. if (component_value.is(Token::Type::Url)) {
  971. auto url_string = component_value.token().url();
  972. if (is_data_url(url_string))
  973. return {};
  974. return context.complete_url(url_string);
  975. }
  976. if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) {
  977. auto& function_values = component_value.function().values();
  978. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  979. for (size_t i = 0; i < function_values.size(); ++i) {
  980. auto& value = function_values[i];
  981. if (value.is(Token::Type::Whitespace))
  982. continue;
  983. if (value.is(Token::Type::String)) {
  984. auto url_string = value.token().string();
  985. if (is_data_url(url_string))
  986. return {};
  987. return context.complete_url(url_string);
  988. }
  989. break;
  990. }
  991. }
  992. return {};
  993. }
  994. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  995. {
  996. dbgln_if(CSS_PARSER_DEBUG, "Parser::convert_to_rule");
  997. if (rule->m_type == StyleRule::Type::At) {
  998. if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  999. Optional<URL> url;
  1000. for (auto& token : rule->prelude()) {
  1001. if (token.is(Token::Type::Whitespace))
  1002. continue;
  1003. if (token.is(Token::Type::String)) {
  1004. url = m_context.complete_url(token.token().string());
  1005. } else {
  1006. url = parse_url_function(m_context, token);
  1007. }
  1008. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1009. if (url.has_value())
  1010. break;
  1011. }
  1012. if (url.has_value())
  1013. return CSSImportRule::create(url.value());
  1014. else
  1015. dbgln("Unable to parse url from @import rule");
  1016. } else {
  1017. dbgln("Unrecognized CSS at-rule: {}", rule->m_name);
  1018. }
  1019. // FIXME: More at rules!
  1020. } else {
  1021. auto prelude_stream = TokenStream(rule->m_prelude);
  1022. auto selectors = parse_a_selector(prelude_stream);
  1023. if (!selectors.has_value() || selectors.value().is_empty()) {
  1024. dbgln("CSSParser: style rule selectors invalid; discarding.");
  1025. prelude_stream.dump_all_tokens();
  1026. return {};
  1027. }
  1028. auto declaration = convert_to_declaration(*rule->m_block);
  1029. if (!declaration) {
  1030. dbgln("CSSParser: style rule declaration invalid; discarding.");
  1031. return {};
  1032. }
  1033. return CSSStyleRule::create(move(selectors.value()), move(*declaration));
  1034. }
  1035. return {};
  1036. }
  1037. RefPtr<CSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  1038. {
  1039. dbgln_if(CSS_PARSER_DEBUG, "Parser::convert_to_declaration");
  1040. if (!block->is_curly())
  1041. return {};
  1042. auto stream = TokenStream(block->m_values);
  1043. return parse_a_list_of_declarations(stream);
  1044. }
  1045. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule& declaration)
  1046. {
  1047. dbgln_if(CSS_PARSER_DEBUG, "Parser::convert_to_style_property");
  1048. auto& property_name = declaration.m_name;
  1049. auto property_id = property_id_from_string(property_name);
  1050. if (property_id == PropertyID::Invalid && property_name.starts_with("--"))
  1051. property_id = PropertyID::Custom;
  1052. if (property_id == PropertyID::Invalid && !property_name.starts_with("-")) {
  1053. dbgln("Parser::convert_to_style_property(): Unrecognized property '{}'", property_name);
  1054. return {};
  1055. }
  1056. auto value_token_stream = TokenStream(declaration.m_values);
  1057. auto value = parse_css_value(property_id, value_token_stream);
  1058. if (!value) {
  1059. dbgln("Parser::convert_to_style_property(): Property '{}' has no value.", property_name);
  1060. return {};
  1061. }
  1062. if (property_id == PropertyID::Custom) {
  1063. return StyleProperty { property_id, value.release_nonnull(), declaration.m_name, declaration.m_important };
  1064. } else {
  1065. return StyleProperty { property_id, value.release_nonnull(), {}, declaration.m_important };
  1066. }
  1067. }
  1068. Optional<float> Parser::try_parse_float(StringView string)
  1069. {
  1070. // FIXME: This is copied from DeprecatedCSSParser, so may not be to spec.
  1071. const char* str = string.characters_without_null_termination();
  1072. size_t len = string.length();
  1073. size_t weight = 1;
  1074. int exp_val = 0;
  1075. float value = 0.0f;
  1076. float fraction = 0.0f;
  1077. bool has_sign = false;
  1078. bool is_negative = false;
  1079. bool is_fractional = false;
  1080. bool is_scientific = false;
  1081. if (str[0] == '-') {
  1082. is_negative = true;
  1083. has_sign = true;
  1084. }
  1085. if (str[0] == '+') {
  1086. has_sign = true;
  1087. }
  1088. for (size_t i = has_sign; i < len; i++) {
  1089. // Looks like we're about to start working on the fractional part
  1090. if (str[i] == '.') {
  1091. is_fractional = true;
  1092. continue;
  1093. }
  1094. if (str[i] == 'e' || str[i] == 'E') {
  1095. if (str[i + 1] == '-' || str[i + 1] == '+')
  1096. exp_val = atoi(str + i + 2);
  1097. else
  1098. exp_val = atoi(str + i + 1);
  1099. is_scientific = true;
  1100. continue;
  1101. }
  1102. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  1103. return {};
  1104. continue;
  1105. }
  1106. if (is_fractional) {
  1107. fraction *= 10;
  1108. fraction += str[i] - '0';
  1109. weight *= 10;
  1110. } else {
  1111. value = value * 10;
  1112. value += str[i] - '0';
  1113. }
  1114. }
  1115. fraction /= weight;
  1116. value += fraction;
  1117. if (is_scientific) {
  1118. bool divide = exp_val < 0;
  1119. if (divide)
  1120. exp_val *= -1;
  1121. for (int i = 0; i < exp_val; i++) {
  1122. if (divide)
  1123. value /= 10;
  1124. else
  1125. value *= 10;
  1126. }
  1127. }
  1128. return is_negative ? -value : value;
  1129. }
  1130. RefPtr<StyleValue> Parser::parse_builtin_or_dynamic_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1131. {
  1132. if (component_value.is(Token::Type::Ident)) {
  1133. auto ident = component_value.token().ident();
  1134. if (ident.equals_ignoring_case("inherit"))
  1135. return InheritStyleValue::create();
  1136. if (ident.equals_ignoring_case("initial"))
  1137. return InitialStyleValue::create();
  1138. // FIXME: Implement `unset` keyword
  1139. }
  1140. if (component_value.is_function()) {
  1141. auto& function = component_value.function();
  1142. if (function.name().equals_ignoring_case("calc")) {
  1143. auto calc_expression = parse_calc_expression(context, function.values());
  1144. // FIXME: Either produce a string value of calc() here, or do so in CalculatedStyleValue::to_string().
  1145. if (calc_expression)
  1146. return CalculatedStyleValue::create("(FIXME:calc to string)", calc_expression.release_nonnull());
  1147. } else if (function.name().equals_ignoring_case("var")) {
  1148. // FIXME: Handle fallback value as second parameter
  1149. // https://www.w3.org/TR/css-variables-1/#using-variables
  1150. if (!component_value.function().values().is_empty()) {
  1151. auto& property_name_token = component_value.function().values().first();
  1152. if (property_name_token.is(Token::Type::Ident))
  1153. return CustomStyleValue::create(property_name_token.token().ident());
  1154. else
  1155. dbgln("First argument to var() function was not an ident: '{}'", property_name_token.to_debug_string());
  1156. }
  1157. }
  1158. }
  1159. return {};
  1160. }
  1161. Optional<Length> Parser::parse_length(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1162. {
  1163. Length::Type type = Length::Type::Undefined;
  1164. Optional<float> numeric_value;
  1165. if (component_value.is(Token::Type::Dimension)) {
  1166. auto length_string = component_value.token().m_value.string_view();
  1167. auto unit_string = component_value.token().m_unit.string_view();
  1168. if (unit_string.equals_ignoring_case("%")) {
  1169. type = Length::Type::Percentage;
  1170. } else if (unit_string.equals_ignoring_case("px")) {
  1171. type = Length::Type::Px;
  1172. } else if (unit_string.equals_ignoring_case("pt")) {
  1173. type = Length::Type::Pt;
  1174. } else if (unit_string.equals_ignoring_case("pc")) {
  1175. type = Length::Type::Pc;
  1176. } else if (unit_string.equals_ignoring_case("mm")) {
  1177. type = Length::Type::Mm;
  1178. } else if (unit_string.equals_ignoring_case("rem")) {
  1179. type = Length::Type::Rem;
  1180. } else if (unit_string.equals_ignoring_case("em")) {
  1181. type = Length::Type::Em;
  1182. } else if (unit_string.equals_ignoring_case("ex")) {
  1183. type = Length::Type::Ex;
  1184. } else if (unit_string.equals_ignoring_case("vw")) {
  1185. type = Length::Type::Vw;
  1186. } else if (unit_string.equals_ignoring_case("vh")) {
  1187. type = Length::Type::Vh;
  1188. } else if (unit_string.equals_ignoring_case("vmax")) {
  1189. type = Length::Type::Vmax;
  1190. } else if (unit_string.equals_ignoring_case("vmin")) {
  1191. type = Length::Type::Vmin;
  1192. } else if (unit_string.equals_ignoring_case("cm")) {
  1193. type = Length::Type::Cm;
  1194. } else if (unit_string.equals_ignoring_case("in")) {
  1195. type = Length::Type::In;
  1196. } else if (unit_string.equals_ignoring_case("Q")) {
  1197. type = Length::Type::Q;
  1198. } else if (context.in_quirks_mode()) {
  1199. type = Length::Type::Px;
  1200. }
  1201. numeric_value = try_parse_float(length_string);
  1202. } else if (component_value.is(Token::Type::Number)) {
  1203. auto value_string = component_value.token().m_value.string_view();
  1204. if (value_string == "0") {
  1205. type = Length::Type::Px;
  1206. numeric_value = 0;
  1207. } else if (context.in_quirks_mode()) {
  1208. type = Length::Type::Px;
  1209. numeric_value = try_parse_float(value_string);
  1210. }
  1211. } else if (component_value.is(Token::Type::Percentage)) {
  1212. type = Length::Type::Percentage;
  1213. auto value_string = component_value.token().m_value.string_view();
  1214. numeric_value = try_parse_float(value_string);
  1215. } else if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto")) {
  1216. return Length::make_auto();
  1217. }
  1218. if (!numeric_value.has_value())
  1219. return {};
  1220. return Length(numeric_value.value(), type);
  1221. }
  1222. RefPtr<StyleValue> Parser::parse_length_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1223. {
  1224. // Numbers with no units can be lengths, in two situations:
  1225. // 1) We're in quirks mode, and it's an integer.
  1226. // 2) It's a 0.
  1227. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1228. // FIXME: "auto" is also treated as a Length, and most of the time that is how it is used, but not always.
  1229. // Possibly it should always be an Identifier, and then quietly converted to a Length when needed, like 0 above.
  1230. // Right now, it instead is quietly converted to an Identifier when needed.
  1231. if (component_value.is(Token::Type::Dimension) || component_value.is(Token::Type::Percentage)
  1232. || (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"sv))
  1233. || (context.in_quirks_mode() && component_value.is(Token::Type::Number) && component_value.token().m_value.string_view() != "0"sv)) {
  1234. auto length = parse_length(context, component_value);
  1235. if (length.has_value())
  1236. return LengthStyleValue::create(length.value());
  1237. }
  1238. return {};
  1239. }
  1240. RefPtr<StyleValue> Parser::parse_numeric_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1241. {
  1242. if (component_value.is(Token::Type::Number)) {
  1243. auto number = component_value.token();
  1244. if (number.m_number_type == Token::NumberType::Integer) {
  1245. return NumericStyleValue::create(number.to_integer());
  1246. } else {
  1247. auto float_value = try_parse_float(number.m_value.string_view());
  1248. if (float_value.has_value())
  1249. return NumericStyleValue::create(float_value.value());
  1250. }
  1251. }
  1252. return {};
  1253. }
  1254. RefPtr<StyleValue> Parser::parse_identifier_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1255. {
  1256. if (component_value.is(Token::Type::Ident)) {
  1257. auto value_id = value_id_from_string(component_value.token().ident());
  1258. if (value_id != ValueID::Invalid)
  1259. return IdentifierStyleValue::create(value_id);
  1260. }
  1261. return {};
  1262. }
  1263. Optional<Color> Parser::parse_color(ParsingContext const&, StyleComponentValueRule const& component_value)
  1264. {
  1265. // https://www.w3.org/TR/css-color-3/
  1266. if (component_value.is(Token::Type::Ident)) {
  1267. auto ident = component_value.token().ident();
  1268. if (ident.equals_ignoring_case("transparent"))
  1269. return Color::from_rgba(0x00000000);
  1270. auto color = Color::from_string(ident.to_string().to_lowercase());
  1271. if (color.has_value())
  1272. return color;
  1273. } else if (component_value.is(Token::Type::Hash)) {
  1274. // FIXME: Read it directly
  1275. auto color = Color::from_string(String::formatted("#{}", component_value.token().m_value.to_string().to_lowercase()));
  1276. if (color.has_value())
  1277. return color;
  1278. } else if (component_value.is_function()) {
  1279. auto& function = component_value.function();
  1280. auto& values = function.values();
  1281. Vector<Token> params;
  1282. for (size_t i = 0; i < values.size(); ++i) {
  1283. auto& value = values.at(i);
  1284. if (value.is(Token::Type::Whitespace))
  1285. continue;
  1286. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  1287. params.append(value.token());
  1288. // Eat following comma and whitespace
  1289. while ((i + 1) < values.size()) {
  1290. auto& next = values.at(i + 1);
  1291. if (next.is(Token::Type::Whitespace))
  1292. i++;
  1293. else if (next.is(Token::Type::Comma))
  1294. break;
  1295. return {};
  1296. }
  1297. }
  1298. }
  1299. if (function.name().equals_ignoring_case("rgb")) {
  1300. if (params.size() != 3)
  1301. return {};
  1302. auto r_val = params[0];
  1303. auto g_val = params[1];
  1304. auto b_val = params[2];
  1305. if (r_val.is(Token::NumberType::Integer)
  1306. && g_val.is(Token::NumberType::Integer)
  1307. && b_val.is(Token::NumberType::Integer)) {
  1308. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1309. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1310. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1311. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value())
  1312. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value());
  1313. } else if (r_val.is(Token::Type::Percentage)
  1314. && g_val.is(Token::Type::Percentage)
  1315. && b_val.is(Token::Type::Percentage)) {
  1316. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1317. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1318. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1319. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value()) {
  1320. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1321. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1322. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1323. return Color(r, g, b);
  1324. }
  1325. }
  1326. } else if (function.name().equals_ignoring_case("rgba")) {
  1327. if (params.size() != 4)
  1328. return {};
  1329. auto r_val = params[0];
  1330. auto g_val = params[1];
  1331. auto b_val = params[2];
  1332. auto a_val = params[3];
  1333. if (r_val.is(Token::NumberType::Integer)
  1334. && g_val.is(Token::NumberType::Integer)
  1335. && b_val.is(Token::NumberType::Integer)
  1336. && a_val.is(Token::Type::Number)) {
  1337. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1338. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1339. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1340. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1341. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1342. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1343. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value(), a);
  1344. }
  1345. } else if (r_val.is(Token::Type::Percentage)
  1346. && g_val.is(Token::Type::Percentage)
  1347. && b_val.is(Token::Type::Percentage)
  1348. && a_val.is(Token::Type::Number)) {
  1349. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1350. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1351. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1352. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1353. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1354. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1355. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1356. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1357. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1358. return Color(r, g, b, a);
  1359. }
  1360. }
  1361. } else if (function.name().equals_ignoring_case("hsl")) {
  1362. if (params.size() != 3)
  1363. return {};
  1364. auto h_val = params[0];
  1365. auto s_val = params[1];
  1366. auto l_val = params[2];
  1367. if (h_val.is(Token::Type::Number)
  1368. && s_val.is(Token::Type::Percentage)
  1369. && l_val.is(Token::Type::Percentage)) {
  1370. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1371. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1372. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1373. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value()) {
  1374. float h = maybe_h.value();
  1375. float s = maybe_s.value() / 100.0f;
  1376. float l = maybe_l.value() / 100.0f;
  1377. return Color::from_hsl(h, s, l);
  1378. }
  1379. }
  1380. } else if (function.name().equals_ignoring_case("hsla")) {
  1381. if (params.size() != 4)
  1382. return {};
  1383. auto h_val = params[0];
  1384. auto s_val = params[1];
  1385. auto l_val = params[2];
  1386. auto a_val = params[3];
  1387. if (h_val.is(Token::Type::Number)
  1388. && s_val.is(Token::Type::Percentage)
  1389. && l_val.is(Token::Type::Percentage)
  1390. && a_val.is(Token::Type::Number)) {
  1391. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1392. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1393. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1394. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1395. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value() && maybe_a.has_value()) {
  1396. float h = maybe_h.value();
  1397. float s = maybe_s.value() / 100.0f;
  1398. float l = maybe_l.value() / 100.0f;
  1399. float a = maybe_a.value();
  1400. return Color::from_hsla(h, s, l, a);
  1401. }
  1402. }
  1403. }
  1404. return {};
  1405. }
  1406. return {};
  1407. }
  1408. RefPtr<StyleValue> Parser::parse_color_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1409. {
  1410. auto color = parse_color(context, component_value);
  1411. if (color.has_value())
  1412. return ColorStyleValue::create(color.value());
  1413. return {};
  1414. }
  1415. RefPtr<StyleValue> Parser::parse_string_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1416. {
  1417. if (component_value.is(Token::Type::String))
  1418. return StringStyleValue::create(component_value.token().string());
  1419. return {};
  1420. }
  1421. RefPtr<StyleValue> Parser::parse_image_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1422. {
  1423. auto url = parse_url_function(context, component_value);
  1424. if (url.has_value())
  1425. return ImageStyleValue::create(url.value(), *context.document());
  1426. // FIXME: Handle gradients.
  1427. return {};
  1428. }
  1429. RefPtr<StyleValue> Parser::parse_background_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1430. {
  1431. auto is_background_repeat = [](StyleValue const& value) -> bool {
  1432. switch (value.to_identifier()) {
  1433. case CSS::ValueID::NoRepeat:
  1434. case CSS::ValueID::Repeat:
  1435. case CSS::ValueID::RepeatX:
  1436. case CSS::ValueID::RepeatY:
  1437. case CSS::ValueID::Round:
  1438. case CSS::ValueID::Space:
  1439. return true;
  1440. default:
  1441. return false;
  1442. }
  1443. };
  1444. auto is_background_image = [](StyleValue const& value) -> bool {
  1445. if (value.is_image())
  1446. return true;
  1447. if (value.to_identifier() == ValueID::None)
  1448. return true;
  1449. return false;
  1450. };
  1451. RefPtr<StyleValue> background_color;
  1452. RefPtr<StyleValue> background_image;
  1453. RefPtr<StyleValue> repeat_x;
  1454. RefPtr<StyleValue> repeat_y;
  1455. // FIXME: Implement background-position.
  1456. // FIXME: Implement background-size.
  1457. // FIXME: Implement background-attachment.
  1458. // FIXME: Implement background-clip.
  1459. // FIXME: Implement background-origin.
  1460. for (size_t i = 0; i < component_values.size(); ++i) {
  1461. auto& part = component_values[i];
  1462. // FIXME: Handle multiple backgrounds, by returning a List of BackgroundStyleValues.
  1463. if (part.is(Token::Type::Comma)) {
  1464. dbgln("CSS Parser does not yet support multiple comma-separated values for background.");
  1465. break;
  1466. }
  1467. auto value = parse_css_value(context, PropertyID::Background, part);
  1468. if (!value) {
  1469. return nullptr;
  1470. }
  1471. if (value->is_color()) {
  1472. if (background_color)
  1473. return nullptr;
  1474. background_color = value.release_nonnull();
  1475. continue;
  1476. }
  1477. if (is_background_image(*value)) {
  1478. if (background_image)
  1479. return nullptr;
  1480. background_image = value.release_nonnull();
  1481. continue;
  1482. }
  1483. if (is_background_repeat(*value)) {
  1484. if (repeat_x)
  1485. return nullptr;
  1486. auto value_id = value->to_identifier();
  1487. if (value_id == ValueID::RepeatX || value_id == ValueID::RepeatY) {
  1488. repeat_x = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat);
  1489. repeat_y = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat);
  1490. continue;
  1491. }
  1492. // Check following value, if it's also a repeat, set both.
  1493. if (i + 1 < component_values.size()) {
  1494. auto next_value = parse_css_value(context, PropertyID::Background, component_values[i + 1]);
  1495. if (next_value && is_background_repeat(*next_value)) {
  1496. ++i;
  1497. repeat_x = value.release_nonnull();
  1498. repeat_y = next_value.release_nonnull();
  1499. continue;
  1500. }
  1501. }
  1502. auto repeat = value.release_nonnull();
  1503. repeat_x = repeat;
  1504. repeat_y = repeat;
  1505. continue;
  1506. }
  1507. return nullptr;
  1508. }
  1509. if (!background_color)
  1510. background_color = ColorStyleValue::create(Color::Transparent);
  1511. if (!background_image)
  1512. background_image = IdentifierStyleValue::create(ValueID::None);
  1513. if (!repeat_x)
  1514. repeat_x = IdentifierStyleValue::create(ValueID::Repeat);
  1515. if (!repeat_y)
  1516. repeat_y = IdentifierStyleValue::create(ValueID::Repeat);
  1517. return BackgroundStyleValue::create(background_color.release_nonnull(), background_image.release_nonnull(), repeat_x.release_nonnull(), repeat_y.release_nonnull());
  1518. }
  1519. RefPtr<StyleValue> Parser::parse_box_shadow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1520. {
  1521. // FIXME: Also support inset, spread-radius and multiple comma-seperated box-shadows
  1522. Length offset_x {};
  1523. Length offset_y {};
  1524. Length blur_radius {};
  1525. Color color {};
  1526. if (component_values.size() < 3 || component_values.size() > 4)
  1527. return nullptr;
  1528. auto maybe_x = parse_length(context, component_values[0]);
  1529. if (!maybe_x.has_value())
  1530. return nullptr;
  1531. offset_x = maybe_x.value();
  1532. auto maybe_y = parse_length(context, component_values[1]);
  1533. if (!maybe_y.has_value())
  1534. return nullptr;
  1535. offset_y = maybe_y.value();
  1536. if (component_values.size() == 3) {
  1537. auto parsed_color = parse_color(context, component_values[2]);
  1538. if (!parsed_color.has_value())
  1539. return nullptr;
  1540. color = parsed_color.value();
  1541. } else if (component_values.size() == 4) {
  1542. auto maybe_blur_radius = parse_length(context, component_values[2]);
  1543. if (!maybe_blur_radius.has_value())
  1544. return nullptr;
  1545. blur_radius = maybe_blur_radius.value();
  1546. auto parsed_color = parse_color(context, component_values[3]);
  1547. if (!parsed_color.has_value())
  1548. return nullptr;
  1549. color = parsed_color.value();
  1550. }
  1551. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  1552. }
  1553. RefPtr<StyleValue> Parser::parse_flex_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1554. {
  1555. auto is_flex_grow_or_shrink = [](StyleValue const& value) -> bool {
  1556. if (value.is_numeric())
  1557. return true;
  1558. return false;
  1559. };
  1560. auto is_flex_basis = [](StyleValue const& value) -> bool {
  1561. if (value.is_length())
  1562. return true;
  1563. switch (value.to_identifier()) {
  1564. case ValueID::Auto:
  1565. case ValueID::Content:
  1566. return true;
  1567. default:
  1568. return false;
  1569. }
  1570. };
  1571. if (component_values.size() == 1) {
  1572. auto value = parse_css_value(context, PropertyID::Flex, component_values[0]);
  1573. if (!value)
  1574. return nullptr;
  1575. switch (value->to_identifier()) {
  1576. case ValueID::Auto: {
  1577. auto one = NumericStyleValue::create(1);
  1578. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  1579. }
  1580. case ValueID::None: {
  1581. auto zero = NumericStyleValue::create(0);
  1582. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  1583. }
  1584. default:
  1585. break;
  1586. }
  1587. }
  1588. RefPtr<StyleValue> flex_grow;
  1589. RefPtr<StyleValue> flex_shrink;
  1590. RefPtr<StyleValue> flex_basis;
  1591. for (size_t i = 0; i < component_values.size(); ++i) {
  1592. auto value = parse_css_value(context, PropertyID::Flex, component_values[i]);
  1593. if (!value)
  1594. return nullptr;
  1595. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  1596. if (value->is_numeric() && static_cast<NumericStyleValue&>(*value).value() == 0) {
  1597. if (flex_grow && flex_shrink && !flex_basis) {
  1598. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  1599. continue;
  1600. }
  1601. }
  1602. if (is_flex_grow_or_shrink(*value)) {
  1603. if (flex_grow)
  1604. return nullptr;
  1605. flex_grow = value.release_nonnull();
  1606. // Flex-shrink may optionally follow directly after.
  1607. if (i + 1 < component_values.size()) {
  1608. auto second_value = parse_css_value(context, PropertyID::Flex, component_values[i + 1]);
  1609. if (second_value && is_flex_grow_or_shrink(*second_value)) {
  1610. flex_shrink = second_value.release_nonnull();
  1611. i++;
  1612. }
  1613. }
  1614. continue;
  1615. }
  1616. if (is_flex_basis(*value)) {
  1617. if (flex_basis)
  1618. return nullptr;
  1619. flex_basis = value.release_nonnull();
  1620. continue;
  1621. }
  1622. return nullptr;
  1623. }
  1624. if (!flex_grow)
  1625. flex_grow = NumericStyleValue::create(0);
  1626. if (!flex_shrink)
  1627. flex_shrink = NumericStyleValue::create(1);
  1628. if (!flex_basis)
  1629. flex_basis = IdentifierStyleValue::create(ValueID::Auto);
  1630. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  1631. }
  1632. RefPtr<StyleValue> Parser::parse_flex_flow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1633. {
  1634. auto is_flex_direction = [](StyleValue const& value) -> bool {
  1635. switch (value.to_identifier()) {
  1636. case ValueID::Row:
  1637. case ValueID::RowReverse:
  1638. case ValueID::Column:
  1639. case ValueID::ColumnReverse:
  1640. return true;
  1641. default:
  1642. return false;
  1643. }
  1644. };
  1645. auto is_flex_wrap = [](StyleValue const& value) -> bool {
  1646. switch (value.to_identifier()) {
  1647. case ValueID::Wrap:
  1648. case ValueID::Nowrap:
  1649. case ValueID::WrapReverse:
  1650. return true;
  1651. default:
  1652. return false;
  1653. }
  1654. };
  1655. if (component_values.size() > 2)
  1656. return nullptr;
  1657. RefPtr<StyleValue> flex_direction;
  1658. RefPtr<StyleValue> flex_wrap;
  1659. for (auto& part : component_values) {
  1660. auto value = Parser::parse_css_value(context, PropertyID::FlexFlow, part);
  1661. if (!value)
  1662. return nullptr;
  1663. if (is_flex_direction(*value)) {
  1664. if (flex_direction)
  1665. return nullptr;
  1666. flex_direction = value.release_nonnull();
  1667. continue;
  1668. }
  1669. if (is_flex_wrap(*value)) {
  1670. if (flex_wrap)
  1671. return nullptr;
  1672. flex_wrap = value.release_nonnull();
  1673. continue;
  1674. }
  1675. }
  1676. if (!flex_direction)
  1677. flex_direction = IdentifierStyleValue::create(ValueID::Row);
  1678. if (!flex_wrap)
  1679. flex_wrap = IdentifierStyleValue::create(ValueID::Nowrap);
  1680. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  1681. }
  1682. RefPtr<StyleValue> Parser::parse_font_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1683. {
  1684. auto is_font_size = [](StyleValue const& value) -> bool {
  1685. if (value.is_length())
  1686. return true;
  1687. switch (value.to_identifier()) {
  1688. case ValueID::XxSmall:
  1689. case ValueID::XSmall:
  1690. case ValueID::Small:
  1691. case ValueID::Medium:
  1692. case ValueID::Large:
  1693. case ValueID::XLarge:
  1694. case ValueID::XxLarge:
  1695. case ValueID::XxxLarge:
  1696. case ValueID::Smaller:
  1697. case ValueID::Larger:
  1698. return true;
  1699. default:
  1700. return false;
  1701. }
  1702. };
  1703. auto is_font_style = [](StyleValue const& value) -> bool {
  1704. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  1705. switch (value.to_identifier()) {
  1706. case ValueID::Normal:
  1707. case ValueID::Italic:
  1708. case ValueID::Oblique:
  1709. return true;
  1710. default:
  1711. return false;
  1712. }
  1713. };
  1714. auto is_font_weight = [](StyleValue const& value) -> bool {
  1715. if (value.is_numeric()) {
  1716. auto weight = static_cast<NumericStyleValue const&>(value).value();
  1717. return (weight >= 1 && weight <= 1000);
  1718. }
  1719. switch (value.to_identifier()) {
  1720. case ValueID::Normal:
  1721. case ValueID::Bold:
  1722. case ValueID::Bolder:
  1723. case ValueID::Lighter:
  1724. return true;
  1725. default:
  1726. return false;
  1727. }
  1728. };
  1729. auto is_line_height = [](StyleValue const& value) -> bool {
  1730. if (value.is_numeric())
  1731. return true;
  1732. if (value.is_length())
  1733. return true;
  1734. if (value.to_identifier() == ValueID::Normal)
  1735. return true;
  1736. return false;
  1737. };
  1738. auto is_font_family = [](StyleValue const& value) -> bool {
  1739. if (value.is_string())
  1740. return true;
  1741. switch (value.to_identifier()) {
  1742. case ValueID::Cursive:
  1743. case ValueID::Fantasy:
  1744. case ValueID::Monospace:
  1745. case ValueID::Serif:
  1746. case ValueID::SansSerif:
  1747. case ValueID::UiMonospace:
  1748. case ValueID::UiRounded:
  1749. case ValueID::UiSerif:
  1750. case ValueID::UiSansSerif:
  1751. return true;
  1752. default:
  1753. return false;
  1754. }
  1755. };
  1756. RefPtr<StyleValue> font_style;
  1757. RefPtr<StyleValue> font_weight;
  1758. RefPtr<StyleValue> font_size;
  1759. RefPtr<StyleValue> line_height;
  1760. NonnullRefPtrVector<StyleValue> font_families;
  1761. // FIXME: Implement font-stretch and font-variant.
  1762. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  1763. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  1764. // So, we have to handle that separately.
  1765. int normal_count = 0;
  1766. for (size_t i = 0; i < component_values.size(); ++i) {
  1767. auto value = parse_css_value(context, PropertyID::Font, component_values[i]);
  1768. if (!value)
  1769. return nullptr;
  1770. if (value->to_identifier() == ValueID::Normal) {
  1771. normal_count++;
  1772. continue;
  1773. }
  1774. if (is_font_style(*value)) {
  1775. if (font_style)
  1776. return nullptr;
  1777. font_style = value.release_nonnull();
  1778. continue;
  1779. }
  1780. if (is_font_weight(*value)) {
  1781. if (font_weight)
  1782. return nullptr;
  1783. font_weight = value.release_nonnull();
  1784. continue;
  1785. }
  1786. if (is_font_size(*value)) {
  1787. if (font_size)
  1788. return nullptr;
  1789. font_size = value.release_nonnull();
  1790. // Consume `/ line-height` if present
  1791. if (i + 2 < component_values.size()) {
  1792. auto maybe_solidus = component_values[i + 1];
  1793. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  1794. auto maybe_line_height = parse_css_value(context, PropertyID::Font, component_values[i + 2]);
  1795. if (!(maybe_line_height && is_line_height(*maybe_line_height)))
  1796. return nullptr;
  1797. line_height = maybe_line_height.release_nonnull();
  1798. i += 2;
  1799. }
  1800. }
  1801. // Consume font-family
  1802. // FIXME: Handle multiple font-families separated by commas, for fallback purposes.
  1803. if (i + 1 < component_values.size()) {
  1804. auto& font_family_part = component_values[i + 1];
  1805. auto maybe_font_family = parse_css_value(context, PropertyID::Font, font_family_part);
  1806. if (!maybe_font_family) {
  1807. // Single-word font-families may not be quoted. We convert it to a String for convenience.
  1808. if (font_family_part.is(Token::Type::Ident))
  1809. maybe_font_family = StringStyleValue::create(font_family_part.token().ident());
  1810. else
  1811. return nullptr;
  1812. } else if (!is_font_family(*maybe_font_family)) {
  1813. dbgln("Unable to parse '{}' as a font-family.", font_family_part.to_debug_string());
  1814. return nullptr;
  1815. }
  1816. font_families.append(maybe_font_family.release_nonnull());
  1817. }
  1818. break;
  1819. }
  1820. return nullptr;
  1821. }
  1822. // Since normal is the default value for all the properties that can have it, we don't have to actually
  1823. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  1824. // We just need to make sure we were not given more normals than will fit.
  1825. int unset_value_count = (font_style ? 1 : 0) + (font_weight ? 1 : 0);
  1826. if (unset_value_count < normal_count)
  1827. return nullptr;
  1828. if (!font_size || font_families.is_empty())
  1829. return nullptr;
  1830. if (!font_style)
  1831. font_style = IdentifierStyleValue::create(ValueID::Normal);
  1832. if (!font_weight)
  1833. font_weight = IdentifierStyleValue::create(ValueID::Normal);
  1834. if (!line_height)
  1835. line_height = IdentifierStyleValue::create(ValueID::Normal);
  1836. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), move(font_families));
  1837. }
  1838. RefPtr<StyleValue> Parser::parse_list_style_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1839. {
  1840. auto is_list_style_image = [](StyleValue const& value) -> bool {
  1841. if (value.is_image())
  1842. return true;
  1843. if (value.is_identifier() && value.to_identifier() == ValueID::None)
  1844. return true;
  1845. return false;
  1846. };
  1847. auto is_list_style_position = [](StyleValue const& value) -> bool {
  1848. switch (value.to_identifier()) {
  1849. case ValueID::Inside:
  1850. case ValueID::Outside:
  1851. return true;
  1852. default:
  1853. return false;
  1854. }
  1855. };
  1856. auto is_list_style_type = [](StyleValue const& value) -> bool {
  1857. // FIXME: Handle strings and symbols("...") syntax
  1858. switch (value.to_identifier()) {
  1859. case CSS::ValueID::None:
  1860. case CSS::ValueID::Disc:
  1861. case CSS::ValueID::Circle:
  1862. case CSS::ValueID::Square:
  1863. case CSS::ValueID::Decimal:
  1864. case CSS::ValueID::DecimalLeadingZero:
  1865. case CSS::ValueID::LowerAlpha:
  1866. case CSS::ValueID::LowerLatin:
  1867. case CSS::ValueID::UpperAlpha:
  1868. case CSS::ValueID::UpperLatin:
  1869. case CSS::ValueID::UpperRoman:
  1870. case CSS::ValueID::LowerRoman:
  1871. return true;
  1872. default:
  1873. return false;
  1874. }
  1875. };
  1876. if (component_values.size() > 3)
  1877. return nullptr;
  1878. RefPtr<StyleValue> list_position;
  1879. RefPtr<StyleValue> list_image;
  1880. RefPtr<StyleValue> list_type;
  1881. int found_nones = 0;
  1882. for (auto& part : component_values) {
  1883. auto value = parse_css_value(context, PropertyID::ListStyle, part);
  1884. if (!value)
  1885. return nullptr;
  1886. if (value->to_identifier() == ValueID::None) {
  1887. found_nones++;
  1888. continue;
  1889. }
  1890. if (is_list_style_position(*value)) {
  1891. if (list_position)
  1892. return nullptr;
  1893. list_position = value.release_nonnull();
  1894. continue;
  1895. }
  1896. if (is_list_style_image(*value)) {
  1897. if (list_image)
  1898. return nullptr;
  1899. list_image = value.release_nonnull();
  1900. continue;
  1901. }
  1902. if (is_list_style_type(*value)) {
  1903. if (list_type)
  1904. return nullptr;
  1905. list_type = value.release_nonnull();
  1906. continue;
  1907. }
  1908. }
  1909. if (found_nones > 2)
  1910. return nullptr;
  1911. if (found_nones == 2) {
  1912. if (list_image || list_type)
  1913. return nullptr;
  1914. auto none = IdentifierStyleValue::create(ValueID::None);
  1915. list_image = none;
  1916. list_type = none;
  1917. } else if (found_nones == 1) {
  1918. if (list_image && list_type)
  1919. return nullptr;
  1920. auto none = IdentifierStyleValue::create(ValueID::None);
  1921. if (!list_image)
  1922. list_image = none;
  1923. if (!list_type)
  1924. list_type = none;
  1925. }
  1926. if (!list_position)
  1927. list_position = IdentifierStyleValue::create(ValueID::Outside);
  1928. if (!list_image)
  1929. list_image = IdentifierStyleValue::create(ValueID::None);
  1930. if (!list_type)
  1931. list_type = IdentifierStyleValue::create(ValueID::Disc);
  1932. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  1933. }
  1934. RefPtr<StyleValue> Parser::parse_text_decoration_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1935. {
  1936. auto is_text_decoration_line = [](StyleValue const& value) -> bool {
  1937. switch (value.to_identifier()) {
  1938. case ValueID::None:
  1939. case ValueID::Underline:
  1940. case ValueID::Overline:
  1941. case ValueID::LineThrough:
  1942. case ValueID::Blink:
  1943. return true;
  1944. default:
  1945. return false;
  1946. }
  1947. };
  1948. auto is_text_decoration_style = [](StyleValue const& value) -> bool {
  1949. switch (value.to_identifier()) {
  1950. case ValueID::Solid:
  1951. case ValueID::Double:
  1952. case ValueID::Dotted:
  1953. case ValueID::Dashed:
  1954. case ValueID::Wavy:
  1955. return true;
  1956. default:
  1957. return false;
  1958. }
  1959. };
  1960. if (component_values.size() > 3)
  1961. return nullptr;
  1962. RefPtr<StyleValue> decoration_line;
  1963. RefPtr<StyleValue> decoration_style;
  1964. RefPtr<StyleValue> decoration_color;
  1965. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  1966. for (auto& part : component_values) {
  1967. auto value = parse_css_value(context, PropertyID::TextDecoration, part);
  1968. if (!value)
  1969. return nullptr;
  1970. if (value->is_color()) {
  1971. if (decoration_color)
  1972. return nullptr;
  1973. decoration_color = value.release_nonnull();
  1974. continue;
  1975. }
  1976. if (is_text_decoration_line(*value)) {
  1977. if (decoration_line)
  1978. return nullptr;
  1979. decoration_line = value.release_nonnull();
  1980. continue;
  1981. }
  1982. if (is_text_decoration_style(*value)) {
  1983. if (decoration_style)
  1984. return nullptr;
  1985. decoration_style = value.release_nonnull();
  1986. continue;
  1987. }
  1988. return nullptr;
  1989. }
  1990. if (!decoration_line)
  1991. decoration_line = IdentifierStyleValue::create(ValueID::None);
  1992. if (!decoration_style)
  1993. decoration_style = IdentifierStyleValue::create(ValueID::Solid);
  1994. // FIXME: Should default to 'currentcolor' special value: https://www.w3.org/TR/css-color-3/#currentcolor
  1995. if (!decoration_color)
  1996. decoration_color = InitialStyleValue::create();
  1997. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  1998. }
  1999. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2000. {
  2001. auto component_values = parse_as_list_of_component_values();
  2002. auto tokens = TokenStream(component_values);
  2003. return parse_css_value(property_id, tokens);
  2004. }
  2005. RefPtr<StyleValue> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2006. {
  2007. Vector<StyleComponentValueRule> component_values;
  2008. while (tokens.has_next_token()) {
  2009. auto& token = tokens.next_token();
  2010. if (token.is(Token::Type::Semicolon)) {
  2011. tokens.reconsume_current_input_token();
  2012. break;
  2013. }
  2014. if (token.is(Token::Type::Whitespace))
  2015. continue;
  2016. component_values.append(token);
  2017. }
  2018. if (component_values.is_empty())
  2019. return {};
  2020. // Special-case property handling
  2021. switch (property_id) {
  2022. case PropertyID::Background:
  2023. if (auto parsed_value = parse_background_value(m_context, component_values))
  2024. return parsed_value;
  2025. break;
  2026. case PropertyID::BoxShadow:
  2027. if (auto parsed_box_shadow = parse_box_shadow_value(m_context, component_values))
  2028. return parsed_box_shadow;
  2029. break;
  2030. case PropertyID::Flex:
  2031. if (auto parsed_value = parse_flex_value(m_context, component_values))
  2032. return parsed_value;
  2033. break;
  2034. case PropertyID::FlexFlow:
  2035. if (auto parsed_value = parse_flex_flow_value(m_context, component_values))
  2036. return parsed_value;
  2037. break;
  2038. case PropertyID::Font:
  2039. if (auto parsed_value = parse_font_value(m_context, component_values))
  2040. return parsed_value;
  2041. break;
  2042. case PropertyID::ListStyle:
  2043. if (auto parsed_value = parse_list_style_value(m_context, component_values))
  2044. return parsed_value;
  2045. break;
  2046. case PropertyID::TextDecoration:
  2047. if (auto parsed_value = parse_text_decoration_value(m_context, component_values))
  2048. return parsed_value;
  2049. break;
  2050. default:
  2051. break;
  2052. }
  2053. if (component_values.size() == 1)
  2054. return parse_css_value(m_context, property_id, component_values.first());
  2055. return ValueListStyleValue::create(move(component_values));
  2056. }
  2057. RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, PropertyID property_id, StyleComponentValueRule const& component_value)
  2058. {
  2059. // FIXME: Figure out if we still need takes_integer_value, and if so, move this information
  2060. // into Properties.json.
  2061. auto takes_integer_value = [](PropertyID property_id) -> bool {
  2062. return property_id == PropertyID::ZIndex
  2063. || property_id == PropertyID::FontWeight
  2064. || property_id == PropertyID::Custom;
  2065. };
  2066. if (takes_integer_value(property_id) && component_value.is(Token::Type::Number)) {
  2067. auto number = component_value.token();
  2068. if (number.m_number_type == Token::NumberType::Integer) {
  2069. return LengthStyleValue::create(Length::make_px(number.to_integer()));
  2070. }
  2071. }
  2072. if (auto builtin_or_dynamic = parse_builtin_or_dynamic_value(context, component_value))
  2073. return builtin_or_dynamic;
  2074. if (auto length = parse_length_value(context, component_value))
  2075. return length;
  2076. if (auto numeric = parse_numeric_value(context, component_value))
  2077. return numeric;
  2078. if (auto identifier = parse_identifier_value(context, component_value))
  2079. return identifier;
  2080. if (auto color = parse_color_value(context, component_value))
  2081. return color;
  2082. if (auto string = parse_string_value(context, component_value))
  2083. return string;
  2084. if (auto image = parse_image_value(context, component_value))
  2085. return image;
  2086. return {};
  2087. }
  2088. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  2089. {
  2090. dbgln_if(CSS_PARSER_DEBUG, "Parser::parse_a_n_plus_b_pattern");
  2091. int a = 0;
  2092. int b = 0;
  2093. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2094. if constexpr (CSS_PARSER_DEBUG) {
  2095. dbgln("Invalid An+B value:");
  2096. values.dump_all_tokens();
  2097. }
  2098. return {};
  2099. };
  2100. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2101. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  2102. values.skip_whitespace();
  2103. if (values.has_next_token()) {
  2104. if constexpr (CSS_PARSER_DEBUG) {
  2105. dbgln("Extra tokens at end of An+B value:");
  2106. values.dump_all_tokens();
  2107. }
  2108. return syntax_error();
  2109. } else {
  2110. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  2111. }
  2112. };
  2113. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  2114. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  2115. };
  2116. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  2117. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  2118. };
  2119. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  2120. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  2121. };
  2122. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  2123. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  2124. };
  2125. auto is_delim = [](StyleComponentValueRule const& value, StringView const& delim) -> bool {
  2126. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  2127. };
  2128. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  2129. if (!value.is(Token::Type::Dimension))
  2130. return false;
  2131. if (value.token().number_type() != Token::NumberType::Integer)
  2132. return false;
  2133. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  2134. return false;
  2135. return true;
  2136. };
  2137. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  2138. if (!value.is(Token::Type::Dimension))
  2139. return false;
  2140. if (value.token().number_type() != Token::NumberType::Integer)
  2141. return false;
  2142. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  2143. return false;
  2144. return true;
  2145. };
  2146. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  2147. if (!value.is(Token::Type::Dimension))
  2148. return false;
  2149. if (value.token().number_type() != Token::NumberType::Integer)
  2150. return false;
  2151. auto dimension_unit = value.token().dimension_unit();
  2152. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2153. return false;
  2154. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  2155. if (!is_ascii_digit(dimension_unit[i]))
  2156. return false;
  2157. }
  2158. return true;
  2159. };
  2160. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2161. if (!value.is(Token::Type::Ident))
  2162. return false;
  2163. auto ident = value.token().ident();
  2164. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2165. return false;
  2166. for (size_t i = 2; i < ident.length(); ++i) {
  2167. if (!is_ascii_digit(ident[i]))
  2168. return false;
  2169. }
  2170. return true;
  2171. };
  2172. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2173. if (!value.is(Token::Type::Ident))
  2174. return false;
  2175. auto ident = value.token().ident();
  2176. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  2177. return false;
  2178. for (size_t i = 3; i < ident.length(); ++i) {
  2179. if (!is_ascii_digit(ident[i]))
  2180. return false;
  2181. }
  2182. return true;
  2183. };
  2184. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  2185. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  2186. };
  2187. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2188. return is_integer(value) && value.token().is_integer_value_signed();
  2189. };
  2190. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2191. return is_integer(value) && !value.token().is_integer_value_signed();
  2192. };
  2193. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  2194. // Unfortunately these can't be in the same order as in the spec.
  2195. values.skip_whitespace();
  2196. auto& first_value = values.next_token();
  2197. // odd | even
  2198. if (first_value.is(Token::Type::Ident)) {
  2199. auto ident = first_value.token().ident();
  2200. if (ident.equals_ignoring_case("odd")) {
  2201. a = 2;
  2202. b = 1;
  2203. return make_return_value();
  2204. } else if (ident.equals_ignoring_case("even")) {
  2205. a = 2;
  2206. return make_return_value();
  2207. }
  2208. }
  2209. // <integer>
  2210. if (is_integer(first_value)) {
  2211. b = first_value.token().to_integer();
  2212. return make_return_value();
  2213. }
  2214. // <n-dimension>
  2215. // <n-dimension> <signed-integer>
  2216. // <n-dimension> ['+' | '-'] <signless-integer>
  2217. if (is_n_dimension(first_value)) {
  2218. a = first_value.token().dimension_value_int();
  2219. values.skip_whitespace();
  2220. auto& second_value = values.next_token();
  2221. if (second_value.is(Token::Type::EndOfFile)) {
  2222. // <n-dimension>
  2223. return make_return_value();
  2224. } else if (is_signed_integer(second_value)) {
  2225. // <n-dimension> <signed-integer>
  2226. b = second_value.token().to_integer();
  2227. return make_return_value();
  2228. }
  2229. values.skip_whitespace();
  2230. auto& third_value = values.next_token();
  2231. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2232. // <n-dimension> ['+' | '-'] <signless-integer>
  2233. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2234. return make_return_value();
  2235. }
  2236. return syntax_error();
  2237. }
  2238. // <ndash-dimension> <signless-integer>
  2239. if (is_ndash_dimension(first_value)) {
  2240. values.skip_whitespace();
  2241. auto& second_value = values.next_token();
  2242. if (is_signless_integer(second_value)) {
  2243. a = first_value.token().dimension_value_int();
  2244. b = -second_value.token().to_integer();
  2245. return make_return_value();
  2246. }
  2247. return syntax_error();
  2248. }
  2249. // <ndashdigit-dimension>
  2250. if (is_ndashdigit_dimension(first_value)) {
  2251. auto& dimension = first_value.token();
  2252. a = dimension.dimension_value_int();
  2253. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  2254. if (maybe_b.has_value()) {
  2255. b = maybe_b.value();
  2256. return make_return_value();
  2257. }
  2258. return syntax_error();
  2259. }
  2260. // <dashndashdigit-ident>
  2261. if (is_dashndashdigit_ident(first_value)) {
  2262. a = -1;
  2263. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  2264. if (maybe_b.has_value()) {
  2265. b = maybe_b.value();
  2266. return make_return_value();
  2267. }
  2268. return syntax_error();
  2269. }
  2270. // -n
  2271. // -n <signed-integer>
  2272. // -n ['+' | '-'] <signless-integer>
  2273. if (is_dashn(first_value)) {
  2274. a = -1;
  2275. values.skip_whitespace();
  2276. auto& second_value = values.next_token();
  2277. if (second_value.is(Token::Type::EndOfFile)) {
  2278. // -n
  2279. return make_return_value();
  2280. } else if (is_signed_integer(second_value)) {
  2281. // -n <signed-integer>
  2282. b = second_value.token().to_integer();
  2283. return make_return_value();
  2284. }
  2285. values.skip_whitespace();
  2286. auto& third_value = values.next_token();
  2287. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2288. // -n ['+' | '-'] <signless-integer>
  2289. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2290. return make_return_value();
  2291. }
  2292. return syntax_error();
  2293. }
  2294. // -n- <signless-integer>
  2295. if (is_dashndash(first_value)) {
  2296. values.skip_whitespace();
  2297. auto& second_value = values.next_token();
  2298. if (is_signless_integer(second_value)) {
  2299. a = -1;
  2300. b = -second_value.token().to_integer();
  2301. return make_return_value();
  2302. }
  2303. return syntax_error();
  2304. }
  2305. // All that's left now are these:
  2306. // '+'?† n
  2307. // '+'?† n <signed-integer>
  2308. // '+'?† n ['+' | '-'] <signless-integer>
  2309. // '+'?† n- <signless-integer>
  2310. // '+'?† <ndashdigit-ident>
  2311. // In all of these cases, the + is optional, and has no effect.
  2312. // So, we just skip the +, and carry on.
  2313. if (!is_delim(first_value, "+"sv)) {
  2314. values.reconsume_current_input_token();
  2315. // We do *not* skip whitespace here.
  2316. }
  2317. auto& first_after_plus = values.next_token();
  2318. // '+'?† n
  2319. // '+'?† n <signed-integer>
  2320. // '+'?† n ['+' | '-'] <signless-integer>
  2321. if (is_n(first_after_plus)) {
  2322. a = 1;
  2323. values.skip_whitespace();
  2324. auto& second_value = values.next_token();
  2325. if (second_value.is(Token::Type::EndOfFile)) {
  2326. // '+'?† n
  2327. return make_return_value();
  2328. } else if (is_signed_integer(second_value)) {
  2329. // '+'?† n <signed-integer>
  2330. b = second_value.token().to_integer();
  2331. return make_return_value();
  2332. }
  2333. values.skip_whitespace();
  2334. auto& third_value = values.next_token();
  2335. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2336. // '+'?† n ['+' | '-'] <signless-integer>
  2337. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2338. return make_return_value();
  2339. }
  2340. return syntax_error();
  2341. }
  2342. // '+'?† n- <signless-integer>
  2343. if (is_ndash(first_after_plus)) {
  2344. values.skip_whitespace();
  2345. auto& second_value = values.next_token();
  2346. if (is_signless_integer(second_value)) {
  2347. a = 1;
  2348. b = -second_value.token().to_integer();
  2349. return make_return_value();
  2350. }
  2351. return syntax_error();
  2352. }
  2353. // '+'?† <ndashdigit-ident>
  2354. if (is_ndashdigit_ident(first_after_plus)) {
  2355. a = 1;
  2356. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  2357. if (maybe_b.has_value()) {
  2358. b = maybe_b.value();
  2359. return make_return_value();
  2360. }
  2361. return syntax_error();
  2362. }
  2363. return syntax_error();
  2364. }
  2365. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(ParsingContext const& context, Vector<StyleComponentValueRule> const& values)
  2366. {
  2367. auto tokens = TokenStream(values);
  2368. return parse_calc_sum(context, tokens);
  2369. }
  2370. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2371. {
  2372. auto current_token = tokens.next_token();
  2373. if (current_token.is_block() && current_token.block().is_paren()) {
  2374. auto block_values = TokenStream(current_token.block().values());
  2375. auto parsed_calc_sum = parse_calc_sum(context, block_values);
  2376. if (!parsed_calc_sum)
  2377. return {};
  2378. return (CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() };
  2379. }
  2380. if (current_token.is(Token::Type::Number)) {
  2381. auto try_the_number = try_parse_float(current_token.token().number_string_value());
  2382. if (try_the_number.has_value())
  2383. return (CalculatedStyleValue::CalcValue) { try_the_number.value() };
  2384. return {};
  2385. }
  2386. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  2387. auto maybe_length = parse_length(context, current_token);
  2388. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  2389. return (CalculatedStyleValue::CalcValue) { maybe_length.value() };
  2390. return {};
  2391. }
  2392. return {};
  2393. }
  2394. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2395. {
  2396. // Note: The default value is not used or passed around.
  2397. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  2398. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  2399. CalculatedStyleValue::CalcNumberValue(0));
  2400. tokens.skip_whitespace();
  2401. auto& op_token = tokens.peek_token();
  2402. if (!op_token.is(Token::Type::Delim))
  2403. return nullptr;
  2404. auto op = op_token.token().delim();
  2405. if (op == "*"sv) {
  2406. tokens.next_token();
  2407. tokens.skip_whitespace();
  2408. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  2409. auto parsed_calc_value = parse_calc_value(context, tokens);
  2410. if (!parsed_calc_value.has_value())
  2411. return nullptr;
  2412. product_with_operator->value = { parsed_calc_value.release_value() };
  2413. } else if (op == "/"sv) {
  2414. tokens.next_token();
  2415. tokens.skip_whitespace();
  2416. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  2417. auto parsed_calc_number_value = parse_calc_number_value(context, tokens);
  2418. if (!parsed_calc_number_value.has_value())
  2419. return nullptr;
  2420. product_with_operator->value = { parsed_calc_number_value.release_value() };
  2421. } else {
  2422. return nullptr;
  2423. }
  2424. return product_with_operator;
  2425. }
  2426. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2427. {
  2428. // Note: The default value is not used or passed around.
  2429. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  2430. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  2431. CalculatedStyleValue::CalcNumberValue(0));
  2432. tokens.skip_whitespace();
  2433. auto& op_token = tokens.peek_token();
  2434. if (!op_token.is(Token::Type::Delim))
  2435. return nullptr;
  2436. auto op = op_token.token().delim();
  2437. if (op == "*"sv) {
  2438. tokens.next_token();
  2439. tokens.skip_whitespace();
  2440. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  2441. } else if (op == "/"sv) {
  2442. tokens.next_token();
  2443. tokens.skip_whitespace();
  2444. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  2445. } else {
  2446. return nullptr;
  2447. }
  2448. auto parsed_calc_value = parse_calc_number_value(context, tokens);
  2449. if (!parsed_calc_value.has_value())
  2450. return nullptr;
  2451. number_product_with_operator->value = parsed_calc_value.release_value();
  2452. return number_product_with_operator;
  2453. }
  2454. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2455. {
  2456. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  2457. CalculatedStyleValue::CalcNumberValue(0),
  2458. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  2459. auto first_calc_number_value_or_error = parse_calc_number_value(context, tokens);
  2460. if (!first_calc_number_value_or_error.has_value())
  2461. return nullptr;
  2462. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  2463. while (tokens.has_next_token()) {
  2464. auto number_product_with_operator = parse_calc_number_product_part_with_operator(context, tokens);
  2465. if (!number_product_with_operator)
  2466. break;
  2467. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  2468. }
  2469. return calc_number_product;
  2470. }
  2471. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2472. {
  2473. if (!(tokens.peek_token().is(Token::Type::Delim)
  2474. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2475. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2476. return nullptr;
  2477. auto& token = tokens.next_token();
  2478. tokens.skip_whitespace();
  2479. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  2480. auto delim = token.token().delim();
  2481. if (delim == "+"sv)
  2482. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  2483. else if (delim == "-"sv)
  2484. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  2485. else
  2486. return nullptr;
  2487. auto calc_number_product = parse_calc_number_product(context, tokens);
  2488. if (!calc_number_product)
  2489. return nullptr;
  2490. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  2491. }
  2492. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2493. {
  2494. auto first_calc_number_product_or_error = parse_calc_number_product(context, tokens);
  2495. if (!first_calc_number_product_or_error)
  2496. return nullptr;
  2497. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  2498. while (tokens.has_next_token()) {
  2499. auto calc_sum_part = parse_calc_number_sum_part_with_operator(context, tokens);
  2500. if (!calc_sum_part)
  2501. return nullptr;
  2502. additional.append(calc_sum_part.release_nonnull());
  2503. }
  2504. tokens.skip_whitespace();
  2505. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  2506. return calc_number_sum;
  2507. }
  2508. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2509. {
  2510. auto& first = tokens.peek_token();
  2511. if (first.is_block() && first.block().is_paren()) {
  2512. tokens.next_token();
  2513. auto block_values = TokenStream(first.block().values());
  2514. auto calc_number_sum = parse_calc_number_sum(context, block_values);
  2515. if (calc_number_sum)
  2516. return { calc_number_sum.release_nonnull() };
  2517. }
  2518. if (!first.is(Token::Type::Number))
  2519. return {};
  2520. tokens.next_token();
  2521. auto try_the_number = try_parse_float(first.token().number_string_value());
  2522. if (!try_the_number.has_value())
  2523. return {};
  2524. return try_the_number.value();
  2525. }
  2526. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2527. {
  2528. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  2529. CalculatedStyleValue::CalcValue(0),
  2530. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  2531. auto first_calc_value_or_error = parse_calc_value(context, tokens);
  2532. if (!first_calc_value_or_error.has_value())
  2533. return nullptr;
  2534. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  2535. while (tokens.has_next_token()) {
  2536. auto product_with_operator = parse_calc_product_part_with_operator(context, tokens);
  2537. if (!product_with_operator)
  2538. break;
  2539. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  2540. }
  2541. return calc_product;
  2542. }
  2543. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2544. {
  2545. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  2546. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  2547. if (!(tokens.peek_token().is(Token::Type::Delim)
  2548. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2549. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2550. return nullptr;
  2551. auto& token = tokens.next_token();
  2552. tokens.skip_whitespace();
  2553. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  2554. auto delim = token.token().delim();
  2555. if (delim == "+"sv)
  2556. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  2557. else if (delim == "-"sv)
  2558. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  2559. else
  2560. return nullptr;
  2561. auto calc_product = parse_calc_product(context, tokens);
  2562. if (!calc_product)
  2563. return nullptr;
  2564. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  2565. };
  2566. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2567. {
  2568. auto parsed_calc_product = parse_calc_product(context, tokens);
  2569. if (!parsed_calc_product)
  2570. return nullptr;
  2571. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  2572. while (tokens.has_next_token()) {
  2573. auto calc_sum_part = parse_calc_sum_part_with_operator(context, tokens);
  2574. if (!calc_sum_part)
  2575. return nullptr;
  2576. additional.append(calc_sum_part.release_nonnull());
  2577. }
  2578. tokens.skip_whitespace();
  2579. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  2580. }
  2581. }
  2582. namespace Web {
  2583. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView const& css)
  2584. {
  2585. if (css.is_empty())
  2586. return CSS::CSSStyleSheet::create({});
  2587. CSS::Parser parser(context, css);
  2588. return parser.parse_as_stylesheet();
  2589. }
  2590. RefPtr<CSS::CSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView const& css)
  2591. {
  2592. if (css.is_empty())
  2593. return CSS::CSSStyleDeclaration::create({}, {});
  2594. CSS::Parser parser(context, css);
  2595. return parser.parse_as_list_of_declarations();
  2596. }
  2597. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView const& string, CSS::PropertyID property_id)
  2598. {
  2599. if (string.is_empty())
  2600. return {};
  2601. CSS::Parser parser(context, string);
  2602. return parser.parse_as_css_value(property_id);
  2603. }
  2604. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView const& selector_text)
  2605. {
  2606. CSS::Parser parser(context, selector_text);
  2607. return parser.parse_as_selector();
  2608. }
  2609. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView const& string)
  2610. {
  2611. auto integer = string.to_int();
  2612. if (integer.has_value())
  2613. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  2614. // FIXME: The const_cast is a hack.
  2615. return parse_css_value(CSS::ParsingContext(const_cast<DOM::Document&>(document)), string);
  2616. }
  2617. }