Parser.cpp 198 KB

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