Parser.cpp 126 KB

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