Parser.cpp 248 KB

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