Parser.cpp 185 KB

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