Parser.cpp 183 KB

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