Parser.cpp 191 KB

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