Parser.cpp 231 KB

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