Parser.cpp 177 KB

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