Parser.cpp 201 KB

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