Parser.cpp 190 KB

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