Parser.cpp 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290
  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/CSSImportRule.h>
  14. #include <LibWeb/CSS/CSSMediaRule.h>
  15. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  16. #include <LibWeb/CSS/CSSStyleRule.h>
  17. #include <LibWeb/CSS/CSSStyleSheet.h>
  18. #include <LibWeb/CSS/CSSSupportsRule.h>
  19. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  20. #include <LibWeb/CSS/Parser/Parser.h>
  21. #include <LibWeb/CSS/Parser/StyleBlockRule.h>
  22. #include <LibWeb/CSS/Parser/StyleComponentValueRule.h>
  23. #include <LibWeb/CSS/Parser/StyleFunctionRule.h>
  24. #include <LibWeb/CSS/Parser/StyleRule.h>
  25. #include <LibWeb/CSS/Selector.h>
  26. #include <LibWeb/DOM/Document.h>
  27. #include <LibWeb/Dump.h>
  28. static void log_parse_error(const SourceLocation& location = SourceLocation::current())
  29. {
  30. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  31. }
  32. namespace Web::CSS {
  33. ParsingContext::ParsingContext(DOM::Document const& document)
  34. : m_document(&document)
  35. {
  36. }
  37. ParsingContext::ParsingContext(DOM::ParentNode& parent_node)
  38. : m_document(&parent_node.document())
  39. {
  40. }
  41. bool ParsingContext::in_quirks_mode() const
  42. {
  43. return m_document ? m_document->in_quirks_mode() : false;
  44. }
  45. AK::URL ParsingContext::complete_url(String const& addr) const
  46. {
  47. return m_document ? m_document->url().complete_url(addr) : AK::URL::create_with_url_or_path(addr);
  48. }
  49. template<typename T>
  50. TokenStream<T>::TokenStream(Vector<T> const& tokens)
  51. : m_tokens(tokens)
  52. , m_eof(make_eof())
  53. {
  54. }
  55. template<typename T>
  56. TokenStream<T>::~TokenStream()
  57. {
  58. }
  59. template<typename T>
  60. bool TokenStream<T>::has_next_token()
  61. {
  62. return (size_t)(m_iterator_offset + 1) < m_tokens.size();
  63. }
  64. template<typename T>
  65. T const& TokenStream<T>::peek_token(int offset)
  66. {
  67. if (!has_next_token())
  68. return m_eof;
  69. return m_tokens.at(m_iterator_offset + offset + 1);
  70. }
  71. template<typename T>
  72. T const& TokenStream<T>::next_token()
  73. {
  74. if (!has_next_token())
  75. return m_eof;
  76. ++m_iterator_offset;
  77. return m_tokens.at(m_iterator_offset);
  78. }
  79. template<typename T>
  80. T const& TokenStream<T>::current_token()
  81. {
  82. if ((size_t)m_iterator_offset >= m_tokens.size())
  83. return m_eof;
  84. return m_tokens.at(m_iterator_offset);
  85. }
  86. template<typename T>
  87. void TokenStream<T>::reconsume_current_input_token()
  88. {
  89. if (m_iterator_offset >= 0)
  90. --m_iterator_offset;
  91. }
  92. template<typename T>
  93. void TokenStream<T>::rewind_to_position(int position)
  94. {
  95. VERIFY(position <= m_iterator_offset);
  96. m_iterator_offset = position;
  97. }
  98. template<typename T>
  99. void TokenStream<T>::skip_whitespace()
  100. {
  101. while (peek_token().is(Token::Type::Whitespace))
  102. next_token();
  103. }
  104. template<>
  105. Token TokenStream<Token>::make_eof()
  106. {
  107. return Tokenizer::create_eof_token();
  108. }
  109. template<>
  110. StyleComponentValueRule TokenStream<StyleComponentValueRule>::make_eof()
  111. {
  112. return StyleComponentValueRule(Tokenizer::create_eof_token());
  113. }
  114. template<typename T>
  115. void TokenStream<T>::dump_all_tokens()
  116. {
  117. dbgln("Dumping all tokens:");
  118. for (size_t i = 0; i < m_tokens.size(); ++i) {
  119. auto& token = m_tokens[i];
  120. if ((i - 1) == (size_t)m_iterator_offset)
  121. dbgln("-> {}", token.to_debug_string());
  122. else
  123. dbgln(" {}", token.to_debug_string());
  124. }
  125. }
  126. Parser::Parser(ParsingContext const& context, StringView input, String const& encoding)
  127. : m_context(context)
  128. , m_tokenizer(input, encoding)
  129. , m_tokens(m_tokenizer.parse())
  130. , m_token_stream(TokenStream(m_tokens))
  131. {
  132. }
  133. Parser::~Parser()
  134. {
  135. }
  136. NonnullRefPtr<CSSStyleSheet> Parser::parse_as_stylesheet()
  137. {
  138. return parse_a_stylesheet(m_token_stream);
  139. }
  140. template<typename T>
  141. NonnullRefPtr<CSSStyleSheet> Parser::parse_a_stylesheet(TokenStream<T>& tokens)
  142. {
  143. auto parser_rules = consume_a_list_of_rules(tokens, true);
  144. NonnullRefPtrVector<CSSRule> rules;
  145. for (auto& raw_rule : parser_rules) {
  146. auto rule = convert_to_rule(raw_rule);
  147. if (rule)
  148. rules.append(*rule);
  149. }
  150. auto stylesheet = CSSStyleSheet::create(rules);
  151. if constexpr (CSS_PARSER_DEBUG) {
  152. dump_sheet(stylesheet);
  153. }
  154. return stylesheet;
  155. }
  156. Optional<SelectorList> Parser::parse_as_selector()
  157. {
  158. auto selector_list = parse_a_selector(m_token_stream);
  159. if (!selector_list.is_error())
  160. return selector_list.release_value();
  161. return {};
  162. }
  163. template<typename T>
  164. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector(TokenStream<T>& tokens)
  165. {
  166. return parse_a_selector_list(tokens);
  167. }
  168. Optional<SelectorList> Parser::parse_as_relative_selector()
  169. {
  170. auto selector_list = parse_a_relative_selector(m_token_stream);
  171. if (!selector_list.is_error())
  172. return selector_list.release_value();
  173. return {};
  174. }
  175. template<typename T>
  176. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector(TokenStream<T>& tokens)
  177. {
  178. return parse_a_relative_selector_list(tokens);
  179. }
  180. template<typename T>
  181. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector_list(TokenStream<T>& tokens)
  182. {
  183. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  184. NonnullRefPtrVector<Selector> selectors;
  185. for (auto& selector_parts : comma_separated_lists) {
  186. auto stream = TokenStream(selector_parts);
  187. auto selector = parse_complex_selector(stream, false);
  188. if (selector.is_error())
  189. return selector.error();
  190. selectors.append(selector.release_value());
  191. }
  192. if (selectors.is_empty())
  193. return ParsingResult::SyntaxError;
  194. return selectors;
  195. }
  196. template<typename T>
  197. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector_list(TokenStream<T>& tokens)
  198. {
  199. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  200. NonnullRefPtrVector<Selector> selectors;
  201. for (auto& selector_parts : comma_separated_lists) {
  202. auto stream = TokenStream(selector_parts);
  203. auto selector = parse_complex_selector(stream, true);
  204. if (selector.is_error())
  205. return selector.error();
  206. selectors.append(selector.release_value());
  207. }
  208. if (selectors.is_empty())
  209. return ParsingResult::SyntaxError;
  210. return selectors;
  211. }
  212. Result<NonnullRefPtr<Selector>, Parser::ParsingResult> Parser::parse_complex_selector(TokenStream<StyleComponentValueRule>& tokens, bool allow_starting_combinator)
  213. {
  214. Vector<Selector::CompoundSelector> compound_selectors;
  215. auto first_selector = parse_compound_selector(tokens);
  216. if (first_selector.is_error())
  217. return first_selector.error();
  218. if (!allow_starting_combinator) {
  219. if (first_selector.value().combinator != Selector::Combinator::Descendant)
  220. return ParsingResult::SyntaxError;
  221. first_selector.value().combinator = Selector::Combinator::None;
  222. }
  223. compound_selectors.append(first_selector.value());
  224. while (tokens.has_next_token()) {
  225. auto compound_selector = parse_compound_selector(tokens);
  226. if (compound_selector.is_error()) {
  227. if (compound_selector.error() == ParsingResult::Done)
  228. break;
  229. else
  230. return compound_selector.error();
  231. }
  232. compound_selectors.append(compound_selector.value());
  233. }
  234. if (compound_selectors.is_empty())
  235. return ParsingResult::SyntaxError;
  236. return Selector::create(move(compound_selectors));
  237. }
  238. Result<Selector::CompoundSelector, Parser::ParsingResult> Parser::parse_compound_selector(TokenStream<StyleComponentValueRule>& tokens)
  239. {
  240. tokens.skip_whitespace();
  241. auto combinator = parse_selector_combinator(tokens).value_or(Selector::Combinator::Descendant);
  242. tokens.skip_whitespace();
  243. Vector<Selector::SimpleSelector> simple_selectors;
  244. while (tokens.has_next_token()) {
  245. auto component = parse_simple_selector(tokens);
  246. if (component.is_error()) {
  247. if (component.error() == ParsingResult::Done)
  248. break;
  249. else
  250. return component.error();
  251. }
  252. simple_selectors.append(component.value());
  253. }
  254. if (simple_selectors.is_empty())
  255. return ParsingResult::Done;
  256. return Selector::CompoundSelector { combinator, move(simple_selectors) };
  257. }
  258. Optional<Selector::Combinator> Parser::parse_selector_combinator(TokenStream<StyleComponentValueRule>& tokens)
  259. {
  260. auto& current_value = tokens.next_token();
  261. if (current_value.is(Token::Type::Delim)) {
  262. auto delim = current_value.token().delim();
  263. if (delim == ">"sv) {
  264. return Selector::Combinator::ImmediateChild;
  265. } else if (delim == "+"sv) {
  266. return Selector::Combinator::NextSibling;
  267. } else if (delim == "~"sv) {
  268. return Selector::Combinator::SubsequentSibling;
  269. } else if (delim == "|"sv) {
  270. auto& next = tokens.peek_token();
  271. if (next.is(Token::Type::EndOfFile))
  272. return {};
  273. if (next.is(Token::Type::Delim) && next.token().delim() == "|"sv) {
  274. tokens.next_token();
  275. return Selector::Combinator::Column;
  276. }
  277. }
  278. }
  279. tokens.reconsume_current_input_token();
  280. return {};
  281. }
  282. Result<Selector::SimpleSelector, Parser::ParsingResult> Parser::parse_simple_selector(TokenStream<StyleComponentValueRule>& tokens)
  283. {
  284. auto peek_token_ends_selector = [&]() -> bool {
  285. auto& value = tokens.peek_token();
  286. return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
  287. };
  288. if (peek_token_ends_selector())
  289. return ParsingResult::Done;
  290. auto& first_value = tokens.next_token();
  291. if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "*"sv) {
  292. return Selector::SimpleSelector {
  293. .type = Selector::SimpleSelector::Type::Universal
  294. };
  295. } else if (first_value.is(Token::Type::Hash)) {
  296. if (first_value.token().hash_type() != Token::HashType::Id) {
  297. dbgln_if(CSS_PARSER_DEBUG, "Selector contains hash token that is not an id: {}", first_value.to_debug_string());
  298. return ParsingResult::SyntaxError;
  299. }
  300. return Selector::SimpleSelector {
  301. .type = Selector::SimpleSelector::Type::Id,
  302. .value = first_value.token().hash_value()
  303. };
  304. } else if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "."sv) {
  305. if (peek_token_ends_selector())
  306. return ParsingResult::SyntaxError;
  307. auto& class_name_value = tokens.next_token();
  308. if (!class_name_value.is(Token::Type::Ident)) {
  309. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident after '.', got: {}", class_name_value.to_debug_string());
  310. return ParsingResult::SyntaxError;
  311. }
  312. return Selector::SimpleSelector {
  313. .type = Selector::SimpleSelector::Type::Class,
  314. .value = class_name_value.token().ident()
  315. };
  316. } else if (first_value.is(Token::Type::Ident)) {
  317. return Selector::SimpleSelector {
  318. .type = Selector::SimpleSelector::Type::TagName,
  319. .value = first_value.token().ident()
  320. };
  321. } else if (first_value.is_block() && first_value.block().is_square()) {
  322. auto attribute_tokens = TokenStream { first_value.block().values() };
  323. attribute_tokens.skip_whitespace();
  324. if (!attribute_tokens.has_next_token()) {
  325. dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
  326. return ParsingResult::SyntaxError;
  327. }
  328. // FIXME: Handle namespace prefix for attribute name.
  329. auto& attribute_part = attribute_tokens.next_token();
  330. if (!attribute_part.is(Token::Type::Ident)) {
  331. dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  332. return ParsingResult::SyntaxError;
  333. }
  334. Selector::SimpleSelector simple_selector {
  335. .type = Selector::SimpleSelector::Type::Attribute,
  336. .attribute = {
  337. .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
  338. // FIXME: Case-sensitivity is defined by the document language.
  339. // HTML is insensitive with attribute names, and our code generally assumes
  340. // they are converted to lowercase, so we do that here too. If we want to be
  341. // correct with XML later, we'll need to keep the original case and then do
  342. // a case-insensitive compare later.
  343. .name = attribute_part.token().ident().to_lowercase_string(),
  344. }
  345. };
  346. attribute_tokens.skip_whitespace();
  347. if (!attribute_tokens.has_next_token())
  348. return simple_selector;
  349. auto& delim_part = attribute_tokens.next_token();
  350. if (!delim_part.is(Token::Type::Delim)) {
  351. dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  352. return ParsingResult::SyntaxError;
  353. }
  354. if (delim_part.token().delim() == "="sv) {
  355. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
  356. } else {
  357. if (!attribute_tokens.has_next_token()) {
  358. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
  359. return ParsingResult::SyntaxError;
  360. }
  361. auto& delim_second_part = attribute_tokens.next_token();
  362. if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == "=")) {
  363. dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  364. return ParsingResult::SyntaxError;
  365. }
  366. if (delim_part.token().delim() == "~"sv) {
  367. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
  368. } else if (delim_part.token().delim() == "*"sv) {
  369. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
  370. } else if (delim_part.token().delim() == "|"sv) {
  371. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
  372. } else if (delim_part.token().delim() == "^"sv) {
  373. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
  374. } else if (delim_part.token().delim() == "$"sv) {
  375. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
  376. } else {
  377. attribute_tokens.reconsume_current_input_token();
  378. }
  379. }
  380. attribute_tokens.skip_whitespace();
  381. if (!attribute_tokens.has_next_token()) {
  382. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
  383. return ParsingResult::SyntaxError;
  384. }
  385. auto& value_part = attribute_tokens.next_token();
  386. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  387. dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  388. return ParsingResult::SyntaxError;
  389. }
  390. simple_selector.attribute.value = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  391. attribute_tokens.skip_whitespace();
  392. // FIXME: Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  393. return simple_selector;
  394. } else if (first_value.is(Token::Type::Colon)) {
  395. if (peek_token_ends_selector())
  396. return ParsingResult::SyntaxError;
  397. bool is_pseudo = false;
  398. if (tokens.peek_token().is(Token::Type::Colon)) {
  399. is_pseudo = true;
  400. tokens.next_token();
  401. if (peek_token_ends_selector())
  402. return ParsingResult::SyntaxError;
  403. }
  404. if (is_pseudo) {
  405. Selector::SimpleSelector simple_selector {
  406. .type = Selector::SimpleSelector::Type::PseudoElement
  407. };
  408. auto& name_token = tokens.next_token();
  409. if (!name_token.is(Token::Type::Ident)) {
  410. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
  411. return ParsingResult::SyntaxError;
  412. }
  413. auto pseudo_name = name_token.token().ident();
  414. if (has_ignored_vendor_prefix(pseudo_name))
  415. return ParsingResult::IncludesIgnoredVendorPrefix;
  416. if (pseudo_name.equals_ignoring_case("after")) {
  417. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  418. } else if (pseudo_name.equals_ignoring_case("before")) {
  419. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  420. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  421. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  422. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  423. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  424. } else {
  425. dbgln("Unrecognized pseudo-element: '::{}'", pseudo_name);
  426. return ParsingResult::SyntaxError;
  427. }
  428. return simple_selector;
  429. }
  430. if (peek_token_ends_selector())
  431. return ParsingResult::SyntaxError;
  432. auto& pseudo_class_token = tokens.next_token();
  433. Selector::SimpleSelector simple_selector {
  434. .type = Selector::SimpleSelector::Type::PseudoClass
  435. };
  436. if (pseudo_class_token.is(Token::Type::Ident)) {
  437. auto pseudo_name = pseudo_class_token.token().ident();
  438. if (has_ignored_vendor_prefix(pseudo_name))
  439. return ParsingResult::IncludesIgnoredVendorPrefix;
  440. if (pseudo_name.equals_ignoring_case("active")) {
  441. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Active;
  442. } else if (pseudo_name.equals_ignoring_case("checked")) {
  443. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Checked;
  444. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  445. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Disabled;
  446. } else if (pseudo_name.equals_ignoring_case("empty")) {
  447. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Empty;
  448. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  449. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Enabled;
  450. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  451. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstChild;
  452. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  453. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstOfType;
  454. } else if (pseudo_name.equals_ignoring_case("focus")) {
  455. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Focus;
  456. } else if (pseudo_name.equals_ignoring_case("hover")) {
  457. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Hover;
  458. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  459. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastChild;
  460. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  461. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastOfType;
  462. } else if (pseudo_name.equals_ignoring_case("link")) {
  463. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Link;
  464. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  465. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::OnlyChild;
  466. } else if (pseudo_name.equals_ignoring_case("root")) {
  467. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Root;
  468. } else if (pseudo_name.equals_ignoring_case("visited")) {
  469. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Visited;
  470. } else if (pseudo_name.equals_ignoring_case("after")) {
  471. // Single-colon syntax allowed for compatibility. https://www.w3.org/TR/selectors/#pseudo-element-syntax
  472. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  473. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  474. } else if (pseudo_name.equals_ignoring_case("before")) {
  475. // See :after
  476. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  477. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  478. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  479. // See :after
  480. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  481. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  482. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  483. // See :after
  484. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  485. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  486. } else {
  487. dbgln("Unrecognized pseudo-class: ':{}'", pseudo_name);
  488. return ParsingResult::SyntaxError;
  489. }
  490. return simple_selector;
  491. } else if (pseudo_class_token.is_function()) {
  492. auto& pseudo_function = pseudo_class_token.function();
  493. if (pseudo_function.name().equals_ignoring_case("not")) {
  494. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Not;
  495. auto function_token_stream = TokenStream(pseudo_function.values());
  496. auto not_selector = parse_a_selector(function_token_stream);
  497. if (not_selector.is_error()) {
  498. dbgln_if(CSS_PARSER_DEBUG, "Invalid selector in :not() clause");
  499. return ParsingResult::SyntaxError;
  500. }
  501. simple_selector.pseudo_class.not_selector = not_selector.release_value();
  502. } else if (pseudo_function.name().equals_ignoring_case("nth-child")) {
  503. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthChild;
  504. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  505. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  506. if (nth_child_pattern.has_value()) {
  507. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  508. } else {
  509. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  510. return ParsingResult::SyntaxError;
  511. }
  512. } else if (pseudo_function.name().equals_ignoring_case("nth-last-child")) {
  513. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthLastChild;
  514. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  515. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  516. if (nth_child_pattern.has_value()) {
  517. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  518. } else {
  519. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  520. return ParsingResult::SyntaxError;
  521. }
  522. } else {
  523. dbgln("Unrecognized pseudo-class function: ':{}'()", pseudo_function.name());
  524. return ParsingResult::SyntaxError;
  525. }
  526. return simple_selector;
  527. } else {
  528. dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
  529. return ParsingResult::SyntaxError;
  530. }
  531. }
  532. // Whitespace is not required between the compound-selector and a combinator.
  533. // So, if we see a combinator, return that this compound-selector is done, instead of a syntax error.
  534. if (first_value.is(Token::Type::Delim)) {
  535. auto delim = first_value.token().delim();
  536. if ((delim == ">"sv) || (delim == "+"sv) || (delim == "~"sv) || (delim == "|"sv)) {
  537. tokens.reconsume_current_input_token();
  538. return ParsingResult::Done;
  539. }
  540. }
  541. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  542. return ParsingResult::SyntaxError;
  543. }
  544. NonnullRefPtrVector<MediaQuery> Parser::parse_as_media_query_list()
  545. {
  546. return parse_a_media_query_list(m_token_stream);
  547. }
  548. template<typename T>
  549. NonnullRefPtrVector<MediaQuery> Parser::parse_a_media_query_list(TokenStream<T>& tokens)
  550. {
  551. // https://www.w3.org/TR/mediaqueries-4/#mq-list
  552. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  553. AK::NonnullRefPtrVector<MediaQuery> media_queries;
  554. for (auto& media_query_parts : comma_separated_lists) {
  555. auto stream = TokenStream(media_query_parts);
  556. media_queries.append(parse_media_query(stream));
  557. }
  558. return media_queries;
  559. }
  560. RefPtr<MediaQuery> Parser::parse_as_media_query()
  561. {
  562. // https://www.w3.org/TR/cssom-1/#parse-a-media-query
  563. auto media_query_list = parse_as_media_query_list();
  564. if (media_query_list.is_empty())
  565. return MediaQuery::create_not_all();
  566. if (media_query_list.size() == 1)
  567. return media_query_list.first();
  568. return nullptr;
  569. }
  570. NonnullRefPtr<MediaQuery> Parser::parse_media_query(TokenStream<StyleComponentValueRule>& tokens)
  571. {
  572. // Returns whether to negate the query
  573. auto consume_initial_modifier = [](auto& tokens) -> Optional<bool> {
  574. auto& token = tokens.next_token();
  575. if (!token.is(Token::Type::Ident)) {
  576. tokens.reconsume_current_input_token();
  577. return {};
  578. }
  579. auto ident = token.token().ident();
  580. if (ident.equals_ignoring_case("not")) {
  581. return true;
  582. } else if (ident.equals_ignoring_case("only")) {
  583. return false;
  584. }
  585. tokens.reconsume_current_input_token();
  586. return {};
  587. };
  588. auto invalid_media_query = [&]() {
  589. // "A media query that does not match the grammar in the previous section must be replaced by `not all`
  590. // during parsing." - https://www.w3.org/TR/mediaqueries-5/#error-handling
  591. if constexpr (CSS_PARSER_DEBUG) {
  592. dbgln("Invalid media query:");
  593. tokens.dump_all_tokens();
  594. }
  595. return MediaQuery::create_not_all();
  596. };
  597. auto media_query = MediaQuery::create();
  598. tokens.skip_whitespace();
  599. // Only `<media-condition>`
  600. if (auto media_condition = consume_media_condition(tokens)) {
  601. tokens.skip_whitespace();
  602. if (tokens.has_next_token())
  603. return invalid_media_query();
  604. media_query->m_media_condition = move(media_condition);
  605. return media_query;
  606. }
  607. // Optional `"only" | "not"`
  608. if (auto modifier = consume_initial_modifier(tokens); modifier.has_value()) {
  609. media_query->m_negated = modifier.value();
  610. tokens.skip_whitespace();
  611. }
  612. // `<media-type>`
  613. if (auto media_type = consume_media_type(tokens); media_type.has_value()) {
  614. media_query->m_media_type = media_type.value();
  615. tokens.skip_whitespace();
  616. } else {
  617. return invalid_media_query();
  618. }
  619. if (!tokens.has_next_token())
  620. return media_query;
  621. // Optional "and <media-condition>"
  622. if (auto maybe_and = tokens.next_token(); maybe_and.is(Token::Type::Ident) && maybe_and.token().ident().equals_ignoring_case("and")) {
  623. if (auto media_condition = consume_media_condition(tokens)) {
  624. tokens.skip_whitespace();
  625. if (tokens.has_next_token())
  626. return invalid_media_query();
  627. media_query->m_media_condition = move(media_condition);
  628. return media_query;
  629. }
  630. return invalid_media_query();
  631. }
  632. return invalid_media_query();
  633. }
  634. OwnPtr<MediaQuery::MediaCondition> Parser::consume_media_condition(TokenStream<StyleComponentValueRule>& tokens)
  635. {
  636. // "not <media-condition>"
  637. // ( `<media-not>` in the grammar )
  638. auto position = tokens.position();
  639. auto& first_token = tokens.peek_token();
  640. if (first_token.is(Token::Type::Ident) && first_token.token().ident().equals_ignoring_case("not"sv)) {
  641. tokens.next_token();
  642. auto condition = new MediaQuery::MediaCondition;
  643. condition->type = MediaQuery::MediaCondition::Type::Not;
  644. if (auto child_condition = consume_media_condition(tokens)) {
  645. condition->conditions.append(child_condition.release_nonnull());
  646. return adopt_own(*condition);
  647. }
  648. tokens.rewind_to_position(position);
  649. return {};
  650. }
  651. // "<media-condition> ([and | or] <media-condition>)*"
  652. // ( `<media-in-parens> [ <media-and>* | <media-or>* ]` in the grammar )
  653. NonnullOwnPtrVector<MediaQuery::MediaCondition> child_conditions;
  654. Optional<MediaQuery::MediaCondition::Type> condition_type {};
  655. auto as_condition_type = [](auto& token) -> Optional<MediaQuery::MediaCondition::Type> {
  656. if (!token.is(Token::Type::Ident))
  657. return {};
  658. auto ident = token.token().ident();
  659. if (ident.equals_ignoring_case("and"))
  660. return MediaQuery::MediaCondition::Type::And;
  661. if (ident.equals_ignoring_case("or"))
  662. return MediaQuery::MediaCondition::Type::Or;
  663. return {};
  664. };
  665. bool is_invalid = false;
  666. tokens.skip_whitespace();
  667. while (tokens.has_next_token()) {
  668. if (!child_conditions.is_empty()) {
  669. // Expect an "and" or "or" here
  670. auto maybe_combination = as_condition_type(tokens.next_token());
  671. if (!maybe_combination.has_value()) {
  672. is_invalid = true;
  673. break;
  674. }
  675. if (!condition_type.has_value()) {
  676. condition_type = maybe_combination.value();
  677. } else if (maybe_combination != condition_type) {
  678. is_invalid = true;
  679. break;
  680. }
  681. }
  682. tokens.skip_whitespace();
  683. if (auto child_feature = consume_media_feature(tokens); child_feature.has_value()) {
  684. auto child = new MediaQuery::MediaCondition;
  685. child->type = MediaQuery::MediaCondition::Type::Single;
  686. child->feature = child_feature.value();
  687. child_conditions.append(adopt_own(*child));
  688. } else {
  689. auto& token = tokens.next_token();
  690. if (!token.is_block() || !token.block().is_paren()) {
  691. is_invalid = true;
  692. break;
  693. }
  694. auto block_tokens = TokenStream { token.block().values() };
  695. if (auto child = consume_media_condition(block_tokens)) {
  696. child_conditions.append(child.release_nonnull());
  697. } else {
  698. is_invalid = true;
  699. break;
  700. }
  701. }
  702. tokens.skip_whitespace();
  703. }
  704. if (!is_invalid && !child_conditions.is_empty()) {
  705. if (child_conditions.size() == 1)
  706. return move(child_conditions.ptr_at(0));
  707. auto condition = new MediaQuery::MediaCondition;
  708. condition->type = condition_type.value();
  709. condition->conditions = move(child_conditions);
  710. return adopt_own(*condition);
  711. }
  712. // `<media-feature>`
  713. tokens.rewind_to_position(position);
  714. if (auto feature = consume_media_feature(tokens); feature.has_value()) {
  715. auto condition = new MediaQuery::MediaCondition;
  716. condition->type = MediaQuery::MediaCondition::Type::Single;
  717. condition->feature = feature.value();
  718. return adopt_own(*condition);
  719. }
  720. // `<general-enclosed>`
  721. tokens.rewind_to_position(position);
  722. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  723. auto condition = new MediaQuery::MediaCondition;
  724. condition->type = MediaQuery::MediaCondition::Type::GeneralEnclosed;
  725. condition->general_enclosed = general_enclosed.release_value();
  726. return adopt_own(*condition);
  727. }
  728. tokens.rewind_to_position(position);
  729. return {};
  730. }
  731. Optional<MediaQuery::MediaFeature> Parser::consume_media_feature(TokenStream<StyleComponentValueRule>& outer_tokens)
  732. {
  733. outer_tokens.skip_whitespace();
  734. auto invalid_feature = [&]() -> Optional<MediaQuery::MediaFeature> {
  735. outer_tokens.reconsume_current_input_token();
  736. return {};
  737. };
  738. auto& block_token = outer_tokens.next_token();
  739. if (block_token.is_block() && block_token.block().is_paren()) {
  740. TokenStream tokens { block_token.block().values() };
  741. tokens.skip_whitespace();
  742. auto& name_token = tokens.next_token();
  743. // FIXME: Range syntax allows a value to come before the name
  744. // https://www.w3.org/TR/mediaqueries-4/#mq-range-context
  745. if (!name_token.is(Token::Type::Ident))
  746. return invalid_feature();
  747. auto feature_name = name_token.token().ident();
  748. tokens.skip_whitespace();
  749. if (!tokens.has_next_token()) {
  750. return MediaQuery::MediaFeature {
  751. .type = MediaQuery::MediaFeature::Type::IsTrue,
  752. .name = feature_name,
  753. };
  754. }
  755. if (!tokens.next_token().is(Token::Type::Colon))
  756. return invalid_feature();
  757. tokens.skip_whitespace();
  758. auto value = parse_media_feature_value(tokens);
  759. if (!value.has_value())
  760. return invalid_feature();
  761. if (tokens.has_next_token())
  762. return invalid_feature();
  763. if (feature_name.starts_with("min-", CaseSensitivity::CaseInsensitive)) {
  764. return MediaQuery::MediaFeature {
  765. .type = MediaQuery::MediaFeature::Type::MinValue,
  766. .name = feature_name.substring_view(4),
  767. .value = value.release_value(),
  768. };
  769. } else if (feature_name.starts_with("max-", CaseSensitivity::CaseInsensitive)) {
  770. return MediaQuery::MediaFeature {
  771. .type = MediaQuery::MediaFeature::Type::MaxValue,
  772. .name = feature_name.substring_view(4),
  773. .value = value.release_value(),
  774. };
  775. }
  776. return MediaQuery::MediaFeature {
  777. .type = MediaQuery::MediaFeature::Type::ExactValue,
  778. .name = feature_name,
  779. .value = value.release_value(),
  780. };
  781. }
  782. return invalid_feature();
  783. }
  784. Optional<MediaQuery::MediaType> Parser::consume_media_type(TokenStream<StyleComponentValueRule>& tokens)
  785. {
  786. auto& token = tokens.next_token();
  787. if (!token.is(Token::Type::Ident)) {
  788. tokens.reconsume_current_input_token();
  789. return {};
  790. }
  791. auto ident = token.token().ident();
  792. if (ident.equals_ignoring_case("all")) {
  793. return MediaQuery::MediaType::All;
  794. } else if (ident.equals_ignoring_case("aural")) {
  795. return MediaQuery::MediaType::Aural;
  796. } else if (ident.equals_ignoring_case("braille")) {
  797. return MediaQuery::MediaType::Braille;
  798. } else if (ident.equals_ignoring_case("embossed")) {
  799. return MediaQuery::MediaType::Embossed;
  800. } else if (ident.equals_ignoring_case("handheld")) {
  801. return MediaQuery::MediaType::Handheld;
  802. } else if (ident.equals_ignoring_case("print")) {
  803. return MediaQuery::MediaType::Print;
  804. } else if (ident.equals_ignoring_case("projection")) {
  805. return MediaQuery::MediaType::Projection;
  806. } else if (ident.equals_ignoring_case("screen")) {
  807. return MediaQuery::MediaType::Screen;
  808. } else if (ident.equals_ignoring_case("speech")) {
  809. return MediaQuery::MediaType::Speech;
  810. } else if (ident.equals_ignoring_case("tty")) {
  811. return MediaQuery::MediaType::TTY;
  812. } else if (ident.equals_ignoring_case("tv")) {
  813. return MediaQuery::MediaType::TV;
  814. }
  815. tokens.reconsume_current_input_token();
  816. return {};
  817. }
  818. // `<mf-value>`, https://www.w3.org/TR/mediaqueries-4/#typedef-mf-value
  819. Optional<MediaFeatureValue> Parser::parse_media_feature_value(TokenStream<StyleComponentValueRule>& tokens)
  820. {
  821. // `<number> | <dimension> | <ident> | <ratio>`
  822. auto position = tokens.position();
  823. tokens.skip_whitespace();
  824. auto& first = tokens.next_token();
  825. // `<number>`
  826. if (first.is(Token::Type::Number))
  827. return MediaFeatureValue(first.token().number_value());
  828. // `<dimension>`
  829. if (auto length = parse_length(first); length.has_value())
  830. return MediaFeatureValue(length.release_value());
  831. // `<ident>`
  832. if (first.is(Token::Type::Ident))
  833. return MediaFeatureValue(first.token().ident());
  834. // FIXME: `<ratio>`, once we have ratios.
  835. tokens.rewind_to_position(position);
  836. return {};
  837. }
  838. RefPtr<Supports> Parser::parse_as_supports()
  839. {
  840. return parse_a_supports(m_token_stream);
  841. }
  842. template<typename T>
  843. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  844. {
  845. auto component_values = parse_a_list_of_component_values(tokens);
  846. TokenStream<StyleComponentValueRule> token_stream { component_values };
  847. auto maybe_condition = parse_supports_condition(token_stream);
  848. token_stream.skip_whitespace();
  849. if (maybe_condition && !token_stream.has_next_token())
  850. return Supports::create(maybe_condition.release_nonnull());
  851. return {};
  852. }
  853. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<StyleComponentValueRule>& tokens)
  854. {
  855. tokens.skip_whitespace();
  856. auto start_position = tokens.position();
  857. auto& peeked_token = tokens.peek_token();
  858. // `not <supports-in-parens>`
  859. if (peeked_token.is(Token::Type::Ident) && peeked_token.token().ident().equals_ignoring_case("not")) {
  860. tokens.next_token();
  861. tokens.skip_whitespace();
  862. auto child = parse_supports_in_parens(tokens);
  863. if (child.has_value()) {
  864. auto* condition = new Supports::Condition;
  865. condition->type = Supports::Condition::Type::Not;
  866. condition->children.append(child.release_value());
  867. return adopt_own(*condition);
  868. }
  869. tokens.rewind_to_position(start_position);
  870. return {};
  871. }
  872. // ` <supports-in-parens> [ and <supports-in-parens> ]*
  873. // | <supports-in-parens> [ or <supports-in-parens> ]*`
  874. Vector<Supports::InParens> children;
  875. Optional<Supports::Condition::Type> condition_type {};
  876. auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
  877. if (!token.is(Token::Type::Ident))
  878. return {};
  879. auto ident = token.token().ident();
  880. if (ident.equals_ignoring_case("and"))
  881. return Supports::Condition::Type::And;
  882. if (ident.equals_ignoring_case("or"))
  883. return Supports::Condition::Type::Or;
  884. return {};
  885. };
  886. bool is_invalid = false;
  887. while (tokens.has_next_token()) {
  888. if (!children.is_empty()) {
  889. // Expect `and` or `or` here
  890. auto maybe_combination = as_condition_type(tokens.next_token());
  891. if (!maybe_combination.has_value()) {
  892. is_invalid = true;
  893. break;
  894. }
  895. if (!condition_type.has_value()) {
  896. condition_type = maybe_combination.value();
  897. } else if (maybe_combination != condition_type) {
  898. is_invalid = true;
  899. break;
  900. }
  901. }
  902. tokens.skip_whitespace();
  903. if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
  904. children.append(in_parens.release_value());
  905. } else {
  906. is_invalid = true;
  907. break;
  908. }
  909. tokens.skip_whitespace();
  910. }
  911. if (!is_invalid && !children.is_empty()) {
  912. auto* condition = new Supports::Condition;
  913. condition->type = condition_type.value_or(Supports::Condition::Type::Or);
  914. condition->children = move(children);
  915. return adopt_own(*condition);
  916. }
  917. tokens.rewind_to_position(start_position);
  918. return {};
  919. }
  920. Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<StyleComponentValueRule>& tokens)
  921. {
  922. tokens.skip_whitespace();
  923. auto start_position = tokens.position();
  924. auto& first_token = tokens.peek_token();
  925. // `( <supports-condition> )`
  926. if (first_token.is_block() && first_token.block().is_paren()) {
  927. tokens.next_token();
  928. tokens.skip_whitespace();
  929. TokenStream child_tokens { first_token.block().values() };
  930. if (auto condition = parse_supports_condition(child_tokens)) {
  931. if (child_tokens.has_next_token()) {
  932. tokens.rewind_to_position(start_position);
  933. return {};
  934. }
  935. return Supports::InParens {
  936. .value = { condition.release_nonnull() }
  937. };
  938. }
  939. tokens.rewind_to_position(start_position);
  940. }
  941. // `<supports-feature>`
  942. if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
  943. return Supports::InParens {
  944. .value = { feature.release_value() }
  945. };
  946. }
  947. // `<general-enclosed>`
  948. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  949. return Supports::InParens {
  950. .value = general_enclosed.release_value()
  951. };
  952. }
  953. tokens.rewind_to_position(start_position);
  954. return {};
  955. }
  956. Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<StyleComponentValueRule>& tokens)
  957. {
  958. tokens.skip_whitespace();
  959. auto start_position = tokens.position();
  960. auto& first_token = tokens.next_token();
  961. // `<supports-decl>`
  962. if (first_token.is_block() && first_token.block().is_paren()) {
  963. TokenStream block_tokens { first_token.block().values() };
  964. if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
  965. return Supports::Feature {
  966. .declaration = declaration->to_string()
  967. };
  968. }
  969. }
  970. tokens.rewind_to_position(start_position);
  971. return {};
  972. }
  973. // https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
  974. Optional<GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<StyleComponentValueRule>& tokens)
  975. {
  976. tokens.skip_whitespace();
  977. auto start_position = tokens.position();
  978. auto& first_token = tokens.next_token();
  979. // `[ <function-token> <any-value>? ) ]`
  980. if (first_token.is_function())
  981. return GeneralEnclosed { first_token.to_string() };
  982. // `( <any-value>? )`
  983. if (first_token.is_block() && first_token.block().is_paren())
  984. return GeneralEnclosed { first_token.to_string() };
  985. tokens.rewind_to_position(start_position);
  986. return {};
  987. }
  988. template<typename T>
  989. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  990. {
  991. NonnullRefPtrVector<StyleRule> rules;
  992. for (;;) {
  993. auto& token = tokens.next_token();
  994. if (token.is(Token::Type::Whitespace)) {
  995. continue;
  996. }
  997. if (token.is(Token::Type::EndOfFile)) {
  998. break;
  999. }
  1000. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  1001. if (top_level) {
  1002. continue;
  1003. }
  1004. tokens.reconsume_current_input_token();
  1005. auto maybe_qualified = consume_a_qualified_rule(tokens);
  1006. if (maybe_qualified) {
  1007. rules.append(maybe_qualified.release_nonnull());
  1008. }
  1009. continue;
  1010. }
  1011. if (token.is(Token::Type::AtKeyword)) {
  1012. tokens.reconsume_current_input_token();
  1013. rules.append(consume_an_at_rule(tokens));
  1014. continue;
  1015. }
  1016. tokens.reconsume_current_input_token();
  1017. auto maybe_qualified = consume_a_qualified_rule(tokens);
  1018. if (maybe_qualified) {
  1019. rules.append(maybe_qualified.release_nonnull());
  1020. }
  1021. }
  1022. return rules;
  1023. }
  1024. template<typename T>
  1025. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  1026. {
  1027. auto& name_ident = tokens.next_token();
  1028. VERIFY(name_ident.is(Token::Type::AtKeyword));
  1029. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::At);
  1030. rule->m_name = ((Token)name_ident).at_keyword();
  1031. for (;;) {
  1032. auto& token = tokens.next_token();
  1033. if (token.is(Token::Type::Semicolon)) {
  1034. return rule;
  1035. }
  1036. if (token.is(Token::Type::EndOfFile)) {
  1037. log_parse_error();
  1038. return rule;
  1039. }
  1040. if (token.is(Token::Type::OpenCurly)) {
  1041. rule->m_block = consume_a_simple_block(tokens);
  1042. return rule;
  1043. }
  1044. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1045. StyleComponentValueRule const& component_value = token;
  1046. if (component_value.is_block() && component_value.block().is_curly()) {
  1047. rule->m_block = component_value.block();
  1048. return rule;
  1049. }
  1050. }
  1051. tokens.reconsume_current_input_token();
  1052. auto value = consume_a_component_value(tokens);
  1053. rule->m_prelude.append(value);
  1054. }
  1055. }
  1056. template<typename T>
  1057. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  1058. {
  1059. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::Qualified);
  1060. for (;;) {
  1061. auto& token = tokens.next_token();
  1062. if (token.is(Token::Type::EndOfFile)) {
  1063. log_parse_error();
  1064. return {};
  1065. }
  1066. if (token.is(Token::Type::OpenCurly)) {
  1067. rule->m_block = consume_a_simple_block(tokens);
  1068. return rule;
  1069. }
  1070. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1071. StyleComponentValueRule const& component_value = token;
  1072. if (component_value.is_block() && component_value.block().is_curly()) {
  1073. rule->m_block = component_value.block();
  1074. return rule;
  1075. }
  1076. }
  1077. tokens.reconsume_current_input_token();
  1078. auto value = consume_a_component_value(tokens);
  1079. rule->m_prelude.append(value);
  1080. }
  1081. return rule;
  1082. }
  1083. template<>
  1084. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  1085. {
  1086. return tokens.next_token();
  1087. }
  1088. template<typename T>
  1089. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  1090. {
  1091. auto& token = tokens.next_token();
  1092. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  1093. return StyleComponentValueRule(consume_a_simple_block(tokens));
  1094. if (token.is(Token::Type::Function))
  1095. return StyleComponentValueRule(consume_a_function(tokens));
  1096. return StyleComponentValueRule(token);
  1097. }
  1098. template<typename T>
  1099. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  1100. {
  1101. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  1102. auto block = make_ref_counted<StyleBlockRule>();
  1103. block->m_token = tokens.current_token();
  1104. for (;;) {
  1105. auto& token = tokens.next_token();
  1106. if (token.is(ending_token)) {
  1107. return block;
  1108. }
  1109. if (token.is(Token::Type::EndOfFile)) {
  1110. log_parse_error();
  1111. return block;
  1112. }
  1113. tokens.reconsume_current_input_token();
  1114. auto value = consume_a_component_value(tokens);
  1115. block->m_values.append(value);
  1116. }
  1117. }
  1118. template<typename T>
  1119. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  1120. {
  1121. auto name_ident = tokens.current_token();
  1122. VERIFY(name_ident.is(Token::Type::Function));
  1123. auto function = make_ref_counted<StyleFunctionRule>(((Token)name_ident).function());
  1124. for (;;) {
  1125. auto& token = tokens.next_token();
  1126. if (token.is(Token::Type::CloseParen)) {
  1127. return function;
  1128. }
  1129. if (token.is(Token::Type::EndOfFile)) {
  1130. log_parse_error();
  1131. return function;
  1132. }
  1133. tokens.reconsume_current_input_token();
  1134. auto value = consume_a_component_value(tokens);
  1135. function->m_values.append(value);
  1136. }
  1137. return function;
  1138. }
  1139. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  1140. template<typename T>
  1141. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  1142. {
  1143. // Note: This algorithm assumes that the next input token has already been checked to
  1144. // be an <ident-token>.
  1145. // To consume a declaration:
  1146. // Consume the next input token.
  1147. tokens.skip_whitespace();
  1148. auto start_position = tokens.position();
  1149. auto& token = tokens.next_token();
  1150. if (!token.is(Token::Type::Ident)) {
  1151. tokens.rewind_to_position(start_position);
  1152. return {};
  1153. }
  1154. // Create a new declaration with its name set to the value of the current input token
  1155. // and its value initially set to the empty list.
  1156. StyleDeclarationRule declaration;
  1157. declaration.m_name = ((Token)token).ident();
  1158. // 1. While the next input token is a <whitespace-token>, consume the next input token.
  1159. tokens.skip_whitespace();
  1160. // 2. If the next input token is anything other than a <colon-token>, this is a parse error.
  1161. // Return nothing.
  1162. auto& maybe_colon = tokens.peek_token();
  1163. if (!maybe_colon.is(Token::Type::Colon)) {
  1164. log_parse_error();
  1165. tokens.rewind_to_position(start_position);
  1166. return {};
  1167. }
  1168. // Otherwise, consume the next input token.
  1169. tokens.next_token();
  1170. // 3. While the next input token is a <whitespace-token>, consume the next input token.
  1171. tokens.skip_whitespace();
  1172. // 4. As long as the next input token is anything other than an <EOF-token>, consume a
  1173. // component value and append it to the declaration’s value.
  1174. for (;;) {
  1175. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1176. break;
  1177. }
  1178. declaration.m_values.append(consume_a_component_value(tokens));
  1179. }
  1180. // 5. If the last two non-<whitespace-token>s in the declaration’s value are a <delim-token>
  1181. // with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive
  1182. // match for "important", remove them from the declaration’s value and set the declaration’s
  1183. // important flag to true.
  1184. if (declaration.m_values.size() >= 2) {
  1185. // Walk backwards from the end until we find "important"
  1186. Optional<size_t> important_index;
  1187. for (size_t i = declaration.m_values.size() - 1; i > 0; i--) {
  1188. auto value = declaration.m_values[i];
  1189. if (value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("important")) {
  1190. important_index = i;
  1191. break;
  1192. }
  1193. if (value.is(Token::Type::Whitespace))
  1194. continue;
  1195. break;
  1196. }
  1197. // Walk backwards from important until we find "!"
  1198. if (important_index.has_value()) {
  1199. Optional<size_t> bang_index;
  1200. for (size_t i = important_index.value() - 1; i > 0; i--) {
  1201. auto value = declaration.m_values[i];
  1202. if (value.is(Token::Type::Delim) && value.token().delim() == "!"sv) {
  1203. bang_index = i;
  1204. break;
  1205. }
  1206. if (value.is(Token::Type::Whitespace))
  1207. continue;
  1208. break;
  1209. }
  1210. if (bang_index.has_value()) {
  1211. declaration.m_values.remove(important_index.value());
  1212. declaration.m_values.remove(bang_index.value());
  1213. declaration.m_important = true;
  1214. }
  1215. }
  1216. }
  1217. // 6. While the last token in the declaration’s value is a <whitespace-token>, remove that token.
  1218. while (!declaration.m_values.is_empty()) {
  1219. auto maybe_whitespace = declaration.m_values.last();
  1220. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  1221. break;
  1222. }
  1223. declaration.m_values.take_last();
  1224. }
  1225. // 7. Return the declaration.
  1226. return declaration;
  1227. }
  1228. template<typename T>
  1229. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  1230. {
  1231. Vector<DeclarationOrAtRule> list;
  1232. for (;;) {
  1233. auto& token = tokens.next_token();
  1234. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  1235. continue;
  1236. }
  1237. if (token.is(Token::Type::EndOfFile)) {
  1238. return list;
  1239. }
  1240. if (token.is(Token::Type::AtKeyword)) {
  1241. tokens.reconsume_current_input_token();
  1242. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  1243. continue;
  1244. }
  1245. if (token.is(Token::Type::Ident)) {
  1246. Vector<StyleComponentValueRule> temp;
  1247. temp.append(token);
  1248. for (;;) {
  1249. auto& peek = tokens.peek_token();
  1250. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  1251. break;
  1252. }
  1253. temp.append(consume_a_component_value(tokens));
  1254. }
  1255. auto token_stream = TokenStream(temp);
  1256. auto maybe_declaration = consume_a_declaration(token_stream);
  1257. if (maybe_declaration.has_value()) {
  1258. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  1259. }
  1260. continue;
  1261. }
  1262. log_parse_error();
  1263. tokens.reconsume_current_input_token();
  1264. for (;;) {
  1265. auto& peek = tokens.peek_token();
  1266. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  1267. break;
  1268. dbgln("Discarding token: '{}'", peek.to_debug_string());
  1269. (void)consume_a_component_value(tokens);
  1270. }
  1271. }
  1272. return list;
  1273. }
  1274. RefPtr<CSSRule> Parser::parse_as_rule()
  1275. {
  1276. return parse_a_rule(m_token_stream);
  1277. }
  1278. template<typename T>
  1279. RefPtr<CSSRule> Parser::parse_a_rule(TokenStream<T>& tokens)
  1280. {
  1281. RefPtr<CSSRule> rule;
  1282. tokens.skip_whitespace();
  1283. auto& token = tokens.peek_token();
  1284. if (token.is(Token::Type::EndOfFile)) {
  1285. return {};
  1286. } else if (token.is(Token::Type::AtKeyword)) {
  1287. auto at_rule = consume_an_at_rule(m_token_stream);
  1288. rule = convert_to_rule(at_rule);
  1289. } else {
  1290. auto qualified_rule = consume_a_qualified_rule(tokens);
  1291. if (!qualified_rule)
  1292. return {};
  1293. rule = convert_to_rule(*qualified_rule);
  1294. }
  1295. tokens.skip_whitespace();
  1296. auto& maybe_eof = tokens.peek_token();
  1297. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1298. return rule;
  1299. }
  1300. return {};
  1301. }
  1302. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  1303. {
  1304. return parse_a_list_of_rules(m_token_stream);
  1305. }
  1306. template<typename T>
  1307. NonnullRefPtrVector<CSSRule> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  1308. {
  1309. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  1310. NonnullRefPtrVector<CSSRule> rules;
  1311. for (auto& rule : parsed_rules) {
  1312. auto converted_rule = convert_to_rule(rule);
  1313. if (converted_rule)
  1314. rules.append(*converted_rule);
  1315. }
  1316. return rules;
  1317. }
  1318. Optional<StyleProperty> Parser::parse_as_declaration()
  1319. {
  1320. return parse_a_declaration(m_token_stream);
  1321. }
  1322. template<typename T>
  1323. Optional<StyleProperty> Parser::parse_a_declaration(TokenStream<T>& tokens)
  1324. {
  1325. tokens.skip_whitespace();
  1326. auto& token = tokens.peek_token();
  1327. if (!token.is(Token::Type::Ident)) {
  1328. return {};
  1329. }
  1330. auto declaration = consume_a_declaration(tokens);
  1331. if (declaration.has_value())
  1332. return convert_to_style_property(declaration.value());
  1333. return {};
  1334. }
  1335. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  1336. {
  1337. return parse_a_list_of_declarations(m_token_stream);
  1338. }
  1339. template<typename T>
  1340. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  1341. {
  1342. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  1343. Vector<StyleProperty> properties;
  1344. HashMap<String, StyleProperty> custom_properties;
  1345. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  1346. if (declaration_or_at_rule.is_at_rule()) {
  1347. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  1348. continue;
  1349. }
  1350. auto& declaration = declaration_or_at_rule.m_declaration;
  1351. auto maybe_property = convert_to_style_property(declaration);
  1352. if (maybe_property.has_value()) {
  1353. auto property = maybe_property.value();
  1354. if (property.property_id == PropertyID::Custom) {
  1355. custom_properties.set(property.custom_name, property);
  1356. } else {
  1357. properties.append(property);
  1358. }
  1359. }
  1360. }
  1361. return PropertyOwningCSSStyleDeclaration::create(move(properties), move(custom_properties));
  1362. }
  1363. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  1364. {
  1365. return parse_a_component_value(m_token_stream);
  1366. }
  1367. template<typename T>
  1368. Optional<StyleComponentValueRule> Parser::parse_a_component_value(TokenStream<T>& tokens)
  1369. {
  1370. tokens.skip_whitespace();
  1371. auto& token = tokens.peek_token();
  1372. if (token.is(Token::Type::EndOfFile)) {
  1373. return {};
  1374. }
  1375. auto value = consume_a_component_value(tokens);
  1376. tokens.skip_whitespace();
  1377. auto& maybe_eof = tokens.peek_token();
  1378. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1379. return value;
  1380. }
  1381. return {};
  1382. }
  1383. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  1384. {
  1385. return parse_a_list_of_component_values(m_token_stream);
  1386. }
  1387. template<typename T>
  1388. Vector<StyleComponentValueRule> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  1389. {
  1390. Vector<StyleComponentValueRule> rules;
  1391. for (;;) {
  1392. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1393. break;
  1394. }
  1395. rules.append(consume_a_component_value(tokens));
  1396. }
  1397. return rules;
  1398. }
  1399. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  1400. {
  1401. return parse_a_comma_separated_list_of_component_values(m_token_stream);
  1402. }
  1403. template<typename T>
  1404. Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  1405. {
  1406. Vector<Vector<StyleComponentValueRule>> lists;
  1407. lists.append({});
  1408. for (;;) {
  1409. auto& next = tokens.next_token();
  1410. if (next.is(Token::Type::Comma)) {
  1411. lists.append({});
  1412. continue;
  1413. } else if (next.is(Token::Type::EndOfFile)) {
  1414. break;
  1415. }
  1416. tokens.reconsume_current_input_token();
  1417. auto component_value = consume_a_component_value(tokens);
  1418. lists.last().append(component_value);
  1419. }
  1420. return lists;
  1421. }
  1422. Optional<AK::URL> Parser::parse_url_function(StyleComponentValueRule const& component_value, AllowedDataUrlType allowed_data_url_type)
  1423. {
  1424. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1425. // FIXME: Handle data: urls (RFC2397)
  1426. auto convert_string_to_url = [&](StringView& url_string) -> Optional<AK::URL> {
  1427. if (url_string.starts_with("data:", CaseSensitivity::CaseInsensitive)) {
  1428. auto data_url = AK::URL(url_string);
  1429. switch (allowed_data_url_type) {
  1430. case AllowedDataUrlType::Image:
  1431. if (data_url.data_mime_type().starts_with("image"sv, CaseSensitivity::CaseInsensitive))
  1432. return data_url;
  1433. break;
  1434. default:
  1435. break;
  1436. }
  1437. return {};
  1438. }
  1439. return m_context.complete_url(url_string);
  1440. };
  1441. if (component_value.is(Token::Type::Url)) {
  1442. auto url_string = component_value.token().url();
  1443. return convert_string_to_url(url_string);
  1444. }
  1445. if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) {
  1446. auto& function_values = component_value.function().values();
  1447. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  1448. for (size_t i = 0; i < function_values.size(); ++i) {
  1449. auto& value = function_values[i];
  1450. if (value.is(Token::Type::Whitespace))
  1451. continue;
  1452. if (value.is(Token::Type::String)) {
  1453. auto url_string = value.token().string();
  1454. return convert_string_to_url(url_string);
  1455. }
  1456. break;
  1457. }
  1458. }
  1459. return {};
  1460. }
  1461. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  1462. {
  1463. if (rule->m_type == StyleRule::Type::At) {
  1464. if (has_ignored_vendor_prefix(rule->m_name)) {
  1465. return {};
  1466. } else if (rule->m_name.equals_ignoring_case("media"sv)) {
  1467. auto media_query_tokens = TokenStream { rule->prelude() };
  1468. auto media_query_list = parse_a_media_query_list(media_query_tokens);
  1469. auto child_tokens = TokenStream { rule->block().values() };
  1470. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1471. NonnullRefPtrVector<CSSRule> child_rules;
  1472. for (auto& raw_rule : parser_rules) {
  1473. if (auto child_rule = convert_to_rule(raw_rule))
  1474. child_rules.append(*child_rule);
  1475. }
  1476. return CSSMediaRule::create(MediaList::create(move(media_query_list)), move(child_rules));
  1477. } else if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  1478. Optional<AK::URL> url;
  1479. for (auto& token : rule->prelude()) {
  1480. if (token.is(Token::Type::Whitespace))
  1481. continue;
  1482. if (token.is(Token::Type::String)) {
  1483. url = m_context.complete_url(token.token().string());
  1484. } else {
  1485. url = parse_url_function(token);
  1486. }
  1487. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1488. if (url.has_value())
  1489. break;
  1490. }
  1491. if (url.has_value())
  1492. return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document()));
  1493. else
  1494. dbgln("Unable to parse url from @import rule");
  1495. } else if (rule->m_name.equals_ignoring_case("supports"sv)) {
  1496. auto supports_tokens = TokenStream { rule->prelude() };
  1497. auto supports = parse_a_supports(supports_tokens);
  1498. if (!supports) {
  1499. if constexpr (CSS_PARSER_DEBUG) {
  1500. dbgln("CSSParser: @supports rule invalid; discarding.");
  1501. supports_tokens.dump_all_tokens();
  1502. }
  1503. return {};
  1504. }
  1505. auto child_tokens = TokenStream { rule->block().values() };
  1506. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1507. NonnullRefPtrVector<CSSRule> child_rules;
  1508. for (auto& raw_rule : parser_rules) {
  1509. if (auto child_rule = convert_to_rule(raw_rule))
  1510. child_rules.append(*child_rule);
  1511. }
  1512. return CSSSupportsRule::create(supports.release_nonnull(), move(child_rules));
  1513. } else {
  1514. dbgln("Unrecognized CSS at-rule: @{}", rule->m_name);
  1515. }
  1516. // FIXME: More at rules!
  1517. } else {
  1518. auto prelude_stream = TokenStream(rule->m_prelude);
  1519. auto selectors = parse_a_selector(prelude_stream);
  1520. if (selectors.is_error()) {
  1521. if (selectors.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1522. dbgln("CSSParser: style rule selectors invalid; discarding.");
  1523. if constexpr (CSS_PARSER_DEBUG) {
  1524. prelude_stream.dump_all_tokens();
  1525. }
  1526. }
  1527. return {};
  1528. }
  1529. if (selectors.value().is_empty()) {
  1530. dbgln("CSSParser: empty selector; discarding.");
  1531. return {};
  1532. }
  1533. auto declaration = convert_to_declaration(*rule->m_block);
  1534. if (!declaration) {
  1535. dbgln("CSSParser: style rule declaration invalid; discarding.");
  1536. return {};
  1537. }
  1538. return CSSStyleRule::create(move(selectors.value()), move(*declaration));
  1539. }
  1540. return {};
  1541. }
  1542. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  1543. {
  1544. if (!block->is_curly())
  1545. return {};
  1546. auto stream = TokenStream(block->m_values);
  1547. return parse_a_list_of_declarations(stream);
  1548. }
  1549. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule const& declaration)
  1550. {
  1551. auto& property_name = declaration.m_name;
  1552. auto property_id = property_id_from_string(property_name);
  1553. if (property_id == PropertyID::Invalid) {
  1554. if (property_name.starts_with("--")) {
  1555. property_id = PropertyID::Custom;
  1556. } else if (has_ignored_vendor_prefix(property_name)) {
  1557. return {};
  1558. } else if (!property_name.starts_with("-")) {
  1559. dbgln("Unrecognized CSS property '{}'", property_name);
  1560. return {};
  1561. }
  1562. }
  1563. auto value_token_stream = TokenStream(declaration.m_values);
  1564. auto value = parse_css_value(property_id, value_token_stream);
  1565. if (value.is_error()) {
  1566. if (value.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1567. dbgln("Unable to parse value for CSS property '{}'.", property_name);
  1568. if constexpr (CSS_PARSER_DEBUG) {
  1569. value_token_stream.dump_all_tokens();
  1570. }
  1571. }
  1572. return {};
  1573. }
  1574. if (property_id == PropertyID::Custom) {
  1575. return StyleProperty { declaration.m_important, property_id, value.release_value(), declaration.m_name };
  1576. } else {
  1577. return StyleProperty { declaration.m_important, property_id, value.release_value(), {} };
  1578. }
  1579. }
  1580. RefPtr<StyleValue> Parser::parse_builtin_value(StyleComponentValueRule const& component_value)
  1581. {
  1582. if (component_value.is(Token::Type::Ident)) {
  1583. auto ident = component_value.token().ident();
  1584. if (ident.equals_ignoring_case("inherit"))
  1585. return InheritStyleValue::the();
  1586. if (ident.equals_ignoring_case("initial"))
  1587. return InitialStyleValue::the();
  1588. if (ident.equals_ignoring_case("unset"))
  1589. return UnsetStyleValue::the();
  1590. // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
  1591. }
  1592. return {};
  1593. }
  1594. RefPtr<StyleValue> Parser::parse_dynamic_value(StyleComponentValueRule const& component_value)
  1595. {
  1596. if (component_value.is_function()) {
  1597. auto& function = component_value.function();
  1598. if (function.name().equals_ignoring_case("calc")) {
  1599. auto calc_expression = parse_calc_expression(function.values());
  1600. // FIXME: Either produce a string value of calc() here, or do so in CalculatedStyleValue::to_string().
  1601. if (calc_expression)
  1602. return CalculatedStyleValue::create("(FIXME:calc to string)", calc_expression.release_nonnull());
  1603. } else if (function.name().equals_ignoring_case("var")) {
  1604. // Declarations using `var()` should already be parsed as an UnresolvedStyleValue before this point.
  1605. VERIFY_NOT_REACHED();
  1606. }
  1607. }
  1608. return {};
  1609. }
  1610. Optional<Length> Parser::parse_length(StyleComponentValueRule const& component_value)
  1611. {
  1612. Length::Type type = Length::Type::Undefined;
  1613. Optional<float> numeric_value;
  1614. if (component_value.is(Token::Type::Dimension)) {
  1615. numeric_value = component_value.token().dimension_value();
  1616. auto unit_string = component_value.token().dimension_unit();
  1617. if (unit_string.equals_ignoring_case("px")) {
  1618. type = Length::Type::Px;
  1619. } else if (unit_string.equals_ignoring_case("pt")) {
  1620. type = Length::Type::Pt;
  1621. } else if (unit_string.equals_ignoring_case("pc")) {
  1622. type = Length::Type::Pc;
  1623. } else if (unit_string.equals_ignoring_case("mm")) {
  1624. type = Length::Type::Mm;
  1625. } else if (unit_string.equals_ignoring_case("rem")) {
  1626. type = Length::Type::Rem;
  1627. } else if (unit_string.equals_ignoring_case("em")) {
  1628. type = Length::Type::Em;
  1629. } else if (unit_string.equals_ignoring_case("ex")) {
  1630. type = Length::Type::Ex;
  1631. } else if (unit_string.equals_ignoring_case("ch")) {
  1632. type = Length::Type::Ch;
  1633. } else if (unit_string.equals_ignoring_case("vw")) {
  1634. type = Length::Type::Vw;
  1635. } else if (unit_string.equals_ignoring_case("vh")) {
  1636. type = Length::Type::Vh;
  1637. } else if (unit_string.equals_ignoring_case("vmax")) {
  1638. type = Length::Type::Vmax;
  1639. } else if (unit_string.equals_ignoring_case("vmin")) {
  1640. type = Length::Type::Vmin;
  1641. } else if (unit_string.equals_ignoring_case("cm")) {
  1642. type = Length::Type::Cm;
  1643. } else if (unit_string.equals_ignoring_case("in")) {
  1644. type = Length::Type::In;
  1645. } else if (unit_string.equals_ignoring_case("Q")) {
  1646. type = Length::Type::Q;
  1647. } else if (unit_string.equals_ignoring_case("%")) {
  1648. // A number followed by `%` must always result in a Percentage token.
  1649. VERIFY_NOT_REACHED();
  1650. } else {
  1651. return {};
  1652. }
  1653. } else if (component_value.is(Token::Type::Percentage)) {
  1654. type = Length::Type::Percentage;
  1655. numeric_value = component_value.token().percentage();
  1656. } else if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto")) {
  1657. return Length::make_auto();
  1658. } else if (component_value.is(Token::Type::Number)) {
  1659. numeric_value = component_value.token().number_value();
  1660. if (numeric_value == 0) {
  1661. type = Length::Type::Px;
  1662. } else if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  1663. // https://quirks.spec.whatwg.org/#quirky-length-value
  1664. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1665. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1666. // expression, and must not be supported in the supports() static method of the CSS interface."
  1667. type = Length::Type::Px;
  1668. }
  1669. }
  1670. if (!numeric_value.has_value())
  1671. return {};
  1672. return Length(numeric_value.value(), type);
  1673. }
  1674. RefPtr<StyleValue> Parser::parse_length_value(StyleComponentValueRule const& component_value)
  1675. {
  1676. // Numbers with no units can be lengths, in two situations:
  1677. // 1) We're in quirks mode, and it's an integer.
  1678. // 2) It's a 0.
  1679. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1680. // FIXME: "auto" is also treated as a Length, and most of the time that is how it is used, but not always.
  1681. // Possibly it should always be an Identifier, and then quietly converted to a Length when needed, like 0 above.
  1682. // Right now, it instead is quietly converted to an Identifier when needed.
  1683. if (component_value.is(Token::Type::Dimension) || component_value.is(Token::Type::Percentage)
  1684. || (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"sv))
  1685. || (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength) && component_value.is(Token::Type::Number) && component_value.token().number_value() != 0)) {
  1686. auto length = parse_length(component_value);
  1687. if (length.has_value())
  1688. return LengthStyleValue::create(length.value());
  1689. }
  1690. return {};
  1691. }
  1692. RefPtr<StyleValue> Parser::parse_numeric_value(StyleComponentValueRule const& component_value)
  1693. {
  1694. if (component_value.is(Token::Type::Number)) {
  1695. auto number = component_value.token();
  1696. if (number.number_type() == Token::NumberType::Integer) {
  1697. return NumericStyleValue::create_integer(number.to_integer());
  1698. } else {
  1699. return NumericStyleValue::create_float(number.number_value());
  1700. }
  1701. }
  1702. return {};
  1703. }
  1704. RefPtr<StyleValue> Parser::parse_identifier_value(StyleComponentValueRule const& component_value)
  1705. {
  1706. if (component_value.is(Token::Type::Ident)) {
  1707. auto value_id = value_id_from_string(component_value.token().ident());
  1708. if (value_id != ValueID::Invalid)
  1709. return IdentifierStyleValue::create(value_id);
  1710. }
  1711. return {};
  1712. }
  1713. Optional<Color> Parser::parse_color(StyleComponentValueRule const& component_value)
  1714. {
  1715. // https://www.w3.org/TR/css-color-3/
  1716. if (component_value.is(Token::Type::Ident)) {
  1717. auto ident = component_value.token().ident();
  1718. auto color = Color::from_string(ident);
  1719. if (color.has_value())
  1720. return color;
  1721. } else if (component_value.is(Token::Type::Hash)) {
  1722. auto color = Color::from_string(String::formatted("#{}", component_value.token().hash_value()));
  1723. if (color.has_value())
  1724. return color;
  1725. return {};
  1726. } else if (component_value.is_function()) {
  1727. auto& function = component_value.function();
  1728. auto& values = function.values();
  1729. Vector<Token> params;
  1730. for (size_t i = 0; i < values.size(); ++i) {
  1731. auto& value = values.at(i);
  1732. if (value.is(Token::Type::Whitespace))
  1733. continue;
  1734. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  1735. params.append(value.token());
  1736. // Eat following comma and whitespace
  1737. while ((i + 1) < values.size()) {
  1738. auto& next = values.at(i + 1);
  1739. if (next.is(Token::Type::Whitespace))
  1740. i++;
  1741. else if (next.is(Token::Type::Comma))
  1742. break;
  1743. return {};
  1744. }
  1745. }
  1746. }
  1747. if (function.name().equals_ignoring_case("rgb")) {
  1748. if (params.size() != 3)
  1749. return {};
  1750. auto r_val = params[0];
  1751. auto g_val = params[1];
  1752. auto b_val = params[2];
  1753. if (r_val.is(Token::NumberType::Integer)
  1754. && g_val.is(Token::NumberType::Integer)
  1755. && b_val.is(Token::NumberType::Integer)) {
  1756. auto r = r_val.to_integer();
  1757. auto g = g_val.to_integer();
  1758. auto b = b_val.to_integer();
  1759. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  1760. return Color(r, g, b);
  1761. } else if (r_val.is(Token::Type::Percentage)
  1762. && g_val.is(Token::Type::Percentage)
  1763. && b_val.is(Token::Type::Percentage)) {
  1764. u8 r = clamp(lroundf(r_val.percentage() * 2.55), 0, 255);
  1765. u8 g = clamp(lroundf(g_val.percentage() * 2.55), 0, 255);
  1766. u8 b = clamp(lroundf(b_val.percentage() * 2.55), 0, 255);
  1767. return Color(r, g, b);
  1768. }
  1769. } else if (function.name().equals_ignoring_case("rgba")) {
  1770. if (params.size() != 4)
  1771. return {};
  1772. auto r_val = params[0];
  1773. auto g_val = params[1];
  1774. auto b_val = params[2];
  1775. auto a_val = params[3];
  1776. if (r_val.is(Token::NumberType::Integer)
  1777. && g_val.is(Token::NumberType::Integer)
  1778. && b_val.is(Token::NumberType::Integer)
  1779. && a_val.is(Token::Type::Number)) {
  1780. auto r = r_val.to_integer();
  1781. auto g = g_val.to_integer();
  1782. auto b = b_val.to_integer();
  1783. auto a = clamp(lroundf(a_val.number_value() * 255.0), 0, 255);
  1784. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  1785. return Color(r, g, b, a);
  1786. } else if (r_val.is(Token::Type::Percentage)
  1787. && g_val.is(Token::Type::Percentage)
  1788. && b_val.is(Token::Type::Percentage)
  1789. && a_val.is(Token::Type::Number)) {
  1790. auto r = r_val.percentage();
  1791. auto g = g_val.percentage();
  1792. auto b = b_val.percentage();
  1793. auto a = a_val.number_value();
  1794. u8 r_255 = clamp(lroundf(r * 2.55), 0, 255);
  1795. u8 g_255 = clamp(lroundf(g * 2.55), 0, 255);
  1796. u8 b_255 = clamp(lroundf(b * 2.55), 0, 255);
  1797. u8 a_255 = clamp(lroundf(a * 255.0), 0, 255);
  1798. return Color(r_255, g_255, b_255, a_255);
  1799. }
  1800. } else if (function.name().equals_ignoring_case("hsl")) {
  1801. if (params.size() != 3)
  1802. return {};
  1803. auto h_val = params[0];
  1804. auto s_val = params[1];
  1805. auto l_val = params[2];
  1806. if (h_val.is(Token::Type::Number)
  1807. && s_val.is(Token::Type::Percentage)
  1808. && l_val.is(Token::Type::Percentage)) {
  1809. auto h = h_val.number_value();
  1810. auto s = s_val.percentage() / 100.0;
  1811. auto l = l_val.percentage() / 100.0;
  1812. return Color::from_hsl(h, s, l);
  1813. }
  1814. } else if (function.name().equals_ignoring_case("hsla")) {
  1815. if (params.size() != 4)
  1816. return {};
  1817. auto h_val = params[0];
  1818. auto s_val = params[1];
  1819. auto l_val = params[2];
  1820. auto a_val = params[3];
  1821. if (h_val.is(Token::Type::Number)
  1822. && s_val.is(Token::Type::Percentage)
  1823. && l_val.is(Token::Type::Percentage)
  1824. && a_val.is(Token::Type::Number)) {
  1825. auto h = h_val.number_value();
  1826. auto s = s_val.percentage() / 100.0;
  1827. auto l = l_val.percentage() / 100.0;
  1828. auto a = a_val.number_value();
  1829. return Color::from_hsla(h, s, l, a);
  1830. }
  1831. }
  1832. return {};
  1833. }
  1834. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  1835. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  1836. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  1837. // aborting on the first step that returns a value:
  1838. // 1. Let cv be the component value.
  1839. auto& cv = component_value;
  1840. String serialization;
  1841. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  1842. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  1843. // 1. If cv’s type flag is not "integer", return an error.
  1844. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  1845. if (cv.token().number_type() != Token::NumberType::Integer)
  1846. return {};
  1847. // 2. If cv’s value is less than zero, return an error.
  1848. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  1849. if (value < 0)
  1850. return {};
  1851. // 3. Let serialization be the serialization of cv’s value, as a base-ten integer using digits 0-9 (U+0030 to U+0039) in the shortest form possible.
  1852. StringBuilder serialization_builder;
  1853. serialization_builder.appendff("{}", value);
  1854. // 4. If cv is a <dimension-token>, append the unit to serialization.
  1855. if (cv.is(Token::Type::Dimension))
  1856. serialization_builder.append(cv.token().dimension_unit());
  1857. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  1858. serialization = serialization_builder.to_string();
  1859. if (serialization_builder.length() < 6) {
  1860. StringBuilder builder;
  1861. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  1862. builder.append('0');
  1863. builder.append(serialization_builder.string_view());
  1864. serialization = builder.to_string();
  1865. }
  1866. }
  1867. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  1868. else {
  1869. if (!cv.is(Token::Type::Ident))
  1870. return {};
  1871. serialization = cv.token().ident();
  1872. }
  1873. // 4. If serialization does not consist of three or six characters, return an error.
  1874. if (serialization.length() != 3 && serialization.length() != 6)
  1875. return {};
  1876. // 5. If serialization contains any characters not in the range [0-9A-Fa-f] (U+0030 to U+0039, U+0041 to U+0046, U+0061 to U+0066), return an error.
  1877. for (auto c : serialization) {
  1878. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  1879. return {};
  1880. }
  1881. // 6. Return the concatenation of "#" (U+0023) and serialization.
  1882. String concatenation = String::formatted("#{}", serialization);
  1883. return Color::from_string(concatenation);
  1884. }
  1885. return {};
  1886. }
  1887. RefPtr<StyleValue> Parser::parse_color_value(StyleComponentValueRule const& component_value)
  1888. {
  1889. auto color = parse_color(component_value);
  1890. if (color.has_value())
  1891. return ColorStyleValue::create(color.value());
  1892. return {};
  1893. }
  1894. RefPtr<StyleValue> Parser::parse_string_value(StyleComponentValueRule const& component_value)
  1895. {
  1896. if (component_value.is(Token::Type::String))
  1897. return StringStyleValue::create(component_value.token().string());
  1898. return {};
  1899. }
  1900. RefPtr<StyleValue> Parser::parse_image_value(StyleComponentValueRule const& component_value)
  1901. {
  1902. auto url = parse_url_function(component_value, AllowedDataUrlType::Image);
  1903. if (url.has_value())
  1904. return ImageStyleValue::create(url.value());
  1905. // FIXME: Handle gradients.
  1906. return {};
  1907. }
  1908. template<typename ParseFunction>
  1909. RefPtr<StyleValue> Parser::parse_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values, ParseFunction parse_one_value)
  1910. {
  1911. auto tokens = TokenStream { component_values };
  1912. auto first = parse_one_value(tokens);
  1913. if (!first || !tokens.has_next_token())
  1914. return first;
  1915. NonnullRefPtrVector<StyleValue> values;
  1916. values.append(first.release_nonnull());
  1917. while (tokens.has_next_token()) {
  1918. if (!tokens.next_token().is(Token::Type::Comma))
  1919. return {};
  1920. if (auto maybe_value = parse_one_value(tokens)) {
  1921. values.append(maybe_value.release_nonnull());
  1922. continue;
  1923. }
  1924. return {};
  1925. }
  1926. return StyleValueList::create(move(values));
  1927. }
  1928. RefPtr<StyleValue> Parser::parse_simple_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values)
  1929. {
  1930. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> RefPtr<StyleValue> {
  1931. auto& token = tokens.next_token();
  1932. if (auto value = parse_css_value(token); value && property_accepts_value(m_context.current_property_id(), *value))
  1933. return value;
  1934. tokens.reconsume_current_input_token();
  1935. return nullptr;
  1936. });
  1937. }
  1938. RefPtr<StyleValue> Parser::parse_background_value(Vector<StyleComponentValueRule> const& component_values)
  1939. {
  1940. NonnullRefPtrVector<StyleValue> background_images;
  1941. NonnullRefPtrVector<StyleValue> background_positions;
  1942. NonnullRefPtrVector<StyleValue> background_sizes;
  1943. NonnullRefPtrVector<StyleValue> background_repeats;
  1944. NonnullRefPtrVector<StyleValue> background_attachments;
  1945. NonnullRefPtrVector<StyleValue> background_clips;
  1946. NonnullRefPtrVector<StyleValue> background_origins;
  1947. RefPtr<StyleValue> background_color;
  1948. // Per-layer values
  1949. RefPtr<StyleValue> background_image;
  1950. RefPtr<StyleValue> background_position;
  1951. RefPtr<StyleValue> background_size;
  1952. RefPtr<StyleValue> background_repeat;
  1953. RefPtr<StyleValue> background_attachment;
  1954. RefPtr<StyleValue> background_clip;
  1955. RefPtr<StyleValue> background_origin;
  1956. bool has_multiple_layers = false;
  1957. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  1958. if (allow_background_color) {
  1959. if (background_color)
  1960. return true;
  1961. } else {
  1962. if (background_color)
  1963. return false;
  1964. }
  1965. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  1966. };
  1967. auto complete_background_layer = [&]() {
  1968. background_images.append(background_image ? background_image.release_nonnull() : property_initial_value(PropertyID::BackgroundImage));
  1969. background_positions.append(background_position ? background_position.release_nonnull() : property_initial_value(PropertyID::BackgroundPosition));
  1970. background_sizes.append(background_size ? background_size.release_nonnull() : property_initial_value(PropertyID::BackgroundSize));
  1971. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : property_initial_value(PropertyID::BackgroundRepeat));
  1972. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : property_initial_value(PropertyID::BackgroundAttachment));
  1973. if (!background_origin && !background_clip) {
  1974. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  1975. background_clip = property_initial_value(PropertyID::BackgroundClip);
  1976. } else if (!background_clip) {
  1977. background_clip = background_origin;
  1978. }
  1979. background_origins.append(background_origin.release_nonnull());
  1980. background_clips.append(background_clip.release_nonnull());
  1981. background_image = nullptr;
  1982. background_position = nullptr;
  1983. background_size = nullptr;
  1984. background_repeat = nullptr;
  1985. background_attachment = nullptr;
  1986. background_clip = nullptr;
  1987. background_origin = nullptr;
  1988. };
  1989. auto tokens = TokenStream { component_values };
  1990. while (tokens.has_next_token()) {
  1991. auto& part = tokens.next_token();
  1992. if (part.is(Token::Type::Comma)) {
  1993. has_multiple_layers = true;
  1994. if (!background_layer_is_valid(false))
  1995. return nullptr;
  1996. complete_background_layer();
  1997. continue;
  1998. }
  1999. auto value = parse_css_value(part);
  2000. if (!value)
  2001. return nullptr;
  2002. if (property_accepts_value(PropertyID::BackgroundAttachment, *value)) {
  2003. if (background_attachment)
  2004. return nullptr;
  2005. background_attachment = value.release_nonnull();
  2006. continue;
  2007. }
  2008. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  2009. if (background_color)
  2010. return nullptr;
  2011. background_color = value.release_nonnull();
  2012. continue;
  2013. }
  2014. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  2015. if (background_image)
  2016. return nullptr;
  2017. background_image = value.release_nonnull();
  2018. continue;
  2019. }
  2020. if (property_accepts_value(PropertyID::BackgroundOrigin, *value)) {
  2021. // background-origin and background-clip accept the same values. From the spec:
  2022. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  2023. // If two values are present, then the first sets background-origin and the second background-clip."
  2024. // - https://www.w3.org/TR/css-backgrounds-3/#background
  2025. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  2026. // If we only get one, we copy the value before creating the BackgroundStyleValue.
  2027. if (!background_origin) {
  2028. background_origin = value.release_nonnull();
  2029. continue;
  2030. }
  2031. if (!background_clip) {
  2032. background_clip = value.release_nonnull();
  2033. continue;
  2034. }
  2035. return nullptr;
  2036. }
  2037. if (property_accepts_value(PropertyID::BackgroundPosition, *value)) {
  2038. if (background_position)
  2039. return nullptr;
  2040. tokens.reconsume_current_input_token();
  2041. if (auto maybe_background_position = parse_single_background_position_value(tokens)) {
  2042. background_position = maybe_background_position.release_nonnull();
  2043. // Attempt to parse `/ <background-size>`
  2044. auto before_slash = tokens.position();
  2045. auto& maybe_slash = tokens.next_token();
  2046. if (maybe_slash.is(Token::Type::Delim) && maybe_slash.token().delim() == "/"sv) {
  2047. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  2048. background_size = maybe_background_size.release_nonnull();
  2049. continue;
  2050. }
  2051. return nullptr;
  2052. }
  2053. tokens.rewind_to_position(before_slash);
  2054. continue;
  2055. }
  2056. return nullptr;
  2057. }
  2058. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  2059. if (background_repeat)
  2060. return nullptr;
  2061. tokens.reconsume_current_input_token();
  2062. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  2063. background_repeat = maybe_repeat.release_nonnull();
  2064. continue;
  2065. }
  2066. return nullptr;
  2067. }
  2068. return nullptr;
  2069. }
  2070. if (!background_layer_is_valid(true))
  2071. return nullptr;
  2072. // We only need to create StyleValueLists if there are multiple layers.
  2073. // Otherwise, we can pass the single StyleValues directly.
  2074. if (has_multiple_layers) {
  2075. complete_background_layer();
  2076. if (!background_color)
  2077. background_color = property_initial_value(PropertyID::BackgroundColor);
  2078. return BackgroundStyleValue::create(
  2079. background_color.release_nonnull(),
  2080. StyleValueList::create(move(background_images)),
  2081. StyleValueList::create(move(background_positions)),
  2082. StyleValueList::create(move(background_sizes)),
  2083. StyleValueList::create(move(background_repeats)),
  2084. StyleValueList::create(move(background_attachments)),
  2085. StyleValueList::create(move(background_origins)),
  2086. StyleValueList::create(move(background_clips)));
  2087. }
  2088. if (!background_color)
  2089. background_color = property_initial_value(PropertyID::BackgroundColor);
  2090. if (!background_image)
  2091. background_image = property_initial_value(PropertyID::BackgroundImage);
  2092. if (!background_position)
  2093. background_position = property_initial_value(PropertyID::BackgroundPosition);
  2094. if (!background_size)
  2095. background_size = property_initial_value(PropertyID::BackgroundSize);
  2096. if (!background_repeat)
  2097. background_repeat = property_initial_value(PropertyID::BackgroundRepeat);
  2098. if (!background_attachment)
  2099. background_attachment = property_initial_value(PropertyID::BackgroundAttachment);
  2100. if (!background_origin && !background_clip) {
  2101. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  2102. background_clip = property_initial_value(PropertyID::BackgroundClip);
  2103. } else if (!background_clip) {
  2104. background_clip = background_origin;
  2105. }
  2106. return BackgroundStyleValue::create(
  2107. background_color.release_nonnull(),
  2108. background_image.release_nonnull(),
  2109. background_position.release_nonnull(),
  2110. background_size.release_nonnull(),
  2111. background_repeat.release_nonnull(),
  2112. background_attachment.release_nonnull(),
  2113. background_origin.release_nonnull(),
  2114. background_clip.release_nonnull());
  2115. }
  2116. RefPtr<StyleValue> Parser::parse_single_background_position_value(TokenStream<StyleComponentValueRule>& tokens)
  2117. {
  2118. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  2119. // "Note: The background-position property also accepts a three-value syntax.
  2120. // This has been disallowed generically because it creates parsing ambiguities
  2121. // when combined with other length or percentage components in a property value."
  2122. // - https://www.w3.org/TR/css-values-4/#typedef-position
  2123. // So, we'll need a separate function to parse <position> later.
  2124. auto start_position = tokens.position();
  2125. auto error = [&]() {
  2126. tokens.rewind_to_position(start_position);
  2127. return nullptr;
  2128. };
  2129. auto to_edge = [](ValueID identifier) -> Optional<PositionEdge> {
  2130. switch (identifier) {
  2131. case ValueID::Top:
  2132. return PositionEdge::Top;
  2133. case ValueID::Bottom:
  2134. return PositionEdge::Bottom;
  2135. case ValueID::Left:
  2136. return PositionEdge::Left;
  2137. case ValueID::Right:
  2138. return PositionEdge::Right;
  2139. default:
  2140. return {};
  2141. }
  2142. };
  2143. auto is_horizontal = [](ValueID identifier) -> bool {
  2144. switch (identifier) {
  2145. case ValueID::Left:
  2146. case ValueID::Right:
  2147. return true;
  2148. default:
  2149. return false;
  2150. }
  2151. };
  2152. auto is_vertical = [](ValueID identifier) -> bool {
  2153. switch (identifier) {
  2154. case ValueID::Top:
  2155. case ValueID::Bottom:
  2156. return true;
  2157. default:
  2158. return false;
  2159. }
  2160. };
  2161. auto zero_offset = Length::make_px(0);
  2162. auto center_offset = Length { 50, Length::Type::Percentage };
  2163. struct EdgeOffset {
  2164. PositionEdge edge;
  2165. Length offset;
  2166. bool edge_provided;
  2167. bool offset_provided;
  2168. };
  2169. Optional<EdgeOffset> horizontal;
  2170. Optional<EdgeOffset> vertical;
  2171. bool found_center = false;
  2172. while (tokens.has_next_token()) {
  2173. // Check if we're done
  2174. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  2175. if (seen_items == 2)
  2176. break;
  2177. auto& token = tokens.peek_token();
  2178. auto maybe_value = parse_css_value(token);
  2179. if (!maybe_value || !property_accepts_value(PropertyID::BackgroundPosition, *maybe_value))
  2180. break;
  2181. tokens.next_token();
  2182. auto value = maybe_value.release_nonnull();
  2183. if (value->has_length()) {
  2184. if (!horizontal.has_value()) {
  2185. horizontal = EdgeOffset { PositionEdge::Left, value->to_length(), false, true };
  2186. } else if (!vertical.has_value()) {
  2187. vertical = EdgeOffset { PositionEdge::Top, value->to_length(), false, true };
  2188. } else {
  2189. return error();
  2190. }
  2191. continue;
  2192. }
  2193. if (value->has_identifier()) {
  2194. auto identifier = value->to_identifier();
  2195. if (is_horizontal(identifier)) {
  2196. Length offset = zero_offset;
  2197. bool offset_provided = false;
  2198. if (tokens.has_next_token()) {
  2199. auto maybe_offset = parse_length(tokens.peek_token());
  2200. if (maybe_offset.has_value()) {
  2201. offset = maybe_offset.value();
  2202. offset_provided = true;
  2203. tokens.next_token();
  2204. }
  2205. }
  2206. horizontal = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2207. } else if (is_vertical(identifier)) {
  2208. Length offset = zero_offset;
  2209. bool offset_provided = false;
  2210. if (tokens.has_next_token()) {
  2211. auto maybe_offset = parse_length(tokens.peek_token());
  2212. if (maybe_offset.has_value()) {
  2213. offset = maybe_offset.value();
  2214. offset_provided = true;
  2215. tokens.next_token();
  2216. }
  2217. }
  2218. vertical = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2219. } else if (identifier == ValueID::Center) {
  2220. found_center = true;
  2221. } else {
  2222. return error();
  2223. }
  2224. continue;
  2225. }
  2226. tokens.reconsume_current_input_token();
  2227. break;
  2228. }
  2229. if (found_center) {
  2230. if (horizontal.has_value() && vertical.has_value())
  2231. return error();
  2232. if (!horizontal.has_value())
  2233. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  2234. if (!vertical.has_value())
  2235. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  2236. }
  2237. if (!horizontal.has_value() && !vertical.has_value())
  2238. return error();
  2239. // Unpack `<edge> <length>`:
  2240. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  2241. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  2242. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  2243. // Split into `x y`
  2244. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  2245. horizontal->offset = zero_offset;
  2246. horizontal->offset_provided = false;
  2247. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  2248. // `y`, reconsume
  2249. vertical->offset = zero_offset;
  2250. vertical->offset_provided = false;
  2251. tokens.reconsume_current_input_token();
  2252. }
  2253. // If only one value is specified, the second value is assumed to be center.
  2254. if (!horizontal.has_value())
  2255. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  2256. if (!vertical.has_value())
  2257. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  2258. return PositionStyleValue::create(
  2259. horizontal->edge, horizontal->offset,
  2260. vertical->edge, vertical->offset);
  2261. }
  2262. RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<StyleComponentValueRule>& tokens)
  2263. {
  2264. auto start_position = tokens.position();
  2265. auto error = [&]() {
  2266. tokens.rewind_to_position(start_position);
  2267. return nullptr;
  2268. };
  2269. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2270. auto value_id = value.to_identifier();
  2271. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2272. };
  2273. auto as_repeat = [](ValueID identifier) {
  2274. switch (identifier) {
  2275. case ValueID::NoRepeat:
  2276. return Repeat::NoRepeat;
  2277. case ValueID::Repeat:
  2278. return Repeat::Repeat;
  2279. case ValueID::Round:
  2280. return Repeat::Round;
  2281. case ValueID::Space:
  2282. return Repeat::Space;
  2283. default:
  2284. VERIFY_NOT_REACHED();
  2285. }
  2286. };
  2287. auto& token = tokens.next_token();
  2288. auto maybe_x_value = parse_css_value(token);
  2289. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_x_value))
  2290. return error();
  2291. auto x_value = maybe_x_value.release_nonnull();
  2292. if (is_directional_repeat(*x_value)) {
  2293. auto value_id = x_value->to_identifier();
  2294. return BackgroundRepeatStyleValue::create(
  2295. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  2296. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  2297. }
  2298. // See if we have a second value for Y
  2299. auto& second_token = tokens.peek_token();
  2300. auto maybe_y_value = parse_css_value(second_token);
  2301. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_y_value)) {
  2302. // We don't have a second value, so use x for both
  2303. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(x_value->to_identifier()));
  2304. }
  2305. tokens.next_token();
  2306. auto y_value = maybe_y_value.release_nonnull();
  2307. if (is_directional_repeat(*y_value))
  2308. return error();
  2309. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(y_value->to_identifier()));
  2310. }
  2311. RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<StyleComponentValueRule>& tokens)
  2312. {
  2313. auto start_position = tokens.position();
  2314. auto error = [&]() {
  2315. tokens.rewind_to_position(start_position);
  2316. return nullptr;
  2317. };
  2318. auto maybe_x_value = parse_css_value(tokens.next_token());
  2319. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_x_value))
  2320. return error();
  2321. auto x_value = maybe_x_value.release_nonnull();
  2322. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain)
  2323. return x_value;
  2324. auto maybe_y_value = parse_css_value(tokens.peek_token());
  2325. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_y_value))
  2326. return BackgroundSizeStyleValue::create(x_value->to_length(), x_value->to_length());
  2327. tokens.next_token();
  2328. auto y_value = maybe_y_value.release_nonnull();
  2329. if (x_value->has_length() && y_value->has_length())
  2330. return BackgroundSizeStyleValue::create(x_value->to_length(), y_value->to_length());
  2331. return error();
  2332. }
  2333. RefPtr<StyleValue> Parser::parse_border_value(Vector<StyleComponentValueRule> const& component_values)
  2334. {
  2335. if (component_values.size() > 3)
  2336. return nullptr;
  2337. RefPtr<StyleValue> border_width;
  2338. RefPtr<StyleValue> border_color;
  2339. RefPtr<StyleValue> border_style;
  2340. for (auto& part : component_values) {
  2341. auto value = parse_css_value(part);
  2342. if (!value)
  2343. return nullptr;
  2344. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  2345. if (border_width)
  2346. return nullptr;
  2347. border_width = value.release_nonnull();
  2348. continue;
  2349. }
  2350. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  2351. if (border_color)
  2352. return nullptr;
  2353. border_color = value.release_nonnull();
  2354. continue;
  2355. }
  2356. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  2357. if (border_style)
  2358. return nullptr;
  2359. border_style = value.release_nonnull();
  2360. continue;
  2361. }
  2362. return nullptr;
  2363. }
  2364. if (!border_width)
  2365. border_width = property_initial_value(PropertyID::BorderWidth);
  2366. if (!border_style)
  2367. border_style = property_initial_value(PropertyID::BorderStyle);
  2368. if (!border_color)
  2369. border_color = property_initial_value(PropertyID::BorderColor);
  2370. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  2371. }
  2372. RefPtr<StyleValue> Parser::parse_border_radius_value(Vector<StyleComponentValueRule> const& component_values)
  2373. {
  2374. if (component_values.size() == 2) {
  2375. auto horizontal = parse_length(component_values[0]);
  2376. auto vertical = parse_length(component_values[1]);
  2377. if (horizontal.has_value() && vertical.has_value())
  2378. return BorderRadiusStyleValue::create(horizontal.value(), vertical.value());
  2379. return nullptr;
  2380. }
  2381. if (component_values.size() == 1) {
  2382. auto radius = parse_length(component_values[0]);
  2383. if (radius.has_value())
  2384. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  2385. return nullptr;
  2386. }
  2387. return nullptr;
  2388. }
  2389. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(Vector<StyleComponentValueRule> const& component_values)
  2390. {
  2391. auto top_left = [&](Vector<Length>& radii) { return radii[0]; };
  2392. auto top_right = [&](Vector<Length>& radii) {
  2393. switch (radii.size()) {
  2394. case 4:
  2395. case 3:
  2396. case 2:
  2397. return radii[1];
  2398. case 1:
  2399. return radii[0];
  2400. default:
  2401. VERIFY_NOT_REACHED();
  2402. }
  2403. };
  2404. auto bottom_right = [&](Vector<Length>& radii) {
  2405. switch (radii.size()) {
  2406. case 4:
  2407. case 3:
  2408. return radii[2];
  2409. case 2:
  2410. case 1:
  2411. return radii[0];
  2412. default:
  2413. VERIFY_NOT_REACHED();
  2414. }
  2415. };
  2416. auto bottom_left = [&](Vector<Length>& radii) {
  2417. switch (radii.size()) {
  2418. case 4:
  2419. return radii[3];
  2420. case 3:
  2421. case 2:
  2422. return radii[1];
  2423. case 1:
  2424. return radii[0];
  2425. default:
  2426. VERIFY_NOT_REACHED();
  2427. }
  2428. };
  2429. Vector<Length> horizontal_radii;
  2430. Vector<Length> vertical_radii;
  2431. bool reading_vertical = false;
  2432. for (auto& value : component_values) {
  2433. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  2434. if (reading_vertical || horizontal_radii.is_empty())
  2435. return nullptr;
  2436. reading_vertical = true;
  2437. continue;
  2438. }
  2439. auto maybe_length = parse_length(value);
  2440. if (!maybe_length.has_value())
  2441. return nullptr;
  2442. if (reading_vertical) {
  2443. vertical_radii.append(maybe_length.value());
  2444. } else {
  2445. horizontal_radii.append(maybe_length.value());
  2446. }
  2447. }
  2448. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2449. || horizontal_radii.is_empty()
  2450. || (reading_vertical && vertical_radii.is_empty()))
  2451. return nullptr;
  2452. NonnullRefPtrVector<StyleValue> border_radii;
  2453. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2454. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  2455. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2456. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  2457. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2458. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  2459. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2460. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  2461. return StyleValueList::create(move(border_radii));
  2462. }
  2463. RefPtr<StyleValue> Parser::parse_box_shadow_value(Vector<StyleComponentValueRule> const& component_values)
  2464. {
  2465. // "none"
  2466. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  2467. auto ident = parse_identifier_value(component_values.first());
  2468. if (ident && ident->to_identifier() == ValueID::None)
  2469. return ident;
  2470. }
  2471. // FIXME: Also support inset, spread-radius and multiple comma-separated box-shadows
  2472. Length offset_x {};
  2473. Length offset_y {};
  2474. Length blur_radius {};
  2475. Color color {};
  2476. if (component_values.size() < 3 || component_values.size() > 4)
  2477. return nullptr;
  2478. auto maybe_x = parse_length(component_values[0]);
  2479. if (!maybe_x.has_value())
  2480. return nullptr;
  2481. offset_x = maybe_x.value();
  2482. auto maybe_y = parse_length(component_values[1]);
  2483. if (!maybe_y.has_value())
  2484. return nullptr;
  2485. offset_y = maybe_y.value();
  2486. if (component_values.size() == 3) {
  2487. auto parsed_color = parse_color(component_values[2]);
  2488. if (!parsed_color.has_value())
  2489. return nullptr;
  2490. color = parsed_color.value();
  2491. } else if (component_values.size() == 4) {
  2492. auto maybe_blur_radius = parse_length(component_values[2]);
  2493. if (!maybe_blur_radius.has_value())
  2494. return nullptr;
  2495. blur_radius = maybe_blur_radius.value();
  2496. auto parsed_color = parse_color(component_values[3]);
  2497. if (!parsed_color.has_value())
  2498. return nullptr;
  2499. color = parsed_color.value();
  2500. }
  2501. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  2502. }
  2503. RefPtr<StyleValue> Parser::parse_flex_value(Vector<StyleComponentValueRule> const& component_values)
  2504. {
  2505. if (component_values.size() == 1) {
  2506. auto value = parse_css_value(component_values[0]);
  2507. if (!value)
  2508. return nullptr;
  2509. switch (value->to_identifier()) {
  2510. case ValueID::Auto: {
  2511. auto one = NumericStyleValue::create_integer(1);
  2512. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  2513. }
  2514. case ValueID::None: {
  2515. auto zero = NumericStyleValue::create_integer(0);
  2516. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  2517. }
  2518. default:
  2519. break;
  2520. }
  2521. }
  2522. RefPtr<StyleValue> flex_grow;
  2523. RefPtr<StyleValue> flex_shrink;
  2524. RefPtr<StyleValue> flex_basis;
  2525. for (size_t i = 0; i < component_values.size(); ++i) {
  2526. auto value = parse_css_value(component_values[i]);
  2527. if (!value)
  2528. return nullptr;
  2529. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  2530. if (value->has_number() && value->to_number() == 0) {
  2531. if (flex_grow && flex_shrink && !flex_basis) {
  2532. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  2533. continue;
  2534. }
  2535. }
  2536. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  2537. if (flex_grow)
  2538. return nullptr;
  2539. flex_grow = value.release_nonnull();
  2540. // Flex-shrink may optionally follow directly after.
  2541. if (i + 1 < component_values.size()) {
  2542. auto second_value = parse_css_value(component_values[i + 1]);
  2543. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  2544. flex_shrink = second_value.release_nonnull();
  2545. i++;
  2546. }
  2547. }
  2548. continue;
  2549. }
  2550. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  2551. if (flex_basis)
  2552. return nullptr;
  2553. flex_basis = value.release_nonnull();
  2554. continue;
  2555. }
  2556. return nullptr;
  2557. }
  2558. if (!flex_grow)
  2559. flex_grow = property_initial_value(PropertyID::FlexGrow);
  2560. if (!flex_shrink)
  2561. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  2562. if (!flex_basis)
  2563. flex_basis = property_initial_value(PropertyID::FlexBasis);
  2564. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  2565. }
  2566. RefPtr<StyleValue> Parser::parse_flex_flow_value(Vector<StyleComponentValueRule> const& component_values)
  2567. {
  2568. if (component_values.size() > 2)
  2569. return nullptr;
  2570. RefPtr<StyleValue> flex_direction;
  2571. RefPtr<StyleValue> flex_wrap;
  2572. for (auto& part : component_values) {
  2573. auto value = parse_css_value(part);
  2574. if (!value)
  2575. return nullptr;
  2576. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  2577. if (flex_direction)
  2578. return nullptr;
  2579. flex_direction = value.release_nonnull();
  2580. continue;
  2581. }
  2582. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  2583. if (flex_wrap)
  2584. return nullptr;
  2585. flex_wrap = value.release_nonnull();
  2586. continue;
  2587. }
  2588. }
  2589. if (!flex_direction)
  2590. flex_direction = property_initial_value(PropertyID::FlexDirection);
  2591. if (!flex_wrap)
  2592. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  2593. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  2594. }
  2595. RefPtr<StyleValue> Parser::parse_font_value(Vector<StyleComponentValueRule> const& component_values)
  2596. {
  2597. RefPtr<StyleValue> font_style;
  2598. RefPtr<StyleValue> font_weight;
  2599. RefPtr<StyleValue> font_size;
  2600. RefPtr<StyleValue> line_height;
  2601. RefPtr<StyleValue> font_families;
  2602. // FIXME: Implement font-stretch and font-variant.
  2603. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  2604. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  2605. // So, we have to handle that separately.
  2606. int normal_count = 0;
  2607. for (size_t i = 0; i < component_values.size(); ++i) {
  2608. auto value = parse_css_value(component_values[i]);
  2609. if (!value)
  2610. return nullptr;
  2611. if (value->to_identifier() == ValueID::Normal) {
  2612. normal_count++;
  2613. continue;
  2614. }
  2615. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  2616. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  2617. if (font_style)
  2618. return nullptr;
  2619. font_style = value.release_nonnull();
  2620. continue;
  2621. }
  2622. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  2623. if (font_weight)
  2624. return nullptr;
  2625. font_weight = value.release_nonnull();
  2626. continue;
  2627. }
  2628. if (property_accepts_value(PropertyID::FontSize, *value)) {
  2629. if (font_size)
  2630. return nullptr;
  2631. font_size = value.release_nonnull();
  2632. // Consume `/ line-height` if present
  2633. if (i + 2 < component_values.size()) {
  2634. auto maybe_solidus = component_values[i + 1];
  2635. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  2636. auto maybe_line_height = parse_css_value(component_values[i + 2]);
  2637. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  2638. return nullptr;
  2639. line_height = maybe_line_height.release_nonnull();
  2640. i += 2;
  2641. }
  2642. }
  2643. // Consume font-families
  2644. auto maybe_font_families = parse_font_family_value(component_values, i + 1);
  2645. if (!maybe_font_families)
  2646. return nullptr;
  2647. font_families = maybe_font_families.release_nonnull();
  2648. break;
  2649. }
  2650. return nullptr;
  2651. }
  2652. // Since normal is the default value for all the properties that can have it, we don't have to actually
  2653. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  2654. // We just need to make sure we were not given more normals than will fit.
  2655. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  2656. if (unset_value_count < normal_count)
  2657. return nullptr;
  2658. if (!font_size || !font_families)
  2659. return nullptr;
  2660. if (!font_style)
  2661. font_style = property_initial_value(PropertyID::FontStyle);
  2662. if (!font_weight)
  2663. font_weight = property_initial_value(PropertyID::FontWeight);
  2664. if (!line_height)
  2665. line_height = property_initial_value(PropertyID::LineHeight);
  2666. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  2667. }
  2668. RefPtr<StyleValue> Parser::parse_font_family_value(Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  2669. {
  2670. auto is_generic_font_family = [](ValueID identifier) -> bool {
  2671. switch (identifier) {
  2672. case ValueID::Cursive:
  2673. case ValueID::Fantasy:
  2674. case ValueID::Monospace:
  2675. case ValueID::Serif:
  2676. case ValueID::SansSerif:
  2677. case ValueID::UiMonospace:
  2678. case ValueID::UiRounded:
  2679. case ValueID::UiSerif:
  2680. case ValueID::UiSansSerif:
  2681. return true;
  2682. default:
  2683. return false;
  2684. }
  2685. };
  2686. auto is_comma_or_eof = [&](size_t i) -> bool {
  2687. if (i < component_values.size()) {
  2688. auto& maybe_comma = component_values[i];
  2689. if (!maybe_comma.is(Token::Type::Comma))
  2690. return false;
  2691. }
  2692. return true;
  2693. };
  2694. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  2695. // eg, these are equivalent:
  2696. // font-family: my cool font\!, serif;
  2697. // font-family: "my cool font!", serif;
  2698. NonnullRefPtrVector<StyleValue> font_families;
  2699. Vector<String> current_name_parts;
  2700. for (size_t i = start_index; i < component_values.size(); ++i) {
  2701. auto& part = component_values[i];
  2702. if (part.is(Token::Type::String)) {
  2703. // `font-family: my cool "font";` is invalid.
  2704. if (!current_name_parts.is_empty())
  2705. return nullptr;
  2706. if (!is_comma_or_eof(i + 1))
  2707. return nullptr;
  2708. font_families.append(StringStyleValue::create(part.token().string()));
  2709. i++;
  2710. continue;
  2711. }
  2712. if (part.is(Token::Type::Ident)) {
  2713. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  2714. auto maybe_ident = parse_css_value(part);
  2715. if (maybe_ident) {
  2716. // CSS-wide keywords are not allowed
  2717. if (maybe_ident->is_builtin())
  2718. return nullptr;
  2719. if (is_generic_font_family(maybe_ident->to_identifier())) {
  2720. // Can't have a generic-font-name as a token in an unquoted font name.
  2721. if (!current_name_parts.is_empty())
  2722. return nullptr;
  2723. if (!is_comma_or_eof(i + 1))
  2724. return nullptr;
  2725. font_families.append(maybe_ident.release_nonnull());
  2726. i++;
  2727. continue;
  2728. }
  2729. }
  2730. current_name_parts.append(part.token().ident());
  2731. continue;
  2732. }
  2733. if (part.is(Token::Type::Comma)) {
  2734. if (current_name_parts.is_empty())
  2735. return nullptr;
  2736. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2737. current_name_parts.clear();
  2738. // Can't have a trailing comma
  2739. if (i + 1 == component_values.size())
  2740. return nullptr;
  2741. continue;
  2742. }
  2743. }
  2744. if (!current_name_parts.is_empty()) {
  2745. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2746. current_name_parts.clear();
  2747. }
  2748. if (font_families.is_empty())
  2749. return nullptr;
  2750. return StyleValueList::create(move(font_families));
  2751. }
  2752. RefPtr<StyleValue> Parser::parse_list_style_value(Vector<StyleComponentValueRule> const& component_values)
  2753. {
  2754. if (component_values.size() > 3)
  2755. return nullptr;
  2756. RefPtr<StyleValue> list_position;
  2757. RefPtr<StyleValue> list_image;
  2758. RefPtr<StyleValue> list_type;
  2759. int found_nones = 0;
  2760. for (auto& part : component_values) {
  2761. auto value = parse_css_value(part);
  2762. if (!value)
  2763. return nullptr;
  2764. if (value->to_identifier() == ValueID::None) {
  2765. found_nones++;
  2766. continue;
  2767. }
  2768. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  2769. if (list_position)
  2770. return nullptr;
  2771. list_position = value.release_nonnull();
  2772. continue;
  2773. }
  2774. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  2775. if (list_image)
  2776. return nullptr;
  2777. list_image = value.release_nonnull();
  2778. continue;
  2779. }
  2780. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  2781. if (list_type)
  2782. return nullptr;
  2783. list_type = value.release_nonnull();
  2784. continue;
  2785. }
  2786. }
  2787. if (found_nones > 2)
  2788. return nullptr;
  2789. if (found_nones == 2) {
  2790. if (list_image || list_type)
  2791. return nullptr;
  2792. auto none = IdentifierStyleValue::create(ValueID::None);
  2793. list_image = none;
  2794. list_type = none;
  2795. } else if (found_nones == 1) {
  2796. if (list_image && list_type)
  2797. return nullptr;
  2798. auto none = IdentifierStyleValue::create(ValueID::None);
  2799. if (!list_image)
  2800. list_image = none;
  2801. if (!list_type)
  2802. list_type = none;
  2803. }
  2804. if (!list_position)
  2805. list_position = property_initial_value(PropertyID::ListStylePosition);
  2806. if (!list_image)
  2807. list_image = property_initial_value(PropertyID::ListStyleImage);
  2808. if (!list_type)
  2809. list_type = property_initial_value(PropertyID::ListStyleType);
  2810. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  2811. }
  2812. RefPtr<StyleValue> Parser::parse_overflow_value(Vector<StyleComponentValueRule> const& component_values)
  2813. {
  2814. if (component_values.size() == 1) {
  2815. auto maybe_value = parse_css_value(component_values.first());
  2816. if (!maybe_value)
  2817. return nullptr;
  2818. auto value = maybe_value.release_nonnull();
  2819. if (property_accepts_value(PropertyID::Overflow, *value))
  2820. return OverflowStyleValue::create(value, value);
  2821. return nullptr;
  2822. }
  2823. if (component_values.size() == 2) {
  2824. auto maybe_x_value = parse_css_value(component_values[0]);
  2825. auto maybe_y_value = parse_css_value(component_values[1]);
  2826. if (!maybe_x_value || !maybe_y_value)
  2827. return nullptr;
  2828. auto x_value = maybe_x_value.release_nonnull();
  2829. auto y_value = maybe_y_value.release_nonnull();
  2830. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  2831. return nullptr;
  2832. }
  2833. return OverflowStyleValue::create(x_value, y_value);
  2834. }
  2835. return nullptr;
  2836. }
  2837. RefPtr<StyleValue> Parser::parse_text_decoration_value(Vector<StyleComponentValueRule> const& component_values)
  2838. {
  2839. if (component_values.size() > 3)
  2840. return nullptr;
  2841. RefPtr<StyleValue> decoration_line;
  2842. RefPtr<StyleValue> decoration_style;
  2843. RefPtr<StyleValue> decoration_color;
  2844. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  2845. for (auto& part : component_values) {
  2846. auto value = parse_css_value(part);
  2847. if (!value)
  2848. return nullptr;
  2849. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  2850. if (decoration_color)
  2851. return nullptr;
  2852. decoration_color = value.release_nonnull();
  2853. continue;
  2854. }
  2855. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  2856. if (decoration_line)
  2857. return nullptr;
  2858. decoration_line = value.release_nonnull();
  2859. continue;
  2860. }
  2861. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  2862. if (decoration_style)
  2863. return nullptr;
  2864. decoration_style = value.release_nonnull();
  2865. continue;
  2866. }
  2867. return nullptr;
  2868. }
  2869. if (!decoration_line)
  2870. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  2871. if (!decoration_style)
  2872. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  2873. if (!decoration_color)
  2874. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  2875. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  2876. }
  2877. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  2878. {
  2879. if (name == "translateY")
  2880. return CSS::TransformFunction::TranslateY;
  2881. return {};
  2882. }
  2883. RefPtr<StyleValue> Parser::parse_transform_value(Vector<StyleComponentValueRule> const& component_values)
  2884. {
  2885. NonnullRefPtrVector<StyleValue> transformations;
  2886. for (auto& part : component_values) {
  2887. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_case("none")) {
  2888. if (!transformations.is_empty())
  2889. return nullptr;
  2890. return IdentifierStyleValue::create(ValueID::None);
  2891. }
  2892. if (!part.is_function())
  2893. return nullptr;
  2894. auto maybe_function = parse_transform_function_name(part.function().name());
  2895. if (!maybe_function.has_value())
  2896. return nullptr;
  2897. NonnullRefPtrVector<StyleValue> values;
  2898. for (auto& value : part.function().values()) {
  2899. if (value.is(Token::Type::Dimension)) {
  2900. auto maybe_length = parse_length(value);
  2901. if (!maybe_length.has_value())
  2902. return nullptr;
  2903. values.append(LengthStyleValue::create(maybe_length.release_value()));
  2904. } else if (value.is(Token::Type::Number)) {
  2905. auto number = parse_numeric_value(value);
  2906. values.append(number.release_nonnull());
  2907. } else {
  2908. dbgln("FIXME: Unsupported value type for transformation!");
  2909. return nullptr;
  2910. }
  2911. }
  2912. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  2913. }
  2914. return StyleValueList::create(move(transformations));
  2915. }
  2916. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2917. {
  2918. auto component_values = parse_as_list_of_component_values();
  2919. auto tokens = TokenStream(component_values);
  2920. auto parsed_value = parse_css_value(property_id, tokens);
  2921. if (parsed_value.is_error())
  2922. return {};
  2923. return parsed_value.release_value();
  2924. }
  2925. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2926. {
  2927. auto block_contains_var = [](StyleBlockRule const& block, auto&& recurse) -> bool {
  2928. for (auto const& token : block.values()) {
  2929. if (token.is_function() && token.function().name().equals_ignoring_case("var"sv))
  2930. return true;
  2931. if (token.is_block() && recurse(token.block(), recurse))
  2932. return true;
  2933. }
  2934. return false;
  2935. };
  2936. m_context.set_current_property_id(property_id);
  2937. Vector<StyleComponentValueRule> component_values;
  2938. bool contains_var = false;
  2939. while (tokens.has_next_token()) {
  2940. auto& token = tokens.next_token();
  2941. if (token.is(Token::Type::Semicolon)) {
  2942. tokens.reconsume_current_input_token();
  2943. break;
  2944. }
  2945. if (property_id != PropertyID::Custom) {
  2946. if (token.is(Token::Type::Whitespace))
  2947. continue;
  2948. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2949. return ParsingResult::IncludesIgnoredVendorPrefix;
  2950. }
  2951. if (!contains_var) {
  2952. if (token.is_function() && token.function().name().equals_ignoring_case("var"sv))
  2953. contains_var = true;
  2954. else if (token.is_block() && block_contains_var(token.block(), block_contains_var))
  2955. contains_var = true;
  2956. }
  2957. component_values.append(token);
  2958. }
  2959. if (property_id == PropertyID::Custom || contains_var)
  2960. return { UnresolvedStyleValue::create(move(component_values), contains_var) };
  2961. if (component_values.is_empty())
  2962. return ParsingResult::SyntaxError;
  2963. if (component_values.size() == 1) {
  2964. if (auto parsed_value = parse_builtin_value(component_values.first()))
  2965. return parsed_value.release_nonnull();
  2966. }
  2967. // Special-case property handling
  2968. switch (property_id) {
  2969. case PropertyID::Background:
  2970. if (auto parsed_value = parse_background_value(component_values))
  2971. return parsed_value.release_nonnull();
  2972. return ParsingResult::SyntaxError;
  2973. case PropertyID::BackgroundAttachment:
  2974. case PropertyID::BackgroundClip:
  2975. case PropertyID::BackgroundImage:
  2976. case PropertyID::BackgroundOrigin:
  2977. if (auto parsed_value = parse_simple_comma_separated_value_list(component_values))
  2978. return parsed_value.release_nonnull();
  2979. return ParsingResult::SyntaxError;
  2980. case PropertyID::BackgroundPosition:
  2981. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); }))
  2982. return parsed_value.release_nonnull();
  2983. return ParsingResult::SyntaxError;
  2984. case PropertyID::BackgroundRepeat:
  2985. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  2986. return parsed_value.release_nonnull();
  2987. return ParsingResult::SyntaxError;
  2988. case PropertyID::BackgroundSize:
  2989. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  2990. return parsed_value.release_nonnull();
  2991. return ParsingResult::SyntaxError;
  2992. case PropertyID::Border:
  2993. case PropertyID::BorderBottom:
  2994. case PropertyID::BorderLeft:
  2995. case PropertyID::BorderRight:
  2996. case PropertyID::BorderTop:
  2997. if (auto parsed_value = parse_border_value(component_values))
  2998. return parsed_value.release_nonnull();
  2999. return ParsingResult::SyntaxError;
  3000. case PropertyID::BorderTopLeftRadius:
  3001. case PropertyID::BorderTopRightRadius:
  3002. case PropertyID::BorderBottomRightRadius:
  3003. case PropertyID::BorderBottomLeftRadius:
  3004. if (auto parsed_value = parse_border_radius_value(component_values))
  3005. return parsed_value.release_nonnull();
  3006. return ParsingResult::SyntaxError;
  3007. case PropertyID::BorderRadius:
  3008. if (auto parsed_value = parse_border_radius_shorthand_value(component_values))
  3009. return parsed_value.release_nonnull();
  3010. return ParsingResult::SyntaxError;
  3011. case PropertyID::BoxShadow:
  3012. if (auto parsed_value = parse_box_shadow_value(component_values))
  3013. return parsed_value.release_nonnull();
  3014. return ParsingResult::SyntaxError;
  3015. case PropertyID::Flex:
  3016. if (auto parsed_value = parse_flex_value(component_values))
  3017. return parsed_value.release_nonnull();
  3018. return ParsingResult::SyntaxError;
  3019. case PropertyID::FlexFlow:
  3020. if (auto parsed_value = parse_flex_flow_value(component_values))
  3021. return parsed_value.release_nonnull();
  3022. return ParsingResult::SyntaxError;
  3023. case PropertyID::Font:
  3024. if (auto parsed_value = parse_font_value(component_values))
  3025. return parsed_value.release_nonnull();
  3026. return ParsingResult::SyntaxError;
  3027. case PropertyID::FontFamily:
  3028. if (auto parsed_value = parse_font_family_value(component_values))
  3029. return parsed_value.release_nonnull();
  3030. return ParsingResult::SyntaxError;
  3031. case PropertyID::ListStyle:
  3032. if (auto parsed_value = parse_list_style_value(component_values))
  3033. return parsed_value.release_nonnull();
  3034. return ParsingResult::SyntaxError;
  3035. case PropertyID::Overflow:
  3036. if (auto parsed_value = parse_overflow_value(component_values))
  3037. return parsed_value.release_nonnull();
  3038. return ParsingResult::SyntaxError;
  3039. case PropertyID::TextDecoration:
  3040. if (auto parsed_value = parse_text_decoration_value(component_values))
  3041. return parsed_value.release_nonnull();
  3042. return ParsingResult::SyntaxError;
  3043. case PropertyID::Transform:
  3044. if (auto parsed_value = parse_transform_value(component_values))
  3045. return parsed_value.release_nonnull();
  3046. return ParsingResult::SyntaxError;
  3047. default:
  3048. break;
  3049. }
  3050. if (component_values.size() == 1) {
  3051. if (auto parsed_value = parse_css_value(component_values.first())) {
  3052. if (property_accepts_value(property_id, *parsed_value))
  3053. return parsed_value.release_nonnull();
  3054. }
  3055. return ParsingResult::SyntaxError;
  3056. }
  3057. // We have multiple values, so treat them as a StyleValueList.
  3058. if (property_maximum_value_count(property_id) > 1) {
  3059. NonnullRefPtrVector<StyleValue> parsed_values;
  3060. for (auto& component_value : component_values) {
  3061. auto parsed_value = parse_css_value(component_value);
  3062. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  3063. return ParsingResult::SyntaxError;
  3064. parsed_values.append(parsed_value.release_nonnull());
  3065. }
  3066. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  3067. return { StyleValueList::create(move(parsed_values)) };
  3068. }
  3069. return ParsingResult::SyntaxError;
  3070. }
  3071. RefPtr<StyleValue> Parser::parse_css_value(StyleComponentValueRule const& component_value)
  3072. {
  3073. if (auto builtin = parse_builtin_value(component_value))
  3074. return builtin;
  3075. if (auto dynamic = parse_dynamic_value(component_value))
  3076. return dynamic;
  3077. // We parse colors before numbers, to catch hashless hex colors.
  3078. if (auto color = parse_color_value(component_value))
  3079. return color;
  3080. if (auto length = parse_length_value(component_value))
  3081. return length;
  3082. if (auto numeric = parse_numeric_value(component_value))
  3083. return numeric;
  3084. if (auto identifier = parse_identifier_value(component_value))
  3085. return identifier;
  3086. if (auto string = parse_string_value(component_value))
  3087. return string;
  3088. if (auto image = parse_image_value(component_value))
  3089. return image;
  3090. return {};
  3091. }
  3092. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  3093. {
  3094. int a = 0;
  3095. int b = 0;
  3096. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3097. if constexpr (CSS_PARSER_DEBUG) {
  3098. dbgln("Invalid An+B value:");
  3099. values.dump_all_tokens();
  3100. }
  3101. return {};
  3102. };
  3103. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3104. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  3105. values.skip_whitespace();
  3106. if (values.has_next_token()) {
  3107. if constexpr (CSS_PARSER_DEBUG) {
  3108. dbgln("Extra tokens at end of An+B value:");
  3109. values.dump_all_tokens();
  3110. }
  3111. return syntax_error();
  3112. } else {
  3113. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  3114. }
  3115. };
  3116. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  3117. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  3118. };
  3119. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  3120. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  3121. };
  3122. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  3123. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  3124. };
  3125. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  3126. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  3127. };
  3128. auto is_delim = [](StyleComponentValueRule const& value, StringView delim) -> bool {
  3129. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  3130. };
  3131. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  3132. if (!value.is(Token::Type::Dimension))
  3133. return false;
  3134. if (value.token().number_type() != Token::NumberType::Integer)
  3135. return false;
  3136. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  3137. return false;
  3138. return true;
  3139. };
  3140. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  3141. if (!value.is(Token::Type::Dimension))
  3142. return false;
  3143. if (value.token().number_type() != Token::NumberType::Integer)
  3144. return false;
  3145. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  3146. return false;
  3147. return true;
  3148. };
  3149. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  3150. if (!value.is(Token::Type::Dimension))
  3151. return false;
  3152. if (value.token().number_type() != Token::NumberType::Integer)
  3153. return false;
  3154. auto dimension_unit = value.token().dimension_unit();
  3155. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3156. return false;
  3157. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  3158. if (!is_ascii_digit(dimension_unit[i]))
  3159. return false;
  3160. }
  3161. return true;
  3162. };
  3163. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3164. if (!value.is(Token::Type::Ident))
  3165. return false;
  3166. auto ident = value.token().ident();
  3167. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3168. return false;
  3169. for (size_t i = 2; i < ident.length(); ++i) {
  3170. if (!is_ascii_digit(ident[i]))
  3171. return false;
  3172. }
  3173. return true;
  3174. };
  3175. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3176. if (!value.is(Token::Type::Ident))
  3177. return false;
  3178. auto ident = value.token().ident();
  3179. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  3180. return false;
  3181. for (size_t i = 3; i < ident.length(); ++i) {
  3182. if (!is_ascii_digit(ident[i]))
  3183. return false;
  3184. }
  3185. return true;
  3186. };
  3187. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  3188. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  3189. };
  3190. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3191. return is_integer(value) && value.token().is_integer_value_signed();
  3192. };
  3193. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3194. return is_integer(value) && !value.token().is_integer_value_signed();
  3195. };
  3196. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  3197. // Unfortunately these can't be in the same order as in the spec.
  3198. values.skip_whitespace();
  3199. auto& first_value = values.next_token();
  3200. // odd | even
  3201. if (first_value.is(Token::Type::Ident)) {
  3202. auto ident = first_value.token().ident();
  3203. if (ident.equals_ignoring_case("odd")) {
  3204. a = 2;
  3205. b = 1;
  3206. return make_return_value();
  3207. } else if (ident.equals_ignoring_case("even")) {
  3208. a = 2;
  3209. return make_return_value();
  3210. }
  3211. }
  3212. // <integer>
  3213. if (is_integer(first_value)) {
  3214. b = first_value.token().to_integer();
  3215. return make_return_value();
  3216. }
  3217. // <n-dimension>
  3218. // <n-dimension> <signed-integer>
  3219. // <n-dimension> ['+' | '-'] <signless-integer>
  3220. if (is_n_dimension(first_value)) {
  3221. a = first_value.token().dimension_value_int();
  3222. values.skip_whitespace();
  3223. auto& second_value = values.next_token();
  3224. if (second_value.is(Token::Type::EndOfFile)) {
  3225. // <n-dimension>
  3226. return make_return_value();
  3227. } else if (is_signed_integer(second_value)) {
  3228. // <n-dimension> <signed-integer>
  3229. b = second_value.token().to_integer();
  3230. return make_return_value();
  3231. }
  3232. values.skip_whitespace();
  3233. auto& third_value = values.next_token();
  3234. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3235. // <n-dimension> ['+' | '-'] <signless-integer>
  3236. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3237. return make_return_value();
  3238. }
  3239. return syntax_error();
  3240. }
  3241. // <ndash-dimension> <signless-integer>
  3242. if (is_ndash_dimension(first_value)) {
  3243. values.skip_whitespace();
  3244. auto& second_value = values.next_token();
  3245. if (is_signless_integer(second_value)) {
  3246. a = first_value.token().dimension_value_int();
  3247. b = -second_value.token().to_integer();
  3248. return make_return_value();
  3249. }
  3250. return syntax_error();
  3251. }
  3252. // <ndashdigit-dimension>
  3253. if (is_ndashdigit_dimension(first_value)) {
  3254. auto& dimension = first_value.token();
  3255. a = dimension.dimension_value_int();
  3256. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  3257. if (maybe_b.has_value()) {
  3258. b = maybe_b.value();
  3259. return make_return_value();
  3260. }
  3261. return syntax_error();
  3262. }
  3263. // <dashndashdigit-ident>
  3264. if (is_dashndashdigit_ident(first_value)) {
  3265. a = -1;
  3266. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  3267. if (maybe_b.has_value()) {
  3268. b = maybe_b.value();
  3269. return make_return_value();
  3270. }
  3271. return syntax_error();
  3272. }
  3273. // -n
  3274. // -n <signed-integer>
  3275. // -n ['+' | '-'] <signless-integer>
  3276. if (is_dashn(first_value)) {
  3277. a = -1;
  3278. values.skip_whitespace();
  3279. auto& second_value = values.next_token();
  3280. if (second_value.is(Token::Type::EndOfFile)) {
  3281. // -n
  3282. return make_return_value();
  3283. } else if (is_signed_integer(second_value)) {
  3284. // -n <signed-integer>
  3285. b = second_value.token().to_integer();
  3286. return make_return_value();
  3287. }
  3288. values.skip_whitespace();
  3289. auto& third_value = values.next_token();
  3290. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3291. // -n ['+' | '-'] <signless-integer>
  3292. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3293. return make_return_value();
  3294. }
  3295. return syntax_error();
  3296. }
  3297. // -n- <signless-integer>
  3298. if (is_dashndash(first_value)) {
  3299. values.skip_whitespace();
  3300. auto& second_value = values.next_token();
  3301. if (is_signless_integer(second_value)) {
  3302. a = -1;
  3303. b = -second_value.token().to_integer();
  3304. return make_return_value();
  3305. }
  3306. return syntax_error();
  3307. }
  3308. // All that's left now are these:
  3309. // '+'?† n
  3310. // '+'?† n <signed-integer>
  3311. // '+'?† n ['+' | '-'] <signless-integer>
  3312. // '+'?† n- <signless-integer>
  3313. // '+'?† <ndashdigit-ident>
  3314. // In all of these cases, the + is optional, and has no effect.
  3315. // So, we just skip the +, and carry on.
  3316. if (!is_delim(first_value, "+"sv)) {
  3317. values.reconsume_current_input_token();
  3318. // We do *not* skip whitespace here.
  3319. }
  3320. auto& first_after_plus = values.next_token();
  3321. // '+'?† n
  3322. // '+'?† n <signed-integer>
  3323. // '+'?† n ['+' | '-'] <signless-integer>
  3324. if (is_n(first_after_plus)) {
  3325. a = 1;
  3326. values.skip_whitespace();
  3327. auto& second_value = values.next_token();
  3328. if (second_value.is(Token::Type::EndOfFile)) {
  3329. // '+'?† n
  3330. return make_return_value();
  3331. } else if (is_signed_integer(second_value)) {
  3332. // '+'?† n <signed-integer>
  3333. b = second_value.token().to_integer();
  3334. return make_return_value();
  3335. }
  3336. values.skip_whitespace();
  3337. auto& third_value = values.next_token();
  3338. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3339. // '+'?† n ['+' | '-'] <signless-integer>
  3340. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3341. return make_return_value();
  3342. }
  3343. return syntax_error();
  3344. }
  3345. // '+'?† n- <signless-integer>
  3346. if (is_ndash(first_after_plus)) {
  3347. values.skip_whitespace();
  3348. auto& second_value = values.next_token();
  3349. if (is_signless_integer(second_value)) {
  3350. a = 1;
  3351. b = -second_value.token().to_integer();
  3352. return make_return_value();
  3353. }
  3354. return syntax_error();
  3355. }
  3356. // '+'?† <ndashdigit-ident>
  3357. if (is_ndashdigit_ident(first_after_plus)) {
  3358. a = 1;
  3359. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  3360. if (maybe_b.has_value()) {
  3361. b = maybe_b.value();
  3362. return make_return_value();
  3363. }
  3364. return syntax_error();
  3365. }
  3366. return syntax_error();
  3367. }
  3368. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(Vector<StyleComponentValueRule> const& values)
  3369. {
  3370. auto tokens = TokenStream(values);
  3371. return parse_calc_sum(tokens);
  3372. }
  3373. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(TokenStream<StyleComponentValueRule>& tokens)
  3374. {
  3375. auto current_token = tokens.next_token();
  3376. if (current_token.is_block() && current_token.block().is_paren()) {
  3377. auto block_values = TokenStream(current_token.block().values());
  3378. auto parsed_calc_sum = parse_calc_sum(block_values);
  3379. if (!parsed_calc_sum)
  3380. return {};
  3381. return CalculatedStyleValue::CalcValue { parsed_calc_sum.release_nonnull() };
  3382. }
  3383. if (current_token.is(Token::Type::Number))
  3384. return CalculatedStyleValue::CalcValue { static_cast<float>(current_token.token().number_value()) };
  3385. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  3386. auto maybe_length = parse_length(current_token);
  3387. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  3388. return CalculatedStyleValue::CalcValue { maybe_length.value() };
  3389. return {};
  3390. }
  3391. return {};
  3392. }
  3393. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3394. {
  3395. // Note: The default value is not used or passed around.
  3396. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  3397. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  3398. CalculatedStyleValue::CalcNumberValue(0));
  3399. tokens.skip_whitespace();
  3400. auto& op_token = tokens.peek_token();
  3401. if (!op_token.is(Token::Type::Delim))
  3402. return nullptr;
  3403. auto op = op_token.token().delim();
  3404. if (op == "*"sv) {
  3405. tokens.next_token();
  3406. tokens.skip_whitespace();
  3407. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  3408. auto parsed_calc_value = parse_calc_value(tokens);
  3409. if (!parsed_calc_value.has_value())
  3410. return nullptr;
  3411. product_with_operator->value = { parsed_calc_value.release_value() };
  3412. } else if (op == "/"sv) {
  3413. tokens.next_token();
  3414. tokens.skip_whitespace();
  3415. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  3416. auto parsed_calc_number_value = parse_calc_number_value(tokens);
  3417. if (!parsed_calc_number_value.has_value())
  3418. return nullptr;
  3419. product_with_operator->value = { parsed_calc_number_value.release_value() };
  3420. } else {
  3421. return nullptr;
  3422. }
  3423. return product_with_operator;
  3424. }
  3425. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3426. {
  3427. // Note: The default value is not used or passed around.
  3428. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  3429. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  3430. CalculatedStyleValue::CalcNumberValue(0));
  3431. tokens.skip_whitespace();
  3432. auto& op_token = tokens.peek_token();
  3433. if (!op_token.is(Token::Type::Delim))
  3434. return nullptr;
  3435. auto op = op_token.token().delim();
  3436. if (op == "*"sv) {
  3437. tokens.next_token();
  3438. tokens.skip_whitespace();
  3439. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  3440. } else if (op == "/"sv) {
  3441. tokens.next_token();
  3442. tokens.skip_whitespace();
  3443. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  3444. } else {
  3445. return nullptr;
  3446. }
  3447. auto parsed_calc_value = parse_calc_number_value(tokens);
  3448. if (!parsed_calc_value.has_value())
  3449. return nullptr;
  3450. number_product_with_operator->value = parsed_calc_value.release_value();
  3451. return number_product_with_operator;
  3452. }
  3453. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(TokenStream<StyleComponentValueRule>& tokens)
  3454. {
  3455. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  3456. CalculatedStyleValue::CalcNumberValue(0),
  3457. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  3458. auto first_calc_number_value_or_error = parse_calc_number_value(tokens);
  3459. if (!first_calc_number_value_or_error.has_value())
  3460. return nullptr;
  3461. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  3462. while (tokens.has_next_token()) {
  3463. auto number_product_with_operator = parse_calc_number_product_part_with_operator(tokens);
  3464. if (!number_product_with_operator)
  3465. break;
  3466. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  3467. }
  3468. return calc_number_product;
  3469. }
  3470. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3471. {
  3472. if (!(tokens.peek_token().is(Token::Type::Delim)
  3473. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3474. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3475. return nullptr;
  3476. auto& token = tokens.next_token();
  3477. tokens.skip_whitespace();
  3478. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  3479. auto delim = token.token().delim();
  3480. if (delim == "+"sv)
  3481. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  3482. else if (delim == "-"sv)
  3483. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  3484. else
  3485. return nullptr;
  3486. auto calc_number_product = parse_calc_number_product(tokens);
  3487. if (!calc_number_product)
  3488. return nullptr;
  3489. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  3490. }
  3491. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(TokenStream<StyleComponentValueRule>& tokens)
  3492. {
  3493. auto first_calc_number_product_or_error = parse_calc_number_product(tokens);
  3494. if (!first_calc_number_product_or_error)
  3495. return nullptr;
  3496. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  3497. while (tokens.has_next_token()) {
  3498. auto calc_sum_part = parse_calc_number_sum_part_with_operator(tokens);
  3499. if (!calc_sum_part)
  3500. return nullptr;
  3501. additional.append(calc_sum_part.release_nonnull());
  3502. }
  3503. tokens.skip_whitespace();
  3504. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  3505. return calc_number_sum;
  3506. }
  3507. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(TokenStream<StyleComponentValueRule>& tokens)
  3508. {
  3509. auto& first = tokens.peek_token();
  3510. if (first.is_block() && first.block().is_paren()) {
  3511. tokens.next_token();
  3512. auto block_values = TokenStream(first.block().values());
  3513. auto calc_number_sum = parse_calc_number_sum(block_values);
  3514. if (calc_number_sum)
  3515. return { calc_number_sum.release_nonnull() };
  3516. }
  3517. if (!first.is(Token::Type::Number))
  3518. return {};
  3519. tokens.next_token();
  3520. return first.token().number_value();
  3521. }
  3522. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(TokenStream<StyleComponentValueRule>& tokens)
  3523. {
  3524. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  3525. CalculatedStyleValue::CalcValue(0),
  3526. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  3527. auto first_calc_value_or_error = parse_calc_value(tokens);
  3528. if (!first_calc_value_or_error.has_value())
  3529. return nullptr;
  3530. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  3531. while (tokens.has_next_token()) {
  3532. auto product_with_operator = parse_calc_product_part_with_operator(tokens);
  3533. if (!product_with_operator)
  3534. break;
  3535. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  3536. }
  3537. return calc_product;
  3538. }
  3539. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3540. {
  3541. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  3542. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  3543. if (!(tokens.peek_token().is(Token::Type::Delim)
  3544. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3545. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3546. return nullptr;
  3547. auto& token = tokens.next_token();
  3548. tokens.skip_whitespace();
  3549. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  3550. auto delim = token.token().delim();
  3551. if (delim == "+"sv)
  3552. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  3553. else if (delim == "-"sv)
  3554. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  3555. else
  3556. return nullptr;
  3557. auto calc_product = parse_calc_product(tokens);
  3558. if (!calc_product)
  3559. return nullptr;
  3560. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  3561. };
  3562. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(TokenStream<StyleComponentValueRule>& tokens)
  3563. {
  3564. auto parsed_calc_product = parse_calc_product(tokens);
  3565. if (!parsed_calc_product)
  3566. return nullptr;
  3567. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  3568. while (tokens.has_next_token()) {
  3569. auto calc_sum_part = parse_calc_sum_part_with_operator(tokens);
  3570. if (!calc_sum_part)
  3571. return nullptr;
  3572. additional.append(calc_sum_part.release_nonnull());
  3573. }
  3574. tokens.skip_whitespace();
  3575. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  3576. }
  3577. bool Parser::has_ignored_vendor_prefix(StringView string)
  3578. {
  3579. if (!string.starts_with('-'))
  3580. return false;
  3581. if (string.starts_with("--"))
  3582. return false;
  3583. if (string.starts_with("-libweb-"))
  3584. return false;
  3585. return true;
  3586. }
  3587. RefPtr<StyleValue> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext const& context, PropertyID property_id, Vector<StyleComponentValueRule> const& tokens)
  3588. {
  3589. if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
  3590. return {};
  3591. CSS::Parser parser(context, "");
  3592. CSS::TokenStream<CSS::StyleComponentValueRule> token_stream { tokens };
  3593. auto result = parser.parse_css_value(property_id, token_stream);
  3594. if (result.is_error())
  3595. return {};
  3596. return result.release_value();
  3597. }
  3598. }
  3599. namespace Web {
  3600. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView css)
  3601. {
  3602. if (css.is_empty())
  3603. return CSS::CSSStyleSheet::create({});
  3604. CSS::Parser parser(context, css);
  3605. return parser.parse_as_stylesheet();
  3606. }
  3607. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView css)
  3608. {
  3609. if (css.is_empty())
  3610. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  3611. CSS::Parser parser(context, css);
  3612. return parser.parse_as_list_of_declarations();
  3613. }
  3614. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
  3615. {
  3616. if (string.is_empty())
  3617. return {};
  3618. CSS::Parser parser(context, string);
  3619. return parser.parse_as_css_value(property_id);
  3620. }
  3621. RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
  3622. {
  3623. CSS::Parser parser(context, css_text);
  3624. return parser.parse_as_rule();
  3625. }
  3626. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView selector_text)
  3627. {
  3628. CSS::Parser parser(context, selector_text);
  3629. return parser.parse_as_selector();
  3630. }
  3631. RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView string)
  3632. {
  3633. CSS::Parser parser(context, string);
  3634. return parser.parse_as_media_query();
  3635. }
  3636. NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView string)
  3637. {
  3638. CSS::Parser parser(context, string);
  3639. return parser.parse_as_media_query_list();
  3640. }
  3641. RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const& context, StringView string)
  3642. {
  3643. if (string.is_empty())
  3644. return {};
  3645. CSS::Parser parser(context, string);
  3646. return parser.parse_as_supports();
  3647. }
  3648. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView string)
  3649. {
  3650. auto integer = string.to_int();
  3651. if (integer.has_value())
  3652. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  3653. return parse_css_value(CSS::ParsingContext(document), string);
  3654. }
  3655. }