Parser.cpp 307 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  6. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  7. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  8. *
  9. * SPDX-License-Identifier: BSD-2-Clause
  10. */
  11. #include <AK/CharacterTypes.h>
  12. #include <AK/Debug.h>
  13. #include <AK/GenericLexer.h>
  14. #include <AK/SourceLocation.h>
  15. #include <AK/TemporaryChange.h>
  16. #include <LibWeb/CSS/CSSFontFaceRule.h>
  17. #include <LibWeb/CSS/CSSImportRule.h>
  18. #include <LibWeb/CSS/CSSKeyframeRule.h>
  19. #include <LibWeb/CSS/CSSKeyframesRule.h>
  20. #include <LibWeb/CSS/CSSMediaRule.h>
  21. #include <LibWeb/CSS/CSSNamespaceRule.h>
  22. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  23. #include <LibWeb/CSS/CSSStyleRule.h>
  24. #include <LibWeb/CSS/CSSStyleSheet.h>
  25. #include <LibWeb/CSS/CSSSupportsRule.h>
  26. #include <LibWeb/CSS/CalculatedOr.h>
  27. #include <LibWeb/CSS/EdgeRect.h>
  28. #include <LibWeb/CSS/MediaList.h>
  29. #include <LibWeb/CSS/Parser/Block.h>
  30. #include <LibWeb/CSS/Parser/ComponentValue.h>
  31. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  32. #include <LibWeb/CSS/Parser/Function.h>
  33. #include <LibWeb/CSS/Parser/Parser.h>
  34. #include <LibWeb/CSS/Parser/Rule.h>
  35. #include <LibWeb/CSS/Selector.h>
  36. #include <LibWeb/CSS/StyleValue.h>
  37. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  38. #include <LibWeb/CSS/StyleValues/BackgroundRepeatStyleValue.h>
  39. #include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h>
  40. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  41. #include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
  42. #include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
  43. #include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
  44. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  45. #include <LibWeb/CSS/StyleValues/EasingStyleValue.h>
  46. #include <LibWeb/CSS/StyleValues/EdgeStyleValue.h>
  47. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  48. #include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
  49. #include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
  50. #include <LibWeb/CSS/StyleValues/GridAutoFlowStyleValue.h>
  51. #include <LibWeb/CSS/StyleValues/GridTemplateAreaStyleValue.h>
  52. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  53. #include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
  54. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  55. #include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
  56. #include <LibWeb/CSS/StyleValues/InheritStyleValue.h>
  57. #include <LibWeb/CSS/StyleValues/InitialStyleValue.h>
  58. #include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
  59. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  60. #include <LibWeb/CSS/StyleValues/MathDepthStyleValue.h>
  61. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  62. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  63. #include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
  64. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  65. #include <LibWeb/CSS/StyleValues/RectStyleValue.h>
  66. #include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
  67. #include <LibWeb/CSS/StyleValues/RevertStyleValue.h>
  68. #include <LibWeb/CSS/StyleValues/ShadowStyleValue.h>
  69. #include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
  70. #include <LibWeb/CSS/StyleValues/StringStyleValue.h>
  71. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  72. #include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
  73. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  74. #include <LibWeb/CSS/StyleValues/URLStyleValue.h>
  75. #include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
  76. #include <LibWeb/CSS/StyleValues/UnsetStyleValue.h>
  77. #include <LibWeb/Dump.h>
  78. #include <LibWeb/Infra/CharacterTypes.h>
  79. #include <LibWeb/Infra/Strings.h>
  80. static void log_parse_error(SourceLocation const& location = SourceLocation::current())
  81. {
  82. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  83. }
  84. namespace Web::CSS::Parser {
  85. static bool contains_single_none_ident(TokenStream<ComponentValue>& tokens)
  86. {
  87. if (tokens.remaining_token_count() > 1)
  88. return false;
  89. if (auto token = tokens.peek_token(); token.is_ident("none"sv))
  90. return true;
  91. return false;
  92. }
  93. ErrorOr<Parser> Parser::create(ParsingContext const& context, StringView input, StringView encoding)
  94. {
  95. auto tokens = TRY(Tokenizer::tokenize(input, encoding));
  96. return Parser { context, move(tokens) };
  97. }
  98. Parser::Parser(ParsingContext const& context, Vector<Token> tokens)
  99. : m_context(context)
  100. , m_tokens(move(tokens))
  101. , m_token_stream(m_tokens)
  102. {
  103. }
  104. Parser::Parser(Parser&& other)
  105. : m_context(other.m_context)
  106. , m_tokens(move(other.m_tokens))
  107. , m_token_stream(m_tokens)
  108. {
  109. // Moving the TokenStream directly from `other` would break it, because TokenStream holds
  110. // a reference to the Vector<Token>, so it would be pointing at the old Parser's tokens.
  111. // So instead, we create a new TokenStream from this Parser's tokens, and then tell it to
  112. // copy the other TokenStream's state. This is quite hacky.
  113. m_token_stream.copy_state({}, other.m_token_stream);
  114. }
  115. // 5.3.3. Parse a stylesheet
  116. // https://www.w3.org/TR/css-syntax-3/#parse-stylesheet
  117. template<typename T>
  118. Parser::ParsedStyleSheet Parser::parse_a_stylesheet(TokenStream<T>& tokens, Optional<AK::URL> location)
  119. {
  120. // To parse a stylesheet from an input given an optional url location:
  121. // 1. If input is a byte stream for stylesheet, decode bytes from input, and set input to the result.
  122. // 2. Normalize input, and set input to the result.
  123. // NOTE: These are done automatically when creating the Parser.
  124. // 3. Create a new stylesheet, with its location set to location (or null, if location was not passed).
  125. ParsedStyleSheet style_sheet;
  126. style_sheet.location = move(location);
  127. // 4. Consume a list of rules from input, with the top-level flag set, and set the stylesheet’s value to the result.
  128. style_sheet.rules = consume_a_list_of_rules(tokens, TopLevel::Yes);
  129. // 5. Return the stylesheet.
  130. return style_sheet;
  131. }
  132. // https://www.w3.org/TR/css-syntax-3/#parse-a-css-stylesheet
  133. CSSStyleSheet* Parser::parse_as_css_stylesheet(Optional<AK::URL> location)
  134. {
  135. // To parse a CSS stylesheet, first parse a stylesheet.
  136. auto style_sheet = parse_a_stylesheet(m_token_stream, {});
  137. // Interpret all of the resulting top-level qualified rules as style rules, defined below.
  138. JS::MarkedVector<CSSRule*> rules(m_context.realm().heap());
  139. for (auto& raw_rule : style_sheet.rules) {
  140. auto* rule = convert_to_rule(raw_rule);
  141. // 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.
  142. if (rule)
  143. rules.append(rule);
  144. }
  145. auto rule_list = CSSRuleList::create(m_context.realm(), rules);
  146. auto media_list = MediaList::create(m_context.realm(), {});
  147. return CSSStyleSheet::create(m_context.realm(), rule_list, media_list, move(location));
  148. }
  149. RefPtr<Supports> Parser::parse_as_supports()
  150. {
  151. return parse_a_supports(m_token_stream);
  152. }
  153. template<typename T>
  154. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  155. {
  156. auto component_values = parse_a_list_of_component_values(tokens);
  157. TokenStream<ComponentValue> token_stream { component_values };
  158. auto maybe_condition = parse_supports_condition(token_stream);
  159. token_stream.skip_whitespace();
  160. if (maybe_condition && !token_stream.has_next_token())
  161. return Supports::create(maybe_condition.release_nonnull());
  162. return {};
  163. }
  164. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<ComponentValue>& tokens)
  165. {
  166. auto transaction = tokens.begin_transaction();
  167. tokens.skip_whitespace();
  168. auto const& peeked_token = tokens.peek_token();
  169. // `not <supports-in-parens>`
  170. if (peeked_token.is_ident("not"sv)) {
  171. tokens.next_token();
  172. tokens.skip_whitespace();
  173. auto child = parse_supports_in_parens(tokens);
  174. if (!child.has_value())
  175. return {};
  176. transaction.commit();
  177. auto condition = make<Supports::Condition>();
  178. condition->type = Supports::Condition::Type::Not;
  179. condition->children.append(child.release_value());
  180. return condition;
  181. }
  182. // ` <supports-in-parens> [ and <supports-in-parens> ]*
  183. // | <supports-in-parens> [ or <supports-in-parens> ]*`
  184. Vector<Supports::InParens> children;
  185. Optional<Supports::Condition::Type> condition_type {};
  186. auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
  187. if (!token.is(Token::Type::Ident))
  188. return {};
  189. auto ident = token.token().ident();
  190. if (ident.equals_ignoring_ascii_case("and"sv))
  191. return Supports::Condition::Type::And;
  192. if (ident.equals_ignoring_ascii_case("or"sv))
  193. return Supports::Condition::Type::Or;
  194. return {};
  195. };
  196. while (tokens.has_next_token()) {
  197. if (!children.is_empty()) {
  198. // Expect `and` or `or` here
  199. auto maybe_combination = as_condition_type(tokens.next_token());
  200. if (!maybe_combination.has_value())
  201. return {};
  202. if (!condition_type.has_value()) {
  203. condition_type = maybe_combination.value();
  204. } else if (maybe_combination != condition_type) {
  205. return {};
  206. }
  207. }
  208. tokens.skip_whitespace();
  209. if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
  210. children.append(in_parens.release_value());
  211. } else {
  212. return {};
  213. }
  214. tokens.skip_whitespace();
  215. }
  216. if (children.is_empty())
  217. return {};
  218. transaction.commit();
  219. auto condition = make<Supports::Condition>();
  220. condition->type = condition_type.value_or(Supports::Condition::Type::Or);
  221. condition->children = move(children);
  222. return condition;
  223. }
  224. Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<ComponentValue>& tokens)
  225. {
  226. // `( <supports-condition> )`
  227. auto const& first_token = tokens.peek_token();
  228. if (first_token.is_block() && first_token.block().is_paren()) {
  229. auto transaction = tokens.begin_transaction();
  230. tokens.next_token();
  231. tokens.skip_whitespace();
  232. TokenStream child_tokens { first_token.block().values() };
  233. if (auto condition = parse_supports_condition(child_tokens)) {
  234. if (child_tokens.has_next_token())
  235. return {};
  236. transaction.commit();
  237. return Supports::InParens {
  238. .value = { condition.release_nonnull() }
  239. };
  240. }
  241. }
  242. // `<supports-feature>`
  243. if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
  244. return Supports::InParens {
  245. .value = { feature.release_value() }
  246. };
  247. }
  248. // `<general-enclosed>`
  249. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  250. return Supports::InParens {
  251. .value = general_enclosed.release_value()
  252. };
  253. }
  254. return {};
  255. }
  256. Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<ComponentValue>& tokens)
  257. {
  258. auto transaction = tokens.begin_transaction();
  259. tokens.skip_whitespace();
  260. auto const& first_token = tokens.next_token();
  261. // `<supports-decl>`
  262. if (first_token.is_block() && first_token.block().is_paren()) {
  263. TokenStream block_tokens { first_token.block().values() };
  264. // FIXME: Parsing and then converting back to a string is weird.
  265. if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
  266. transaction.commit();
  267. return Supports::Feature {
  268. Supports::Declaration { declaration->to_string(), JS::make_handle(m_context.realm()) }
  269. };
  270. }
  271. }
  272. // `<supports-selector-fn>`
  273. if (first_token.is_function("selector"sv)) {
  274. // FIXME: Parsing and then converting back to a string is weird.
  275. StringBuilder builder;
  276. for (auto const& item : first_token.function().values())
  277. builder.append(item.to_string());
  278. transaction.commit();
  279. return Supports::Feature {
  280. Supports::Selector { builder.to_string().release_value_but_fixme_should_propagate_errors(), JS::make_handle(m_context.realm()) }
  281. };
  282. }
  283. return {};
  284. }
  285. // https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
  286. Optional<GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<ComponentValue>& tokens)
  287. {
  288. auto transaction = tokens.begin_transaction();
  289. tokens.skip_whitespace();
  290. auto const& first_token = tokens.next_token();
  291. // `[ <function-token> <any-value>? ) ]`
  292. if (first_token.is_function()) {
  293. transaction.commit();
  294. return GeneralEnclosed { first_token.to_string() };
  295. }
  296. // `( <any-value>? )`
  297. if (first_token.is_block() && first_token.block().is_paren()) {
  298. transaction.commit();
  299. return GeneralEnclosed { first_token.to_string() };
  300. }
  301. return {};
  302. }
  303. // 5.4.1. Consume a list of rules
  304. // https://www.w3.org/TR/css-syntax-3/#consume-list-of-rules
  305. template<typename T>
  306. Vector<NonnullRefPtr<Rule>> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, TopLevel top_level)
  307. {
  308. // To consume a list of rules, given a top-level flag:
  309. // Create an initially empty list of rules.
  310. Vector<NonnullRefPtr<Rule>> rules;
  311. // Repeatedly consume the next input token:
  312. for (;;) {
  313. auto& token = tokens.next_token();
  314. // <whitespace-token>
  315. if (token.is(Token::Type::Whitespace)) {
  316. // Do nothing.
  317. continue;
  318. }
  319. // <EOF-token>
  320. if (token.is(Token::Type::EndOfFile)) {
  321. // Return the list of rules.
  322. return rules;
  323. }
  324. // <CDO-token>
  325. // <CDC-token>
  326. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  327. // If the top-level flag is set, do nothing.
  328. if (top_level == TopLevel::Yes)
  329. continue;
  330. // Otherwise, reconsume the current input token.
  331. tokens.reconsume_current_input_token();
  332. // Consume a qualified rule. If anything is returned, append it to the list of rules.
  333. if (auto maybe_qualified = consume_a_qualified_rule(tokens))
  334. rules.append(maybe_qualified.release_nonnull());
  335. continue;
  336. }
  337. // <at-keyword-token>
  338. if (token.is(Token::Type::AtKeyword)) {
  339. // Reconsume the current input token.
  340. tokens.reconsume_current_input_token();
  341. // Consume an at-rule, and append the returned value to the list of rules.
  342. rules.append(consume_an_at_rule(tokens));
  343. continue;
  344. }
  345. // anything else
  346. {
  347. // Reconsume the current input token.
  348. tokens.reconsume_current_input_token();
  349. // Consume a qualified rule. If anything is returned, append it to the list of rules.
  350. if (auto maybe_qualified = consume_a_qualified_rule(tokens))
  351. rules.append(maybe_qualified.release_nonnull());
  352. continue;
  353. }
  354. }
  355. }
  356. // 5.4.2. Consume an at-rule
  357. // https://www.w3.org/TR/css-syntax-3/#consume-at-rule
  358. template<typename T>
  359. NonnullRefPtr<Rule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  360. {
  361. // To consume an at-rule:
  362. // Consume the next input token.
  363. auto& name_ident = tokens.next_token();
  364. VERIFY(name_ident.is(Token::Type::AtKeyword));
  365. // 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.
  366. // NOTE: We create the Rule fully initialized when we return it instead.
  367. auto at_rule_name = ((Token)name_ident).at_keyword();
  368. Vector<ComponentValue> prelude;
  369. RefPtr<Block> block;
  370. // Repeatedly consume the next input token:
  371. for (;;) {
  372. auto& token = tokens.next_token();
  373. // <semicolon-token>
  374. if (token.is(Token::Type::Semicolon)) {
  375. // Return the at-rule.
  376. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  377. }
  378. // <EOF-token>
  379. if (token.is(Token::Type::EndOfFile)) {
  380. // This is a parse error. Return the at-rule.
  381. log_parse_error();
  382. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  383. }
  384. // <{-token>
  385. if (token.is(Token::Type::OpenCurly)) {
  386. // Consume a simple block and assign it to the at-rule’s block. Return the at-rule.
  387. block = consume_a_simple_block(tokens);
  388. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  389. }
  390. // simple block with an associated token of <{-token>
  391. if constexpr (IsSame<T, ComponentValue>) {
  392. ComponentValue const& component_value = token;
  393. if (component_value.is_block() && component_value.block().is_curly()) {
  394. // Assign the block to the at-rule’s block. Return the at-rule.
  395. block = component_value.block();
  396. return Rule::make_at_rule(move(at_rule_name), move(prelude), move(block));
  397. }
  398. }
  399. // anything else
  400. {
  401. // Reconsume the current input token.
  402. tokens.reconsume_current_input_token();
  403. // Consume a component value. Append the returned value to the at-rule’s prelude.
  404. prelude.append(consume_a_component_value(tokens));
  405. }
  406. }
  407. }
  408. // 5.4.3. Consume a qualified rule
  409. // https://www.w3.org/TR/css-syntax-3/#consume-qualified-rule
  410. template<typename T>
  411. RefPtr<Rule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  412. {
  413. // To consume a qualified rule:
  414. // Create a new qualified rule with its prelude initially set to an empty list, and its value initially set to nothing.
  415. // NOTE: We create the Rule fully initialized when we return it instead.
  416. Vector<ComponentValue> prelude;
  417. RefPtr<Block> block;
  418. // Repeatedly consume the next input token:
  419. for (;;) {
  420. auto& token = tokens.next_token();
  421. // <EOF-token>
  422. if (token.is(Token::Type::EndOfFile)) {
  423. // This is a parse error. Return nothing.
  424. log_parse_error();
  425. return {};
  426. }
  427. // <{-token>
  428. if (token.is(Token::Type::OpenCurly)) {
  429. // Consume a simple block and assign it to the qualified rule’s block. Return the qualified rule.
  430. block = consume_a_simple_block(tokens);
  431. return Rule::make_qualified_rule(move(prelude), move(block));
  432. }
  433. // simple block with an associated token of <{-token>
  434. if constexpr (IsSame<T, ComponentValue>) {
  435. ComponentValue const& component_value = token;
  436. if (component_value.is_block() && component_value.block().is_curly()) {
  437. // Assign the block to the qualified rule’s block. Return the qualified rule.
  438. block = component_value.block();
  439. return Rule::make_qualified_rule(move(prelude), move(block));
  440. }
  441. }
  442. // anything else
  443. {
  444. // Reconsume the current input token.
  445. tokens.reconsume_current_input_token();
  446. // Consume a component value. Append the returned value to the qualified rule’s prelude.
  447. prelude.append(consume_a_component_value(tokens));
  448. }
  449. }
  450. }
  451. // 5.4.4. Consume a style block’s contents
  452. // https://www.w3.org/TR/css-syntax-3/#consume-a-style-blocks-contents
  453. template<typename T>
  454. Vector<DeclarationOrAtRule> Parser::consume_a_style_blocks_contents(TokenStream<T>& tokens)
  455. {
  456. // To consume a style block’s contents:
  457. // Create an initially empty list of declarations decls, and an initially empty list of rules rules.
  458. Vector<DeclarationOrAtRule> declarations;
  459. Vector<DeclarationOrAtRule> rules;
  460. // Repeatedly consume the next input token:
  461. for (;;) {
  462. auto& token = tokens.next_token();
  463. // <whitespace-token>
  464. // <semicolon-token>
  465. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  466. // Do nothing.
  467. continue;
  468. }
  469. // <EOF-token>
  470. if (token.is(Token::Type::EndOfFile)) {
  471. // Extend decls with rules, then return decls.
  472. declarations.extend(move(rules));
  473. return declarations;
  474. }
  475. // <at-keyword-token>
  476. if (token.is(Token::Type::AtKeyword)) {
  477. // Reconsume the current input token.
  478. tokens.reconsume_current_input_token();
  479. // Consume an at-rule, and append the result to rules.
  480. rules.empend(consume_an_at_rule(tokens));
  481. continue;
  482. }
  483. // <ident-token>
  484. if (token.is(Token::Type::Ident)) {
  485. // Initialize a temporary list initially filled with the current input token.
  486. Vector<ComponentValue> temporary_list;
  487. temporary_list.append(token);
  488. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  489. // consume a component value and append it to the temporary list.
  490. for (;;) {
  491. auto& next_input_token = tokens.peek_token();
  492. if (next_input_token.is(Token::Type::Semicolon) || next_input_token.is(Token::Type::EndOfFile))
  493. break;
  494. temporary_list.append(consume_a_component_value(tokens));
  495. }
  496. // Consume a declaration from the temporary list. If anything was returned, append it to decls.
  497. auto token_stream = TokenStream(temporary_list);
  498. if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
  499. declarations.empend(maybe_declaration.release_value());
  500. continue;
  501. }
  502. // <delim-token> with a value of "&" (U+0026 AMPERSAND)
  503. if (token.is_delim('&')) {
  504. // Reconsume the current input token.
  505. tokens.reconsume_current_input_token();
  506. // Consume a qualified rule. If anything was returned, append it to rules.
  507. if (auto qualified_rule = consume_a_qualified_rule(tokens))
  508. rules.empend(qualified_rule);
  509. continue;
  510. }
  511. // anything else
  512. {
  513. // This is a parse error.
  514. log_parse_error();
  515. // Reconsume the current input token.
  516. tokens.reconsume_current_input_token();
  517. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  518. // consume a component value and throw away the returned value.
  519. for (;;) {
  520. auto& peek = tokens.peek_token();
  521. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  522. break;
  523. (void)consume_a_component_value(tokens);
  524. }
  525. }
  526. }
  527. }
  528. template<>
  529. ComponentValue Parser::consume_a_component_value(TokenStream<ComponentValue>& tokens)
  530. {
  531. // Note: This overload is called once tokens have already been converted into component values,
  532. // so we do not need to do the work in the more general overload.
  533. return tokens.next_token();
  534. }
  535. // 5.4.7. Consume a component value
  536. // https://www.w3.org/TR/css-syntax-3/#consume-component-value
  537. template<typename T>
  538. ComponentValue Parser::consume_a_component_value(TokenStream<T>& tokens)
  539. {
  540. // To consume a component value:
  541. // Consume the next input token.
  542. auto& token = tokens.next_token();
  543. // If the current input token is a <{-token>, <[-token>, or <(-token>, consume a simple block and return it.
  544. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  545. return ComponentValue(consume_a_simple_block(tokens));
  546. // Otherwise, if the current input token is a <function-token>, consume a function and return it.
  547. if (token.is(Token::Type::Function))
  548. return ComponentValue(consume_a_function(tokens));
  549. // Otherwise, return the current input token.
  550. return ComponentValue(token);
  551. }
  552. // 5.4.8. Consume a simple block
  553. // https://www.w3.org/TR/css-syntax-3/#consume-simple-block
  554. template<typename T>
  555. NonnullRefPtr<Block> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  556. {
  557. // Note: This algorithm assumes that the current input token has already been checked
  558. // to be an <{-token>, <[-token>, or <(-token>.
  559. // To consume a simple block:
  560. // The ending token is the mirror variant of the current input token.
  561. // (E.g. if it was called with <[-token>, the ending token is <]-token>.)
  562. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  563. // Create a simple block with its associated token set to the current input token
  564. // and with its value initially set to an empty list.
  565. // NOTE: We create the Block fully initialized when we return it instead.
  566. Token block_token = tokens.current_token();
  567. Vector<ComponentValue> block_values;
  568. // Repeatedly consume the next input token and process it as follows:
  569. for (;;) {
  570. auto& token = tokens.next_token();
  571. // ending token
  572. if (token.is(ending_token)) {
  573. // Return the block.
  574. return Block::create(move(block_token), move(block_values));
  575. }
  576. // <EOF-token>
  577. if (token.is(Token::Type::EndOfFile)) {
  578. // This is a parse error. Return the block.
  579. log_parse_error();
  580. return Block::create(move(block_token), move(block_values));
  581. }
  582. // anything else
  583. {
  584. // Reconsume the current input token.
  585. tokens.reconsume_current_input_token();
  586. // Consume a component value and append it to the value of the block.
  587. block_values.empend(consume_a_component_value(tokens));
  588. }
  589. }
  590. }
  591. // 5.4.9. Consume a function
  592. // https://www.w3.org/TR/css-syntax-3/#consume-function
  593. template<typename T>
  594. NonnullRefPtr<Function> Parser::consume_a_function(TokenStream<T>& tokens)
  595. {
  596. // Note: This algorithm assumes that the current input token has already been checked to be a <function-token>.
  597. auto name_ident = tokens.current_token();
  598. VERIFY(name_ident.is(Token::Type::Function));
  599. // To consume a function:
  600. // Create a function with its name equal to the value of the current input token
  601. // and with its value initially set to an empty list.
  602. // NOTE: We create the Function fully initialized when we return it instead.
  603. auto function_name = ((Token)name_ident).function();
  604. Vector<ComponentValue> function_values;
  605. // Repeatedly consume the next input token and process it as follows:
  606. for (;;) {
  607. auto& token = tokens.next_token();
  608. // <)-token>
  609. if (token.is(Token::Type::CloseParen)) {
  610. // Return the function.
  611. return Function::create(move(function_name), move(function_values));
  612. }
  613. // <EOF-token>
  614. if (token.is(Token::Type::EndOfFile)) {
  615. // This is a parse error. Return the function.
  616. log_parse_error();
  617. return Function::create(move(function_name), move(function_values));
  618. }
  619. // anything else
  620. {
  621. // Reconsume the current input token.
  622. tokens.reconsume_current_input_token();
  623. // Consume a component value and append the returned value to the function’s value.
  624. function_values.append(consume_a_component_value(tokens));
  625. }
  626. }
  627. }
  628. // 5.4.6. Consume a declaration
  629. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  630. template<typename T>
  631. Optional<Declaration> Parser::consume_a_declaration(TokenStream<T>& tokens)
  632. {
  633. // Note: This algorithm assumes that the next input token has already been checked to
  634. // be an <ident-token>.
  635. // NOTE: This is not true in our implementation! For convenience, we both skip whitespace
  636. // and gracefully handle the first token not being an <ident-token>.
  637. // To consume a declaration:
  638. // Consume the next input token.
  639. auto transaction = tokens.begin_transaction();
  640. tokens.skip_whitespace();
  641. auto& token = tokens.next_token();
  642. // NOTE: Not to spec, handle the case where the input token *isn't* an <ident-token>.
  643. if (!token.is(Token::Type::Ident))
  644. return {};
  645. // Create a new declaration with its name set to the value of the current input token
  646. // and its value initially set to the empty list.
  647. // NOTE: We create a fully-initialized Declaration just before returning it instead.
  648. auto declaration_name = ((Token)token).ident();
  649. Vector<ComponentValue> declaration_values;
  650. Important declaration_important = Important::No;
  651. // 1. While the next input token is a <whitespace-token>, consume the next input token.
  652. tokens.skip_whitespace();
  653. // 2. If the next input token is anything other than a <colon-token>, this is a parse error.
  654. // Return nothing.
  655. auto& maybe_colon = tokens.peek_token();
  656. if (!maybe_colon.is(Token::Type::Colon)) {
  657. log_parse_error();
  658. return {};
  659. }
  660. // Otherwise, consume the next input token.
  661. tokens.next_token();
  662. // 3. While the next input token is a <whitespace-token>, consume the next input token.
  663. tokens.skip_whitespace();
  664. // 4. As long as the next input token is anything other than an <EOF-token>, consume a
  665. // component value and append it to the declaration’s value.
  666. for (;;) {
  667. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  668. break;
  669. }
  670. declaration_values.append(consume_a_component_value(tokens));
  671. }
  672. // 5. If the last two non-<whitespace-token>s in the declaration’s value are a <delim-token>
  673. // with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive
  674. // match for "important", remove them from the declaration’s value and set the declaration’s
  675. // important flag to true.
  676. if (declaration_values.size() >= 2) {
  677. // Walk backwards from the end until we find "important"
  678. Optional<size_t> important_index;
  679. for (size_t i = declaration_values.size() - 1; i > 0; i--) {
  680. auto value = declaration_values[i];
  681. if (value.is_ident("important"sv)) {
  682. important_index = i;
  683. break;
  684. }
  685. if (value.is(Token::Type::Whitespace))
  686. continue;
  687. break;
  688. }
  689. // Walk backwards from important until we find "!"
  690. if (important_index.has_value()) {
  691. Optional<size_t> bang_index;
  692. for (size_t i = important_index.value() - 1; i > 0; i--) {
  693. auto value = declaration_values[i];
  694. if (value.is_delim('!')) {
  695. bang_index = i;
  696. break;
  697. }
  698. if (value.is(Token::Type::Whitespace))
  699. continue;
  700. break;
  701. }
  702. if (bang_index.has_value()) {
  703. declaration_values.remove(important_index.value());
  704. declaration_values.remove(bang_index.value());
  705. declaration_important = Important::Yes;
  706. }
  707. }
  708. }
  709. // 6. While the last token in the declaration’s value is a <whitespace-token>, remove that token.
  710. while (!declaration_values.is_empty()) {
  711. auto maybe_whitespace = declaration_values.last();
  712. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  713. break;
  714. }
  715. declaration_values.take_last();
  716. }
  717. // 7. Return the declaration.
  718. transaction.commit();
  719. return Declaration { move(declaration_name), move(declaration_values), declaration_important };
  720. }
  721. // 5.4.5. Consume a list of declarations
  722. // https://www.w3.org/TR/css-syntax-3/#consume-list-of-declarations
  723. template<typename T>
  724. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  725. {
  726. // To consume a list of declarations:
  727. // Create an initially empty list of declarations.
  728. Vector<DeclarationOrAtRule> list_of_declarations;
  729. // Repeatedly consume the next input token:
  730. for (;;) {
  731. auto& token = tokens.next_token();
  732. // <whitespace-token>
  733. // <semicolon-token>
  734. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  735. // Do nothing.
  736. continue;
  737. }
  738. // <EOF-token>
  739. if (token.is(Token::Type::EndOfFile)) {
  740. // Return the list of declarations.
  741. return list_of_declarations;
  742. }
  743. // <at-keyword-token>
  744. if (token.is(Token::Type::AtKeyword)) {
  745. // Reconsume the current input token.
  746. tokens.reconsume_current_input_token();
  747. // Consume an at-rule. Append the returned rule to the list of declarations.
  748. list_of_declarations.empend(consume_an_at_rule(tokens));
  749. continue;
  750. }
  751. // <ident-token>
  752. if (token.is(Token::Type::Ident)) {
  753. // Initialize a temporary list initially filled with the current input token.
  754. Vector<ComponentValue> temporary_list;
  755. temporary_list.append(token);
  756. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  757. // consume a component value and append it to the temporary list.
  758. for (;;) {
  759. auto& peek = tokens.peek_token();
  760. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  761. break;
  762. temporary_list.append(consume_a_component_value(tokens));
  763. }
  764. // Consume a declaration from the temporary list. If anything was returned, append it to the list of declarations.
  765. auto token_stream = TokenStream(temporary_list);
  766. if (auto maybe_declaration = consume_a_declaration(token_stream); maybe_declaration.has_value())
  767. list_of_declarations.empend(maybe_declaration.value());
  768. continue;
  769. }
  770. // anything else
  771. {
  772. // This is a parse error.
  773. log_parse_error();
  774. // Reconsume the current input token.
  775. tokens.reconsume_current_input_token();
  776. // As long as the next input token is anything other than a <semicolon-token> or <EOF-token>,
  777. // consume a component value and throw away the returned value.
  778. for (;;) {
  779. auto& peek = tokens.peek_token();
  780. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  781. break;
  782. dbgln_if(CSS_PARSER_DEBUG, "Discarding token: '{}'", peek.to_debug_string());
  783. (void)consume_a_component_value(tokens);
  784. }
  785. }
  786. }
  787. }
  788. CSSRule* Parser::parse_as_css_rule()
  789. {
  790. auto maybe_rule = parse_a_rule(m_token_stream);
  791. if (maybe_rule)
  792. return convert_to_rule(maybe_rule.release_nonnull());
  793. return {};
  794. }
  795. // 5.3.5. Parse a rule
  796. // https://www.w3.org/TR/css-syntax-3/#parse-rule
  797. template<typename T>
  798. RefPtr<Rule> Parser::parse_a_rule(TokenStream<T>& tokens)
  799. {
  800. // To parse a rule from input:
  801. RefPtr<Rule> rule;
  802. // 1. Normalize input, and set input to the result.
  803. // Note: This is done when initializing the Parser.
  804. // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  805. tokens.skip_whitespace();
  806. // 3. If the next input token from input is an <EOF-token>, return a syntax error.
  807. auto& token = tokens.peek_token();
  808. if (token.is(Token::Type::EndOfFile)) {
  809. return {};
  810. }
  811. // 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.
  812. else if (token.is(Token::Type::AtKeyword)) {
  813. rule = consume_an_at_rule(m_token_stream);
  814. }
  815. // Otherwise, consume a qualified rule from input and let rule be the return value. If nothing was returned, return a syntax error.
  816. else {
  817. auto qualified_rule = consume_a_qualified_rule(tokens);
  818. if (!qualified_rule)
  819. return {};
  820. rule = qualified_rule;
  821. }
  822. // 4. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  823. tokens.skip_whitespace();
  824. // 5. If the next input token from input is an <EOF-token>, return rule. Otherwise, return a syntax error.
  825. if (tokens.peek_token().is(Token::Type::EndOfFile))
  826. return rule;
  827. return {};
  828. }
  829. // 5.3.4. Parse a list of rules
  830. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-rules
  831. template<typename T>
  832. Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  833. {
  834. // To parse a list of rules from input:
  835. // 1. Normalize input, and set input to the result.
  836. // Note: This is done when initializing the Parser.
  837. // 2. Consume a list of rules from the input, with the top-level flag unset.
  838. auto list_of_rules = consume_a_list_of_rules(tokens, TopLevel::No);
  839. // 3. Return the returned list.
  840. return list_of_rules;
  841. }
  842. template Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<Token>& tokens);
  843. template Vector<NonnullRefPtr<Rule>> Parser::parse_a_list_of_rules(TokenStream<ComponentValue>& tokens);
  844. Optional<StyleProperty> Parser::parse_as_supports_condition()
  845. {
  846. auto maybe_declaration = parse_a_declaration(m_token_stream);
  847. if (maybe_declaration.has_value())
  848. return convert_to_style_property(maybe_declaration.release_value());
  849. return {};
  850. }
  851. // 5.3.6. Parse a declaration
  852. // https://www.w3.org/TR/css-syntax-3/#parse-a-declaration
  853. template<typename T>
  854. Optional<Declaration> Parser::parse_a_declaration(TokenStream<T>& tokens)
  855. {
  856. // To parse a declaration from input:
  857. // 1. Normalize input, and set input to the result.
  858. // Note: This is done when initializing the Parser.
  859. // 2. While the next input token from input is a <whitespace-token>, consume the next input token.
  860. tokens.skip_whitespace();
  861. // 3. If the next input token from input is not an <ident-token>, return a syntax error.
  862. auto& token = tokens.peek_token();
  863. if (!token.is(Token::Type::Ident)) {
  864. return {};
  865. }
  866. // 4. Consume a declaration from input. If anything was returned, return it. Otherwise, return a syntax error.
  867. if (auto declaration = consume_a_declaration(tokens); declaration.has_value())
  868. return declaration.release_value();
  869. return {};
  870. }
  871. // 5.3.7. Parse a style block’s contents
  872. // https://www.w3.org/TR/css-syntax-3/#parse-style-blocks-contents
  873. template<typename T>
  874. Vector<DeclarationOrAtRule> Parser::parse_a_style_blocks_contents(TokenStream<T>& tokens)
  875. {
  876. // To parse a style block’s contents from input:
  877. // 1. Normalize input, and set input to the result.
  878. // Note: This is done when initializing the Parser.
  879. // 2. Consume a style block’s contents from input, and return the result.
  880. return consume_a_style_blocks_contents(tokens);
  881. }
  882. // 5.3.8. Parse a list of declarations
  883. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-declarations
  884. template<typename T>
  885. Vector<DeclarationOrAtRule> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  886. {
  887. // To parse a list of declarations from input:
  888. // 1. Normalize input, and set input to the result.
  889. // Note: This is done when initializing the Parser.
  890. // 2. Consume a list of declarations from input, and return the result.
  891. return consume_a_list_of_declarations(tokens);
  892. }
  893. Optional<ComponentValue> Parser::parse_as_component_value()
  894. {
  895. return parse_a_component_value(m_token_stream);
  896. }
  897. // 5.3.9. Parse a component value
  898. // https://www.w3.org/TR/css-syntax-3/#parse-component-value
  899. template<typename T>
  900. Optional<ComponentValue> Parser::parse_a_component_value(TokenStream<T>& tokens)
  901. {
  902. // To parse a component value from input:
  903. // 1. Normalize input, and set input to the result.
  904. // Note: This is done when initializing the Parser.
  905. // 2. While the next input token from input is a <whitespace-token>, consume the next input token from input.
  906. tokens.skip_whitespace();
  907. // 3. If the next input token from input is an <EOF-token>, return a syntax error.
  908. if (tokens.peek_token().is(Token::Type::EndOfFile))
  909. return {};
  910. // 4. Consume a component value from input and let value be the return value.
  911. auto value = consume_a_component_value(tokens);
  912. // 5. While the next input token from input is a <whitespace-token>, consume the next input token.
  913. tokens.skip_whitespace();
  914. // 6. If the next input token from input is an <EOF-token>, return value. Otherwise, return a syntax error.
  915. if (tokens.peek_token().is(Token::Type::EndOfFile))
  916. return value;
  917. return {};
  918. }
  919. // 5.3.10. Parse a list of component values
  920. // https://www.w3.org/TR/css-syntax-3/#parse-list-of-component-values
  921. template<typename T>
  922. Vector<ComponentValue> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  923. {
  924. // To parse a list of component values from input:
  925. // 1. Normalize input, and set input to the result.
  926. // Note: This is done when initializing the Parser.
  927. // 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.
  928. Vector<ComponentValue> component_values;
  929. for (;;) {
  930. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  931. break;
  932. }
  933. component_values.append(consume_a_component_value(tokens));
  934. }
  935. return component_values;
  936. }
  937. // 5.3.11. Parse a comma-separated list of component values
  938. // https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values
  939. template<typename T>
  940. Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  941. {
  942. // To parse a comma-separated list of component values from input:
  943. // 1. Normalize input, and set input to the result.
  944. // Note: This is done when initializing the Parser.
  945. // 2. Let list of cvls be an initially empty list of component value lists.
  946. Vector<Vector<ComponentValue>> list_of_component_value_lists;
  947. // 3. Repeatedly consume a component value from input until an <EOF-token> or <comma-token> is returned,
  948. // appending the returned values (except the final <EOF-token> or <comma-token>) into a list.
  949. // Append the list to list of cvls.
  950. // If it was a <comma-token> that was returned, repeat this step.
  951. Vector<ComponentValue> current_list;
  952. for (;;) {
  953. auto component_value = consume_a_component_value(tokens);
  954. if (component_value.is(Token::Type::EndOfFile)) {
  955. list_of_component_value_lists.append(move(current_list));
  956. break;
  957. }
  958. if (component_value.is(Token::Type::Comma)) {
  959. list_of_component_value_lists.append(move(current_list));
  960. current_list = {};
  961. continue;
  962. }
  963. current_list.append(component_value);
  964. }
  965. // 4. Return list of cvls.
  966. return list_of_component_value_lists;
  967. }
  968. template Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<ComponentValue>&);
  969. template Vector<Vector<ComponentValue>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<Token>&);
  970. ElementInlineCSSStyleDeclaration* Parser::parse_as_style_attribute(DOM::Element& element)
  971. {
  972. auto declarations_and_at_rules = parse_a_list_of_declarations(m_token_stream);
  973. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  974. return ElementInlineCSSStyleDeclaration::create(element, move(properties), move(custom_properties));
  975. }
  976. Optional<AK::URL> Parser::parse_url_function(ComponentValue const& component_value)
  977. {
  978. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  979. auto convert_string_to_url = [&](StringView url_string) -> Optional<AK::URL> {
  980. auto url = m_context.complete_url(url_string);
  981. if (url.is_valid())
  982. return url;
  983. return {};
  984. };
  985. if (component_value.is(Token::Type::Url)) {
  986. auto url_string = component_value.token().url();
  987. return convert_string_to_url(url_string);
  988. }
  989. if (component_value.is_function("url"sv)) {
  990. auto const& function_values = component_value.function().values();
  991. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  992. for (size_t i = 0; i < function_values.size(); ++i) {
  993. auto const& value = function_values[i];
  994. if (value.is(Token::Type::Whitespace))
  995. continue;
  996. if (value.is(Token::Type::String)) {
  997. auto url_string = value.token().string();
  998. return convert_string_to_url(url_string);
  999. }
  1000. break;
  1001. }
  1002. }
  1003. return {};
  1004. }
  1005. RefPtr<StyleValue> Parser::parse_url_value(ComponentValue const& component_value)
  1006. {
  1007. auto url = parse_url_function(component_value);
  1008. if (!url.has_value())
  1009. return nullptr;
  1010. return URLStyleValue::create(*url);
  1011. }
  1012. CSSRule* Parser::convert_to_rule(NonnullRefPtr<Rule> rule)
  1013. {
  1014. if (rule->is_at_rule()) {
  1015. if (has_ignored_vendor_prefix(rule->at_rule_name()))
  1016. return {};
  1017. if (rule->at_rule_name().equals_ignoring_ascii_case("font-face"sv)) {
  1018. if (!rule->block() || !rule->block()->is_curly()) {
  1019. dbgln_if(CSS_PARSER_DEBUG, "@font-face rule is malformed.");
  1020. return {};
  1021. }
  1022. TokenStream tokens { rule->block()->values() };
  1023. return parse_font_face_rule(tokens);
  1024. }
  1025. if (rule->at_rule_name().equals_ignoring_ascii_case("import"sv) && !rule->prelude().is_empty()) {
  1026. Optional<AK::URL> url;
  1027. for (auto const& token : rule->prelude()) {
  1028. if (token.is(Token::Type::Whitespace))
  1029. continue;
  1030. if (token.is(Token::Type::String)) {
  1031. url = m_context.complete_url(token.token().string());
  1032. } else {
  1033. url = parse_url_function(token);
  1034. }
  1035. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1036. if (url.has_value())
  1037. break;
  1038. }
  1039. if (url.has_value())
  1040. return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document()));
  1041. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse url from @import rule");
  1042. return {};
  1043. }
  1044. if (rule->at_rule_name().equals_ignoring_ascii_case("media"sv))
  1045. return convert_to_media_rule(rule);
  1046. if (rule->at_rule_name().equals_ignoring_ascii_case("supports"sv)) {
  1047. auto supports_tokens = TokenStream { rule->prelude() };
  1048. auto supports = parse_a_supports(supports_tokens);
  1049. if (!supports) {
  1050. if constexpr (CSS_PARSER_DEBUG) {
  1051. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @supports rule invalid; discarding.");
  1052. supports_tokens.dump_all_tokens();
  1053. }
  1054. return {};
  1055. }
  1056. if (!rule->block())
  1057. return {};
  1058. auto child_tokens = TokenStream { rule->block()->values() };
  1059. auto parser_rules = parse_a_list_of_rules(child_tokens);
  1060. JS::MarkedVector<CSSRule*> child_rules(m_context.realm().heap());
  1061. for (auto& raw_rule : parser_rules) {
  1062. if (auto* child_rule = convert_to_rule(raw_rule))
  1063. child_rules.append(child_rule);
  1064. }
  1065. auto rule_list = CSSRuleList::create(m_context.realm(), child_rules);
  1066. return CSSSupportsRule::create(m_context.realm(), supports.release_nonnull(), rule_list);
  1067. }
  1068. if (rule->at_rule_name().equals_ignoring_ascii_case("keyframes"sv)) {
  1069. auto prelude_stream = TokenStream { rule->prelude() };
  1070. prelude_stream.skip_whitespace();
  1071. auto token = prelude_stream.next_token();
  1072. if (!token.is_token()) {
  1073. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes has invalid prelude, prelude = {}; discarding.", rule->prelude());
  1074. return {};
  1075. }
  1076. auto name_token = token.token();
  1077. prelude_stream.skip_whitespace();
  1078. if (prelude_stream.has_next_token()) {
  1079. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes has invalid prelude, prelude = {}; discarding.", rule->prelude());
  1080. return {};
  1081. }
  1082. if (name_token.is(Token::Type::Ident) && (is_css_wide_keyword(name_token.ident()) || name_token.ident().equals_ignoring_ascii_case("none"sv))) {
  1083. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule name is invalid: {}; discarding.", name_token.ident());
  1084. return {};
  1085. }
  1086. if (!name_token.is(Token::Type::String) && !name_token.is(Token::Type::Ident)) {
  1087. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule name is invalid: {}; discarding.", name_token.to_debug_string());
  1088. return {};
  1089. }
  1090. auto name = name_token.to_string();
  1091. if (!rule->block())
  1092. return {};
  1093. auto child_tokens = TokenStream { rule->block()->values() };
  1094. JS::MarkedVector<JS::NonnullGCPtr<CSSKeyframeRule>> keyframes(m_context.realm().heap());
  1095. while (child_tokens.has_next_token()) {
  1096. child_tokens.skip_whitespace();
  1097. // keyframe-selector = <keyframe-keyword> | <percentage>
  1098. // keyframe-keyword = "from" | "to"
  1099. // selector = <keyframe-selector>#
  1100. // keyframes-block = "{" <declaration-list>? "}"
  1101. // keyframe-rule = <selector> <keyframes-block>
  1102. auto selectors = Vector<CSS::Percentage> {};
  1103. while (child_tokens.has_next_token()) {
  1104. child_tokens.skip_whitespace();
  1105. if (!child_tokens.has_next_token())
  1106. break;
  1107. auto tok = child_tokens.next_token();
  1108. if (!tok.is_token()) {
  1109. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule has invalid selector: {}; discarding.", tok.to_debug_string());
  1110. child_tokens.reconsume_current_input_token();
  1111. break;
  1112. }
  1113. auto token = tok.token();
  1114. auto read_a_selector = false;
  1115. if (token.is(Token::Type::Ident)) {
  1116. if (token.ident().equals_ignoring_ascii_case("from"sv)) {
  1117. selectors.append(CSS::Percentage(0));
  1118. read_a_selector = true;
  1119. }
  1120. if (token.ident().equals_ignoring_ascii_case("to"sv)) {
  1121. selectors.append(CSS::Percentage(100));
  1122. read_a_selector = true;
  1123. }
  1124. } else if (token.is(Token::Type::Percentage)) {
  1125. selectors.append(CSS::Percentage(token.percentage()));
  1126. read_a_selector = true;
  1127. }
  1128. if (read_a_selector) {
  1129. child_tokens.skip_whitespace();
  1130. if (child_tokens.next_token().is(Token::Type::Comma))
  1131. continue;
  1132. }
  1133. child_tokens.reconsume_current_input_token();
  1134. break;
  1135. }
  1136. if (!child_tokens.has_next_token())
  1137. break;
  1138. child_tokens.skip_whitespace();
  1139. auto token = child_tokens.next_token();
  1140. if (token.is_block()) {
  1141. auto block_tokens = token.block().values();
  1142. auto block_stream = TokenStream { block_tokens };
  1143. auto block_declarations = parse_a_list_of_declarations(block_stream);
  1144. auto style = convert_to_style_declaration(block_declarations);
  1145. for (auto& selector : selectors) {
  1146. auto keyframe_rule = CSSKeyframeRule::create(m_context.realm(), selector, *style);
  1147. keyframes.append(keyframe_rule);
  1148. }
  1149. } else {
  1150. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @keyframes rule has invalid block: {}; discarding.", token.to_debug_string());
  1151. }
  1152. }
  1153. return CSSKeyframesRule::create(m_context.realm(), name, move(keyframes));
  1154. }
  1155. if (rule->at_rule_name().equals_ignoring_ascii_case("namespace"sv)) {
  1156. // https://drafts.csswg.org/css-namespaces/#syntax
  1157. auto token_stream = TokenStream { rule->prelude() };
  1158. token_stream.skip_whitespace();
  1159. auto token = token_stream.next_token();
  1160. Optional<FlyString> prefix = {};
  1161. if (token.is(Token::Type::Ident)) {
  1162. prefix = token.token().ident();
  1163. token_stream.skip_whitespace();
  1164. token = token_stream.next_token();
  1165. }
  1166. FlyString namespace_uri;
  1167. if (token.is(Token::Type::String)) {
  1168. namespace_uri = token.token().string();
  1169. } else if (auto url = parse_url_function(token); url.has_value()) {
  1170. namespace_uri = MUST(url.value().to_string());
  1171. } else {
  1172. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @namespace rule invalid; discarding.");
  1173. return {};
  1174. }
  1175. token_stream.skip_whitespace();
  1176. if (token_stream.has_next_token()) {
  1177. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @namespace rule invalid; discarding.");
  1178. return {};
  1179. }
  1180. return CSSNamespaceRule::create(m_context.realm(), prefix, namespace_uri);
  1181. }
  1182. // FIXME: More at rules!
  1183. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS at-rule: @{}", rule->at_rule_name());
  1184. return {};
  1185. }
  1186. auto prelude_stream = TokenStream(rule->prelude());
  1187. auto selectors = parse_a_selector_list(prelude_stream, SelectorType::Standalone);
  1188. if (selectors.is_error()) {
  1189. if (selectors.error() == ParseError::SyntaxError) {
  1190. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule selectors invalid; discarding.");
  1191. if constexpr (CSS_PARSER_DEBUG) {
  1192. prelude_stream.dump_all_tokens();
  1193. }
  1194. }
  1195. return {};
  1196. }
  1197. if (selectors.value().is_empty()) {
  1198. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: empty selector; discarding.");
  1199. return {};
  1200. }
  1201. if (!rule->block()->is_curly())
  1202. return {};
  1203. auto stream = TokenStream(rule->block()->values());
  1204. auto declarations_and_at_rules = parse_a_style_blocks_contents(stream);
  1205. auto* declaration = convert_to_style_declaration(declarations_and_at_rules);
  1206. if (!declaration) {
  1207. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: style rule declaration invalid; discarding.");
  1208. return {};
  1209. }
  1210. return CSSStyleRule::create(m_context.realm(), move(selectors.value()), *declaration);
  1211. }
  1212. auto Parser::extract_properties(Vector<DeclarationOrAtRule> const& declarations_and_at_rules) -> PropertiesAndCustomProperties
  1213. {
  1214. PropertiesAndCustomProperties result;
  1215. for (auto const& declaration_or_at_rule : declarations_and_at_rules) {
  1216. if (declaration_or_at_rule.is_at_rule()) {
  1217. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  1218. continue;
  1219. }
  1220. auto const& declaration = declaration_or_at_rule.declaration();
  1221. if (auto maybe_property = convert_to_style_property(declaration); maybe_property.has_value()) {
  1222. auto property = maybe_property.release_value();
  1223. if (property.property_id == PropertyID::Custom) {
  1224. result.custom_properties.set(property.custom_name, property);
  1225. } else {
  1226. result.properties.append(move(property));
  1227. }
  1228. }
  1229. }
  1230. return result;
  1231. }
  1232. PropertyOwningCSSStyleDeclaration* Parser::convert_to_style_declaration(Vector<DeclarationOrAtRule> const& declarations_and_at_rules)
  1233. {
  1234. auto [properties, custom_properties] = extract_properties(declarations_and_at_rules);
  1235. return PropertyOwningCSSStyleDeclaration::create(m_context.realm(), move(properties), move(custom_properties));
  1236. }
  1237. Optional<StyleProperty> Parser::convert_to_style_property(Declaration const& declaration)
  1238. {
  1239. auto const& property_name = declaration.name();
  1240. auto property_id = property_id_from_string(property_name);
  1241. if (!property_id.has_value()) {
  1242. if (property_name.bytes_as_string_view().starts_with("--"sv)) {
  1243. property_id = PropertyID::Custom;
  1244. } else if (has_ignored_vendor_prefix(property_name)) {
  1245. return {};
  1246. } else if (!property_name.bytes_as_string_view().starts_with('-')) {
  1247. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized CSS property '{}'", property_name);
  1248. return {};
  1249. }
  1250. }
  1251. auto value_token_stream = TokenStream(declaration.values());
  1252. auto value = parse_css_value(property_id.value(), value_token_stream);
  1253. if (value.is_error()) {
  1254. if (value.error() == ParseError::SyntaxError) {
  1255. dbgln_if(CSS_PARSER_DEBUG, "Unable to parse value for CSS property '{}'.", property_name);
  1256. if constexpr (CSS_PARSER_DEBUG) {
  1257. value_token_stream.dump_all_tokens();
  1258. }
  1259. }
  1260. return {};
  1261. }
  1262. if (property_id.value() == PropertyID::Custom)
  1263. return StyleProperty { declaration.importance(), property_id.value(), value.release_value(), declaration.name() };
  1264. return StyleProperty { declaration.importance(), property_id.value(), value.release_value(), {} };
  1265. }
  1266. RefPtr<StyleValue> Parser::parse_builtin_value(ComponentValue const& component_value)
  1267. {
  1268. if (component_value.is(Token::Type::Ident)) {
  1269. auto ident = component_value.token().ident();
  1270. if (ident.equals_ignoring_ascii_case("inherit"sv))
  1271. return InheritStyleValue::the();
  1272. if (ident.equals_ignoring_ascii_case("initial"sv))
  1273. return InitialStyleValue::the();
  1274. if (ident.equals_ignoring_ascii_case("unset"sv))
  1275. return UnsetStyleValue::the();
  1276. if (ident.equals_ignoring_ascii_case("revert"sv))
  1277. return RevertStyleValue::the();
  1278. // FIXME: Implement `revert-layer` from CSS-CASCADE-5.
  1279. }
  1280. return nullptr;
  1281. }
  1282. RefPtr<CalculatedStyleValue> Parser::parse_calculated_value(ComponentValue const& component_value)
  1283. {
  1284. if (!component_value.is_function())
  1285. return nullptr;
  1286. auto const& function = component_value.function();
  1287. auto function_node = parse_a_calc_function_node(function);
  1288. if (!function_node)
  1289. return nullptr;
  1290. auto function_type = function_node->determine_type(m_context.current_property_id());
  1291. if (!function_type.has_value())
  1292. return nullptr;
  1293. return CalculatedStyleValue::create(function_node.release_nonnull(), function_type.release_value());
  1294. }
  1295. OwnPtr<CalculationNode> Parser::parse_a_calc_function_node(Function const& function)
  1296. {
  1297. if (function.name().equals_ignoring_ascii_case("calc"sv))
  1298. return parse_a_calculation(function.values());
  1299. if (auto maybe_function = parse_math_function(m_context.current_property_id(), function))
  1300. return maybe_function;
  1301. return nullptr;
  1302. }
  1303. Optional<Dimension> Parser::parse_dimension(ComponentValue const& component_value)
  1304. {
  1305. if (component_value.is(Token::Type::Dimension)) {
  1306. auto numeric_value = component_value.token().dimension_value();
  1307. auto unit_string = component_value.token().dimension_unit();
  1308. if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
  1309. return Length { numeric_value, length_type.release_value() };
  1310. if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
  1311. return Angle { numeric_value, angle_type.release_value() };
  1312. if (auto flex_type = Flex::unit_from_name(unit_string); flex_type.has_value())
  1313. return Flex { numeric_value, flex_type.release_value() };
  1314. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  1315. return Frequency { numeric_value, frequency_type.release_value() };
  1316. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  1317. return Resolution { numeric_value, resolution_type.release_value() };
  1318. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  1319. return Time { numeric_value, time_type.release_value() };
  1320. }
  1321. if (component_value.is(Token::Type::Percentage))
  1322. return Percentage { component_value.token().percentage() };
  1323. if (component_value.is(Token::Type::Number)) {
  1324. auto numeric_value = component_value.token().number_value();
  1325. if (numeric_value == 0)
  1326. return Length::make_px(0);
  1327. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  1328. // https://quirks.spec.whatwg.org/#quirky-length-value
  1329. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1330. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1331. // expression, and must not be supported in the supports() static method of the CSS interface."
  1332. return Length::make_px(CSSPixels::nearest_value_for(numeric_value));
  1333. }
  1334. }
  1335. return {};
  1336. }
  1337. Optional<AngleOrCalculated> Parser::parse_angle(TokenStream<ComponentValue>& tokens)
  1338. {
  1339. auto transaction = tokens.begin_transaction();
  1340. auto& token = tokens.next_token();
  1341. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1342. if (dimension->is_angle()) {
  1343. transaction.commit();
  1344. return dimension->angle();
  1345. }
  1346. return {};
  1347. }
  1348. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_angle()) {
  1349. transaction.commit();
  1350. return calc.release_nonnull();
  1351. }
  1352. return {};
  1353. }
  1354. Optional<AnglePercentage> Parser::parse_angle_percentage(TokenStream<ComponentValue>& tokens)
  1355. {
  1356. auto transaction = tokens.begin_transaction();
  1357. auto& token = tokens.next_token();
  1358. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1359. if (dimension->is_angle_percentage()) {
  1360. transaction.commit();
  1361. return dimension->angle_percentage();
  1362. }
  1363. return {};
  1364. }
  1365. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_angle_percentage()) {
  1366. transaction.commit();
  1367. return calc.release_nonnull();
  1368. }
  1369. return {};
  1370. }
  1371. Optional<FlexOrCalculated> Parser::parse_flex(TokenStream<ComponentValue>& tokens)
  1372. {
  1373. auto transaction = tokens.begin_transaction();
  1374. auto& token = tokens.next_token();
  1375. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1376. if (dimension->is_flex()) {
  1377. transaction.commit();
  1378. return dimension->flex();
  1379. }
  1380. return {};
  1381. }
  1382. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_flex()) {
  1383. transaction.commit();
  1384. return calc.release_nonnull();
  1385. }
  1386. return {};
  1387. }
  1388. Optional<FrequencyOrCalculated> Parser::parse_frequency(TokenStream<ComponentValue>& tokens)
  1389. {
  1390. auto transaction = tokens.begin_transaction();
  1391. auto& token = tokens.next_token();
  1392. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1393. if (dimension->is_frequency()) {
  1394. transaction.commit();
  1395. return dimension->frequency();
  1396. }
  1397. return {};
  1398. }
  1399. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_frequency()) {
  1400. transaction.commit();
  1401. return calc.release_nonnull();
  1402. }
  1403. return {};
  1404. }
  1405. Optional<FrequencyPercentage> Parser::parse_frequency_percentage(TokenStream<ComponentValue>& tokens)
  1406. {
  1407. auto transaction = tokens.begin_transaction();
  1408. auto& token = tokens.next_token();
  1409. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1410. if (dimension->is_frequency_percentage()) {
  1411. transaction.commit();
  1412. return dimension->frequency_percentage();
  1413. }
  1414. return {};
  1415. }
  1416. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_frequency_percentage()) {
  1417. transaction.commit();
  1418. return calc.release_nonnull();
  1419. }
  1420. return {};
  1421. }
  1422. Optional<IntegerOrCalculated> Parser::parse_integer(TokenStream<ComponentValue>& tokens)
  1423. {
  1424. auto transaction = tokens.begin_transaction();
  1425. auto& token = tokens.next_token();
  1426. if (token.is(Token::Type::Number) && token.token().number().is_integer()) {
  1427. transaction.commit();
  1428. return token.token().to_integer();
  1429. }
  1430. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_number()) {
  1431. transaction.commit();
  1432. return calc.release_nonnull();
  1433. }
  1434. return {};
  1435. }
  1436. Optional<LengthOrCalculated> Parser::parse_length(TokenStream<ComponentValue>& tokens)
  1437. {
  1438. auto transaction = tokens.begin_transaction();
  1439. auto& token = tokens.next_token();
  1440. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1441. if (dimension->is_length()) {
  1442. transaction.commit();
  1443. return dimension->length();
  1444. }
  1445. return {};
  1446. }
  1447. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length()) {
  1448. transaction.commit();
  1449. return calc.release_nonnull();
  1450. }
  1451. return {};
  1452. }
  1453. Optional<LengthPercentage> Parser::parse_length_percentage(TokenStream<ComponentValue>& tokens)
  1454. {
  1455. auto transaction = tokens.begin_transaction();
  1456. auto& token = tokens.next_token();
  1457. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1458. if (dimension->is_length_percentage()) {
  1459. transaction.commit();
  1460. return dimension->length_percentage();
  1461. }
  1462. return {};
  1463. }
  1464. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length_percentage()) {
  1465. transaction.commit();
  1466. return calc.release_nonnull();
  1467. }
  1468. return {};
  1469. }
  1470. Optional<NumberOrCalculated> Parser::parse_number(TokenStream<ComponentValue>& tokens)
  1471. {
  1472. auto transaction = tokens.begin_transaction();
  1473. auto& token = tokens.next_token();
  1474. if (token.is(Token::Type::Number)) {
  1475. transaction.commit();
  1476. return token.token().number_value();
  1477. }
  1478. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_number()) {
  1479. transaction.commit();
  1480. return calc.release_nonnull();
  1481. }
  1482. return {};
  1483. }
  1484. Optional<ResolutionOrCalculated> Parser::parse_resolution(TokenStream<ComponentValue>& tokens)
  1485. {
  1486. auto transaction = tokens.begin_transaction();
  1487. auto& token = tokens.next_token();
  1488. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1489. if (dimension->is_resolution()) {
  1490. transaction.commit();
  1491. return dimension->resolution();
  1492. }
  1493. return {};
  1494. }
  1495. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_resolution()) {
  1496. transaction.commit();
  1497. return calc.release_nonnull();
  1498. }
  1499. return {};
  1500. }
  1501. Optional<TimeOrCalculated> Parser::parse_time(TokenStream<ComponentValue>& tokens)
  1502. {
  1503. auto transaction = tokens.begin_transaction();
  1504. auto& token = tokens.next_token();
  1505. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1506. if (dimension->is_time()) {
  1507. transaction.commit();
  1508. return dimension->time();
  1509. }
  1510. return {};
  1511. }
  1512. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_time()) {
  1513. transaction.commit();
  1514. return calc.release_nonnull();
  1515. }
  1516. return {};
  1517. }
  1518. Optional<TimePercentage> Parser::parse_time_percentage(TokenStream<ComponentValue>& tokens)
  1519. {
  1520. auto transaction = tokens.begin_transaction();
  1521. auto& token = tokens.next_token();
  1522. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  1523. if (dimension->is_time_percentage()) {
  1524. transaction.commit();
  1525. return dimension->time_percentage();
  1526. }
  1527. return {};
  1528. }
  1529. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_time_percentage()) {
  1530. transaction.commit();
  1531. return calc.release_nonnull();
  1532. }
  1533. return {};
  1534. }
  1535. Optional<LengthOrCalculated> Parser::parse_source_size_value(TokenStream<ComponentValue>& tokens)
  1536. {
  1537. if (tokens.peek_token().is_ident("auto"sv)) {
  1538. (void)tokens.next_token(); // auto
  1539. return LengthOrCalculated { Length::make_auto() };
  1540. }
  1541. return parse_length(tokens);
  1542. }
  1543. Optional<Ratio> Parser::parse_ratio(TokenStream<ComponentValue>& tokens)
  1544. {
  1545. auto transaction = tokens.begin_transaction();
  1546. tokens.skip_whitespace();
  1547. auto read_number_value = [this](ComponentValue const& component_value) -> Optional<double> {
  1548. if (component_value.is(Token::Type::Number)) {
  1549. return component_value.token().number_value();
  1550. } else if (component_value.is_function()) {
  1551. auto maybe_calc = parse_calculated_value(component_value);
  1552. if (!maybe_calc || !maybe_calc->resolves_to_number())
  1553. return {};
  1554. if (auto resolved_number = maybe_calc->resolve_number(); resolved_number.has_value() && resolved_number.value() >= 0) {
  1555. return resolved_number.value();
  1556. }
  1557. }
  1558. return {};
  1559. };
  1560. // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
  1561. auto maybe_numerator = read_number_value(tokens.next_token());
  1562. if (!maybe_numerator.has_value() || maybe_numerator.value() < 0)
  1563. return {};
  1564. auto numerator = maybe_numerator.value();
  1565. {
  1566. auto two_value_transaction = tokens.begin_transaction();
  1567. tokens.skip_whitespace();
  1568. auto solidus = tokens.next_token();
  1569. tokens.skip_whitespace();
  1570. auto maybe_denominator = read_number_value(tokens.next_token());
  1571. if (solidus.is_delim('/') && maybe_denominator.has_value() && maybe_denominator.value() >= 0) {
  1572. auto denominator = maybe_denominator.value();
  1573. // Two-value ratio
  1574. two_value_transaction.commit();
  1575. transaction.commit();
  1576. return Ratio { numerator, denominator };
  1577. }
  1578. }
  1579. // Single-value ratio
  1580. transaction.commit();
  1581. return Ratio { numerator };
  1582. }
  1583. // https://www.w3.org/TR/css-syntax-3/#urange-syntax
  1584. Optional<Gfx::UnicodeRange> Parser::parse_unicode_range(TokenStream<ComponentValue>& tokens)
  1585. {
  1586. auto transaction = tokens.begin_transaction();
  1587. tokens.skip_whitespace();
  1588. // <urange> =
  1589. // u '+' <ident-token> '?'* |
  1590. // u <dimension-token> '?'* |
  1591. // u <number-token> '?'* |
  1592. // u <number-token> <dimension-token> |
  1593. // u <number-token> <number-token> |
  1594. // u '+' '?'+
  1595. // (All with no whitespace in between tokens.)
  1596. // NOTE: Parsing this is different from usual. We take these steps:
  1597. // 1. Match the grammar above against the tokens, concatenating them into a string using their original representation.
  1598. // 2. Then, parse that string according to the spec algorithm.
  1599. // Step 2 is performed by calling the other parse_unicode_range() overload.
  1600. auto is_ending_token = [](ComponentValue const& component_value) {
  1601. return component_value.is(Token::Type::EndOfFile)
  1602. || component_value.is(Token::Type::Comma)
  1603. || component_value.is(Token::Type::Semicolon)
  1604. || component_value.is(Token::Type::Whitespace);
  1605. };
  1606. auto create_unicode_range = [&](StringView text, auto& local_transaction) -> Optional<Gfx::UnicodeRange> {
  1607. auto maybe_unicode_range = parse_unicode_range(text);
  1608. if (maybe_unicode_range.has_value()) {
  1609. local_transaction.commit();
  1610. transaction.commit();
  1611. }
  1612. return maybe_unicode_range;
  1613. };
  1614. // All options start with 'u'/'U'.
  1615. auto const& u = tokens.next_token();
  1616. if (!u.is_ident("u"sv)) {
  1617. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> does not start with 'u'");
  1618. return {};
  1619. }
  1620. auto const& second_token = tokens.next_token();
  1621. // u '+' <ident-token> '?'* |
  1622. // u '+' '?'+
  1623. if (second_token.is_delim('+')) {
  1624. auto local_transaction = tokens.begin_transaction();
  1625. StringBuilder string_builder;
  1626. string_builder.append(second_token.token().representation());
  1627. auto const& third_token = tokens.next_token();
  1628. if (third_token.is(Token::Type::Ident) || third_token.is_delim('?')) {
  1629. string_builder.append(third_token.token().representation());
  1630. while (tokens.peek_token().is_delim('?'))
  1631. string_builder.append(tokens.next_token().token().representation());
  1632. if (is_ending_token(tokens.peek_token()))
  1633. return create_unicode_range(string_builder.string_view(), local_transaction);
  1634. }
  1635. }
  1636. // u <dimension-token> '?'*
  1637. if (second_token.is(Token::Type::Dimension)) {
  1638. auto local_transaction = tokens.begin_transaction();
  1639. StringBuilder string_builder;
  1640. string_builder.append(second_token.token().representation());
  1641. while (tokens.peek_token().is_delim('?'))
  1642. string_builder.append(tokens.next_token().token().representation());
  1643. if (is_ending_token(tokens.peek_token()))
  1644. return create_unicode_range(string_builder.string_view(), local_transaction);
  1645. }
  1646. // u <number-token> '?'* |
  1647. // u <number-token> <dimension-token> |
  1648. // u <number-token> <number-token>
  1649. if (second_token.is(Token::Type::Number)) {
  1650. auto local_transaction = tokens.begin_transaction();
  1651. StringBuilder string_builder;
  1652. string_builder.append(second_token.token().representation());
  1653. if (is_ending_token(tokens.peek_token()))
  1654. return create_unicode_range(string_builder.string_view(), local_transaction);
  1655. auto const& third_token = tokens.next_token();
  1656. if (third_token.is_delim('?')) {
  1657. string_builder.append(third_token.token().representation());
  1658. while (tokens.peek_token().is_delim('?'))
  1659. string_builder.append(tokens.next_token().token().representation());
  1660. if (is_ending_token(tokens.peek_token()))
  1661. return create_unicode_range(string_builder.string_view(), local_transaction);
  1662. } else if (third_token.is(Token::Type::Dimension)) {
  1663. string_builder.append(third_token.token().representation());
  1664. if (is_ending_token(tokens.peek_token()))
  1665. return create_unicode_range(string_builder.string_view(), local_transaction);
  1666. } else if (third_token.is(Token::Type::Number)) {
  1667. string_builder.append(third_token.token().representation());
  1668. if (is_ending_token(tokens.peek_token()))
  1669. return create_unicode_range(string_builder.string_view(), local_transaction);
  1670. }
  1671. }
  1672. if constexpr (CSS_PARSER_DEBUG) {
  1673. dbgln("CSSParser: Tokens did not match <urange> grammar.");
  1674. tokens.dump_all_tokens();
  1675. }
  1676. return {};
  1677. }
  1678. Optional<Gfx::UnicodeRange> Parser::parse_unicode_range(StringView text)
  1679. {
  1680. auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<Gfx::UnicodeRange> {
  1681. // https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point
  1682. constexpr u32 maximum_allowed_code_point = 0x10FFFF;
  1683. // To determine what codepoints the <urange> represents:
  1684. // 1. If end value is greater than the maximum allowed code point,
  1685. // the <urange> is invalid and a syntax error.
  1686. if (end_value > maximum_allowed_code_point) {
  1687. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: end_value ({}) > maximum ({})", end_value, maximum_allowed_code_point);
  1688. return {};
  1689. }
  1690. // 2. If start value is greater than end value, the <urange> is invalid and a syntax error.
  1691. if (start_value > end_value) {
  1692. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: start_value ({}) > end_value ({})", start_value, end_value);
  1693. return {};
  1694. }
  1695. // 3. Otherwise, the <urange> represents a contiguous range of codepoints from start value to end value, inclusive.
  1696. return Gfx::UnicodeRange { start_value, end_value };
  1697. };
  1698. // 1. Skipping the first u token, concatenate the representations of all the tokens in the production together.
  1699. // Let this be text.
  1700. // NOTE: The concatenation is already done by the caller.
  1701. GenericLexer lexer { text };
  1702. // 2. If the first character of text is U+002B PLUS SIGN, consume it.
  1703. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  1704. if (lexer.next_is('+')) {
  1705. lexer.consume();
  1706. } else {
  1707. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Second character of <urange> was not '+'; got: '{}'", lexer.consume());
  1708. return {};
  1709. }
  1710. // 3. Consume as many hex digits from text as possible.
  1711. // then consume as many U+003F QUESTION MARK (?) code points as possible.
  1712. auto hex_digits = lexer.consume_while(is_ascii_hex_digit);
  1713. auto question_marks = lexer.consume_while([](auto it) { return it == '?'; });
  1714. // If zero code points were consumed, or more than six code points were consumed,
  1715. // this is an invalid <urange>, and this algorithm must exit.
  1716. size_t consumed_code_points = hex_digits.length() + question_marks.length();
  1717. if (consumed_code_points == 0 || consumed_code_points > 6) {
  1718. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value had {} digits/?s, expected between 1 and 6.", consumed_code_points);
  1719. return {};
  1720. }
  1721. StringView start_value_code_points { hex_digits.characters_without_null_termination(), consumed_code_points };
  1722. // If any U+003F QUESTION MARK (?) code points were consumed, then:
  1723. if (question_marks.length() > 0) {
  1724. // 1. If there are any code points left in text, this is an invalid <urange>,
  1725. // and this algorithm must exit.
  1726. if (lexer.tell_remaining() != 0) {
  1727. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  1728. return {};
  1729. }
  1730. // 2. Interpret the consumed code points as a hexadecimal number,
  1731. // with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
  1732. // This is the start value.
  1733. auto start_value_string = start_value_code_points.replace("?"sv, "0"sv, ReplaceMode::All);
  1734. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
  1735. if (!maybe_start_value.has_value()) {
  1736. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
  1737. return {};
  1738. }
  1739. u32 start_value = maybe_start_value.release_value();
  1740. // 3. Interpret the consumed code points as a hexadecimal number again,
  1741. // with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
  1742. // This is the end value.
  1743. auto end_value_string = start_value_code_points.replace("?"sv, "F"sv, ReplaceMode::All);
  1744. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
  1745. if (!maybe_end_value.has_value()) {
  1746. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");
  1747. return {};
  1748. }
  1749. u32 end_value = maybe_end_value.release_value();
  1750. // 4. Exit this algorithm.
  1751. return make_valid_unicode_range(start_value, end_value);
  1752. }
  1753. // Otherwise, interpret the consumed code points as a hexadecimal number. This is the start value.
  1754. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_code_points);
  1755. if (!maybe_start_value.has_value()) {
  1756. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value did not parse as hex number.");
  1757. return {};
  1758. }
  1759. u32 start_value = maybe_start_value.release_value();
  1760. // 4. If there are no code points left in text, The end value is the same as the start value.
  1761. // Exit this algorithm.
  1762. if (lexer.tell_remaining() == 0)
  1763. return make_valid_unicode_range(start_value, start_value);
  1764. // 5. If the next code point in text is U+002D HYPHEN-MINUS (-), consume it.
  1765. if (lexer.next_is('-')) {
  1766. lexer.consume();
  1767. }
  1768. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  1769. else {
  1770. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start and end values not separated by '-'.");
  1771. return {};
  1772. }
  1773. // 6. Consume as many hex digits as possible from text.
  1774. auto end_hex_digits = lexer.consume_while(is_ascii_hex_digit);
  1775. // If zero hex digits were consumed, or more than 6 hex digits were consumed,
  1776. // this is an invalid <urange>, and this algorithm must exit.
  1777. if (end_hex_digits.length() == 0 || end_hex_digits.length() > 6) {
  1778. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value had {} digits, expected between 1 and 6.", end_hex_digits.length());
  1779. return {};
  1780. }
  1781. // If there are any code points left in text, this is an invalid <urange>, and this algorithm must exit.
  1782. if (lexer.tell_remaining() != 0) {
  1783. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  1784. return {};
  1785. }
  1786. // 7. Interpret the consumed code points as a hexadecimal number. This is the end value.
  1787. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_hex_digits);
  1788. if (!maybe_end_value.has_value()) {
  1789. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value did not parse as hex number.");
  1790. return {};
  1791. }
  1792. u32 end_value = maybe_end_value.release_value();
  1793. return make_valid_unicode_range(start_value, end_value);
  1794. }
  1795. RefPtr<StyleValue> Parser::parse_dimension_value(ComponentValue const& component_value)
  1796. {
  1797. auto dimension = parse_dimension(component_value);
  1798. if (!dimension.has_value())
  1799. return nullptr;
  1800. if (dimension->is_angle())
  1801. return AngleStyleValue::create(dimension->angle());
  1802. if (dimension->is_frequency())
  1803. return FrequencyStyleValue::create(dimension->frequency());
  1804. if (dimension->is_length())
  1805. return LengthStyleValue::create(dimension->length());
  1806. if (dimension->is_percentage())
  1807. return PercentageStyleValue::create(dimension->percentage());
  1808. if (dimension->is_resolution())
  1809. return ResolutionStyleValue::create(dimension->resolution());
  1810. if (dimension->is_time())
  1811. return TimeStyleValue::create(dimension->time());
  1812. VERIFY_NOT_REACHED();
  1813. }
  1814. RefPtr<StyleValue> Parser::parse_integer_value(TokenStream<ComponentValue>& tokens)
  1815. {
  1816. auto peek_token = tokens.peek_token();
  1817. if (peek_token.is(Token::Type::Number) && peek_token.token().number().is_integer()) {
  1818. (void)tokens.next_token();
  1819. return IntegerStyleValue::create(peek_token.token().number().integer_value());
  1820. }
  1821. return nullptr;
  1822. }
  1823. RefPtr<StyleValue> Parser::parse_number_value(TokenStream<ComponentValue>& tokens)
  1824. {
  1825. auto peek_token = tokens.peek_token();
  1826. if (peek_token.is(Token::Type::Number)) {
  1827. (void)tokens.next_token();
  1828. return NumberStyleValue::create(peek_token.token().number().value());
  1829. }
  1830. return nullptr;
  1831. }
  1832. RefPtr<StyleValue> Parser::parse_number_or_percentage_value(TokenStream<ComponentValue>& tokens)
  1833. {
  1834. auto peek_token = tokens.peek_token();
  1835. if (peek_token.is(Token::Type::Number)) {
  1836. (void)tokens.next_token();
  1837. return NumberStyleValue::create(peek_token.token().number().value());
  1838. }
  1839. if (peek_token.is(Token::Type::Percentage)) {
  1840. (void)tokens.next_token();
  1841. return PercentageStyleValue::create(Percentage(peek_token.token().percentage()));
  1842. }
  1843. return nullptr;
  1844. }
  1845. RefPtr<StyleValue> Parser::parse_identifier_value(ComponentValue const& component_value)
  1846. {
  1847. if (component_value.is(Token::Type::Ident)) {
  1848. auto value_id = value_id_from_string(component_value.token().ident());
  1849. if (value_id.has_value())
  1850. return IdentifierStyleValue::create(value_id.value());
  1851. }
  1852. return nullptr;
  1853. }
  1854. Optional<Color> Parser::parse_rgb_or_hsl_color(StringView function_name, Vector<ComponentValue> const& component_values)
  1855. {
  1856. Token params[4];
  1857. bool legacy_syntax = false;
  1858. auto tokens = TokenStream { component_values };
  1859. tokens.skip_whitespace();
  1860. auto const& component1 = tokens.next_token();
  1861. if (!component1.is(Token::Type::Number)
  1862. && !component1.is(Token::Type::Percentage)
  1863. && !component1.is(Token::Type::Dimension))
  1864. return {};
  1865. params[0] = component1.token();
  1866. tokens.skip_whitespace();
  1867. if (tokens.peek_token().is(Token::Type::Comma)) {
  1868. legacy_syntax = true;
  1869. tokens.next_token();
  1870. }
  1871. tokens.skip_whitespace();
  1872. auto const& component2 = tokens.next_token();
  1873. if (!component2.is(Token::Type::Number) && !component2.is(Token::Type::Percentage))
  1874. return {};
  1875. params[1] = component2.token();
  1876. tokens.skip_whitespace();
  1877. if (legacy_syntax && !tokens.next_token().is(Token::Type::Comma))
  1878. return {};
  1879. tokens.skip_whitespace();
  1880. auto const& component3 = tokens.next_token();
  1881. if (!component3.is(Token::Type::Number) && !component3.is(Token::Type::Percentage))
  1882. return {};
  1883. params[2] = component3.token();
  1884. tokens.skip_whitespace();
  1885. auto const& alpha_separator = tokens.peek_token();
  1886. bool has_comma = alpha_separator.is(Token::Type::Comma);
  1887. bool has_slash = alpha_separator.is_delim('/');
  1888. if (legacy_syntax ? has_comma : has_slash) {
  1889. tokens.next_token();
  1890. tokens.skip_whitespace();
  1891. auto const& component4 = tokens.next_token();
  1892. if (!component4.is(Token::Type::Number) && !component4.is(Token::Type::Percentage))
  1893. return {};
  1894. params[3] = component4.token();
  1895. }
  1896. tokens.skip_whitespace();
  1897. if (tokens.has_next_token())
  1898. return {};
  1899. if (function_name.equals_ignoring_ascii_case("rgb"sv)
  1900. || function_name.equals_ignoring_ascii_case("rgba"sv)) {
  1901. // https://www.w3.org/TR/css-color-4/#rgb-functions
  1902. u8 a_val = 255;
  1903. if (params[3].is(Token::Type::Number))
  1904. a_val = clamp(lround(params[3].number_value() * 255.0), 0, 255);
  1905. else if (params[3].is(Token::Type::Percentage))
  1906. a_val = clamp(lround(params[3].percentage() * 2.55), 0, 255);
  1907. if (params[0].is(Token::Type::Number)
  1908. && params[1].is(Token::Type::Number)
  1909. && params[2].is(Token::Type::Number)) {
  1910. u8 r_val = clamp(llroundf(params[0].number_value()), 0, 255);
  1911. u8 g_val = clamp(llroundf(params[1].number_value()), 0, 255);
  1912. u8 b_val = clamp(llroundf(params[2].number_value()), 0, 255);
  1913. return Color(r_val, g_val, b_val, a_val);
  1914. }
  1915. if (params[0].is(Token::Type::Percentage)
  1916. && params[1].is(Token::Type::Percentage)
  1917. && params[2].is(Token::Type::Percentage)) {
  1918. u8 r_val = lround(clamp(params[0].percentage() * 2.55, 0, 255));
  1919. u8 g_val = lround(clamp(params[1].percentage() * 2.55, 0, 255));
  1920. u8 b_val = lround(clamp(params[2].percentage() * 2.55, 0, 255));
  1921. return Color(r_val, g_val, b_val, a_val);
  1922. }
  1923. } else if (function_name.equals_ignoring_ascii_case("hsl"sv)
  1924. || function_name.equals_ignoring_ascii_case("hsla"sv)) {
  1925. // https://www.w3.org/TR/css-color-4/#the-hsl-notation
  1926. auto a_val = 1.0;
  1927. if (params[3].is(Token::Type::Number))
  1928. a_val = params[3].number_value();
  1929. else if (params[3].is(Token::Type::Percentage))
  1930. a_val = params[3].percentage() / 100.0;
  1931. if (params[0].is(Token::Type::Dimension)
  1932. && params[1].is(Token::Type::Percentage)
  1933. && params[2].is(Token::Type::Percentage)) {
  1934. auto numeric_value = params[0].dimension_value();
  1935. auto unit_string = params[0].dimension_unit();
  1936. auto angle_type = Angle::unit_from_name(unit_string);
  1937. if (!angle_type.has_value())
  1938. return {};
  1939. auto angle = Angle { numeric_value, angle_type.release_value() };
  1940. float h_val = fmod(angle.to_degrees(), 360.0);
  1941. float s_val = params[1].percentage() / 100.0;
  1942. float l_val = params[2].percentage() / 100.0;
  1943. return Color::from_hsla(h_val, s_val, l_val, a_val);
  1944. }
  1945. if (params[0].is(Token::Type::Number)
  1946. && params[1].is(Token::Type::Percentage)
  1947. && params[2].is(Token::Type::Percentage)) {
  1948. float h_val = fmod(params[0].number_value(), 360.0);
  1949. float s_val = params[1].percentage() / 100.0;
  1950. float l_val = params[2].percentage() / 100.0;
  1951. return Color::from_hsla(h_val, s_val, l_val, a_val);
  1952. }
  1953. }
  1954. return {};
  1955. }
  1956. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  1957. RefPtr<StyleValue> Parser::parse_rect_value(ComponentValue const& component_value)
  1958. {
  1959. if (!component_value.is_function("rect"sv))
  1960. return nullptr;
  1961. Vector<Length, 4> params;
  1962. auto tokens = TokenStream { component_value.function().values() };
  1963. enum class CommaRequirement {
  1964. Unknown,
  1965. RequiresCommas,
  1966. RequiresNoCommas
  1967. };
  1968. enum class Side {
  1969. Top = 0,
  1970. Right = 1,
  1971. Bottom = 2,
  1972. Left = 3
  1973. };
  1974. auto comma_requirement = CommaRequirement::Unknown;
  1975. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  1976. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  1977. // <left> specify offsets from the left border edge of the box.
  1978. for (size_t side = 0; side < 4; side++) {
  1979. tokens.skip_whitespace();
  1980. // <top>, <right>, <bottom>, and <left> may either have a <length> value or 'auto'.
  1981. // Negative lengths are permitted.
  1982. if (tokens.peek_token().is_ident("auto"sv)) {
  1983. (void)tokens.next_token(); // `auto`
  1984. params.append(Length::make_auto());
  1985. } else {
  1986. auto maybe_length = parse_length(tokens);
  1987. if (!maybe_length.has_value())
  1988. return nullptr;
  1989. // FIXME: Support calculated lengths
  1990. params.append(maybe_length.value().value());
  1991. }
  1992. tokens.skip_whitespace();
  1993. // The last side, should be no more tokens following it.
  1994. if (static_cast<Side>(side) == Side::Left) {
  1995. if (tokens.has_next_token())
  1996. return nullptr;
  1997. break;
  1998. }
  1999. bool next_is_comma = tokens.peek_token().is(Token::Type::Comma);
  2000. // Authors should separate offset values with commas. User agents must support separation
  2001. // with commas, but may also support separation without commas (but not a combination),
  2002. // because a previous revision of this specification was ambiguous in this respect.
  2003. if (comma_requirement == CommaRequirement::Unknown)
  2004. comma_requirement = next_is_comma ? CommaRequirement::RequiresCommas : CommaRequirement::RequiresNoCommas;
  2005. if (comma_requirement == CommaRequirement::RequiresCommas) {
  2006. if (next_is_comma)
  2007. tokens.next_token();
  2008. else
  2009. return nullptr;
  2010. } else if (comma_requirement == CommaRequirement::RequiresNoCommas) {
  2011. if (next_is_comma)
  2012. return nullptr;
  2013. } else {
  2014. VERIFY_NOT_REACHED();
  2015. }
  2016. }
  2017. return RectStyleValue::create(EdgeRect { params[0], params[1], params[2], params[3] });
  2018. }
  2019. Optional<Color> Parser::parse_color(ComponentValue const& component_value)
  2020. {
  2021. // https://www.w3.org/TR/css-color-4/
  2022. if (component_value.is(Token::Type::Ident)) {
  2023. auto ident = component_value.token().ident();
  2024. auto color = Color::from_string(ident);
  2025. if (color.has_value())
  2026. return color;
  2027. } else if (component_value.is(Token::Type::Hash)) {
  2028. auto color = Color::from_string(MUST(String::formatted("#{}", component_value.token().hash_value())));
  2029. if (color.has_value())
  2030. return color;
  2031. return {};
  2032. } else if (component_value.is_function()) {
  2033. auto const& function = component_value.function();
  2034. auto const& values = function.values();
  2035. return parse_rgb_or_hsl_color(function.name(), values);
  2036. }
  2037. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  2038. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  2039. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  2040. // aborting on the first step that returns a value:
  2041. // 1. Let cv be the component value.
  2042. auto const& cv = component_value;
  2043. String serialization;
  2044. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  2045. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  2046. // 1. If cv’s type flag is not "integer", return an error.
  2047. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  2048. if (!cv.token().number().is_integer())
  2049. return {};
  2050. // 2. If cv’s value is less than zero, return an error.
  2051. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  2052. if (value < 0)
  2053. return {};
  2054. // 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.
  2055. StringBuilder serialization_builder;
  2056. serialization_builder.appendff("{}", value);
  2057. // 4. If cv is a <dimension-token>, append the unit to serialization.
  2058. if (cv.is(Token::Type::Dimension))
  2059. serialization_builder.append(cv.token().dimension_unit());
  2060. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  2061. serialization = MUST(serialization_builder.to_string());
  2062. if (serialization_builder.length() < 6) {
  2063. StringBuilder builder;
  2064. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  2065. builder.append('0');
  2066. builder.append(serialization_builder.string_view());
  2067. serialization = MUST(builder.to_string());
  2068. }
  2069. }
  2070. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  2071. else {
  2072. if (!cv.is(Token::Type::Ident))
  2073. return {};
  2074. serialization = cv.token().ident().to_string();
  2075. }
  2076. // 4. If serialization does not consist of three or six characters, return an error.
  2077. if (serialization.bytes().size() != 3 && serialization.bytes().size() != 6)
  2078. return {};
  2079. // 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.
  2080. for (auto c : serialization.bytes_as_string_view()) {
  2081. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  2082. return {};
  2083. }
  2084. // 6. Return the concatenation of "#" (U+0023) and serialization.
  2085. return Color::from_string(MUST(String::formatted("#{}", serialization)));
  2086. }
  2087. return {};
  2088. }
  2089. RefPtr<StyleValue> Parser::parse_color_value(ComponentValue const& component_value)
  2090. {
  2091. auto color = parse_color(component_value);
  2092. if (color.has_value())
  2093. return ColorStyleValue::create(color.value());
  2094. if (component_value.is(Token::Type::Ident)) {
  2095. auto ident = value_id_from_string(component_value.token().ident());
  2096. if (ident.has_value() && IdentifierStyleValue::is_color(ident.value()))
  2097. return IdentifierStyleValue::create(ident.value());
  2098. }
  2099. return nullptr;
  2100. }
  2101. RefPtr<StyleValue> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  2102. {
  2103. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  2104. return RatioStyleValue::create(ratio.release_value());
  2105. return nullptr;
  2106. }
  2107. RefPtr<StyleValue> Parser::parse_string_value(ComponentValue const& component_value)
  2108. {
  2109. if (component_value.is(Token::Type::String))
  2110. return StringStyleValue::create(component_value.token().string().to_string());
  2111. return nullptr;
  2112. }
  2113. RefPtr<StyleValue> Parser::parse_image_value(ComponentValue const& component_value)
  2114. {
  2115. auto url = parse_url_function(component_value);
  2116. if (url.has_value())
  2117. return ImageStyleValue::create(url.value());
  2118. auto linear_gradient = parse_linear_gradient_function(component_value);
  2119. if (linear_gradient)
  2120. return linear_gradient;
  2121. auto conic_gradient = parse_conic_gradient_function(component_value);
  2122. if (conic_gradient)
  2123. return conic_gradient;
  2124. return parse_radial_gradient_function(component_value);
  2125. }
  2126. // https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint
  2127. RefPtr<StyleValue> Parser::parse_paint_value(TokenStream<ComponentValue>& tokens)
  2128. {
  2129. // `<paint> = none | <color> | <url> [none | <color>]? | context-fill | context-stroke`
  2130. auto parse_color_or_none = [&]() -> Optional<RefPtr<StyleValue>> {
  2131. if (auto color = parse_color_value(tokens.peek_token())) {
  2132. (void)tokens.next_token();
  2133. return color;
  2134. }
  2135. // NOTE: <color> also accepts identifiers, so we do this identifier check last.
  2136. if (tokens.peek_token().is(Token::Type::Ident)) {
  2137. auto maybe_ident = value_id_from_string(tokens.peek_token().token().ident());
  2138. if (maybe_ident.has_value()) {
  2139. // FIXME: Accept `context-fill` and `context-stroke`
  2140. switch (*maybe_ident) {
  2141. case ValueID::None:
  2142. (void)tokens.next_token();
  2143. return IdentifierStyleValue::create(*maybe_ident);
  2144. default:
  2145. return nullptr;
  2146. }
  2147. }
  2148. }
  2149. return OptionalNone {};
  2150. };
  2151. // FIMXE: Allow context-fill/context-stroke here
  2152. if (auto color_or_none = parse_color_or_none(); color_or_none.has_value())
  2153. return *color_or_none;
  2154. if (auto url = parse_url_value(tokens.peek_token())) {
  2155. (void)tokens.next_token();
  2156. tokens.skip_whitespace();
  2157. if (auto color_or_none = parse_color_or_none(); color_or_none == nullptr) {
  2158. // Fail to parse if the fallback is invalid, but otherwise ignore it.
  2159. // FIXME: Use fallback color
  2160. return nullptr;
  2161. }
  2162. return url;
  2163. }
  2164. return nullptr;
  2165. }
  2166. // https://www.w3.org/TR/css-values-4/#position
  2167. RefPtr<PositionStyleValue> Parser::parse_position_value(TokenStream<ComponentValue>& tokens, PositionParsingMode position_parsing_mode)
  2168. {
  2169. auto parse_position_edge = [](ComponentValue const& token) -> Optional<PositionEdge> {
  2170. if (!token.is(Token::Type::Ident))
  2171. return {};
  2172. auto ident = value_id_from_string(token.token().ident());
  2173. if (!ident.has_value())
  2174. return {};
  2175. return value_id_to_position_edge(*ident);
  2176. };
  2177. auto parse_length_percentage = [&](ComponentValue const& token) -> Optional<LengthPercentage> {
  2178. if (token.is(Token::Type::EndOfFile))
  2179. return {};
  2180. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  2181. if (dimension->is_length_percentage())
  2182. return dimension->length_percentage();
  2183. return {};
  2184. }
  2185. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length_percentage())
  2186. return LengthPercentage { calc.release_nonnull() };
  2187. return {};
  2188. };
  2189. auto is_horizontal = [](PositionEdge edge, bool accept_center) -> bool {
  2190. switch (edge) {
  2191. case PositionEdge::Left:
  2192. case PositionEdge::Right:
  2193. return true;
  2194. case PositionEdge::Center:
  2195. return accept_center;
  2196. default:
  2197. return false;
  2198. }
  2199. };
  2200. auto is_vertical = [](PositionEdge edge, bool accept_center) -> bool {
  2201. switch (edge) {
  2202. case PositionEdge::Top:
  2203. case PositionEdge::Bottom:
  2204. return true;
  2205. case PositionEdge::Center:
  2206. return accept_center;
  2207. default:
  2208. return false;
  2209. }
  2210. };
  2211. auto make_edge_style_value = [](PositionEdge position_edge, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  2212. if (position_edge == PositionEdge::Center)
  2213. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  2214. return EdgeStyleValue::create(position_edge, Length::make_px(0));
  2215. };
  2216. // <position> = [
  2217. // [ left | center | right | top | bottom | <length-percentage> ]
  2218. // |
  2219. // [ left | center | right ] && [ top | center | bottom ]
  2220. // |
  2221. // [ left | center | right | <length-percentage> ]
  2222. // [ top | center | bottom | <length-percentage> ]
  2223. // |
  2224. // [ [ left | right ] <length-percentage> ] &&
  2225. // [ [ top | bottom ] <length-percentage> ]
  2226. // ]
  2227. // [ left | center | right | top | bottom | <length-percentage> ]
  2228. auto alternative_1 = [&]() -> RefPtr<PositionStyleValue> {
  2229. auto transaction = tokens.begin_transaction();
  2230. tokens.skip_whitespace();
  2231. auto const& token = tokens.next_token();
  2232. // [ left | center | right | top | bottom ]
  2233. if (auto maybe_edge = parse_position_edge(token); maybe_edge.has_value()) {
  2234. auto edge = maybe_edge.release_value();
  2235. transaction.commit();
  2236. // [ left | right ]
  2237. if (is_horizontal(edge, false))
  2238. return PositionStyleValue::create(make_edge_style_value(edge, true), make_edge_style_value(PositionEdge::Center, false));
  2239. // [ top | bottom ]
  2240. if (is_vertical(edge, false))
  2241. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(edge, false));
  2242. // [ center ]
  2243. VERIFY(edge == PositionEdge::Center);
  2244. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(PositionEdge::Center, false));
  2245. }
  2246. // [ <length-percentage> ]
  2247. if (auto maybe_percentage = parse_length_percentage(token); maybe_percentage.has_value()) {
  2248. transaction.commit();
  2249. return PositionStyleValue::create(EdgeStyleValue::create(PositionEdge::Left, *maybe_percentage), make_edge_style_value(PositionEdge::Center, false));
  2250. }
  2251. return nullptr;
  2252. };
  2253. // [ left | center | right ] && [ top | center | bottom ]
  2254. auto alternative_2 = [&]() -> RefPtr<PositionStyleValue> {
  2255. auto transaction = tokens.begin_transaction();
  2256. tokens.skip_whitespace();
  2257. // Parse out two position edges
  2258. auto maybe_first_edge = parse_position_edge(tokens.next_token());
  2259. if (!maybe_first_edge.has_value())
  2260. return nullptr;
  2261. auto first_edge = maybe_first_edge.release_value();
  2262. tokens.skip_whitespace();
  2263. auto maybe_second_edge = parse_position_edge(tokens.next_token());
  2264. if (!maybe_second_edge.has_value())
  2265. return nullptr;
  2266. auto second_edge = maybe_second_edge.release_value();
  2267. // If 'left' or 'right' is given, that position is X and the other is Y.
  2268. // Conversely -
  2269. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  2270. if (is_vertical(first_edge, false) || is_horizontal(second_edge, false))
  2271. swap(first_edge, second_edge);
  2272. // [ left | center | right ] [ top | bottom | center ]
  2273. if (is_horizontal(first_edge, true) && is_vertical(second_edge, true)) {
  2274. transaction.commit();
  2275. return PositionStyleValue::create(make_edge_style_value(first_edge, true), make_edge_style_value(second_edge, false));
  2276. }
  2277. return nullptr;
  2278. };
  2279. // [ left | center | right | <length-percentage> ]
  2280. // [ top | center | bottom | <length-percentage> ]
  2281. auto alternative_3 = [&]() -> RefPtr<PositionStyleValue> {
  2282. auto transaction = tokens.begin_transaction();
  2283. auto parse_position_or_length = [&](bool as_horizontal) -> RefPtr<EdgeStyleValue> {
  2284. tokens.skip_whitespace();
  2285. auto const& token = tokens.next_token();
  2286. if (auto maybe_position = parse_position_edge(token); maybe_position.has_value()) {
  2287. auto position = maybe_position.release_value();
  2288. bool valid = as_horizontal ? is_horizontal(position, true) : is_vertical(position, true);
  2289. if (!valid)
  2290. return nullptr;
  2291. return make_edge_style_value(position, as_horizontal);
  2292. }
  2293. auto maybe_length = parse_length_percentage(token);
  2294. if (!maybe_length.has_value())
  2295. return nullptr;
  2296. return EdgeStyleValue::create(as_horizontal ? PositionEdge::Left : PositionEdge::Top, maybe_length.release_value());
  2297. };
  2298. // [ left | center | right | <length-percentage> ]
  2299. auto horizontal_edge = parse_position_or_length(true);
  2300. if (!horizontal_edge)
  2301. return nullptr;
  2302. // [ top | center | bottom | <length-percentage> ]
  2303. auto vertical_edge = parse_position_or_length(false);
  2304. if (!vertical_edge)
  2305. return nullptr;
  2306. transaction.commit();
  2307. return PositionStyleValue::create(horizontal_edge.release_nonnull(), vertical_edge.release_nonnull());
  2308. };
  2309. // [ [ left | right ] <length-percentage> ] &&
  2310. // [ [ top | bottom ] <length-percentage> ]
  2311. auto alternative_4 = [&]() -> RefPtr<PositionStyleValue> {
  2312. struct PositionAndLength {
  2313. PositionEdge position;
  2314. LengthPercentage length;
  2315. };
  2316. auto parse_position_and_length = [&]() -> Optional<PositionAndLength> {
  2317. tokens.skip_whitespace();
  2318. auto maybe_position = parse_position_edge(tokens.next_token());
  2319. if (!maybe_position.has_value())
  2320. return {};
  2321. tokens.skip_whitespace();
  2322. auto maybe_length = parse_length_percentage(tokens.next_token());
  2323. if (!maybe_length.has_value())
  2324. return {};
  2325. return PositionAndLength {
  2326. .position = maybe_position.release_value(),
  2327. .length = maybe_length.release_value(),
  2328. };
  2329. };
  2330. auto transaction = tokens.begin_transaction();
  2331. auto maybe_group1 = parse_position_and_length();
  2332. if (!maybe_group1.has_value())
  2333. return nullptr;
  2334. auto maybe_group2 = parse_position_and_length();
  2335. if (!maybe_group2.has_value())
  2336. return nullptr;
  2337. auto group1 = maybe_group1.release_value();
  2338. auto group2 = maybe_group2.release_value();
  2339. // [ [ left | right ] <length-percentage> ] [ [ top | bottom ] <length-percentage> ]
  2340. if (is_horizontal(group1.position, false) && is_vertical(group2.position, false)) {
  2341. transaction.commit();
  2342. return PositionStyleValue::create(EdgeStyleValue::create(group1.position, group1.length), EdgeStyleValue::create(group2.position, group2.length));
  2343. }
  2344. // [ [ top | bottom ] <length-percentage> ] [ [ left | right ] <length-percentage> ]
  2345. if (is_vertical(group1.position, false) && is_horizontal(group2.position, false)) {
  2346. transaction.commit();
  2347. return PositionStyleValue::create(EdgeStyleValue::create(group2.position, group2.length), EdgeStyleValue::create(group1.position, group1.length));
  2348. }
  2349. return nullptr;
  2350. };
  2351. // The extra 3-value syntax that's allowed for background-position:
  2352. // [ center | [ left | right ] <length-percentage>? ] &&
  2353. // [ center | [ top | bottom ] <length-percentage>? ]
  2354. auto alternative_5_for_background_position = [&]() -> RefPtr<PositionStyleValue> {
  2355. auto transaction = tokens.begin_transaction();
  2356. struct PositionAndMaybeLength {
  2357. PositionEdge position;
  2358. Optional<LengthPercentage> length;
  2359. };
  2360. // [ <position> <length-percentage>? ]
  2361. auto parse_position_and_maybe_length = [&]() -> Optional<PositionAndMaybeLength> {
  2362. tokens.skip_whitespace();
  2363. auto maybe_position = parse_position_edge(tokens.next_token());
  2364. if (!maybe_position.has_value())
  2365. return {};
  2366. tokens.skip_whitespace();
  2367. auto maybe_length = parse_length_percentage(tokens.peek_token());
  2368. if (maybe_length.has_value()) {
  2369. // 'center' cannot be followed by a <length-percentage>
  2370. if (maybe_position.value() == PositionEdge::Center && maybe_length.has_value())
  2371. return {};
  2372. tokens.next_token();
  2373. }
  2374. return PositionAndMaybeLength {
  2375. .position = maybe_position.release_value(),
  2376. .length = move(maybe_length),
  2377. };
  2378. };
  2379. auto maybe_group1 = parse_position_and_maybe_length();
  2380. if (!maybe_group1.has_value())
  2381. return nullptr;
  2382. auto maybe_group2 = parse_position_and_maybe_length();
  2383. if (!maybe_group2.has_value())
  2384. return nullptr;
  2385. auto group1 = maybe_group1.release_value();
  2386. auto group2 = maybe_group2.release_value();
  2387. // 2-value or 4-value if both <length-percentage>s are present or missing.
  2388. if (group1.length.has_value() == group2.length.has_value())
  2389. return nullptr;
  2390. // If 'left' or 'right' is given, that position is X and the other is Y.
  2391. // Conversely -
  2392. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  2393. if (is_vertical(group1.position, false) || is_horizontal(group2.position, false))
  2394. swap(group1, group2);
  2395. // [ center | [ left | right ] ]
  2396. if (!is_horizontal(group1.position, true))
  2397. return nullptr;
  2398. // [ center | [ top | bottom ] ]
  2399. if (!is_vertical(group2.position, true))
  2400. return nullptr;
  2401. auto to_style_value = [&](PositionAndMaybeLength const& group, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  2402. if (group.position == PositionEdge::Center)
  2403. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  2404. return EdgeStyleValue::create(group.position, group.length.value_or(Length::make_px(0)));
  2405. };
  2406. transaction.commit();
  2407. return PositionStyleValue::create(to_style_value(group1, true), to_style_value(group2, false));
  2408. };
  2409. // Note: The alternatives must be attempted in this order since shorter alternatives can match a prefix of longer ones.
  2410. if (auto position = alternative_4())
  2411. return position;
  2412. if (position_parsing_mode == PositionParsingMode::BackgroundPosition) {
  2413. if (auto position = alternative_5_for_background_position())
  2414. return position;
  2415. }
  2416. if (auto position = alternative_3())
  2417. return position;
  2418. if (auto position = alternative_2())
  2419. return position;
  2420. if (auto position = alternative_1())
  2421. return position;
  2422. return nullptr;
  2423. }
  2424. template<typename ParseFunction>
  2425. RefPtr<StyleValue> Parser::parse_comma_separated_value_list(TokenStream<ComponentValue>& tokens, ParseFunction parse_one_value)
  2426. {
  2427. auto first = parse_one_value(tokens);
  2428. if (!first || !tokens.has_next_token())
  2429. return first;
  2430. StyleValueVector values;
  2431. values.append(first.release_nonnull());
  2432. while (tokens.has_next_token()) {
  2433. if (!tokens.next_token().is(Token::Type::Comma))
  2434. return nullptr;
  2435. if (auto maybe_value = parse_one_value(tokens)) {
  2436. values.append(maybe_value.release_nonnull());
  2437. continue;
  2438. }
  2439. return nullptr;
  2440. }
  2441. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  2442. }
  2443. RefPtr<StyleValue> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  2444. {
  2445. return parse_comma_separated_value_list(tokens, [this, property_id](auto& tokens) -> RefPtr<StyleValue> {
  2446. if (auto value = parse_css_value_for_property(property_id, tokens))
  2447. return value;
  2448. tokens.reconsume_current_input_token();
  2449. return nullptr;
  2450. });
  2451. }
  2452. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  2453. {
  2454. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  2455. }
  2456. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  2457. RefPtr<StyleValue> Parser::parse_aspect_ratio_value(TokenStream<ComponentValue>& tokens)
  2458. {
  2459. // `auto || <ratio>`
  2460. RefPtr<StyleValue> auto_value;
  2461. RefPtr<StyleValue> ratio_value;
  2462. auto transaction = tokens.begin_transaction();
  2463. while (tokens.has_next_token()) {
  2464. auto maybe_value = parse_css_value_for_property(PropertyID::AspectRatio, tokens);
  2465. if (!maybe_value)
  2466. return nullptr;
  2467. if (maybe_value->is_ratio()) {
  2468. if (ratio_value)
  2469. return nullptr;
  2470. ratio_value = maybe_value.release_nonnull();
  2471. continue;
  2472. }
  2473. if (maybe_value->is_identifier() && maybe_value->as_identifier().id() == ValueID::Auto) {
  2474. if (auto_value)
  2475. return nullptr;
  2476. auto_value = maybe_value.release_nonnull();
  2477. continue;
  2478. }
  2479. return nullptr;
  2480. }
  2481. if (auto_value && ratio_value) {
  2482. transaction.commit();
  2483. return StyleValueList::create(
  2484. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  2485. StyleValueList::Separator::Space);
  2486. }
  2487. if (ratio_value) {
  2488. transaction.commit();
  2489. return ratio_value.release_nonnull();
  2490. }
  2491. if (auto_value) {
  2492. transaction.commit();
  2493. return auto_value.release_nonnull();
  2494. }
  2495. return nullptr;
  2496. }
  2497. RefPtr<StyleValue> Parser::parse_background_value(TokenStream<ComponentValue>& tokens)
  2498. {
  2499. auto transaction = tokens.begin_transaction();
  2500. auto make_background_shorthand = [&](auto background_color, auto background_image, auto background_position, auto background_size, auto background_repeat, auto background_attachment, auto background_origin, auto background_clip) {
  2501. return ShorthandStyleValue::create(PropertyID::Background,
  2502. { PropertyID::BackgroundColor, PropertyID::BackgroundImage, PropertyID::BackgroundPosition, PropertyID::BackgroundSize, PropertyID::BackgroundRepeat, PropertyID::BackgroundAttachment, PropertyID::BackgroundOrigin, PropertyID::BackgroundClip },
  2503. { move(background_color), move(background_image), move(background_position), move(background_size), move(background_repeat), move(background_attachment), move(background_origin), move(background_clip) });
  2504. };
  2505. StyleValueVector background_images;
  2506. StyleValueVector background_positions;
  2507. StyleValueVector background_sizes;
  2508. StyleValueVector background_repeats;
  2509. StyleValueVector background_attachments;
  2510. StyleValueVector background_clips;
  2511. StyleValueVector background_origins;
  2512. RefPtr<StyleValue> background_color;
  2513. auto initial_background_image = property_initial_value(m_context.realm(), PropertyID::BackgroundImage);
  2514. auto initial_background_position = property_initial_value(m_context.realm(), PropertyID::BackgroundPosition);
  2515. auto initial_background_size = property_initial_value(m_context.realm(), PropertyID::BackgroundSize);
  2516. auto initial_background_repeat = property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat);
  2517. auto initial_background_attachment = property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment);
  2518. auto initial_background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
  2519. auto initial_background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
  2520. auto initial_background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
  2521. // Per-layer values
  2522. RefPtr<StyleValue> background_image;
  2523. RefPtr<StyleValue> background_position;
  2524. RefPtr<StyleValue> background_size;
  2525. RefPtr<StyleValue> background_repeat;
  2526. RefPtr<StyleValue> background_attachment;
  2527. RefPtr<StyleValue> background_clip;
  2528. RefPtr<StyleValue> background_origin;
  2529. bool has_multiple_layers = false;
  2530. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  2531. Vector<PropertyID> remaining_layer_properties {
  2532. PropertyID::BackgroundAttachment,
  2533. PropertyID::BackgroundClip,
  2534. PropertyID::BackgroundColor,
  2535. PropertyID::BackgroundImage,
  2536. PropertyID::BackgroundOrigin,
  2537. PropertyID::BackgroundPosition,
  2538. PropertyID::BackgroundRepeat,
  2539. };
  2540. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  2541. if (allow_background_color) {
  2542. if (background_color)
  2543. return true;
  2544. } else {
  2545. if (background_color)
  2546. return false;
  2547. }
  2548. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  2549. };
  2550. auto complete_background_layer = [&]() {
  2551. background_images.append(background_image ? background_image.release_nonnull() : initial_background_image);
  2552. background_positions.append(background_position ? background_position.release_nonnull() : initial_background_position);
  2553. background_sizes.append(background_size ? background_size.release_nonnull() : initial_background_size);
  2554. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat);
  2555. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment);
  2556. if (!background_origin && !background_clip) {
  2557. background_origin = initial_background_origin;
  2558. background_clip = initial_background_clip;
  2559. } else if (!background_clip) {
  2560. background_clip = background_origin;
  2561. }
  2562. background_origins.append(background_origin.release_nonnull());
  2563. background_clips.append(background_clip.release_nonnull());
  2564. background_image = nullptr;
  2565. background_position = nullptr;
  2566. background_size = nullptr;
  2567. background_repeat = nullptr;
  2568. background_attachment = nullptr;
  2569. background_clip = nullptr;
  2570. background_origin = nullptr;
  2571. remaining_layer_properties.clear_with_capacity();
  2572. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  2573. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  2574. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  2575. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  2576. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  2577. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  2578. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  2579. };
  2580. while (tokens.has_next_token()) {
  2581. if (tokens.peek_token().is(Token::Type::Comma)) {
  2582. has_multiple_layers = true;
  2583. if (!background_layer_is_valid(false))
  2584. return nullptr;
  2585. complete_background_layer();
  2586. (void)tokens.next_token();
  2587. continue;
  2588. }
  2589. auto value_and_property = parse_css_value_for_properties(remaining_layer_properties, tokens);
  2590. if (!value_and_property.has_value())
  2591. return nullptr;
  2592. auto& value = value_and_property->style_value;
  2593. remove_property(remaining_layer_properties, value_and_property->property);
  2594. switch (value_and_property->property) {
  2595. case PropertyID::BackgroundAttachment:
  2596. VERIFY(!background_attachment);
  2597. background_attachment = value.release_nonnull();
  2598. continue;
  2599. case PropertyID::BackgroundColor:
  2600. VERIFY(!background_color);
  2601. background_color = value.release_nonnull();
  2602. continue;
  2603. case PropertyID::BackgroundImage:
  2604. VERIFY(!background_image);
  2605. background_image = value.release_nonnull();
  2606. continue;
  2607. case PropertyID::BackgroundClip:
  2608. case PropertyID::BackgroundOrigin: {
  2609. // background-origin and background-clip accept the same values. From the spec:
  2610. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  2611. // If two values are present, then the first sets background-origin and the second background-clip."
  2612. // - https://www.w3.org/TR/css-backgrounds-3/#background
  2613. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  2614. // If we only get one, we copy the value before creating the ShorthandStyleValue.
  2615. if (!background_origin) {
  2616. background_origin = value.release_nonnull();
  2617. } else if (!background_clip) {
  2618. background_clip = value.release_nonnull();
  2619. } else {
  2620. VERIFY_NOT_REACHED();
  2621. }
  2622. continue;
  2623. }
  2624. case PropertyID::BackgroundPosition: {
  2625. VERIFY(!background_position);
  2626. background_position = value.release_nonnull();
  2627. // Attempt to parse `/ <background-size>`
  2628. auto background_size_transaction = tokens.begin_transaction();
  2629. auto& maybe_slash = tokens.next_token();
  2630. if (maybe_slash.is_delim('/')) {
  2631. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  2632. background_size_transaction.commit();
  2633. background_size = maybe_background_size.release_nonnull();
  2634. continue;
  2635. }
  2636. return nullptr;
  2637. }
  2638. continue;
  2639. }
  2640. case PropertyID::BackgroundRepeat: {
  2641. VERIFY(!background_repeat);
  2642. tokens.reconsume_current_input_token();
  2643. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  2644. background_repeat = maybe_repeat.release_nonnull();
  2645. continue;
  2646. }
  2647. return nullptr;
  2648. }
  2649. default:
  2650. VERIFY_NOT_REACHED();
  2651. }
  2652. return nullptr;
  2653. }
  2654. if (!background_layer_is_valid(true))
  2655. return nullptr;
  2656. // We only need to create StyleValueLists if there are multiple layers.
  2657. // Otherwise, we can pass the single StyleValues directly.
  2658. if (has_multiple_layers) {
  2659. complete_background_layer();
  2660. if (!background_color)
  2661. background_color = initial_background_color;
  2662. transaction.commit();
  2663. return make_background_shorthand(
  2664. background_color.release_nonnull(),
  2665. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  2666. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  2667. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  2668. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  2669. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  2670. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  2671. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  2672. }
  2673. if (!background_color)
  2674. background_color = initial_background_color;
  2675. if (!background_image)
  2676. background_image = initial_background_image;
  2677. if (!background_position)
  2678. background_position = initial_background_position;
  2679. if (!background_size)
  2680. background_size = initial_background_size;
  2681. if (!background_repeat)
  2682. background_repeat = initial_background_repeat;
  2683. if (!background_attachment)
  2684. background_attachment = initial_background_attachment;
  2685. if (!background_origin && !background_clip) {
  2686. background_origin = initial_background_origin;
  2687. background_clip = initial_background_clip;
  2688. } else if (!background_clip) {
  2689. background_clip = background_origin;
  2690. }
  2691. transaction.commit();
  2692. return make_background_shorthand(
  2693. background_color.release_nonnull(),
  2694. background_image.release_nonnull(),
  2695. background_position.release_nonnull(),
  2696. background_size.release_nonnull(),
  2697. background_repeat.release_nonnull(),
  2698. background_attachment.release_nonnull(),
  2699. background_origin.release_nonnull(),
  2700. background_clip.release_nonnull());
  2701. }
  2702. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  2703. {
  2704. if (value->is_percentage())
  2705. return LengthPercentage { value->as_percentage().percentage() };
  2706. if (value->is_length())
  2707. return LengthPercentage { value->as_length().length() };
  2708. if (value->is_calculated())
  2709. return LengthPercentage { value->as_calculated() };
  2710. return {};
  2711. }
  2712. RefPtr<StyleValue> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  2713. {
  2714. PositionEdge relative_edge {};
  2715. if (property == PropertyID::BackgroundPositionX) {
  2716. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  2717. relative_edge = PositionEdge::Left;
  2718. } else if (property == PropertyID::BackgroundPositionY) {
  2719. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  2720. relative_edge = PositionEdge::Top;
  2721. } else {
  2722. VERIFY_NOT_REACHED();
  2723. }
  2724. auto transaction = tokens.begin_transaction();
  2725. if (!tokens.has_next_token())
  2726. return nullptr;
  2727. auto value = parse_css_value_for_property(property, tokens);
  2728. if (!value)
  2729. return nullptr;
  2730. if (value->is_identifier()) {
  2731. auto identifier = value->to_identifier();
  2732. if (identifier == ValueID::Center) {
  2733. transaction.commit();
  2734. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  2735. }
  2736. if (auto edge = value_id_to_position_edge(identifier); edge.has_value()) {
  2737. relative_edge = *edge;
  2738. } else {
  2739. return nullptr;
  2740. }
  2741. if (tokens.has_next_token()) {
  2742. value = parse_css_value_for_property(property, tokens);
  2743. if (!value) {
  2744. transaction.commit();
  2745. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  2746. }
  2747. }
  2748. }
  2749. auto offset = style_value_to_length_percentage(value);
  2750. if (offset.has_value()) {
  2751. transaction.commit();
  2752. return EdgeStyleValue::create(relative_edge, *offset);
  2753. }
  2754. // If no offset is provided create this element but with an offset of default value of zero
  2755. transaction.commit();
  2756. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  2757. }
  2758. RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  2759. {
  2760. auto transaction = tokens.begin_transaction();
  2761. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2762. auto value_id = value.to_identifier();
  2763. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2764. };
  2765. auto as_repeat = [](ValueID identifier) -> Optional<Repeat> {
  2766. switch (identifier) {
  2767. case ValueID::NoRepeat:
  2768. return Repeat::NoRepeat;
  2769. case ValueID::Repeat:
  2770. return Repeat::Repeat;
  2771. case ValueID::Round:
  2772. return Repeat::Round;
  2773. case ValueID::Space:
  2774. return Repeat::Space;
  2775. default:
  2776. return {};
  2777. }
  2778. };
  2779. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  2780. if (!maybe_x_value)
  2781. return nullptr;
  2782. auto x_value = maybe_x_value.release_nonnull();
  2783. if (is_directional_repeat(*x_value)) {
  2784. auto value_id = x_value->to_identifier();
  2785. transaction.commit();
  2786. return BackgroundRepeatStyleValue::create(
  2787. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  2788. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  2789. }
  2790. auto x_repeat = as_repeat(x_value->to_identifier());
  2791. if (!x_repeat.has_value())
  2792. return nullptr;
  2793. // See if we have a second value for Y
  2794. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  2795. if (!maybe_y_value) {
  2796. // We don't have a second value, so use x for both
  2797. transaction.commit();
  2798. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  2799. }
  2800. auto y_value = maybe_y_value.release_nonnull();
  2801. if (is_directional_repeat(*y_value))
  2802. return nullptr;
  2803. auto y_repeat = as_repeat(y_value->to_identifier());
  2804. if (!y_repeat.has_value())
  2805. return nullptr;
  2806. transaction.commit();
  2807. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  2808. }
  2809. RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  2810. {
  2811. auto transaction = tokens.begin_transaction();
  2812. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  2813. if (style_value.has_auto())
  2814. return LengthPercentage { Length::make_auto() };
  2815. if (style_value.is_percentage())
  2816. return LengthPercentage { style_value.as_percentage().percentage() };
  2817. if (style_value.is_length())
  2818. return LengthPercentage { style_value.as_length().length() };
  2819. if (style_value.is_calculated())
  2820. return LengthPercentage { style_value.as_calculated() };
  2821. return {};
  2822. };
  2823. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  2824. if (!maybe_x_value)
  2825. return nullptr;
  2826. auto x_value = maybe_x_value.release_nonnull();
  2827. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain) {
  2828. transaction.commit();
  2829. return x_value;
  2830. }
  2831. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  2832. if (!maybe_y_value) {
  2833. auto y_value = LengthPercentage { Length::make_auto() };
  2834. auto x_size = get_length_percentage(*x_value);
  2835. if (!x_size.has_value())
  2836. return nullptr;
  2837. transaction.commit();
  2838. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  2839. }
  2840. auto y_value = maybe_y_value.release_nonnull();
  2841. auto x_size = get_length_percentage(*x_value);
  2842. auto y_size = get_length_percentage(*y_value);
  2843. if (!x_size.has_value() || !y_size.has_value())
  2844. return nullptr;
  2845. transaction.commit();
  2846. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  2847. }
  2848. RefPtr<StyleValue> Parser::parse_border_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  2849. {
  2850. RefPtr<StyleValue> border_width;
  2851. RefPtr<StyleValue> border_color;
  2852. RefPtr<StyleValue> border_style;
  2853. auto color_property = PropertyID::Invalid;
  2854. auto style_property = PropertyID::Invalid;
  2855. auto width_property = PropertyID::Invalid;
  2856. switch (property_id) {
  2857. case PropertyID::Border:
  2858. color_property = PropertyID::BorderColor;
  2859. style_property = PropertyID::BorderStyle;
  2860. width_property = PropertyID::BorderWidth;
  2861. break;
  2862. case PropertyID::BorderBottom:
  2863. color_property = PropertyID::BorderBottomColor;
  2864. style_property = PropertyID::BorderBottomStyle;
  2865. width_property = PropertyID::BorderBottomWidth;
  2866. break;
  2867. case PropertyID::BorderLeft:
  2868. color_property = PropertyID::BorderLeftColor;
  2869. style_property = PropertyID::BorderLeftStyle;
  2870. width_property = PropertyID::BorderLeftWidth;
  2871. break;
  2872. case PropertyID::BorderRight:
  2873. color_property = PropertyID::BorderRightColor;
  2874. style_property = PropertyID::BorderRightStyle;
  2875. width_property = PropertyID::BorderRightWidth;
  2876. break;
  2877. case PropertyID::BorderTop:
  2878. color_property = PropertyID::BorderTopColor;
  2879. style_property = PropertyID::BorderTopStyle;
  2880. width_property = PropertyID::BorderTopWidth;
  2881. break;
  2882. default:
  2883. VERIFY_NOT_REACHED();
  2884. }
  2885. auto remaining_longhands = Vector { width_property, color_property, style_property };
  2886. auto transaction = tokens.begin_transaction();
  2887. while (tokens.has_next_token()) {
  2888. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  2889. if (!property_and_value.has_value())
  2890. return nullptr;
  2891. auto& value = property_and_value->style_value;
  2892. remove_property(remaining_longhands, property_and_value->property);
  2893. if (property_and_value->property == width_property) {
  2894. VERIFY(!border_width);
  2895. border_width = value.release_nonnull();
  2896. } else if (property_and_value->property == color_property) {
  2897. VERIFY(!border_color);
  2898. border_color = value.release_nonnull();
  2899. } else if (property_and_value->property == style_property) {
  2900. VERIFY(!border_style);
  2901. border_style = value.release_nonnull();
  2902. } else {
  2903. VERIFY_NOT_REACHED();
  2904. }
  2905. }
  2906. if (!border_width)
  2907. border_width = property_initial_value(m_context.realm(), width_property);
  2908. if (!border_style)
  2909. border_style = property_initial_value(m_context.realm(), style_property);
  2910. if (!border_color)
  2911. border_color = property_initial_value(m_context.realm(), color_property);
  2912. transaction.commit();
  2913. return ShorthandStyleValue::create(property_id,
  2914. { width_property, style_property, color_property },
  2915. { border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull() });
  2916. }
  2917. RefPtr<StyleValue> Parser::parse_border_radius_value(TokenStream<ComponentValue>& tokens)
  2918. {
  2919. if (tokens.remaining_token_count() == 2) {
  2920. auto transaction = tokens.begin_transaction();
  2921. auto horizontal = parse_length_percentage(tokens);
  2922. auto vertical = parse_length_percentage(tokens);
  2923. if (horizontal.has_value() && vertical.has_value()) {
  2924. transaction.commit();
  2925. return BorderRadiusStyleValue::create(horizontal.release_value(), vertical.release_value());
  2926. }
  2927. }
  2928. if (tokens.remaining_token_count() == 1) {
  2929. auto transaction = tokens.begin_transaction();
  2930. auto radius = parse_length_percentage(tokens);
  2931. if (radius.has_value()) {
  2932. transaction.commit();
  2933. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  2934. }
  2935. }
  2936. return nullptr;
  2937. }
  2938. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(TokenStream<ComponentValue>& tokens)
  2939. {
  2940. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  2941. auto top_right = [&](Vector<LengthPercentage>& radii) {
  2942. switch (radii.size()) {
  2943. case 4:
  2944. case 3:
  2945. case 2:
  2946. return radii[1];
  2947. case 1:
  2948. return radii[0];
  2949. default:
  2950. VERIFY_NOT_REACHED();
  2951. }
  2952. };
  2953. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  2954. switch (radii.size()) {
  2955. case 4:
  2956. case 3:
  2957. return radii[2];
  2958. case 2:
  2959. case 1:
  2960. return radii[0];
  2961. default:
  2962. VERIFY_NOT_REACHED();
  2963. }
  2964. };
  2965. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  2966. switch (radii.size()) {
  2967. case 4:
  2968. return radii[3];
  2969. case 3:
  2970. case 2:
  2971. return radii[1];
  2972. case 1:
  2973. return radii[0];
  2974. default:
  2975. VERIFY_NOT_REACHED();
  2976. }
  2977. };
  2978. Vector<LengthPercentage> horizontal_radii;
  2979. Vector<LengthPercentage> vertical_radii;
  2980. bool reading_vertical = false;
  2981. auto transaction = tokens.begin_transaction();
  2982. while (tokens.has_next_token()) {
  2983. if (tokens.peek_token().is_delim('/')) {
  2984. if (reading_vertical || horizontal_radii.is_empty())
  2985. return nullptr;
  2986. reading_vertical = true;
  2987. (void)tokens.next_token(); // `/`
  2988. continue;
  2989. }
  2990. auto maybe_dimension = parse_length_percentage(tokens);
  2991. if (!maybe_dimension.has_value())
  2992. return nullptr;
  2993. if (reading_vertical) {
  2994. vertical_radii.append(maybe_dimension.release_value());
  2995. } else {
  2996. horizontal_radii.append(maybe_dimension.release_value());
  2997. }
  2998. }
  2999. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  3000. || horizontal_radii.is_empty()
  3001. || (reading_vertical && vertical_radii.is_empty()))
  3002. return nullptr;
  3003. auto top_left_radius = BorderRadiusStyleValue::create(top_left(horizontal_radii),
  3004. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii));
  3005. auto top_right_radius = BorderRadiusStyleValue::create(top_right(horizontal_radii),
  3006. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii));
  3007. auto bottom_right_radius = BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  3008. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii));
  3009. auto bottom_left_radius = BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  3010. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii));
  3011. transaction.commit();
  3012. return ShorthandStyleValue::create(PropertyID::BorderRadius,
  3013. { PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius },
  3014. { move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius) });
  3015. }
  3016. RefPtr<StyleValue> Parser::parse_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  3017. {
  3018. // "none"
  3019. if (contains_single_none_ident(tokens))
  3020. return parse_identifier_value(tokens.next_token());
  3021. return parse_comma_separated_value_list(tokens, [this, allow_inset_keyword](auto& tokens) {
  3022. return parse_single_shadow_value(tokens, allow_inset_keyword);
  3023. });
  3024. }
  3025. RefPtr<StyleValue> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  3026. {
  3027. auto transaction = tokens.begin_transaction();
  3028. Optional<Color> color;
  3029. RefPtr<StyleValue> offset_x;
  3030. RefPtr<StyleValue> offset_y;
  3031. RefPtr<StyleValue> blur_radius;
  3032. RefPtr<StyleValue> spread_distance;
  3033. Optional<ShadowPlacement> placement;
  3034. auto possibly_dynamic_length = [&](ComponentValue const& token) -> RefPtr<StyleValue> {
  3035. auto tokens = TokenStream<ComponentValue>::of_single_token(token);
  3036. auto maybe_length = parse_length(tokens);
  3037. if (!maybe_length.has_value())
  3038. return nullptr;
  3039. return maybe_length->as_style_value();
  3040. };
  3041. while (tokens.has_next_token()) {
  3042. auto const& token = tokens.peek_token();
  3043. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  3044. if (color.has_value())
  3045. return nullptr;
  3046. color = maybe_color.release_value();
  3047. tokens.next_token();
  3048. continue;
  3049. }
  3050. if (auto maybe_offset_x = possibly_dynamic_length(token); maybe_offset_x) {
  3051. // horizontal offset
  3052. if (offset_x)
  3053. return nullptr;
  3054. offset_x = maybe_offset_x;
  3055. tokens.next_token();
  3056. // vertical offset
  3057. if (!tokens.has_next_token())
  3058. return nullptr;
  3059. auto maybe_offset_y = possibly_dynamic_length(tokens.peek_token());
  3060. if (!maybe_offset_y)
  3061. return nullptr;
  3062. offset_y = maybe_offset_y;
  3063. tokens.next_token();
  3064. // blur radius (optional)
  3065. if (!tokens.has_next_token())
  3066. break;
  3067. auto maybe_blur_radius = possibly_dynamic_length(tokens.peek_token());
  3068. if (!maybe_blur_radius)
  3069. continue;
  3070. blur_radius = maybe_blur_radius;
  3071. tokens.next_token();
  3072. // spread distance (optional)
  3073. if (!tokens.has_next_token())
  3074. break;
  3075. auto maybe_spread_distance = possibly_dynamic_length(tokens.peek_token());
  3076. if (!maybe_spread_distance)
  3077. continue;
  3078. spread_distance = maybe_spread_distance;
  3079. tokens.next_token();
  3080. continue;
  3081. }
  3082. if (allow_inset_keyword == AllowInsetKeyword::Yes && token.is_ident("inset"sv)) {
  3083. if (placement.has_value())
  3084. return nullptr;
  3085. placement = ShadowPlacement::Inner;
  3086. tokens.next_token();
  3087. continue;
  3088. }
  3089. if (token.is(Token::Type::Comma))
  3090. break;
  3091. return nullptr;
  3092. }
  3093. // FIXME: If color is absent, default to `currentColor`
  3094. if (!color.has_value())
  3095. color = Color::NamedColor::Black;
  3096. // x/y offsets are required
  3097. if (!offset_x || !offset_y)
  3098. return nullptr;
  3099. // Other lengths default to 0
  3100. if (!blur_radius)
  3101. blur_radius = LengthStyleValue::create(Length::make_px(0));
  3102. if (!spread_distance)
  3103. spread_distance = LengthStyleValue::create(Length::make_px(0));
  3104. // Placement is outer by default
  3105. if (!placement.has_value())
  3106. placement = ShadowPlacement::Outer;
  3107. transaction.commit();
  3108. return ShadowStyleValue::create(color.release_value(), offset_x.release_nonnull(), offset_y.release_nonnull(), blur_radius.release_nonnull(), spread_distance.release_nonnull(), placement.release_value());
  3109. }
  3110. RefPtr<StyleValue> Parser::parse_content_value(TokenStream<ComponentValue>& tokens)
  3111. {
  3112. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  3113. auto transaction = tokens.begin_transaction();
  3114. auto is_single_value_identifier = [](ValueID identifier) -> bool {
  3115. switch (identifier) {
  3116. case ValueID::None:
  3117. case ValueID::Normal:
  3118. return true;
  3119. default:
  3120. return false;
  3121. }
  3122. };
  3123. if (tokens.remaining_token_count() == 1) {
  3124. if (auto identifier = parse_identifier_value(tokens.peek_token())) {
  3125. if (is_single_value_identifier(identifier->to_identifier())) {
  3126. (void)tokens.next_token();
  3127. transaction.commit();
  3128. return identifier;
  3129. }
  3130. }
  3131. }
  3132. StyleValueVector content_values;
  3133. StyleValueVector alt_text_values;
  3134. bool in_alt_text = false;
  3135. while (tokens.has_next_token()) {
  3136. auto& next = tokens.peek_token();
  3137. if (next.is_delim('/')) {
  3138. if (in_alt_text || content_values.is_empty())
  3139. return nullptr;
  3140. in_alt_text = true;
  3141. (void)tokens.next_token();
  3142. continue;
  3143. }
  3144. if (auto style_value = parse_css_value_for_property(PropertyID::Content, tokens)) {
  3145. if (is_single_value_identifier(style_value->to_identifier()))
  3146. return nullptr;
  3147. if (in_alt_text) {
  3148. alt_text_values.append(style_value.release_nonnull());
  3149. } else {
  3150. content_values.append(style_value.release_nonnull());
  3151. }
  3152. continue;
  3153. }
  3154. return nullptr;
  3155. }
  3156. if (content_values.is_empty())
  3157. return nullptr;
  3158. if (in_alt_text && alt_text_values.is_empty())
  3159. return nullptr;
  3160. RefPtr<StyleValueList> alt_text;
  3161. if (!alt_text_values.is_empty())
  3162. alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);
  3163. transaction.commit();
  3164. return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
  3165. }
  3166. // https://www.w3.org/TR/css-display-3/#the-display-properties
  3167. RefPtr<StyleValue> Parser::parse_display_value(TokenStream<ComponentValue>& tokens)
  3168. {
  3169. auto parse_single_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  3170. auto transaction = tokens.begin_transaction();
  3171. if (auto identifier_value = parse_identifier_value(tokens.next_token())) {
  3172. auto identifier = identifier_value->to_identifier();
  3173. if (identifier == ValueID::ListItem) {
  3174. transaction.commit();
  3175. return Display::from_short(Display::Short::ListItem);
  3176. }
  3177. if (auto display_outside = value_id_to_display_outside(identifier); display_outside.has_value()) {
  3178. transaction.commit();
  3179. switch (display_outside.value()) {
  3180. case DisplayOutside::Block:
  3181. return Display::from_short(Display::Short::Block);
  3182. case DisplayOutside::Inline:
  3183. return Display::from_short(Display::Short::Inline);
  3184. case DisplayOutside::RunIn:
  3185. return Display::from_short(Display::Short::RunIn);
  3186. }
  3187. }
  3188. if (auto display_inside = value_id_to_display_inside(identifier); display_inside.has_value()) {
  3189. transaction.commit();
  3190. switch (display_inside.value()) {
  3191. case DisplayInside::Flow:
  3192. return Display::from_short(Display::Short::Flow);
  3193. case DisplayInside::FlowRoot:
  3194. return Display::from_short(Display::Short::FlowRoot);
  3195. case DisplayInside::Table:
  3196. return Display::from_short(Display::Short::Table);
  3197. case DisplayInside::Flex:
  3198. return Display::from_short(Display::Short::Flex);
  3199. case DisplayInside::Grid:
  3200. return Display::from_short(Display::Short::Grid);
  3201. case DisplayInside::Ruby:
  3202. return Display::from_short(Display::Short::Ruby);
  3203. case DisplayInside::Math:
  3204. return Display::from_short(Display::Short::Math);
  3205. }
  3206. }
  3207. if (auto display_internal = value_id_to_display_internal(identifier); display_internal.has_value()) {
  3208. transaction.commit();
  3209. return Display { display_internal.value() };
  3210. }
  3211. if (auto display_box = value_id_to_display_box(identifier); display_box.has_value()) {
  3212. transaction.commit();
  3213. switch (display_box.value()) {
  3214. case DisplayBox::Contents:
  3215. return Display::from_short(Display::Short::Contents);
  3216. case DisplayBox::None:
  3217. return Display::from_short(Display::Short::None);
  3218. }
  3219. }
  3220. if (auto display_legacy = value_id_to_display_legacy(identifier); display_legacy.has_value()) {
  3221. transaction.commit();
  3222. switch (display_legacy.value()) {
  3223. case DisplayLegacy::InlineBlock:
  3224. return Display::from_short(Display::Short::InlineBlock);
  3225. case DisplayLegacy::InlineTable:
  3226. return Display::from_short(Display::Short::InlineTable);
  3227. case DisplayLegacy::InlineFlex:
  3228. return Display::from_short(Display::Short::InlineFlex);
  3229. case DisplayLegacy::InlineGrid:
  3230. return Display::from_short(Display::Short::InlineGrid);
  3231. }
  3232. }
  3233. }
  3234. return OptionalNone {};
  3235. };
  3236. auto parse_multi_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  3237. auto list_item = Display::ListItem::No;
  3238. Optional<DisplayInside> inside;
  3239. Optional<DisplayOutside> outside;
  3240. auto transaction = tokens.begin_transaction();
  3241. while (tokens.has_next_token()) {
  3242. auto& token = tokens.next_token();
  3243. if (auto value = parse_identifier_value(token)) {
  3244. auto identifier = value->to_identifier();
  3245. if (identifier == ValueID::ListItem) {
  3246. if (list_item == Display::ListItem::Yes)
  3247. return {};
  3248. list_item = Display::ListItem::Yes;
  3249. continue;
  3250. }
  3251. if (auto inside_value = value_id_to_display_inside(identifier); inside_value.has_value()) {
  3252. if (inside.has_value())
  3253. return {};
  3254. inside = inside_value.value();
  3255. continue;
  3256. }
  3257. if (auto outside_value = value_id_to_display_outside(identifier); outside_value.has_value()) {
  3258. if (outside.has_value())
  3259. return {};
  3260. outside = outside_value.value();
  3261. continue;
  3262. }
  3263. }
  3264. // Not a display value, abort.
  3265. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized display value: `{}`", token.to_string());
  3266. return {};
  3267. }
  3268. // The spec does not allow any other inside values to be combined with list-item
  3269. // <display-outside>? && [ flow | flow-root ]? && list-item
  3270. if (list_item == Display::ListItem::Yes && inside.has_value() && inside != DisplayInside::Flow && inside != DisplayInside::FlowRoot)
  3271. return {};
  3272. transaction.commit();
  3273. return Display { outside.value_or(DisplayOutside::Block), inside.value_or(DisplayInside::Flow), list_item };
  3274. };
  3275. Optional<Display> display;
  3276. if (tokens.remaining_token_count() == 1)
  3277. display = parse_single_component_display(tokens);
  3278. else
  3279. display = parse_multi_component_display(tokens);
  3280. if (display.has_value())
  3281. return DisplayStyleValue::create(display.value());
  3282. return nullptr;
  3283. }
  3284. RefPtr<StyleValue> Parser::parse_filter_value_list_value(TokenStream<ComponentValue>& tokens)
  3285. {
  3286. auto transaction = tokens.begin_transaction();
  3287. if (contains_single_none_ident(tokens)) {
  3288. transaction.commit();
  3289. return parse_identifier_value(tokens.next_token());
  3290. }
  3291. // FIXME: <url>s are ignored for now
  3292. // <filter-value-list> = [ <filter-function> | <url> ]+
  3293. enum class FilterToken {
  3294. // Color filters:
  3295. Brightness,
  3296. Contrast,
  3297. Grayscale,
  3298. Invert,
  3299. Opacity,
  3300. Saturate,
  3301. Sepia,
  3302. // Special filters:
  3303. Blur,
  3304. DropShadow,
  3305. HueRotate
  3306. };
  3307. auto filter_token_to_operation = [&](auto filter) {
  3308. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  3309. return static_cast<Filter::Color::Operation>(filter);
  3310. };
  3311. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  3312. if (token.is(Token::Type::Percentage))
  3313. return NumberPercentage(Percentage(token.token().percentage()));
  3314. if (token.is(Token::Type::Number))
  3315. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  3316. return {};
  3317. };
  3318. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  3319. if (name.equals_ignoring_ascii_case("blur"sv))
  3320. return FilterToken::Blur;
  3321. if (name.equals_ignoring_ascii_case("brightness"sv))
  3322. return FilterToken::Brightness;
  3323. if (name.equals_ignoring_ascii_case("contrast"sv))
  3324. return FilterToken::Contrast;
  3325. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  3326. return FilterToken::DropShadow;
  3327. if (name.equals_ignoring_ascii_case("grayscale"sv))
  3328. return FilterToken::Grayscale;
  3329. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  3330. return FilterToken::HueRotate;
  3331. if (name.equals_ignoring_ascii_case("invert"sv))
  3332. return FilterToken::Invert;
  3333. if (name.equals_ignoring_ascii_case("opacity"sv))
  3334. return FilterToken::Opacity;
  3335. if (name.equals_ignoring_ascii_case("saturate"sv))
  3336. return FilterToken::Saturate;
  3337. if (name.equals_ignoring_ascii_case("sepia"sv))
  3338. return FilterToken::Sepia;
  3339. return {};
  3340. };
  3341. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  3342. TokenStream tokens { function_values };
  3343. tokens.skip_whitespace();
  3344. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  3345. tokens.skip_whitespace();
  3346. if (tokens.has_next_token())
  3347. return {};
  3348. return filter;
  3349. };
  3350. if (filter_token == FilterToken::Blur) {
  3351. // blur( <length>? )
  3352. if (!tokens.has_next_token())
  3353. return Filter::Blur {};
  3354. auto blur_radius = parse_length(tokens);
  3355. tokens.skip_whitespace();
  3356. if (!blur_radius.has_value())
  3357. return {};
  3358. // FIXME: Support calculated radius
  3359. return if_no_more_tokens_return(Filter::Blur { blur_radius->value() });
  3360. } else if (filter_token == FilterToken::DropShadow) {
  3361. if (!tokens.has_next_token())
  3362. return {};
  3363. // drop-shadow( [ <color>? && <length>{2,3} ] )
  3364. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  3365. Optional<LengthOrCalculated> maybe_radius = {};
  3366. auto maybe_color = parse_color(tokens.peek_token());
  3367. if (maybe_color.has_value())
  3368. (void)tokens.next_token();
  3369. auto x_offset = parse_length(tokens);
  3370. tokens.skip_whitespace();
  3371. if (!x_offset.has_value() || !tokens.has_next_token()) {
  3372. return {};
  3373. }
  3374. auto y_offset = parse_length(tokens);
  3375. if (!y_offset.has_value()) {
  3376. return {};
  3377. }
  3378. if (tokens.has_next_token()) {
  3379. maybe_radius = parse_length(tokens);
  3380. if (!maybe_color.has_value() && (!maybe_radius.has_value() || tokens.has_next_token())) {
  3381. maybe_color = parse_color(tokens.next_token());
  3382. tokens.skip_whitespace();
  3383. if (!maybe_color.has_value()) {
  3384. return {};
  3385. }
  3386. } else if (!maybe_radius.has_value()) {
  3387. return {};
  3388. }
  3389. }
  3390. // FIXME: Support calculated offsets and radius
  3391. return if_no_more_tokens_return(Filter::DropShadow { x_offset->value(), y_offset->value(), maybe_radius.map([](auto& it) { return it.value(); }), maybe_color });
  3392. } else if (filter_token == FilterToken::HueRotate) {
  3393. // hue-rotate( [ <angle> | <zero> ]? )
  3394. if (!tokens.has_next_token())
  3395. return Filter::HueRotate {};
  3396. auto& token = tokens.next_token();
  3397. if (token.is(Token::Type::Number)) {
  3398. // hue-rotate(0)
  3399. auto number = token.token().number();
  3400. if (number.is_integer() && number.integer_value() == 0)
  3401. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  3402. return {};
  3403. }
  3404. if (!token.is(Token::Type::Dimension))
  3405. return {};
  3406. auto angle_value = token.token().dimension_value();
  3407. auto angle_unit_name = token.token().dimension_unit();
  3408. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  3409. if (!angle_unit.has_value())
  3410. return {};
  3411. Angle angle { angle_value, angle_unit.release_value() };
  3412. return if_no_more_tokens_return(Filter::HueRotate { angle });
  3413. } else {
  3414. // Simple filters:
  3415. // brightness( <number-percentage>? )
  3416. // contrast( <number-percentage>? )
  3417. // grayscale( <number-percentage>? )
  3418. // invert( <number-percentage>? )
  3419. // opacity( <number-percentage>? )
  3420. // sepia( <number-percentage>? )
  3421. // saturate( <number-percentage>? )
  3422. if (!tokens.has_next_token())
  3423. return Filter::Color { filter_token_to_operation(filter_token) };
  3424. auto amount = parse_number_percentage(tokens.next_token());
  3425. if (!amount.has_value())
  3426. return {};
  3427. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  3428. }
  3429. };
  3430. Vector<FilterFunction> filter_value_list {};
  3431. while (tokens.has_next_token()) {
  3432. tokens.skip_whitespace();
  3433. if (!tokens.has_next_token())
  3434. break;
  3435. auto& token = tokens.next_token();
  3436. if (!token.is_function())
  3437. return nullptr;
  3438. auto filter_token = parse_filter_function_name(token.function().name());
  3439. if (!filter_token.has_value())
  3440. return nullptr;
  3441. auto filter_function = parse_filter_function(*filter_token, token.function().values());
  3442. if (!filter_function.has_value())
  3443. return nullptr;
  3444. filter_value_list.append(*filter_function);
  3445. }
  3446. if (filter_value_list.is_empty())
  3447. return nullptr;
  3448. transaction.commit();
  3449. return FilterValueListStyleValue::create(move(filter_value_list));
  3450. }
  3451. RefPtr<StyleValue> Parser::parse_flex_value(TokenStream<ComponentValue>& tokens)
  3452. {
  3453. auto transaction = tokens.begin_transaction();
  3454. auto make_flex_shorthand = [&](NonnullRefPtr<StyleValue> flex_grow, NonnullRefPtr<StyleValue> flex_shrink, NonnullRefPtr<StyleValue> flex_basis) {
  3455. transaction.commit();
  3456. return ShorthandStyleValue::create(PropertyID::Flex,
  3457. { PropertyID::FlexGrow, PropertyID::FlexShrink, PropertyID::FlexBasis },
  3458. { move(flex_grow), move(flex_shrink), move(flex_basis) });
  3459. };
  3460. if (tokens.remaining_token_count() == 1) {
  3461. // One-value syntax: <flex-grow> | <flex-basis> | none
  3462. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  3463. auto property_and_value = parse_css_value_for_properties(properties, tokens);
  3464. if (!property_and_value.has_value())
  3465. return nullptr;
  3466. auto& value = property_and_value->style_value;
  3467. switch (property_and_value->property) {
  3468. case PropertyID::FlexGrow: {
  3469. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  3470. // https://github.com/w3c/csswg-drafts/issues/5742
  3471. auto flex_basis = PercentageStyleValue::create(Percentage(0));
  3472. auto one = NumberStyleValue::create(1);
  3473. return make_flex_shorthand(*value, one, flex_basis);
  3474. }
  3475. case PropertyID::FlexBasis: {
  3476. auto one = NumberStyleValue::create(1);
  3477. return make_flex_shorthand(one, one, *value);
  3478. }
  3479. case PropertyID::Flex: {
  3480. if (value->is_identifier() && value->to_identifier() == ValueID::None) {
  3481. auto zero = NumberStyleValue::create(0);
  3482. return make_flex_shorthand(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  3483. }
  3484. break;
  3485. }
  3486. default:
  3487. VERIFY_NOT_REACHED();
  3488. }
  3489. return nullptr;
  3490. }
  3491. RefPtr<StyleValue> flex_grow;
  3492. RefPtr<StyleValue> flex_shrink;
  3493. RefPtr<StyleValue> flex_basis;
  3494. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  3495. // if FlexGrow (along with optional FlexShrink) have already been specified.
  3496. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  3497. while (tokens.has_next_token()) {
  3498. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3499. if (!property_and_value.has_value())
  3500. return nullptr;
  3501. auto& value = property_and_value->style_value;
  3502. remove_property(remaining_longhands, property_and_value->property);
  3503. switch (property_and_value->property) {
  3504. case PropertyID::FlexGrow: {
  3505. VERIFY(!flex_grow);
  3506. flex_grow = value.release_nonnull();
  3507. // Flex-shrink may optionally follow directly after.
  3508. auto maybe_flex_shrink = parse_css_value_for_property(PropertyID::FlexShrink, tokens);
  3509. if (maybe_flex_shrink)
  3510. flex_shrink = maybe_flex_shrink.release_nonnull();
  3511. continue;
  3512. }
  3513. case PropertyID::FlexBasis: {
  3514. VERIFY(!flex_basis);
  3515. flex_basis = value.release_nonnull();
  3516. continue;
  3517. }
  3518. default:
  3519. VERIFY_NOT_REACHED();
  3520. }
  3521. }
  3522. if (!flex_grow)
  3523. flex_grow = property_initial_value(m_context.realm(), PropertyID::FlexGrow);
  3524. if (!flex_shrink)
  3525. flex_shrink = property_initial_value(m_context.realm(), PropertyID::FlexShrink);
  3526. if (!flex_basis) {
  3527. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  3528. // https://github.com/w3c/csswg-drafts/issues/5742
  3529. flex_basis = PercentageStyleValue::create(Percentage(0));
  3530. }
  3531. return make_flex_shorthand(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  3532. }
  3533. RefPtr<StyleValue> Parser::parse_flex_flow_value(TokenStream<ComponentValue>& tokens)
  3534. {
  3535. RefPtr<StyleValue> flex_direction;
  3536. RefPtr<StyleValue> flex_wrap;
  3537. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  3538. auto transaction = tokens.begin_transaction();
  3539. while (tokens.has_next_token()) {
  3540. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3541. if (!property_and_value.has_value())
  3542. return nullptr;
  3543. auto& value = property_and_value->style_value;
  3544. remove_property(remaining_longhands, property_and_value->property);
  3545. switch (property_and_value->property) {
  3546. case PropertyID::FlexDirection:
  3547. VERIFY(!flex_direction);
  3548. flex_direction = value.release_nonnull();
  3549. continue;
  3550. case PropertyID::FlexWrap:
  3551. VERIFY(!flex_wrap);
  3552. flex_wrap = value.release_nonnull();
  3553. continue;
  3554. default:
  3555. VERIFY_NOT_REACHED();
  3556. }
  3557. }
  3558. if (!flex_direction)
  3559. flex_direction = property_initial_value(m_context.realm(), PropertyID::FlexDirection);
  3560. if (!flex_wrap)
  3561. flex_wrap = property_initial_value(m_context.realm(), PropertyID::FlexWrap);
  3562. transaction.commit();
  3563. return ShorthandStyleValue::create(PropertyID::FlexFlow,
  3564. { PropertyID::FlexDirection, PropertyID::FlexWrap },
  3565. { flex_direction.release_nonnull(), flex_wrap.release_nonnull() });
  3566. }
  3567. static bool is_generic_font_family(ValueID identifier)
  3568. {
  3569. switch (identifier) {
  3570. case ValueID::Cursive:
  3571. case ValueID::Fantasy:
  3572. case ValueID::Monospace:
  3573. case ValueID::Serif:
  3574. case ValueID::SansSerif:
  3575. case ValueID::UiMonospace:
  3576. case ValueID::UiRounded:
  3577. case ValueID::UiSerif:
  3578. case ValueID::UiSansSerif:
  3579. return true;
  3580. default:
  3581. return false;
  3582. }
  3583. }
  3584. RefPtr<StyleValue> Parser::parse_font_value(TokenStream<ComponentValue>& tokens)
  3585. {
  3586. RefPtr<StyleValue> font_stretch;
  3587. RefPtr<StyleValue> font_style;
  3588. RefPtr<StyleValue> font_weight;
  3589. RefPtr<StyleValue> font_size;
  3590. RefPtr<StyleValue> line_height;
  3591. RefPtr<StyleValue> font_families;
  3592. RefPtr<StyleValue> font_variant;
  3593. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  3594. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  3595. // So, we have to handle that separately.
  3596. int normal_count = 0;
  3597. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStretch, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight };
  3598. auto transaction = tokens.begin_transaction();
  3599. while (tokens.has_next_token()) {
  3600. auto& peek_token = tokens.peek_token();
  3601. if (peek_token.is_ident("normal"sv)) {
  3602. normal_count++;
  3603. (void)tokens.next_token();
  3604. continue;
  3605. }
  3606. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3607. if (!property_and_value.has_value())
  3608. return nullptr;
  3609. auto& value = property_and_value->style_value;
  3610. remove_property(remaining_longhands, property_and_value->property);
  3611. switch (property_and_value->property) {
  3612. case PropertyID::FontSize: {
  3613. VERIFY(!font_size);
  3614. font_size = value.release_nonnull();
  3615. // Consume `/ line-height` if present
  3616. if (tokens.peek_token().is_delim('/')) {
  3617. (void)tokens.next_token();
  3618. auto maybe_line_height = parse_css_value_for_property(PropertyID::LineHeight, tokens);
  3619. if (!maybe_line_height)
  3620. return nullptr;
  3621. line_height = maybe_line_height.release_nonnull();
  3622. }
  3623. // Consume font-families
  3624. auto maybe_font_families = parse_font_family_value(tokens);
  3625. // font-family comes last, so we must not have any tokens left over.
  3626. if (!maybe_font_families || tokens.has_next_token())
  3627. return nullptr;
  3628. font_families = maybe_font_families.release_nonnull();
  3629. continue;
  3630. }
  3631. case PropertyID::FontStretch: {
  3632. VERIFY(!font_stretch);
  3633. font_stretch = value.release_nonnull();
  3634. continue;
  3635. }
  3636. case PropertyID::FontStyle: {
  3637. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  3638. VERIFY(!font_style);
  3639. font_style = value.release_nonnull();
  3640. continue;
  3641. }
  3642. case PropertyID::FontVariant: {
  3643. VERIFY(!font_variant);
  3644. font_variant = value.release_nonnull();
  3645. continue;
  3646. }
  3647. case PropertyID::FontWeight: {
  3648. VERIFY(!font_weight);
  3649. font_weight = value.release_nonnull();
  3650. continue;
  3651. }
  3652. default:
  3653. VERIFY_NOT_REACHED();
  3654. }
  3655. return nullptr;
  3656. }
  3657. // Since normal is the default value for all the properties that can have it, we don't have to actually
  3658. // set anything to normal here. It'll be set when we create the ShorthandStyleValue below.
  3659. // We just need to make sure we were not given more normals than will fit.
  3660. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1) + (font_variant ? 0 : 1) + (font_stretch ? 0 : 1);
  3661. if (unset_value_count < normal_count)
  3662. return nullptr;
  3663. if (!font_size || !font_families)
  3664. return nullptr;
  3665. if (!font_style)
  3666. font_style = property_initial_value(m_context.realm(), PropertyID::FontStyle);
  3667. if (!font_variant)
  3668. font_variant = property_initial_value(m_context.realm(), PropertyID::FontVariant);
  3669. if (!font_weight)
  3670. font_weight = property_initial_value(m_context.realm(), PropertyID::FontWeight);
  3671. if (!font_stretch)
  3672. font_stretch = property_initial_value(m_context.realm(), PropertyID::FontStretch);
  3673. if (!line_height)
  3674. line_height = property_initial_value(m_context.realm(), PropertyID::LineHeight);
  3675. transaction.commit();
  3676. return ShorthandStyleValue::create(PropertyID::Font,
  3677. { PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontStretch, PropertyID::FontSize, PropertyID::LineHeight, PropertyID::FontFamily },
  3678. { font_style.release_nonnull(), font_variant.release_nonnull(), font_weight.release_nonnull(), font_stretch.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull() });
  3679. }
  3680. RefPtr<StyleValue> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  3681. {
  3682. auto next_is_comma_or_eof = [&]() -> bool {
  3683. return !tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma);
  3684. };
  3685. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  3686. // eg, these are equivalent:
  3687. // font-family: my cool font\!, serif;
  3688. // font-family: "my cool font!", serif;
  3689. StyleValueVector font_families;
  3690. Vector<String> current_name_parts;
  3691. while (tokens.has_next_token()) {
  3692. auto const& peek = tokens.peek_token();
  3693. if (peek.is(Token::Type::String)) {
  3694. // `font-family: my cool "font";` is invalid.
  3695. if (!current_name_parts.is_empty())
  3696. return nullptr;
  3697. (void)tokens.next_token(); // String
  3698. if (!next_is_comma_or_eof())
  3699. return nullptr;
  3700. font_families.append(StringStyleValue::create(peek.token().string().to_string()));
  3701. (void)tokens.next_token(); // Comma
  3702. continue;
  3703. }
  3704. if (peek.is(Token::Type::Ident)) {
  3705. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  3706. // CSS-wide keywords are not allowed
  3707. if (auto builtin = parse_builtin_value(peek))
  3708. return nullptr;
  3709. auto maybe_ident = value_id_from_string(peek.token().ident());
  3710. // Can't have a generic-font-name as a token in an unquoted font name.
  3711. if (maybe_ident.has_value() && is_generic_font_family(maybe_ident.value())) {
  3712. if (!current_name_parts.is_empty())
  3713. return nullptr;
  3714. (void)tokens.next_token(); // Ident
  3715. if (!next_is_comma_or_eof())
  3716. return nullptr;
  3717. font_families.append(IdentifierStyleValue::create(maybe_ident.value()));
  3718. (void)tokens.next_token(); // Comma
  3719. continue;
  3720. }
  3721. current_name_parts.append(tokens.next_token().token().ident().to_string());
  3722. continue;
  3723. }
  3724. if (peek.is(Token::Type::Comma)) {
  3725. if (current_name_parts.is_empty())
  3726. return nullptr;
  3727. (void)tokens.next_token(); // Comma
  3728. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  3729. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  3730. current_name_parts.clear();
  3731. // Can't have a trailing comma
  3732. if (!tokens.has_next_token())
  3733. return nullptr;
  3734. continue;
  3735. }
  3736. return nullptr;
  3737. }
  3738. if (!current_name_parts.is_empty()) {
  3739. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  3740. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  3741. current_name_parts.clear();
  3742. }
  3743. if (font_families.is_empty())
  3744. return nullptr;
  3745. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  3746. }
  3747. CSSRule* Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
  3748. {
  3749. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  3750. Optional<FlyString> font_family;
  3751. Vector<FontFace::Source> src;
  3752. Vector<Gfx::UnicodeRange> unicode_range;
  3753. Optional<int> weight;
  3754. Optional<int> slope;
  3755. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  3756. if (declaration_or_at_rule.is_at_rule()) {
  3757. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-face; discarding.");
  3758. continue;
  3759. }
  3760. auto const& declaration = declaration_or_at_rule.declaration();
  3761. if (declaration.name().equals_ignoring_ascii_case("font-weight"sv)) {
  3762. TokenStream token_stream { declaration.values() };
  3763. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  3764. weight = value.value()->to_font_weight();
  3765. }
  3766. continue;
  3767. }
  3768. if (declaration.name().equals_ignoring_ascii_case("font-style"sv)) {
  3769. TokenStream token_stream { declaration.values() };
  3770. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  3771. slope = value.value()->to_font_slope();
  3772. }
  3773. continue;
  3774. }
  3775. if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
  3776. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  3777. // Ideally they could share code.
  3778. Vector<FlyString> font_family_parts;
  3779. bool had_syntax_error = false;
  3780. for (size_t i = 0; i < declaration.values().size(); ++i) {
  3781. auto const& part = declaration.values()[i];
  3782. if (part.is(Token::Type::Whitespace))
  3783. continue;
  3784. if (part.is(Token::Type::String)) {
  3785. if (!font_family_parts.is_empty()) {
  3786. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3787. had_syntax_error = true;
  3788. break;
  3789. }
  3790. font_family_parts.append(part.token().string());
  3791. continue;
  3792. }
  3793. if (part.is(Token::Type::Ident)) {
  3794. if (is_css_wide_keyword(part.token().ident())) {
  3795. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3796. had_syntax_error = true;
  3797. break;
  3798. }
  3799. auto value_id = value_id_from_string(part.token().ident());
  3800. if (value_id.has_value() && is_generic_font_family(value_id.value())) {
  3801. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3802. had_syntax_error = true;
  3803. break;
  3804. }
  3805. font_family_parts.append(part.token().ident());
  3806. continue;
  3807. }
  3808. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3809. had_syntax_error = true;
  3810. break;
  3811. }
  3812. if (had_syntax_error || font_family_parts.is_empty())
  3813. continue;
  3814. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  3815. continue;
  3816. }
  3817. if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
  3818. TokenStream token_stream { declaration.values() };
  3819. Vector<FontFace::Source> supported_sources = parse_font_face_src(token_stream);
  3820. if (!supported_sources.is_empty())
  3821. src = move(supported_sources);
  3822. continue;
  3823. }
  3824. if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
  3825. Vector<Gfx::UnicodeRange> unicode_ranges;
  3826. bool unicode_range_invalid = false;
  3827. TokenStream all_tokens { declaration.values() };
  3828. auto range_token_lists = parse_a_comma_separated_list_of_component_values(all_tokens);
  3829. for (auto& range_tokens : range_token_lists) {
  3830. TokenStream range_token_stream { range_tokens };
  3831. auto maybe_unicode_range = parse_unicode_range(range_token_stream);
  3832. if (!maybe_unicode_range.has_value()) {
  3833. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face unicode-range format invalid; discarding.");
  3834. unicode_range_invalid = true;
  3835. break;
  3836. }
  3837. unicode_ranges.append(maybe_unicode_range.release_value());
  3838. }
  3839. if (unicode_range_invalid || unicode_ranges.is_empty())
  3840. continue;
  3841. unicode_range = move(unicode_ranges);
  3842. continue;
  3843. }
  3844. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-face; discarding.", declaration.name());
  3845. }
  3846. if (!font_family.has_value()) {
  3847. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  3848. return {};
  3849. }
  3850. if (unicode_range.is_empty()) {
  3851. unicode_range.empend(0x0u, 0x10FFFFu);
  3852. }
  3853. return CSSFontFaceRule::create(m_context.realm(), FontFace { font_family.release_value(), weight, slope, move(src), move(unicode_range) });
  3854. }
  3855. Vector<FontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values)
  3856. {
  3857. // FIXME: Get this information from the system somehow?
  3858. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  3859. auto font_format_is_supported = [](StringView name) {
  3860. // The spec requires us to treat opentype and truetype as synonymous.
  3861. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv, "woff2"sv))
  3862. return true;
  3863. return false;
  3864. };
  3865. Vector<FontFace::Source> supported_sources;
  3866. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  3867. for (auto const& source_token_list : list_of_source_token_lists) {
  3868. TokenStream source_tokens { source_token_list };
  3869. source_tokens.skip_whitespace();
  3870. auto const& first = source_tokens.next_token();
  3871. // <url> [ format(<font-format>)]?
  3872. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  3873. if (auto maybe_url = parse_url_function(first); maybe_url.has_value()) {
  3874. auto url = maybe_url.release_value();
  3875. if (!url.is_valid()) {
  3876. continue;
  3877. }
  3878. Optional<FlyString> format;
  3879. source_tokens.skip_whitespace();
  3880. if (!source_tokens.has_next_token()) {
  3881. supported_sources.empend(move(url), format);
  3882. continue;
  3883. }
  3884. auto maybe_function = source_tokens.next_token();
  3885. if (!maybe_function.is_function()) {
  3886. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  3887. return {};
  3888. }
  3889. auto const& function = maybe_function.function();
  3890. if (function.name().equals_ignoring_ascii_case("format"sv)) {
  3891. TokenStream format_tokens { function.values() };
  3892. format_tokens.skip_whitespace();
  3893. auto const& format_name_token = format_tokens.next_token();
  3894. StringView format_name;
  3895. if (format_name_token.is(Token::Type::Ident)) {
  3896. format_name = format_name_token.token().ident();
  3897. } else if (format_name_token.is(Token::Type::String)) {
  3898. format_name = format_name_token.token().string();
  3899. } else {
  3900. 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());
  3901. return {};
  3902. }
  3903. if (!font_format_is_supported(format_name)) {
  3904. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  3905. continue;
  3906. }
  3907. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  3908. } else {
  3909. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
  3910. return {};
  3911. }
  3912. source_tokens.skip_whitespace();
  3913. if (source_tokens.has_next_token()) {
  3914. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
  3915. return {};
  3916. }
  3917. supported_sources.empend(move(url), format);
  3918. continue;
  3919. }
  3920. if (first.is_function("local"sv)) {
  3921. if (first.function().values().is_empty()) {
  3922. continue;
  3923. }
  3924. supported_sources.empend(first.function().values().first().to_string(), Optional<FlyString> {});
  3925. continue;
  3926. }
  3927. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  3928. return {};
  3929. }
  3930. return supported_sources;
  3931. }
  3932. RefPtr<StyleValue> Parser::parse_list_style_value(TokenStream<ComponentValue>& tokens)
  3933. {
  3934. RefPtr<StyleValue> list_position;
  3935. RefPtr<StyleValue> list_image;
  3936. RefPtr<StyleValue> list_type;
  3937. int found_nones = 0;
  3938. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  3939. auto transaction = tokens.begin_transaction();
  3940. while (tokens.has_next_token()) {
  3941. if (auto peek = tokens.peek_token(); peek.is_ident("none"sv)) {
  3942. (void)tokens.next_token();
  3943. found_nones++;
  3944. continue;
  3945. }
  3946. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3947. if (!property_and_value.has_value())
  3948. return nullptr;
  3949. auto& value = property_and_value->style_value;
  3950. remove_property(remaining_longhands, property_and_value->property);
  3951. switch (property_and_value->property) {
  3952. case PropertyID::ListStylePosition: {
  3953. VERIFY(!list_position);
  3954. list_position = value.release_nonnull();
  3955. continue;
  3956. }
  3957. case PropertyID::ListStyleImage: {
  3958. VERIFY(!list_image);
  3959. list_image = value.release_nonnull();
  3960. continue;
  3961. }
  3962. case PropertyID::ListStyleType: {
  3963. VERIFY(!list_type);
  3964. list_type = value.release_nonnull();
  3965. continue;
  3966. }
  3967. default:
  3968. VERIFY_NOT_REACHED();
  3969. }
  3970. }
  3971. if (found_nones > 2)
  3972. return nullptr;
  3973. if (found_nones == 2) {
  3974. if (list_image || list_type)
  3975. return nullptr;
  3976. auto none = IdentifierStyleValue::create(ValueID::None);
  3977. list_image = none;
  3978. list_type = none;
  3979. } else if (found_nones == 1) {
  3980. if (list_image && list_type)
  3981. return nullptr;
  3982. auto none = IdentifierStyleValue::create(ValueID::None);
  3983. if (!list_image)
  3984. list_image = none;
  3985. if (!list_type)
  3986. list_type = none;
  3987. }
  3988. if (!list_position)
  3989. list_position = property_initial_value(m_context.realm(), PropertyID::ListStylePosition);
  3990. if (!list_image)
  3991. list_image = property_initial_value(m_context.realm(), PropertyID::ListStyleImage);
  3992. if (!list_type)
  3993. list_type = property_initial_value(m_context.realm(), PropertyID::ListStyleType);
  3994. transaction.commit();
  3995. return ShorthandStyleValue::create(PropertyID::ListStyle,
  3996. { PropertyID::ListStylePosition, PropertyID::ListStyleImage, PropertyID::ListStyleType },
  3997. { list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull() });
  3998. }
  3999. RefPtr<StyleValue> Parser::parse_math_depth_value(TokenStream<ComponentValue>& tokens)
  4000. {
  4001. // https://w3c.github.io/mathml-core/#propdef-math-depth
  4002. // auto-add | add(<integer>) | <integer>
  4003. auto transaction = tokens.begin_transaction();
  4004. auto token = tokens.next_token();
  4005. if (tokens.has_next_token())
  4006. return nullptr;
  4007. // auto-add
  4008. if (token.is_ident("auto-add"sv)) {
  4009. transaction.commit();
  4010. return MathDepthStyleValue::create_auto_add();
  4011. }
  4012. // FIXME: Make it easier to parse "thing that might be <bar> or literally anything that resolves to it" and get rid of this
  4013. auto parse_something_that_resolves_to_integer = [this](ComponentValue& token) -> RefPtr<StyleValue> {
  4014. if (token.is(Token::Type::Number) && token.token().number().is_integer())
  4015. return IntegerStyleValue::create(token.token().to_integer());
  4016. if (auto value = parse_calculated_value(token); value && value->resolves_to_number())
  4017. return value;
  4018. return nullptr;
  4019. };
  4020. // add(<integer>)
  4021. if (token.is_function("add"sv)) {
  4022. auto add_tokens = TokenStream { token.function().values() };
  4023. add_tokens.skip_whitespace();
  4024. auto integer_token = add_tokens.next_token();
  4025. add_tokens.skip_whitespace();
  4026. if (add_tokens.has_next_token())
  4027. return nullptr;
  4028. if (auto integer_value = parse_something_that_resolves_to_integer(integer_token)) {
  4029. transaction.commit();
  4030. return MathDepthStyleValue::create_add(integer_value.release_nonnull());
  4031. }
  4032. return nullptr;
  4033. }
  4034. // <integer>
  4035. if (auto integer_value = parse_something_that_resolves_to_integer(token)) {
  4036. transaction.commit();
  4037. return MathDepthStyleValue::create_integer(integer_value.release_nonnull());
  4038. }
  4039. return nullptr;
  4040. }
  4041. RefPtr<StyleValue> Parser::parse_overflow_value(TokenStream<ComponentValue>& tokens)
  4042. {
  4043. auto transaction = tokens.begin_transaction();
  4044. auto maybe_x_value = parse_css_value_for_property(PropertyID::OverflowX, tokens);
  4045. if (!maybe_x_value)
  4046. return nullptr;
  4047. auto maybe_y_value = parse_css_value_for_property(PropertyID::OverflowY, tokens);
  4048. transaction.commit();
  4049. if (maybe_y_value) {
  4050. return ShorthandStyleValue::create(PropertyID::Overflow,
  4051. { PropertyID::OverflowX, PropertyID::OverflowY },
  4052. { maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull() });
  4053. }
  4054. return ShorthandStyleValue::create(PropertyID::Overflow,
  4055. { PropertyID::OverflowX, PropertyID::OverflowY },
  4056. { *maybe_x_value, *maybe_x_value });
  4057. }
  4058. RefPtr<StyleValue> Parser::parse_place_content_value(TokenStream<ComponentValue>& tokens)
  4059. {
  4060. auto transaction = tokens.begin_transaction();
  4061. auto maybe_align_content_value = parse_css_value_for_property(PropertyID::AlignContent, tokens);
  4062. if (!maybe_align_content_value)
  4063. return nullptr;
  4064. if (!tokens.has_next_token()) {
  4065. if (!property_accepts_identifier(PropertyID::JustifyContent, maybe_align_content_value->to_identifier()))
  4066. return nullptr;
  4067. transaction.commit();
  4068. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  4069. { PropertyID::AlignContent, PropertyID::JustifyContent },
  4070. { *maybe_align_content_value, *maybe_align_content_value });
  4071. }
  4072. auto maybe_justify_content_value = parse_css_value_for_property(PropertyID::JustifyContent, tokens);
  4073. if (!maybe_justify_content_value)
  4074. return nullptr;
  4075. transaction.commit();
  4076. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  4077. { PropertyID::AlignContent, PropertyID::JustifyContent },
  4078. { maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull() });
  4079. }
  4080. RefPtr<StyleValue> Parser::parse_place_items_value(TokenStream<ComponentValue>& tokens)
  4081. {
  4082. auto transaction = tokens.begin_transaction();
  4083. auto maybe_align_items_value = parse_css_value_for_property(PropertyID::AlignItems, tokens);
  4084. if (!maybe_align_items_value)
  4085. return nullptr;
  4086. if (!tokens.has_next_token()) {
  4087. if (!property_accepts_identifier(PropertyID::JustifyItems, maybe_align_items_value->to_identifier()))
  4088. return nullptr;
  4089. transaction.commit();
  4090. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  4091. { PropertyID::AlignItems, PropertyID::JustifyItems },
  4092. { *maybe_align_items_value, *maybe_align_items_value });
  4093. }
  4094. auto maybe_justify_items_value = parse_css_value_for_property(PropertyID::JustifyItems, tokens);
  4095. if (!maybe_justify_items_value)
  4096. return nullptr;
  4097. transaction.commit();
  4098. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  4099. { PropertyID::AlignItems, PropertyID::JustifyItems },
  4100. { *maybe_align_items_value, *maybe_justify_items_value });
  4101. }
  4102. RefPtr<StyleValue> Parser::parse_place_self_value(TokenStream<ComponentValue>& tokens)
  4103. {
  4104. auto transaction = tokens.begin_transaction();
  4105. auto maybe_align_self_value = parse_css_value_for_property(PropertyID::AlignSelf, tokens);
  4106. if (!maybe_align_self_value)
  4107. return nullptr;
  4108. if (!tokens.has_next_token()) {
  4109. if (!property_accepts_identifier(PropertyID::JustifySelf, maybe_align_self_value->to_identifier()))
  4110. return nullptr;
  4111. transaction.commit();
  4112. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  4113. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  4114. { *maybe_align_self_value, *maybe_align_self_value });
  4115. }
  4116. auto maybe_justify_self_value = parse_css_value_for_property(PropertyID::JustifySelf, tokens);
  4117. if (!maybe_justify_self_value)
  4118. return nullptr;
  4119. transaction.commit();
  4120. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  4121. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  4122. { *maybe_align_self_value, *maybe_justify_self_value });
  4123. }
  4124. RefPtr<StyleValue> Parser::parse_quotes_value(TokenStream<ComponentValue>& tokens)
  4125. {
  4126. // https://www.w3.org/TR/css-content-3/#quotes-property
  4127. // auto | none | [ <string> <string> ]+
  4128. auto transaction = tokens.begin_transaction();
  4129. if (tokens.remaining_token_count() == 1) {
  4130. auto identifier = parse_identifier_value(tokens.next_token());
  4131. if (identifier && property_accepts_identifier(PropertyID::Quotes, identifier->to_identifier())) {
  4132. transaction.commit();
  4133. return identifier;
  4134. }
  4135. return nullptr;
  4136. }
  4137. // Parse an even number of <string> values.
  4138. if (tokens.remaining_token_count() % 2 != 0)
  4139. return nullptr;
  4140. StyleValueVector string_values;
  4141. while (tokens.has_next_token()) {
  4142. auto maybe_string = parse_string_value(tokens.next_token());
  4143. if (!maybe_string)
  4144. return nullptr;
  4145. string_values.append(maybe_string.release_nonnull());
  4146. }
  4147. transaction.commit();
  4148. return StyleValueList::create(move(string_values), StyleValueList::Separator::Space);
  4149. }
  4150. RefPtr<StyleValue> Parser::parse_text_decoration_value(TokenStream<ComponentValue>& tokens)
  4151. {
  4152. RefPtr<StyleValue> decoration_line;
  4153. RefPtr<StyleValue> decoration_thickness;
  4154. RefPtr<StyleValue> decoration_style;
  4155. RefPtr<StyleValue> decoration_color;
  4156. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  4157. auto transaction = tokens.begin_transaction();
  4158. while (tokens.has_next_token()) {
  4159. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4160. if (!property_and_value.has_value())
  4161. return nullptr;
  4162. auto& value = property_and_value->style_value;
  4163. remove_property(remaining_longhands, property_and_value->property);
  4164. switch (property_and_value->property) {
  4165. case PropertyID::TextDecorationColor: {
  4166. VERIFY(!decoration_color);
  4167. decoration_color = value.release_nonnull();
  4168. continue;
  4169. }
  4170. case PropertyID::TextDecorationLine: {
  4171. VERIFY(!decoration_line);
  4172. tokens.reconsume_current_input_token();
  4173. auto parsed_decoration_line = parse_text_decoration_line_value(tokens);
  4174. if (!parsed_decoration_line)
  4175. return nullptr;
  4176. decoration_line = parsed_decoration_line.release_nonnull();
  4177. continue;
  4178. }
  4179. case PropertyID::TextDecorationThickness: {
  4180. VERIFY(!decoration_thickness);
  4181. decoration_thickness = value.release_nonnull();
  4182. continue;
  4183. }
  4184. case PropertyID::TextDecorationStyle: {
  4185. VERIFY(!decoration_style);
  4186. decoration_style = value.release_nonnull();
  4187. continue;
  4188. }
  4189. default:
  4190. VERIFY_NOT_REACHED();
  4191. }
  4192. }
  4193. if (!decoration_line)
  4194. decoration_line = property_initial_value(m_context.realm(), PropertyID::TextDecorationLine);
  4195. if (!decoration_thickness)
  4196. decoration_thickness = property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness);
  4197. if (!decoration_style)
  4198. decoration_style = property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle);
  4199. if (!decoration_color)
  4200. decoration_color = property_initial_value(m_context.realm(), PropertyID::TextDecorationColor);
  4201. transaction.commit();
  4202. return ShorthandStyleValue::create(PropertyID::TextDecoration,
  4203. { PropertyID::TextDecorationLine, PropertyID::TextDecorationThickness, PropertyID::TextDecorationStyle, PropertyID::TextDecorationColor },
  4204. { decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull() });
  4205. }
  4206. RefPtr<StyleValue> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  4207. {
  4208. StyleValueVector style_values;
  4209. while (tokens.has_next_token()) {
  4210. auto maybe_value = parse_css_value_for_property(PropertyID::TextDecorationLine, tokens);
  4211. if (!maybe_value)
  4212. break;
  4213. auto value = maybe_value.release_nonnull();
  4214. if (auto maybe_line = value_id_to_text_decoration_line(value->to_identifier()); maybe_line.has_value()) {
  4215. if (maybe_line == TextDecorationLine::None) {
  4216. if (!style_values.is_empty())
  4217. break;
  4218. return value;
  4219. }
  4220. if (style_values.contains_slow(value))
  4221. break;
  4222. style_values.append(move(value));
  4223. continue;
  4224. }
  4225. break;
  4226. }
  4227. if (style_values.is_empty())
  4228. return nullptr;
  4229. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  4230. }
  4231. RefPtr<StyleValue> Parser::parse_easing_value(TokenStream<ComponentValue>& tokens)
  4232. {
  4233. auto transaction = tokens.begin_transaction();
  4234. tokens.skip_whitespace();
  4235. auto const& part = tokens.next_token();
  4236. StringView name;
  4237. Optional<Vector<ComponentValue> const&> arguments;
  4238. if (part.is(Token::Type::Ident)) {
  4239. name = part.token().ident();
  4240. } else if (part.is_function()) {
  4241. name = part.function().name();
  4242. arguments = part.function().values();
  4243. } else {
  4244. return nullptr;
  4245. }
  4246. auto maybe_function = easing_function_from_string(name);
  4247. if (!maybe_function.has_value())
  4248. return nullptr;
  4249. auto function = maybe_function.release_value();
  4250. auto function_metadata = easing_function_metadata(function);
  4251. if (function_metadata.parameters.is_empty() && arguments.has_value()) {
  4252. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: 0", name);
  4253. return nullptr;
  4254. }
  4255. StyleValueVector values;
  4256. size_t argument_index = 0;
  4257. if (arguments.has_value()) {
  4258. auto argument_tokens = TokenStream { *arguments };
  4259. auto arguments_values = parse_a_comma_separated_list_of_component_values(argument_tokens);
  4260. if (arguments_values.size() > function_metadata.parameters.size()) {
  4261. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", name, function_metadata.parameters.size());
  4262. return nullptr;
  4263. }
  4264. for (auto& argument_values : arguments_values) {
  4265. // Prune any whitespace before and after the actual argument values.
  4266. argument_values.remove_all_matching([](auto& value) { return value.is(Token::Type::Whitespace); });
  4267. if (argument_values.size() != 1) {
  4268. dbgln_if(CSS_PARSER_DEBUG, "Too many values in argument to {}. max: 1", name);
  4269. return nullptr;
  4270. }
  4271. auto& value = argument_values[0];
  4272. switch (function_metadata.parameters[argument_index].type) {
  4273. case EasingFunctionParameterType::Number: {
  4274. if (value.is(Token::Type::Number))
  4275. values.append(NumberStyleValue::create(value.token().number().value()));
  4276. else
  4277. return nullptr;
  4278. break;
  4279. }
  4280. case EasingFunctionParameterType::NumberZeroToOne: {
  4281. if (value.is(Token::Type::Number) && value.token().number_value() >= 0 && value.token().number_value() <= 1)
  4282. values.append(NumberStyleValue::create(value.token().number().value()));
  4283. else
  4284. return nullptr;
  4285. break;
  4286. }
  4287. case EasingFunctionParameterType::Integer: {
  4288. if (value.is(Token::Type::Number) && value.token().number().is_integer())
  4289. values.append(IntegerStyleValue::create(value.token().number().integer_value()));
  4290. else
  4291. return nullptr;
  4292. break;
  4293. }
  4294. case EasingFunctionParameterType::StepPosition: {
  4295. if (!value.is(Token::Type::Ident))
  4296. return nullptr;
  4297. auto ident = parse_identifier_value(value);
  4298. if (!ident)
  4299. return nullptr;
  4300. switch (ident->to_identifier()) {
  4301. case ValueID::JumpStart:
  4302. case ValueID::JumpEnd:
  4303. case ValueID::JumpNone:
  4304. case ValueID::Start:
  4305. case ValueID::End:
  4306. values.append(*ident);
  4307. break;
  4308. default:
  4309. return nullptr;
  4310. }
  4311. }
  4312. }
  4313. ++argument_index;
  4314. }
  4315. }
  4316. if (argument_index < function_metadata.parameters.size() && !function_metadata.parameters[argument_index].is_optional) {
  4317. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  4318. return nullptr;
  4319. }
  4320. transaction.commit();
  4321. return EasingStyleValue::create(function, move(values));
  4322. }
  4323. RefPtr<StyleValue> Parser::parse_transform_value(TokenStream<ComponentValue>& tokens)
  4324. {
  4325. if (contains_single_none_ident(tokens)) {
  4326. tokens.next_token(); // none
  4327. return IdentifierStyleValue::create(ValueID::None);
  4328. }
  4329. StyleValueVector transformations;
  4330. auto transaction = tokens.begin_transaction();
  4331. while (tokens.has_next_token()) {
  4332. auto const& part = tokens.next_token();
  4333. if (!part.is_function())
  4334. return nullptr;
  4335. auto maybe_function = transform_function_from_string(part.function().name());
  4336. if (!maybe_function.has_value())
  4337. return nullptr;
  4338. auto function = maybe_function.release_value();
  4339. auto function_metadata = transform_function_metadata(function);
  4340. StyleValueVector values;
  4341. auto argument_tokens = TokenStream { part.function().values() };
  4342. argument_tokens.skip_whitespace();
  4343. size_t argument_index = 0;
  4344. while (argument_tokens.has_next_token()) {
  4345. if (argument_index == function_metadata.parameters.size()) {
  4346. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
  4347. return nullptr;
  4348. }
  4349. auto const& value = argument_tokens.next_token();
  4350. RefPtr<CalculatedStyleValue> maybe_calc_value = parse_calculated_value(value);
  4351. switch (function_metadata.parameters[argument_index].type) {
  4352. case TransformFunctionParameterType::Angle: {
  4353. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  4354. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  4355. values.append(maybe_calc_value.release_nonnull());
  4356. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  4357. values.append(AngleStyleValue::create(Angle::make_degrees(0)));
  4358. } else {
  4359. auto dimension_value = parse_dimension_value(value);
  4360. if (!dimension_value || !dimension_value->is_angle())
  4361. return nullptr;
  4362. values.append(dimension_value.release_nonnull());
  4363. }
  4364. break;
  4365. }
  4366. case TransformFunctionParameterType::Length:
  4367. case TransformFunctionParameterType::LengthNone: {
  4368. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  4369. values.append(maybe_calc_value.release_nonnull());
  4370. } else {
  4371. if (function_metadata.parameters[argument_index].type == TransformFunctionParameterType::LengthNone) {
  4372. auto identifier_value = parse_identifier_value(value);
  4373. if (identifier_value && identifier_value->to_identifier() == ValueID::None) {
  4374. values.append(identifier_value.release_nonnull());
  4375. argument_index++;
  4376. continue;
  4377. }
  4378. }
  4379. auto dimension_value = parse_dimension_value(value);
  4380. if (!dimension_value)
  4381. return nullptr;
  4382. if (dimension_value->is_length())
  4383. values.append(dimension_value.release_nonnull());
  4384. else
  4385. return nullptr;
  4386. }
  4387. break;
  4388. }
  4389. case TransformFunctionParameterType::LengthPercentage: {
  4390. if (maybe_calc_value && maybe_calc_value->resolves_to_length_percentage()) {
  4391. values.append(maybe_calc_value.release_nonnull());
  4392. } else {
  4393. auto dimension_value = parse_dimension_value(value);
  4394. if (!dimension_value)
  4395. return nullptr;
  4396. if (dimension_value->is_percentage() || dimension_value->is_length())
  4397. values.append(dimension_value.release_nonnull());
  4398. else
  4399. return nullptr;
  4400. }
  4401. break;
  4402. }
  4403. case TransformFunctionParameterType::Number: {
  4404. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  4405. values.append(maybe_calc_value.release_nonnull());
  4406. } else {
  4407. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  4408. argument_tokens.reconsume_current_input_token();
  4409. auto number = parse_number_value(argument_tokens);
  4410. if (!number)
  4411. return nullptr;
  4412. values.append(number.release_nonnull());
  4413. }
  4414. break;
  4415. }
  4416. case TransformFunctionParameterType::NumberPercentage: {
  4417. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  4418. values.append(maybe_calc_value.release_nonnull());
  4419. } else {
  4420. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  4421. argument_tokens.reconsume_current_input_token();
  4422. auto number_or_percentage = parse_number_or_percentage_value(argument_tokens);
  4423. if (!number_or_percentage)
  4424. return nullptr;
  4425. values.append(number_or_percentage.release_nonnull());
  4426. }
  4427. break;
  4428. }
  4429. }
  4430. argument_tokens.skip_whitespace();
  4431. if (argument_tokens.has_next_token()) {
  4432. // Arguments must be separated by commas.
  4433. if (!argument_tokens.next_token().is(Token::Type::Comma))
  4434. return nullptr;
  4435. argument_tokens.skip_whitespace();
  4436. // If there are no more parameters after the comma, this is invalid.
  4437. if (!argument_tokens.has_next_token())
  4438. return nullptr;
  4439. }
  4440. argument_index++;
  4441. }
  4442. if (argument_index < function_metadata.parameters.size() && function_metadata.parameters[argument_index].required) {
  4443. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  4444. return nullptr;
  4445. }
  4446. transformations.append(TransformationStyleValue::create(function, move(values)));
  4447. }
  4448. transaction.commit();
  4449. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  4450. }
  4451. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  4452. // FIXME: This only supports a 2D position
  4453. RefPtr<StyleValue> Parser::parse_transform_origin_value(TokenStream<ComponentValue>& tokens)
  4454. {
  4455. enum class Axis {
  4456. None,
  4457. X,
  4458. Y,
  4459. };
  4460. struct AxisOffset {
  4461. Axis axis;
  4462. NonnullRefPtr<StyleValue> offset;
  4463. };
  4464. auto to_axis_offset = [](RefPtr<StyleValue> value) -> Optional<AxisOffset> {
  4465. if (!value)
  4466. return OptionalNone {};
  4467. if (value->is_percentage())
  4468. return AxisOffset { Axis::None, value->as_percentage() };
  4469. if (value->is_length())
  4470. return AxisOffset { Axis::None, value->as_length() };
  4471. if (value->is_identifier()) {
  4472. switch (value->to_identifier()) {
  4473. case ValueID::Top:
  4474. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
  4475. case ValueID::Left:
  4476. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
  4477. case ValueID::Center:
  4478. return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
  4479. case ValueID::Bottom:
  4480. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
  4481. case ValueID::Right:
  4482. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
  4483. default:
  4484. return OptionalNone {};
  4485. }
  4486. }
  4487. return OptionalNone {};
  4488. };
  4489. auto transaction = tokens.begin_transaction();
  4490. auto make_list = [&transaction](NonnullRefPtr<StyleValue> const& x_value, NonnullRefPtr<StyleValue> const& y_value) -> NonnullRefPtr<StyleValueList> {
  4491. transaction.commit();
  4492. return StyleValueList::create(StyleValueVector { x_value, y_value }, StyleValueList::Separator::Space);
  4493. };
  4494. switch (tokens.remaining_token_count()) {
  4495. case 1: {
  4496. auto single_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4497. if (!single_value.has_value())
  4498. return nullptr;
  4499. // If only one value is specified, the second value is assumed to be center.
  4500. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  4501. switch (single_value->axis) {
  4502. case Axis::None:
  4503. case Axis::X:
  4504. return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
  4505. case Axis::Y:
  4506. return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
  4507. }
  4508. VERIFY_NOT_REACHED();
  4509. }
  4510. case 2: {
  4511. auto first_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4512. auto second_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4513. if (!first_value.has_value() || !second_value.has_value())
  4514. return nullptr;
  4515. RefPtr<StyleValue> x_value;
  4516. RefPtr<StyleValue> y_value;
  4517. if (first_value->axis == Axis::X) {
  4518. x_value = first_value->offset;
  4519. } else if (first_value->axis == Axis::Y) {
  4520. y_value = first_value->offset;
  4521. }
  4522. if (second_value->axis == Axis::X) {
  4523. if (x_value)
  4524. return nullptr;
  4525. x_value = second_value->offset;
  4526. // Put the other in Y since its axis can't have been X
  4527. y_value = first_value->offset;
  4528. } else if (second_value->axis == Axis::Y) {
  4529. if (y_value)
  4530. return nullptr;
  4531. y_value = second_value->offset;
  4532. // Put the other in X since its axis can't have been Y
  4533. x_value = first_value->offset;
  4534. } else {
  4535. if (x_value) {
  4536. VERIFY(!y_value);
  4537. y_value = second_value->offset;
  4538. } else {
  4539. VERIFY(!x_value);
  4540. x_value = second_value->offset;
  4541. }
  4542. }
  4543. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  4544. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  4545. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  4546. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  4547. x_value = first_value->offset;
  4548. y_value = second_value->offset;
  4549. }
  4550. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  4551. }
  4552. }
  4553. return nullptr;
  4554. }
  4555. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  4556. {
  4557. auto component_values = parse_a_list_of_component_values(m_token_stream);
  4558. auto tokens = TokenStream(component_values);
  4559. auto parsed_value = parse_css_value(property_id, tokens);
  4560. if (parsed_value.is_error())
  4561. return nullptr;
  4562. return parsed_value.release_value();
  4563. }
  4564. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  4565. {
  4566. if (component_value.is_function()) {
  4567. if (auto maybe_calculated = parse_calculated_value(component_value)) {
  4568. if (maybe_calculated->resolves_to_length_percentage())
  4569. return GridSize(LengthPercentage(maybe_calculated.release_nonnull()));
  4570. // FIXME: Support calculated <flex>
  4571. }
  4572. return {};
  4573. }
  4574. if (component_value.is_ident("auto"sv))
  4575. return GridSize::make_auto();
  4576. if (component_value.is_ident("max-content"sv))
  4577. return GridSize(GridSize::Type::MaxContent);
  4578. if (component_value.is_ident("min-content"sv))
  4579. return GridSize(GridSize::Type::MinContent);
  4580. auto dimension = parse_dimension(component_value);
  4581. if (!dimension.has_value())
  4582. return {};
  4583. if (dimension->is_length())
  4584. return GridSize(dimension->length());
  4585. else if (dimension->is_percentage())
  4586. return GridSize(dimension->percentage());
  4587. else if (dimension->is_flex())
  4588. return GridSize(dimension->flex());
  4589. return {};
  4590. }
  4591. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  4592. {
  4593. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  4594. // 'minmax(min, max)'
  4595. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  4596. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  4597. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  4598. auto function_tokens = TokenStream(component_values);
  4599. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  4600. if (comma_separated_list.size() != 2)
  4601. return {};
  4602. TokenStream part_one_tokens { comma_separated_list[0] };
  4603. part_one_tokens.skip_whitespace();
  4604. if (!part_one_tokens.has_next_token())
  4605. return {};
  4606. auto current_token = part_one_tokens.next_token();
  4607. auto min_grid_size = parse_grid_size(current_token);
  4608. TokenStream part_two_tokens { comma_separated_list[1] };
  4609. part_two_tokens.skip_whitespace();
  4610. if (!part_two_tokens.has_next_token())
  4611. return {};
  4612. current_token = part_two_tokens.next_token();
  4613. auto max_grid_size = parse_grid_size(current_token);
  4614. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  4615. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  4616. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  4617. if (min_grid_size.value().is_flexible_length())
  4618. return {};
  4619. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  4620. }
  4621. return {};
  4622. }
  4623. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  4624. {
  4625. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  4626. // 7.2.3.1. Syntax of repeat()
  4627. // The generic form of the repeat() syntax is, approximately,
  4628. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  4629. auto is_auto_fill = false;
  4630. auto is_auto_fit = false;
  4631. auto function_tokens = TokenStream(component_values);
  4632. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  4633. if (comma_separated_list.size() != 2)
  4634. return {};
  4635. // The first argument specifies the number of repetitions.
  4636. TokenStream part_one_tokens { comma_separated_list[0] };
  4637. part_one_tokens.skip_whitespace();
  4638. if (!part_one_tokens.has_next_token())
  4639. return {};
  4640. auto& current_token = part_one_tokens.next_token();
  4641. auto repeat_count = 0;
  4642. if (current_token.is(Token::Type::Number) && current_token.token().number().is_integer() && current_token.token().number_value() > 0)
  4643. repeat_count = current_token.token().number_value();
  4644. else if (current_token.is_ident("auto-fill"sv))
  4645. is_auto_fill = true;
  4646. else if (current_token.is_ident("auto-fit"sv))
  4647. is_auto_fit = true;
  4648. // The second argument is a track list, which is repeated that number of times.
  4649. TokenStream part_two_tokens { comma_separated_list[1] };
  4650. part_two_tokens.skip_whitespace();
  4651. if (!part_two_tokens.has_next_token())
  4652. return {};
  4653. Vector<Variant<ExplicitGridTrack, GridLineNames>> repeat_params;
  4654. auto last_object_was_line_names = false;
  4655. while (part_two_tokens.has_next_token()) {
  4656. auto token = part_two_tokens.next_token();
  4657. Vector<String> line_names;
  4658. if (token.is_block()) {
  4659. if (last_object_was_line_names)
  4660. return {};
  4661. last_object_was_line_names = true;
  4662. if (!token.block().is_square())
  4663. return {};
  4664. TokenStream block_tokens { token.block().values() };
  4665. while (block_tokens.has_next_token()) {
  4666. auto current_block_token = block_tokens.next_token();
  4667. line_names.append(current_block_token.token().ident().to_string());
  4668. block_tokens.skip_whitespace();
  4669. }
  4670. repeat_params.append(GridLineNames { move(line_names) });
  4671. part_two_tokens.skip_whitespace();
  4672. } else {
  4673. last_object_was_line_names = false;
  4674. auto track_sizing_function = parse_track_sizing_function(token);
  4675. if (!track_sizing_function.has_value())
  4676. return {};
  4677. // However, there are some restrictions:
  4678. // The repeat() notation can’t be nested.
  4679. if (track_sizing_function.value().is_repeat())
  4680. return {};
  4681. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  4682. if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit))
  4683. return {};
  4684. repeat_params.append(track_sizing_function.value());
  4685. part_two_tokens.skip_whitespace();
  4686. }
  4687. }
  4688. // Thus the precise syntax of the repeat() notation has several forms:
  4689. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  4690. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  4691. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  4692. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  4693. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  4694. // fixed number of repetitions.
  4695. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  4696. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  4697. // list, but the same track list can also contain <fixed-repeat>s.
  4698. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  4699. // subgrid keyword and cannot specify track sizes, only line names.
  4700. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  4701. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  4702. // 1fr [b a] 1fr [b].
  4703. if (is_auto_fill)
  4704. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFill);
  4705. else if (is_auto_fit)
  4706. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFit);
  4707. else
  4708. return GridRepeat(GridTrackSizeList(move(repeat_params)), repeat_count);
  4709. }
  4710. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  4711. {
  4712. if (token.is_function()) {
  4713. auto const& function_token = token.function();
  4714. if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
  4715. auto maybe_repeat = parse_repeat(function_token.values());
  4716. if (maybe_repeat.has_value())
  4717. return CSS::ExplicitGridTrack(maybe_repeat.value());
  4718. else
  4719. return {};
  4720. } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
  4721. auto maybe_min_max_value = parse_min_max(function_token.values());
  4722. if (maybe_min_max_value.has_value())
  4723. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  4724. else
  4725. return {};
  4726. } else if (auto maybe_calculated = parse_calculated_value(token)) {
  4727. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_calculated.release_nonnull())));
  4728. }
  4729. return {};
  4730. } else if (token.is_ident("auto"sv)) {
  4731. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  4732. } else if (token.is_block()) {
  4733. return {};
  4734. } else {
  4735. auto grid_size = parse_grid_size(token);
  4736. if (!grid_size.has_value())
  4737. return {};
  4738. return CSS::ExplicitGridTrack(grid_size.value());
  4739. }
  4740. }
  4741. RefPtr<StyleValue> Parser::parse_grid_track_size_list(TokenStream<ComponentValue>& tokens, bool allow_separate_line_name_blocks)
  4742. {
  4743. auto transaction = tokens.begin_transaction();
  4744. if (contains_single_none_ident(tokens)) {
  4745. tokens.next_token();
  4746. transaction.commit();
  4747. return GridTrackSizeListStyleValue::make_none();
  4748. }
  4749. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  4750. auto last_object_was_line_names = false;
  4751. while (tokens.has_next_token()) {
  4752. auto token = tokens.next_token();
  4753. if (token.is_block()) {
  4754. if (last_object_was_line_names && !allow_separate_line_name_blocks) {
  4755. transaction.commit();
  4756. return GridTrackSizeListStyleValue::make_auto();
  4757. }
  4758. last_object_was_line_names = true;
  4759. Vector<String> line_names;
  4760. if (!token.block().is_square()) {
  4761. transaction.commit();
  4762. return GridTrackSizeListStyleValue::make_auto();
  4763. }
  4764. TokenStream block_tokens { token.block().values() };
  4765. block_tokens.skip_whitespace();
  4766. while (block_tokens.has_next_token()) {
  4767. auto current_block_token = block_tokens.next_token();
  4768. line_names.append(current_block_token.token().ident().to_string());
  4769. block_tokens.skip_whitespace();
  4770. }
  4771. track_list.append(GridLineNames { move(line_names) });
  4772. } else {
  4773. last_object_was_line_names = false;
  4774. auto track_sizing_function = parse_track_sizing_function(token);
  4775. if (!track_sizing_function.has_value()) {
  4776. transaction.commit();
  4777. return GridTrackSizeListStyleValue::make_auto();
  4778. }
  4779. // FIXME: Handle multiple repeat values (should combine them here, or remove
  4780. // any other ones if the first one is auto-fill, etc.)
  4781. track_list.append(track_sizing_function.value());
  4782. }
  4783. }
  4784. transaction.commit();
  4785. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  4786. }
  4787. // https://www.w3.org/TR/css-grid-1/#grid-auto-flow-property
  4788. RefPtr<GridAutoFlowStyleValue> Parser::parse_grid_auto_flow_value(TokenStream<ComponentValue>& tokens)
  4789. {
  4790. // [ row | column ] || dense
  4791. if (!tokens.has_next_token())
  4792. return nullptr;
  4793. auto transaction = tokens.begin_transaction();
  4794. auto parse_axis = [&]() -> Optional<GridAutoFlowStyleValue::Axis> {
  4795. auto transaction = tokens.begin_transaction();
  4796. auto token = tokens.next_token();
  4797. if (!token.is(Token::Type::Ident))
  4798. return {};
  4799. auto const& ident = token.token().ident();
  4800. if (ident.equals_ignoring_ascii_case("row"sv)) {
  4801. transaction.commit();
  4802. return GridAutoFlowStyleValue::Axis::Row;
  4803. } else if (ident.equals_ignoring_ascii_case("column"sv)) {
  4804. transaction.commit();
  4805. return GridAutoFlowStyleValue::Axis::Column;
  4806. }
  4807. return {};
  4808. };
  4809. auto parse_dense = [&]() -> Optional<GridAutoFlowStyleValue::Dense> {
  4810. auto transaction = tokens.begin_transaction();
  4811. auto token = tokens.next_token();
  4812. if (!token.is(Token::Type::Ident))
  4813. return {};
  4814. auto const& ident = token.token().ident();
  4815. if (ident.equals_ignoring_ascii_case("dense"sv)) {
  4816. transaction.commit();
  4817. return GridAutoFlowStyleValue::Dense::Yes;
  4818. }
  4819. return {};
  4820. };
  4821. Optional<GridAutoFlowStyleValue::Axis> axis;
  4822. Optional<GridAutoFlowStyleValue::Dense> dense;
  4823. if (axis = parse_axis(); axis.has_value()) {
  4824. dense = parse_dense();
  4825. } else if (dense = parse_dense(); dense.has_value()) {
  4826. axis = parse_axis();
  4827. }
  4828. if (tokens.has_next_token())
  4829. return nullptr;
  4830. transaction.commit();
  4831. return GridAutoFlowStyleValue::create(axis.value_or(GridAutoFlowStyleValue::Axis::Row), dense.value_or(GridAutoFlowStyleValue::Dense::No));
  4832. }
  4833. RefPtr<StyleValue> Parser::parse_grid_auto_track_sizes(TokenStream<ComponentValue>& tokens)
  4834. {
  4835. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  4836. // <track-size>+
  4837. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  4838. auto transaction = tokens.begin_transaction();
  4839. while (tokens.has_next_token()) {
  4840. auto token = tokens.next_token();
  4841. auto track_sizing_function = parse_track_sizing_function(token);
  4842. if (!track_sizing_function.has_value()) {
  4843. transaction.commit();
  4844. return GridTrackSizeListStyleValue::make_auto();
  4845. }
  4846. // FIXME: Handle multiple repeat values (should combine them here, or remove
  4847. // any other ones if the first one is auto-fill, etc.)
  4848. track_list.append(track_sizing_function.value());
  4849. }
  4850. transaction.commit();
  4851. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  4852. }
  4853. RefPtr<StyleValue> Parser::parse_grid_track_placement(TokenStream<ComponentValue>& tokens)
  4854. {
  4855. // FIXME: This shouldn't be needed. Right now, the below code returns a StyleValue even if no tokens are consumed!
  4856. if (!tokens.has_next_token())
  4857. return nullptr;
  4858. // https://www.w3.org/TR/css-grid-2/#line-placement
  4859. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  4860. // <grid-line> =
  4861. // auto |
  4862. // <custom-ident> |
  4863. // [ <integer> && <custom-ident>? ] |
  4864. // [ span && [ <integer> || <custom-ident> ] ]
  4865. auto is_valid_integer = [](auto& token) -> bool {
  4866. // An <integer> value of zero makes the declaration invalid.
  4867. if (token.is(Token::Type::Number) && token.token().number().is_integer() && token.token().number_value() != 0)
  4868. return true;
  4869. return false;
  4870. };
  4871. auto is_custom_ident = [](auto& token) -> bool {
  4872. // The <custom-ident> additionally excludes the keywords span and auto.
  4873. if (token.is(Token::Type::Ident) && !token.is_ident("span"sv) && !token.is_ident("auto"sv))
  4874. return true;
  4875. return false;
  4876. };
  4877. auto transaction = tokens.begin_transaction();
  4878. // FIXME: Handle the single-token case inside the loop instead, so that we can more easily call this from
  4879. // `parse_grid_area_shorthand_value()` using a single TokenStream.
  4880. if (tokens.remaining_token_count() == 1) {
  4881. auto& token = tokens.next_token();
  4882. if (auto maybe_calculated = parse_calculated_value(token); maybe_calculated && maybe_calculated->resolves_to_number()) {
  4883. transaction.commit();
  4884. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(maybe_calculated->resolve_integer().value()), {}));
  4885. }
  4886. if (token.is_ident("auto"sv)) {
  4887. transaction.commit();
  4888. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto());
  4889. }
  4890. if (token.is_ident("span"sv)) {
  4891. transaction.commit();
  4892. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(1));
  4893. }
  4894. if (is_valid_integer(token)) {
  4895. transaction.commit();
  4896. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(token.token().number_value()), {}));
  4897. }
  4898. if (is_custom_ident(token)) {
  4899. transaction.commit();
  4900. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line({}, token.token().ident().to_string()));
  4901. }
  4902. return nullptr;
  4903. }
  4904. auto span_value = false;
  4905. auto span_or_position_value = 0;
  4906. String identifier_value;
  4907. while (tokens.has_next_token()) {
  4908. auto& token = tokens.peek_token();
  4909. if (token.is_ident("auto"sv))
  4910. return nullptr;
  4911. if (token.is_ident("span"sv)) {
  4912. if (span_value)
  4913. return nullptr;
  4914. (void)tokens.next_token(); // span
  4915. span_value = true;
  4916. continue;
  4917. }
  4918. if (is_valid_integer(token)) {
  4919. if (span_or_position_value != 0)
  4920. return nullptr;
  4921. span_or_position_value = static_cast<int>(tokens.next_token().token().to_integer());
  4922. continue;
  4923. }
  4924. if (is_custom_ident(token)) {
  4925. if (!identifier_value.is_empty())
  4926. return nullptr;
  4927. identifier_value = tokens.next_token().token().ident().to_string();
  4928. continue;
  4929. }
  4930. break;
  4931. }
  4932. // Negative integers or zero are invalid.
  4933. if (span_value && span_or_position_value < 1)
  4934. return nullptr;
  4935. // If the <integer> is omitted, it defaults to 1.
  4936. if (span_or_position_value == 0)
  4937. span_or_position_value = 1;
  4938. transaction.commit();
  4939. if (!identifier_value.is_empty())
  4940. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(span_or_position_value, identifier_value));
  4941. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(span_or_position_value));
  4942. }
  4943. RefPtr<StyleValue> Parser::parse_grid_track_placement_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  4944. {
  4945. auto start_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnStart : PropertyID::GridRowStart;
  4946. auto end_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnEnd : PropertyID::GridRowEnd;
  4947. auto transaction = tokens.begin_transaction();
  4948. auto current_token = tokens.next_token();
  4949. Vector<ComponentValue> track_start_placement_tokens;
  4950. while (true) {
  4951. if (current_token.is_delim('/'))
  4952. break;
  4953. track_start_placement_tokens.append(current_token);
  4954. if (!tokens.has_next_token())
  4955. break;
  4956. current_token = tokens.next_token();
  4957. }
  4958. Vector<ComponentValue> track_end_placement_tokens;
  4959. if (tokens.has_next_token()) {
  4960. current_token = tokens.next_token();
  4961. while (true) {
  4962. track_end_placement_tokens.append(current_token);
  4963. if (!tokens.has_next_token())
  4964. break;
  4965. current_token = tokens.next_token();
  4966. }
  4967. }
  4968. TokenStream track_start_placement_token_stream { track_start_placement_tokens };
  4969. auto parsed_start_value = parse_grid_track_placement(track_start_placement_token_stream);
  4970. if (parsed_start_value && track_end_placement_tokens.is_empty()) {
  4971. transaction.commit();
  4972. return ShorthandStyleValue::create(property_id,
  4973. { start_property, end_property },
  4974. { parsed_start_value.release_nonnull(), GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto()) });
  4975. }
  4976. TokenStream track_end_placement_token_stream { track_end_placement_tokens };
  4977. auto parsed_end_value = parse_grid_track_placement(track_end_placement_token_stream);
  4978. if (parsed_start_value && parsed_end_value) {
  4979. transaction.commit();
  4980. return ShorthandStyleValue::create(property_id,
  4981. { start_property, end_property },
  4982. { parsed_start_value.release_nonnull(), parsed_end_value.release_nonnull() });
  4983. }
  4984. return nullptr;
  4985. }
  4986. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  4987. // 7.4. Explicit Grid Shorthand: the grid-template property
  4988. RefPtr<StyleValue> Parser::parse_grid_track_size_list_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  4989. {
  4990. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  4991. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  4992. // none
  4993. // - Sets all three properties to their initial values (none).
  4994. // <'grid-template-rows'> / <'grid-template-columns'>
  4995. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  4996. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  4997. // - Sets grid-template-areas to the strings listed.
  4998. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  4999. // and splicing in the named lines defined before/after each size.
  5000. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  5001. auto transaction = tokens.begin_transaction();
  5002. // FIXME: Read the parts in place if possible, instead of constructing separate vectors and streams.
  5003. Vector<ComponentValue> template_rows_tokens;
  5004. Vector<ComponentValue> template_columns_tokens;
  5005. Vector<ComponentValue> template_area_tokens;
  5006. bool found_forward_slash = false;
  5007. while (tokens.has_next_token()) {
  5008. auto& token = tokens.next_token();
  5009. if (token.is_delim('/')) {
  5010. if (found_forward_slash)
  5011. return nullptr;
  5012. found_forward_slash = true;
  5013. continue;
  5014. }
  5015. if (found_forward_slash) {
  5016. template_columns_tokens.append(token);
  5017. continue;
  5018. }
  5019. if (token.is(Token::Type::String))
  5020. template_area_tokens.append(token);
  5021. else
  5022. template_rows_tokens.append(token);
  5023. }
  5024. TokenStream template_area_token_stream { template_area_tokens };
  5025. TokenStream template_rows_token_stream { template_rows_tokens };
  5026. TokenStream template_columns_token_stream { template_columns_tokens };
  5027. auto parsed_template_areas_values = parse_grid_template_areas_value(template_area_token_stream);
  5028. auto parsed_template_rows_values = parse_grid_track_size_list(template_rows_token_stream, true);
  5029. auto parsed_template_columns_values = parse_grid_track_size_list(template_columns_token_stream);
  5030. if (template_area_token_stream.has_next_token()
  5031. || template_rows_token_stream.has_next_token()
  5032. || template_columns_token_stream.has_next_token())
  5033. return nullptr;
  5034. transaction.commit();
  5035. return ShorthandStyleValue::create(property_id,
  5036. { PropertyID::GridTemplateAreas, PropertyID::GridTemplateRows, PropertyID::GridTemplateColumns },
  5037. { parsed_template_areas_values.release_nonnull(), parsed_template_rows_values.release_nonnull(), parsed_template_columns_values.release_nonnull() });
  5038. }
  5039. RefPtr<StyleValue> Parser::parse_grid_area_shorthand_value(TokenStream<ComponentValue>& tokens)
  5040. {
  5041. auto transaction = tokens.begin_transaction();
  5042. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  5043. while (tokens.has_next_token()) {
  5044. auto& current_token = tokens.next_token();
  5045. if (check_for_delimiter && current_token.is_delim('/'))
  5046. break;
  5047. placement_tokens.append(current_token);
  5048. }
  5049. };
  5050. Vector<ComponentValue> row_start_placement_tokens;
  5051. parse_placement_tokens(row_start_placement_tokens);
  5052. Vector<ComponentValue> column_start_placement_tokens;
  5053. if (tokens.has_next_token())
  5054. parse_placement_tokens(column_start_placement_tokens);
  5055. Vector<ComponentValue> row_end_placement_tokens;
  5056. if (tokens.has_next_token())
  5057. parse_placement_tokens(row_end_placement_tokens);
  5058. Vector<ComponentValue> column_end_placement_tokens;
  5059. if (tokens.has_next_token())
  5060. parse_placement_tokens(column_end_placement_tokens, false);
  5061. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  5062. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  5063. // grid-column-end.
  5064. TokenStream row_start_placement_token_stream { row_start_placement_tokens };
  5065. auto row_start_style_value = parse_grid_track_placement(row_start_placement_token_stream);
  5066. if (row_start_placement_token_stream.has_next_token())
  5067. return nullptr;
  5068. TokenStream column_start_placement_token_stream { column_start_placement_tokens };
  5069. auto column_start_style_value = parse_grid_track_placement(column_start_placement_token_stream);
  5070. if (column_start_placement_token_stream.has_next_token())
  5071. return nullptr;
  5072. TokenStream row_end_placement_token_stream { row_end_placement_tokens };
  5073. auto row_end_style_value = parse_grid_track_placement(row_end_placement_token_stream);
  5074. if (row_end_placement_token_stream.has_next_token())
  5075. return nullptr;
  5076. TokenStream column_end_placement_token_stream { column_end_placement_tokens };
  5077. auto column_end_style_value = parse_grid_track_placement(column_end_placement_token_stream);
  5078. if (column_end_placement_token_stream.has_next_token())
  5079. return nullptr;
  5080. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  5081. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  5082. // fourth value.
  5083. auto row_start = GridTrackPlacement::make_auto();
  5084. auto column_start = GridTrackPlacement::make_auto();
  5085. auto row_end = GridTrackPlacement::make_auto();
  5086. auto column_end = GridTrackPlacement::make_auto();
  5087. if (row_start_style_value)
  5088. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5089. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  5090. // that value. Otherwise, it is set to auto.
  5091. if (column_start_style_value)
  5092. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5093. else
  5094. column_start = row_start;
  5095. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  5096. // <custom-ident>; otherwise, it is set to auto.
  5097. if (row_end_style_value)
  5098. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5099. else
  5100. row_end = column_start;
  5101. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  5102. // that <custom-ident>; otherwise, it is set to auto.
  5103. if (column_end_style_value)
  5104. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  5105. else
  5106. column_end = row_end;
  5107. transaction.commit();
  5108. return ShorthandStyleValue::create(PropertyID::GridArea,
  5109. { PropertyID::GridRowStart, PropertyID::GridColumnStart, PropertyID::GridRowEnd, PropertyID::GridColumnEnd },
  5110. { GridTrackPlacementStyleValue::create(row_start), GridTrackPlacementStyleValue::create(column_start), GridTrackPlacementStyleValue::create(row_end), GridTrackPlacementStyleValue::create(column_end) });
  5111. }
  5112. RefPtr<StyleValue> Parser::parse_grid_shorthand_value(TokenStream<ComponentValue>& tokens)
  5113. {
  5114. // <'grid-template'> |
  5115. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  5116. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  5117. return parse_grid_track_size_list_shorthand_value(PropertyID::Grid, tokens);
  5118. }
  5119. // https://www.w3.org/TR/css-grid-1/#grid-template-areas-property
  5120. RefPtr<StyleValue> Parser::parse_grid_template_areas_value(TokenStream<ComponentValue>& tokens)
  5121. {
  5122. // none | <string>+
  5123. Vector<Vector<String>> grid_area_rows;
  5124. if (contains_single_none_ident(tokens)) {
  5125. (void)tokens.next_token(); // none
  5126. return GridTemplateAreaStyleValue::create(move(grid_area_rows));
  5127. }
  5128. auto transaction = tokens.begin_transaction();
  5129. while (tokens.has_next_token() && tokens.peek_token().is(Token::Type::String)) {
  5130. Vector<String> grid_area_columns;
  5131. auto const parts = MUST(tokens.next_token().token().string().to_string().split(' '));
  5132. for (auto& part : parts) {
  5133. grid_area_columns.append(part);
  5134. }
  5135. grid_area_rows.append(move(grid_area_columns));
  5136. }
  5137. transaction.commit();
  5138. return GridTemplateAreaStyleValue::create(grid_area_rows);
  5139. }
  5140. static bool block_contains_var_or_attr(Block const& block);
  5141. static bool function_contains_var_or_attr(Function const& function)
  5142. {
  5143. if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
  5144. return true;
  5145. for (auto const& token : function.values()) {
  5146. if (token.is_function() && function_contains_var_or_attr(token.function()))
  5147. return true;
  5148. if (token.is_block() && block_contains_var_or_attr(token.block()))
  5149. return true;
  5150. }
  5151. return false;
  5152. }
  5153. bool block_contains_var_or_attr(Block const& block)
  5154. {
  5155. for (auto const& token : block.values()) {
  5156. if (token.is_function() && function_contains_var_or_attr(token.function()))
  5157. return true;
  5158. if (token.is_block() && block_contains_var_or_attr(token.block()))
  5159. return true;
  5160. }
  5161. return false;
  5162. }
  5163. Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& unprocessed_tokens)
  5164. {
  5165. m_context.set_current_property_id(property_id);
  5166. Vector<ComponentValue> component_values;
  5167. bool contains_var_or_attr = false;
  5168. bool const property_accepts_custom_ident = property_accepts_type(property_id, ValueType::CustomIdent);
  5169. while (unprocessed_tokens.has_next_token()) {
  5170. auto const& token = unprocessed_tokens.next_token();
  5171. if (token.is(Token::Type::Semicolon)) {
  5172. unprocessed_tokens.reconsume_current_input_token();
  5173. break;
  5174. }
  5175. if (property_id != PropertyID::Custom) {
  5176. if (token.is(Token::Type::Whitespace))
  5177. continue;
  5178. if (!property_accepts_custom_ident && token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  5179. return ParseError::IncludesIgnoredVendorPrefix;
  5180. }
  5181. if (!contains_var_or_attr) {
  5182. if (token.is_function() && function_contains_var_or_attr(token.function()))
  5183. contains_var_or_attr = true;
  5184. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  5185. contains_var_or_attr = true;
  5186. }
  5187. component_values.append(token);
  5188. }
  5189. if (property_id == PropertyID::Custom || contains_var_or_attr)
  5190. return UnresolvedStyleValue::create(move(component_values), contains_var_or_attr);
  5191. if (component_values.is_empty())
  5192. return ParseError::SyntaxError;
  5193. if (component_values.size() == 1) {
  5194. if (auto parsed_value = parse_builtin_value(component_values.first()))
  5195. return parsed_value.release_nonnull();
  5196. }
  5197. // Special-case property handling
  5198. auto tokens = TokenStream { component_values };
  5199. switch (property_id) {
  5200. case PropertyID::AspectRatio:
  5201. if (auto parsed_value = parse_aspect_ratio_value(tokens); parsed_value && !tokens.has_next_token())
  5202. return parsed_value.release_nonnull();
  5203. return ParseError::SyntaxError;
  5204. case PropertyID::BackdropFilter:
  5205. if (auto parsed_value = parse_filter_value_list_value(tokens); parsed_value && !tokens.has_next_token())
  5206. return parsed_value.release_nonnull();
  5207. return ParseError::SyntaxError;
  5208. case PropertyID::Background:
  5209. if (auto parsed_value = parse_background_value(tokens); parsed_value && !tokens.has_next_token())
  5210. return parsed_value.release_nonnull();
  5211. return ParseError::SyntaxError;
  5212. case PropertyID::BackgroundAttachment:
  5213. case PropertyID::BackgroundClip:
  5214. case PropertyID::BackgroundImage:
  5215. case PropertyID::BackgroundOrigin:
  5216. if (auto parsed_value = parse_simple_comma_separated_value_list(property_id, tokens))
  5217. return parsed_value.release_nonnull();
  5218. return ParseError::SyntaxError;
  5219. case PropertyID::BackgroundPosition:
  5220. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_position_value(tokens, PositionParsingMode::BackgroundPosition); }))
  5221. return parsed_value.release_nonnull();
  5222. return ParseError::SyntaxError;
  5223. case PropertyID::BackgroundPositionX:
  5224. case PropertyID::BackgroundPositionY:
  5225. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this, property_id](auto& tokens) { return parse_single_background_position_x_or_y_value(tokens, property_id); }))
  5226. return parsed_value.release_nonnull();
  5227. return ParseError::SyntaxError;
  5228. case PropertyID::BackgroundRepeat:
  5229. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  5230. return parsed_value.release_nonnull();
  5231. return ParseError::SyntaxError;
  5232. case PropertyID::BackgroundSize:
  5233. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  5234. return parsed_value.release_nonnull();
  5235. return ParseError::SyntaxError;
  5236. case PropertyID::Border:
  5237. case PropertyID::BorderBottom:
  5238. case PropertyID::BorderLeft:
  5239. case PropertyID::BorderRight:
  5240. case PropertyID::BorderTop:
  5241. if (auto parsed_value = parse_border_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  5242. return parsed_value.release_nonnull();
  5243. return ParseError::SyntaxError;
  5244. case PropertyID::BorderTopLeftRadius:
  5245. case PropertyID::BorderTopRightRadius:
  5246. case PropertyID::BorderBottomRightRadius:
  5247. case PropertyID::BorderBottomLeftRadius:
  5248. if (auto parsed_value = parse_border_radius_value(tokens); parsed_value && !tokens.has_next_token())
  5249. return parsed_value.release_nonnull();
  5250. return ParseError::SyntaxError;
  5251. case PropertyID::BorderRadius:
  5252. if (auto parsed_value = parse_border_radius_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  5253. return parsed_value.release_nonnull();
  5254. return ParseError::SyntaxError;
  5255. case PropertyID::BoxShadow:
  5256. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::Yes); parsed_value && !tokens.has_next_token())
  5257. return parsed_value.release_nonnull();
  5258. return ParseError::SyntaxError;
  5259. case PropertyID::Content:
  5260. if (auto parsed_value = parse_content_value(tokens); parsed_value && !tokens.has_next_token())
  5261. return parsed_value.release_nonnull();
  5262. return ParseError::SyntaxError;
  5263. case PropertyID::Display:
  5264. if (auto parsed_value = parse_display_value(tokens); parsed_value && !tokens.has_next_token())
  5265. return parsed_value.release_nonnull();
  5266. return ParseError::SyntaxError;
  5267. case PropertyID::Flex:
  5268. if (auto parsed_value = parse_flex_value(tokens); parsed_value && !tokens.has_next_token())
  5269. return parsed_value.release_nonnull();
  5270. return ParseError::SyntaxError;
  5271. case PropertyID::FlexFlow:
  5272. if (auto parsed_value = parse_flex_flow_value(tokens); parsed_value && !tokens.has_next_token())
  5273. return parsed_value.release_nonnull();
  5274. return ParseError::SyntaxError;
  5275. case PropertyID::Font:
  5276. if (auto parsed_value = parse_font_value(tokens); parsed_value && !tokens.has_next_token())
  5277. return parsed_value.release_nonnull();
  5278. return ParseError::SyntaxError;
  5279. case PropertyID::FontFamily:
  5280. if (auto parsed_value = parse_font_family_value(tokens); parsed_value && !tokens.has_next_token())
  5281. return parsed_value.release_nonnull();
  5282. return ParseError::SyntaxError;
  5283. case PropertyID::GridArea:
  5284. if (auto parsed_value = parse_grid_area_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  5285. return parsed_value.release_nonnull();
  5286. return ParseError::SyntaxError;
  5287. case PropertyID::GridAutoFlow:
  5288. if (auto parsed_value = parse_grid_auto_flow_value(tokens); parsed_value && !tokens.has_next_token())
  5289. return parsed_value.release_nonnull();
  5290. return ParseError::SyntaxError;
  5291. case PropertyID::GridColumn:
  5292. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  5293. return parsed_value.release_nonnull();
  5294. return ParseError::SyntaxError;
  5295. case PropertyID::GridColumnEnd:
  5296. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5297. return parsed_value.release_nonnull();
  5298. return ParseError::SyntaxError;
  5299. case PropertyID::GridColumnStart:
  5300. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5301. return parsed_value.release_nonnull();
  5302. return ParseError::SyntaxError;
  5303. case PropertyID::GridRow:
  5304. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  5305. return parsed_value.release_nonnull();
  5306. return ParseError::SyntaxError;
  5307. case PropertyID::GridRowEnd:
  5308. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5309. return parsed_value.release_nonnull();
  5310. return ParseError::SyntaxError;
  5311. case PropertyID::GridRowStart:
  5312. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5313. return parsed_value.release_nonnull();
  5314. return ParseError::SyntaxError;
  5315. case PropertyID::Grid:
  5316. if (auto parsed_value = parse_grid_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  5317. return parsed_value.release_nonnull();
  5318. return ParseError::SyntaxError;
  5319. case PropertyID::GridTemplate:
  5320. if (auto parsed_value = parse_grid_track_size_list_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  5321. return parsed_value.release_nonnull();
  5322. return ParseError::SyntaxError;
  5323. case PropertyID::GridTemplateAreas:
  5324. if (auto parsed_value = parse_grid_template_areas_value(tokens); parsed_value && !tokens.has_next_token())
  5325. return parsed_value.release_nonnull();
  5326. return ParseError::SyntaxError;
  5327. case PropertyID::GridTemplateColumns:
  5328. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  5329. return parsed_value.release_nonnull();
  5330. return ParseError::SyntaxError;
  5331. case PropertyID::GridTemplateRows:
  5332. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  5333. return parsed_value.release_nonnull();
  5334. return ParseError::SyntaxError;
  5335. case PropertyID::GridAutoColumns:
  5336. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  5337. return parsed_value.release_nonnull();
  5338. return ParseError::SyntaxError;
  5339. case PropertyID::GridAutoRows:
  5340. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  5341. return parsed_value.release_nonnull();
  5342. return ParseError::SyntaxError;
  5343. case PropertyID::ListStyle:
  5344. if (auto parsed_value = parse_list_style_value(tokens); parsed_value && !tokens.has_next_token())
  5345. return parsed_value.release_nonnull();
  5346. return ParseError::SyntaxError;
  5347. case PropertyID::MathDepth:
  5348. if (auto parsed_value = parse_math_depth_value(tokens); parsed_value && !tokens.has_next_token())
  5349. return parsed_value.release_nonnull();
  5350. return ParseError::SyntaxError;
  5351. case PropertyID::Overflow:
  5352. if (auto parsed_value = parse_overflow_value(tokens); parsed_value && !tokens.has_next_token())
  5353. return parsed_value.release_nonnull();
  5354. return ParseError::SyntaxError;
  5355. case PropertyID::PlaceContent:
  5356. if (auto parsed_value = parse_place_content_value(tokens); parsed_value && !tokens.has_next_token())
  5357. return parsed_value.release_nonnull();
  5358. return ParseError::SyntaxError;
  5359. case PropertyID::PlaceItems:
  5360. if (auto parsed_value = parse_place_items_value(tokens); parsed_value && !tokens.has_next_token())
  5361. return parsed_value.release_nonnull();
  5362. return ParseError::SyntaxError;
  5363. case PropertyID::PlaceSelf:
  5364. if (auto parsed_value = parse_place_self_value(tokens); parsed_value && !tokens.has_next_token())
  5365. return parsed_value.release_nonnull();
  5366. return ParseError::SyntaxError;
  5367. case PropertyID::Quotes:
  5368. if (auto parsed_value = parse_quotes_value(tokens); parsed_value && !tokens.has_next_token())
  5369. return parsed_value.release_nonnull();
  5370. return ParseError::SyntaxError;
  5371. case PropertyID::TextDecoration:
  5372. if (auto parsed_value = parse_text_decoration_value(tokens); parsed_value && !tokens.has_next_token())
  5373. return parsed_value.release_nonnull();
  5374. return ParseError::SyntaxError;
  5375. case PropertyID::TextDecorationLine:
  5376. if (auto parsed_value = parse_text_decoration_line_value(tokens); parsed_value && !tokens.has_next_token())
  5377. return parsed_value.release_nonnull();
  5378. return ParseError::SyntaxError;
  5379. case PropertyID::TextShadow:
  5380. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::No); parsed_value && !tokens.has_next_token())
  5381. return parsed_value.release_nonnull();
  5382. return ParseError::SyntaxError;
  5383. case PropertyID::Transform:
  5384. if (auto parsed_value = parse_transform_value(tokens); parsed_value && !tokens.has_next_token())
  5385. return parsed_value.release_nonnull();
  5386. return ParseError::SyntaxError;
  5387. case PropertyID::TransformOrigin:
  5388. if (auto parsed_value = parse_transform_origin_value(tokens); parsed_value && !tokens.has_next_token())
  5389. return parsed_value.release_nonnull();
  5390. return ParseError ::SyntaxError;
  5391. default:
  5392. break;
  5393. }
  5394. // If there's only 1 ComponentValue, we can only produce a single StyleValue.
  5395. if (component_values.size() == 1) {
  5396. auto stream = TokenStream { component_values };
  5397. if (auto parsed_value = parse_css_value_for_property(property_id, stream))
  5398. return parsed_value.release_nonnull();
  5399. } else {
  5400. StyleValueVector parsed_values;
  5401. auto stream = TokenStream { component_values };
  5402. while (auto parsed_value = parse_css_value_for_property(property_id, stream)) {
  5403. parsed_values.append(parsed_value.release_nonnull());
  5404. if (!stream.has_next_token())
  5405. break;
  5406. }
  5407. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 StyleValue, return it directly.
  5408. if (parsed_values.size() == 1)
  5409. return *parsed_values.take_first();
  5410. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  5411. return StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space);
  5412. }
  5413. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  5414. auto unassigned_properties = longhands_for_shorthand(property_id);
  5415. if (unassigned_properties.is_empty())
  5416. return ParseError::SyntaxError;
  5417. auto stream = TokenStream { component_values };
  5418. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<StyleValue const>>> assigned_values;
  5419. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  5420. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  5421. if (property_and_value.has_value()) {
  5422. auto property = property_and_value->property;
  5423. auto value = property_and_value->style_value;
  5424. auto& values = assigned_values.ensure(to_underlying(property));
  5425. if (values.size() + 1 == property_maximum_value_count(property)) {
  5426. // We're done with this property, move on to the next one.
  5427. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  5428. }
  5429. values.append(value.release_nonnull());
  5430. continue;
  5431. }
  5432. // No property matched, so we're done.
  5433. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.peek_token().to_debug_string());
  5434. for (auto id : unassigned_properties)
  5435. dbgln(" {}", string_from_property_id(id));
  5436. break;
  5437. }
  5438. for (auto& property : unassigned_properties)
  5439. assigned_values.ensure(to_underlying(property)).append(property_initial_value(m_context.realm(), property));
  5440. stream.skip_whitespace();
  5441. if (stream.has_next_token())
  5442. return ParseError::SyntaxError;
  5443. Vector<PropertyID> longhand_properties;
  5444. longhand_properties.ensure_capacity(assigned_values.size());
  5445. for (auto& it : assigned_values)
  5446. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  5447. StyleValueVector longhand_values;
  5448. longhand_values.ensure_capacity(assigned_values.size());
  5449. for (auto& it : assigned_values) {
  5450. if (it.value.size() == 1)
  5451. longhand_values.unchecked_append(it.value.take_first());
  5452. else
  5453. longhand_values.unchecked_append(StyleValueList::create(move(it.value), StyleValueList::Separator::Space));
  5454. }
  5455. return { ShorthandStyleValue::create(property_id, move(longhand_properties), move(longhand_values)) };
  5456. }
  5457. RefPtr<StyleValue> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  5458. {
  5459. return parse_css_value_for_properties({ &property_id, 1 }, tokens)
  5460. .map([](auto& it) { return it.style_value; })
  5461. .value_or(nullptr);
  5462. }
  5463. Optional<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  5464. {
  5465. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  5466. for (auto const& property : property_ids) {
  5467. if (property_accepts_type(property, value_type))
  5468. return property;
  5469. }
  5470. return {};
  5471. };
  5472. auto any_property_accepts_type_percentage = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  5473. for (auto const& property : property_ids) {
  5474. if (property_accepts_type(property, value_type) && property_accepts_type(property, ValueType::Percentage))
  5475. return property;
  5476. }
  5477. return {};
  5478. };
  5479. auto any_property_accepts_identifier = [](ReadonlySpan<PropertyID> property_ids, ValueID identifier) -> Optional<PropertyID> {
  5480. for (auto const& property : property_ids) {
  5481. if (property_accepts_identifier(property, identifier))
  5482. return property;
  5483. }
  5484. return {};
  5485. };
  5486. auto& peek_token = tokens.peek_token();
  5487. if (auto property = any_property_accepts_type(property_ids, ValueType::EasingFunction); property.has_value()) {
  5488. if (auto maybe_easing_function = parse_easing_value(tokens))
  5489. return PropertyAndValue { *property, maybe_easing_function };
  5490. }
  5491. if (peek_token.is(Token::Type::Ident)) {
  5492. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  5493. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  5494. auto ident = value_id_from_string(peek_token.token().ident());
  5495. if (ident.has_value()) {
  5496. if (auto property = any_property_accepts_identifier(property_ids, ident.value()); property.has_value()) {
  5497. (void)tokens.next_token();
  5498. return PropertyAndValue { *property, IdentifierStyleValue::create(ident.value()) };
  5499. }
  5500. }
  5501. // Custom idents
  5502. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  5503. (void)tokens.next_token();
  5504. return PropertyAndValue { *property, CustomIdentStyleValue::create(peek_token.token().ident()) };
  5505. }
  5506. }
  5507. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  5508. if (auto maybe_color = parse_color_value(peek_token)) {
  5509. (void)tokens.next_token();
  5510. return PropertyAndValue { *property, maybe_color };
  5511. }
  5512. }
  5513. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  5514. if (auto maybe_image = parse_image_value(peek_token)) {
  5515. (void)tokens.next_token();
  5516. return PropertyAndValue { *property, maybe_image };
  5517. }
  5518. }
  5519. if (auto property = any_property_accepts_type(property_ids, ValueType::Position); property.has_value()) {
  5520. if (auto maybe_position = parse_position_value(tokens))
  5521. return PropertyAndValue { *property, maybe_position };
  5522. }
  5523. if (auto property = any_property_accepts_type(property_ids, ValueType::BackgroundPosition); property.has_value()) {
  5524. if (auto maybe_position = parse_position_value(tokens, PositionParsingMode::BackgroundPosition))
  5525. return PropertyAndValue { *property, maybe_position };
  5526. }
  5527. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  5528. if (auto maybe_ratio = parse_ratio_value(tokens))
  5529. return PropertyAndValue { *property, maybe_ratio };
  5530. }
  5531. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  5532. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  5533. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  5534. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  5535. if (property_accepting_integer.has_value()) {
  5536. auto transaction = tokens.begin_transaction();
  5537. if (auto integer = parse_integer_value(tokens); integer && property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  5538. transaction.commit();
  5539. return PropertyAndValue { *property_accepting_integer, integer };
  5540. }
  5541. }
  5542. if (property_accepting_number.has_value()) {
  5543. auto transaction = tokens.begin_transaction();
  5544. if (auto number = parse_number_value(tokens); number && property_accepts_number(*property_accepting_number, number->as_number().number())) {
  5545. transaction.commit();
  5546. return PropertyAndValue { *property_accepting_number, number };
  5547. }
  5548. }
  5549. }
  5550. if (peek_token.is(Token::Type::Percentage)) {
  5551. auto percentage = Percentage(peek_token.token().percentage());
  5552. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  5553. (void)tokens.next_token();
  5554. return PropertyAndValue { *property, PercentageStyleValue::create(percentage) };
  5555. }
  5556. }
  5557. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  5558. if (auto maybe_rect = parse_rect_value(peek_token)) {
  5559. (void)tokens.next_token();
  5560. return PropertyAndValue { *property, maybe_rect };
  5561. }
  5562. }
  5563. if (peek_token.is(Token::Type::String)) {
  5564. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  5565. return PropertyAndValue { *property, StringStyleValue::create(tokens.next_token().token().string().to_string()) };
  5566. }
  5567. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  5568. if (auto url = parse_url_value(peek_token)) {
  5569. (void)tokens.next_token();
  5570. return PropertyAndValue { *property, url };
  5571. }
  5572. }
  5573. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  5574. || any_property_accepts_type(property_ids, ValueType::Flex).has_value()
  5575. || any_property_accepts_type(property_ids, ValueType::Frequency).has_value()
  5576. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  5577. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  5578. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  5579. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  5580. if (property_accepts_dimension) {
  5581. if (peek_token.is(Token::Type::Number) && m_context.is_parsing_svg_presentation_attribute()) {
  5582. auto transaction = tokens.begin_transaction();
  5583. auto token = tokens.next_token();
  5584. // https://svgwg.org/svg2-draft/types.html#presentation-attribute-css-value
  5585. // We need to allow <number> in any place that expects a <length> or <angle>.
  5586. // FIXME: How should these numbers be interpreted? https://github.com/w3c/svgwg/issues/792
  5587. // For now: Convert them to px lengths, or deg angles.
  5588. auto angle = Angle::make_degrees(token.token().number_value());
  5589. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  5590. transaction.commit();
  5591. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  5592. }
  5593. auto length = Length::make_px(CSSPixels::nearest_value_for(token.token().number_value()));
  5594. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  5595. transaction.commit();
  5596. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  5597. }
  5598. }
  5599. auto transaction = tokens.begin_transaction();
  5600. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  5601. (void)tokens.next_token();
  5602. auto dimension = maybe_dimension.release_value();
  5603. if (dimension.is_angle()) {
  5604. auto angle = dimension.angle();
  5605. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  5606. transaction.commit();
  5607. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  5608. }
  5609. }
  5610. if (dimension.is_flex()) {
  5611. auto flex = dimension.flex();
  5612. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value() && property_accepts_flex(*property, flex)) {
  5613. transaction.commit();
  5614. return PropertyAndValue { *property, FlexStyleValue::create(flex) };
  5615. }
  5616. }
  5617. if (dimension.is_frequency()) {
  5618. auto frequency = dimension.frequency();
  5619. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  5620. transaction.commit();
  5621. return PropertyAndValue { *property, FrequencyStyleValue::create(frequency) };
  5622. }
  5623. }
  5624. if (dimension.is_length()) {
  5625. auto length = dimension.length();
  5626. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  5627. transaction.commit();
  5628. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  5629. }
  5630. }
  5631. if (dimension.is_resolution()) {
  5632. auto resolution = dimension.resolution();
  5633. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  5634. transaction.commit();
  5635. return PropertyAndValue { *property, ResolutionStyleValue::create(resolution) };
  5636. }
  5637. }
  5638. if (dimension.is_time()) {
  5639. auto time = dimension.time();
  5640. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  5641. transaction.commit();
  5642. return PropertyAndValue { *property, TimeStyleValue::create(time) };
  5643. }
  5644. }
  5645. }
  5646. }
  5647. // In order to not end up parsing `calc()` and other math expressions multiple times,
  5648. // we parse it once, and then see if its resolved type matches what the property accepts.
  5649. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  5650. if (auto maybe_calculated = parse_calculated_value(peek_token); maybe_calculated) {
  5651. (void)tokens.next_token();
  5652. auto& calculated = *maybe_calculated;
  5653. // This is a bit sensitive to ordering: `<foo>` and `<percentage>` have to be checked before `<foo-percentage>`.
  5654. // FIXME: When parsing SVG presentation attributes, <number> is permitted wherever <length>, <length-percentage>, or <angle> are.
  5655. // The specifics are unclear, so I'm ignoring this for calculated values for now.
  5656. // See https://github.com/w3c/svgwg/issues/792
  5657. if (calculated.resolves_to_percentage()) {
  5658. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  5659. return PropertyAndValue { *property, calculated };
  5660. } else if (calculated.resolves_to_angle()) {
  5661. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  5662. return PropertyAndValue { *property, calculated };
  5663. } else if (calculated.resolves_to_angle_percentage()) {
  5664. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Angle); property.has_value())
  5665. return PropertyAndValue { *property, calculated };
  5666. } else if (calculated.resolves_to_flex()) {
  5667. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value())
  5668. return PropertyAndValue { *property, calculated };
  5669. } else if (calculated.resolves_to_frequency()) {
  5670. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  5671. return PropertyAndValue { *property, calculated };
  5672. } else if (calculated.resolves_to_frequency_percentage()) {
  5673. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Frequency); property.has_value())
  5674. return PropertyAndValue { *property, calculated };
  5675. } else if (calculated.resolves_to_number()) {
  5676. if (property_accepts_numeric) {
  5677. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  5678. return PropertyAndValue { property_or_resolved, calculated };
  5679. }
  5680. } else if (calculated.resolves_to_number_percentage()) {
  5681. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Number); property.has_value())
  5682. return PropertyAndValue { *property, calculated };
  5683. } else if (calculated.resolves_to_length()) {
  5684. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  5685. return PropertyAndValue { *property, calculated };
  5686. } else if (calculated.resolves_to_length_percentage()) {
  5687. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Length); property.has_value())
  5688. return PropertyAndValue { *property, calculated };
  5689. } else if (calculated.resolves_to_time()) {
  5690. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  5691. return PropertyAndValue { *property, calculated };
  5692. } else if (calculated.resolves_to_time_percentage()) {
  5693. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Time); property.has_value())
  5694. return PropertyAndValue { *property, calculated };
  5695. }
  5696. }
  5697. }
  5698. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  5699. if (auto value = parse_paint_value(tokens))
  5700. return PropertyAndValue { *property, value.release_nonnull() };
  5701. }
  5702. return OptionalNone {};
  5703. }
  5704. class UnparsedCalculationNode final : public CalculationNode {
  5705. public:
  5706. static NonnullOwnPtr<UnparsedCalculationNode> create(ComponentValue component_value)
  5707. {
  5708. return adopt_own(*new (nothrow) UnparsedCalculationNode(move(component_value)));
  5709. }
  5710. virtual ~UnparsedCalculationNode() = default;
  5711. ComponentValue& component_value() { return m_component_value; }
  5712. virtual String to_string() const override { VERIFY_NOT_REACHED(); }
  5713. virtual Optional<CalculatedStyleValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  5714. virtual Optional<CSSNumericType> determine_type(Web::CSS::PropertyID) const override { VERIFY_NOT_REACHED(); }
  5715. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  5716. virtual CalculatedStyleValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  5717. virtual void for_each_child_node(AK::Function<void(NonnullOwnPtr<CalculationNode>&)> const&) override { }
  5718. virtual void dump(StringBuilder& builder, int indent) const override
  5719. {
  5720. builder.appendff("{: >{}}UNPARSED({})\n", "", indent, m_component_value.to_debug_string());
  5721. }
  5722. virtual bool equals(CalculationNode const&) const override { return false; }
  5723. private:
  5724. UnparsedCalculationNode(ComponentValue component_value)
  5725. : CalculationNode(Type::Unparsed)
  5726. , m_component_value(move(component_value))
  5727. {
  5728. }
  5729. ComponentValue m_component_value;
  5730. };
  5731. // https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
  5732. LengthOrCalculated Parser::Parser::parse_as_sizes_attribute()
  5733. {
  5734. // 1. Let unparsed sizes list be the result of parsing a comma-separated list of component values
  5735. // from the value of element's sizes attribute (or the empty string, if the attribute is absent).
  5736. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  5737. // 2. Let size be null.
  5738. Optional<LengthOrCalculated> size;
  5739. // 3. For each unparsed size in unparsed sizes list:
  5740. for (auto& unparsed_size : unparsed_sizes_list) {
  5741. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  5742. // If unparsed size is now empty, that is a parse error; continue.
  5743. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  5744. unparsed_size.take_last();
  5745. if (unparsed_size.is_empty()) {
  5746. log_parse_error();
  5747. continue;
  5748. }
  5749. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  5750. // let size be its value and remove the component value from unparsed size.
  5751. // FIXME: Any CSS function other than the math functions is invalid.
  5752. // Otherwise, there is a parse error; continue.
  5753. auto last_value_stream = TokenStream<ComponentValue>::of_single_token(unparsed_size.last());
  5754. if (auto source_size_value = parse_source_size_value(last_value_stream); source_size_value.has_value()) {
  5755. size = source_size_value.value();
  5756. unparsed_size.take_last();
  5757. } else {
  5758. log_parse_error();
  5759. continue;
  5760. }
  5761. // 3. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  5762. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  5763. unparsed_size.take_last();
  5764. // If unparsed size is now empty, then return size.
  5765. if (unparsed_size.is_empty())
  5766. return size.value();
  5767. // FIXME: If this was not the keyword auto and it was not the last item in unparsed sizes list, that is a parse error.
  5768. // 4. Parse the remaining component values in unparsed size as a <media-condition>.
  5769. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  5770. TokenStream<ComponentValue> token_stream { unparsed_size };
  5771. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  5772. auto context_window = m_context.window();
  5773. if (context_window && media_condition && media_condition->evaluate(*context_window) == MatchResult::True) {
  5774. return size.value();
  5775. }
  5776. // 5. If size is not auto, then return size.
  5777. if (size.value().is_calculated() || !size.value().value().is_auto())
  5778. return size.value();
  5779. }
  5780. return Length(100, Length::Type::Vw);
  5781. }
  5782. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  5783. OwnPtr<CalculationNode> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  5784. {
  5785. // 1. Discard any <whitespace-token>s from values.
  5786. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  5787. struct Operator {
  5788. char delim;
  5789. };
  5790. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  5791. Vector<Value> values;
  5792. for (auto& value : original_values) {
  5793. if (value.is(Token::Type::Whitespace))
  5794. continue;
  5795. if (value.is(Token::Type::Delim)) {
  5796. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  5797. // NOTE: Sequential operators are invalid syntax.
  5798. if (!values.is_empty() && values.last().has<Operator>())
  5799. return nullptr;
  5800. values.append(Operator { static_cast<char>(value.token().delim()) });
  5801. continue;
  5802. }
  5803. }
  5804. if (value.is(Token::Type::Ident)) {
  5805. auto maybe_constant = CalculationNode::constant_type_from_string(value.token().ident());
  5806. if (maybe_constant.has_value()) {
  5807. values.append({ ConstantCalculationNode::create(maybe_constant.value()) });
  5808. continue;
  5809. }
  5810. }
  5811. if (value.is(Token::Type::Number)) {
  5812. values.append({ NumericCalculationNode::create(value.token().number()) });
  5813. continue;
  5814. }
  5815. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  5816. if (dimension->is_angle())
  5817. values.append({ NumericCalculationNode::create(dimension->angle()) });
  5818. else if (dimension->is_frequency())
  5819. values.append({ NumericCalculationNode::create(dimension->frequency()) });
  5820. else if (dimension->is_length())
  5821. values.append({ NumericCalculationNode::create(dimension->length()) });
  5822. else if (dimension->is_percentage())
  5823. values.append({ NumericCalculationNode::create(dimension->percentage()) });
  5824. // FIXME: Resolutions, once calc() supports them.
  5825. else if (dimension->is_time())
  5826. values.append({ NumericCalculationNode::create(dimension->time()) });
  5827. else if (dimension->is_flex()) {
  5828. // https://www.w3.org/TR/css3-grid-layout/#fr-unit
  5829. // NOTE: <flex> values are not <length>s (nor are they compatible with <length>s, like some <percentage> values),
  5830. // so they cannot be represented in or combined with other unit types in calc() expressions.
  5831. return nullptr;
  5832. } else {
  5833. VERIFY_NOT_REACHED();
  5834. }
  5835. continue;
  5836. }
  5837. values.append({ UnparsedCalculationNode::create(value) });
  5838. }
  5839. // If we have no values, the syntax is invalid.
  5840. if (values.is_empty())
  5841. return nullptr;
  5842. // NOTE: If the first or last value is an operator, the syntax is invalid.
  5843. if (values.first().has<Operator>() || values.last().has<Operator>())
  5844. return nullptr;
  5845. // 3. Collect children into Product and Invert nodes.
  5846. // For every consecutive run of value items in values separated by "*" or "/" operators:
  5847. while (true) {
  5848. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  5849. return item.template has<Operator>()
  5850. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  5851. });
  5852. if (!first_product_operator.has_value())
  5853. break;
  5854. auto start_of_run = first_product_operator.value() - 1;
  5855. auto end_of_run = first_product_operator.value() + 1;
  5856. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  5857. auto& item = values[i];
  5858. if (!item.has<Operator>()) {
  5859. end_of_run = i - 1;
  5860. break;
  5861. }
  5862. auto delim = item.get<Operator>().delim;
  5863. if (!first_is_one_of(delim, '*', '/')) {
  5864. end_of_run = i - 1;
  5865. break;
  5866. }
  5867. }
  5868. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  5869. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  5870. run_values.append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>()));
  5871. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  5872. auto& operator_ = values[i].get<Operator>().delim;
  5873. auto& rhs = values[i + 1];
  5874. if (operator_ == '/') {
  5875. run_values.append(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  5876. continue;
  5877. }
  5878. VERIFY(operator_ == '*');
  5879. run_values.append(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  5880. }
  5881. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  5882. auto product_node = ProductCalculationNode::create(move(run_values));
  5883. values.remove(start_of_run, end_of_run - start_of_run + 1);
  5884. values.insert(start_of_run, { move(product_node) });
  5885. }
  5886. // 4. Collect children into Sum and Negate nodes.
  5887. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  5888. {
  5889. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  5890. for (auto i = 0u; i < values.size(); ++i) {
  5891. auto& maybe_minus_operator = values[i];
  5892. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  5893. continue;
  5894. auto rhs_index = ++i;
  5895. auto& rhs = values[rhs_index];
  5896. NonnullOwnPtr<CalculationNode> negate_node = NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  5897. values.remove(rhs_index);
  5898. values.insert(rhs_index, move(negate_node));
  5899. }
  5900. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  5901. if (values.size() == 1) {
  5902. values.first().visit(
  5903. [&](ComponentValue& component_value) {
  5904. if (component_value.is_block() && component_value.block().is_paren())
  5905. single_value = UnparsedCalculationNode::create(component_value);
  5906. },
  5907. [&](NonnullOwnPtr<CalculationNode>& node) {
  5908. if (node->type() == CalculationNode::Type::Product)
  5909. single_value = move(node);
  5910. },
  5911. [](auto&) {});
  5912. }
  5913. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  5914. if (!single_value.has_value()) {
  5915. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  5916. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  5917. value_items.ensure_capacity(values.size());
  5918. for (auto& value : values) {
  5919. if (value.has<Operator>())
  5920. continue;
  5921. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  5922. }
  5923. single_value = SumCalculationNode::create(move(value_items));
  5924. }
  5925. }
  5926. // 5. At this point values is a tree of Sum, Product, Negate, and Invert nodes, with other types of values at the leaf nodes. Process the leaf nodes.
  5927. // For every leaf node leaf in values:
  5928. bool parsing_failed_for_child_node = false;
  5929. single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) {
  5930. if (node->type() != CalculationNode::Type::Unparsed)
  5931. return;
  5932. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  5933. auto& component_value = unparsed_node.component_value();
  5934. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  5935. if (component_value.is_block() && component_value.block().is_paren()) {
  5936. auto leaf_calculation = parse_a_calculation(component_value.block().values());
  5937. if (!leaf_calculation) {
  5938. parsing_failed_for_child_node = true;
  5939. return;
  5940. }
  5941. node = leaf_calculation.release_nonnull();
  5942. return;
  5943. }
  5944. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  5945. // NOTE: All function tokens at this point should be math functions.
  5946. else if (component_value.is_function()) {
  5947. auto& function = component_value.function();
  5948. auto leaf_calculation = parse_a_calc_function_node(function);
  5949. if (!leaf_calculation) {
  5950. parsing_failed_for_child_node = true;
  5951. return;
  5952. }
  5953. node = leaf_calculation.release_nonnull();
  5954. return;
  5955. }
  5956. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  5957. // So, the calc() is invalid.
  5958. dbgln_if(CSS_PARSER_DEBUG, "Leftover UnparsedCalculationNode in calc tree! That probably means the syntax is invalid, but maybe we just didn't implement `{}` yet.", component_value.to_debug_string());
  5959. parsing_failed_for_child_node = true;
  5960. return;
  5961. });
  5962. if (parsing_failed_for_child_node)
  5963. return nullptr;
  5964. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  5965. return single_value.release_value();
  5966. }
  5967. bool Parser::has_ignored_vendor_prefix(StringView string)
  5968. {
  5969. if (!string.starts_with('-'))
  5970. return false;
  5971. if (string.starts_with("--"sv))
  5972. return false;
  5973. if (string.starts_with("-libweb-"sv))
  5974. return false;
  5975. return true;
  5976. }
  5977. NonnullRefPtr<StyleValue> Parser::resolve_unresolved_style_value(Badge<StyleComputer>, ParsingContext const& context, DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  5978. {
  5979. // Unresolved always contains a var() or attr(), unless it is a custom property's value, in which case we shouldn't be trying
  5980. // to produce a different StyleValue from it.
  5981. VERIFY(unresolved.contains_var_or_attr());
  5982. // If the value is invalid, we fall back to `unset`: https://www.w3.org/TR/css-variables-1/#invalid-at-computed-value-time
  5983. auto parser = MUST(Parser::create(context, ""sv));
  5984. return parser.resolve_unresolved_style_value(element, pseudo_element, property_id, unresolved);
  5985. }
  5986. class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> {
  5987. public:
  5988. static NonnullRefPtr<PropertyDependencyNode> create(String name)
  5989. {
  5990. return adopt_ref(*new PropertyDependencyNode(move(name)));
  5991. }
  5992. void add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  5993. {
  5994. for (auto const& child : m_children) {
  5995. if (child->m_name == new_child->m_name)
  5996. return;
  5997. }
  5998. // We detect self-reference already.
  5999. VERIFY(new_child->m_name != m_name);
  6000. m_children.append(move(new_child));
  6001. }
  6002. bool has_cycles()
  6003. {
  6004. if (m_marked)
  6005. return true;
  6006. TemporaryChange change { m_marked, true };
  6007. for (auto& child : m_children) {
  6008. if (child->has_cycles())
  6009. return true;
  6010. }
  6011. return false;
  6012. }
  6013. private:
  6014. explicit PropertyDependencyNode(String name)
  6015. : m_name(move(name))
  6016. {
  6017. }
  6018. String m_name;
  6019. Vector<NonnullRefPtr<PropertyDependencyNode>> m_children;
  6020. bool m_marked { false };
  6021. };
  6022. NonnullRefPtr<StyleValue> Parser::resolve_unresolved_style_value(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  6023. {
  6024. TokenStream unresolved_values_without_variables_expanded { unresolved.values() };
  6025. Vector<ComponentValue> values_with_variables_expanded;
  6026. HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  6027. if (!expand_variables(element, pseudo_element, string_from_property_id(property_id), dependencies, unresolved_values_without_variables_expanded, values_with_variables_expanded))
  6028. return UnsetStyleValue::the();
  6029. TokenStream unresolved_values_with_variables_expanded { values_with_variables_expanded };
  6030. Vector<ComponentValue> expanded_values;
  6031. if (!expand_unresolved_values(element, string_from_property_id(property_id), unresolved_values_with_variables_expanded, expanded_values))
  6032. return UnsetStyleValue::the();
  6033. auto expanded_value_tokens = TokenStream { expanded_values };
  6034. if (auto parsed_value = parse_css_value(property_id, expanded_value_tokens); !parsed_value.is_error())
  6035. return parsed_value.release_value();
  6036. return UnsetStyleValue::the();
  6037. }
  6038. static RefPtr<StyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, FlyString const& custom_property_name)
  6039. {
  6040. if (pseudo_element.has_value()) {
  6041. if (auto it = element.custom_properties(pseudo_element).find(custom_property_name.to_string()); it != element.custom_properties(pseudo_element).end())
  6042. return it->value.value;
  6043. }
  6044. for (auto const* current_element = &element; current_element; current_element = current_element->parent_element()) {
  6045. if (auto it = current_element->custom_properties({}).find(custom_property_name.to_string()); it != current_element->custom_properties({}).end())
  6046. return it->value.value;
  6047. }
  6048. return nullptr;
  6049. }
  6050. bool Parser::expand_variables(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, StringView property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  6051. {
  6052. // Arbitrary large value chosen to avoid the billion-laughs attack.
  6053. // https://www.w3.org/TR/css-variables-1/#long-variables
  6054. size_t const MAX_VALUE_COUNT = 16384;
  6055. if (source.remaining_token_count() + dest.size() > MAX_VALUE_COUNT) {
  6056. dbgln("Stopped expanding CSS variables: maximum length reached.");
  6057. return false;
  6058. }
  6059. auto get_dependency_node = [&](FlyString name) -> NonnullRefPtr<PropertyDependencyNode> {
  6060. if (auto existing = dependencies.get(name); existing.has_value())
  6061. return *existing.value();
  6062. auto new_node = PropertyDependencyNode::create(name.to_string());
  6063. dependencies.set(name, new_node);
  6064. return new_node;
  6065. };
  6066. while (source.has_next_token()) {
  6067. auto const& value = source.next_token();
  6068. if (value.is_block()) {
  6069. auto const& source_block = value.block();
  6070. Vector<ComponentValue> block_values;
  6071. TokenStream source_block_contents { source_block.values() };
  6072. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_block_contents, block_values))
  6073. return false;
  6074. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  6075. dest.empend(block);
  6076. continue;
  6077. }
  6078. if (!value.is_function()) {
  6079. dest.empend(value);
  6080. continue;
  6081. }
  6082. if (!value.function().name().equals_ignoring_ascii_case("var"sv)) {
  6083. auto const& source_function = value.function();
  6084. Vector<ComponentValue> function_values;
  6085. TokenStream source_function_contents { source_function.values() };
  6086. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_function_contents, function_values))
  6087. return false;
  6088. NonnullRefPtr<Function> function = Function::create(source_function.name(), move(function_values));
  6089. dest.empend(function);
  6090. continue;
  6091. }
  6092. TokenStream var_contents { value.function().values() };
  6093. var_contents.skip_whitespace();
  6094. if (!var_contents.has_next_token())
  6095. return false;
  6096. auto const& custom_property_name_token = var_contents.next_token();
  6097. if (!custom_property_name_token.is(Token::Type::Ident))
  6098. return false;
  6099. auto custom_property_name = custom_property_name_token.token().ident();
  6100. if (!custom_property_name.bytes_as_string_view().starts_with("--"sv))
  6101. return false;
  6102. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  6103. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  6104. // but rebuilding it every time.
  6105. if (custom_property_name == property_name)
  6106. return false;
  6107. auto parent = get_dependency_node(MUST(FlyString::from_utf8(property_name)));
  6108. auto child = get_dependency_node(custom_property_name);
  6109. parent->add_child(child);
  6110. if (parent->has_cycles())
  6111. return false;
  6112. if (auto custom_property_value = get_custom_property(element, pseudo_element, custom_property_name)) {
  6113. VERIFY(custom_property_value->is_unresolved());
  6114. TokenStream custom_property_tokens { custom_property_value->as_unresolved().values() };
  6115. if (!expand_variables(element, pseudo_element, custom_property_name, dependencies, custom_property_tokens, dest))
  6116. return false;
  6117. continue;
  6118. }
  6119. // Use the provided fallback value, if any.
  6120. var_contents.skip_whitespace();
  6121. if (var_contents.has_next_token()) {
  6122. auto const& comma_token = var_contents.next_token();
  6123. if (!comma_token.is(Token::Type::Comma))
  6124. return false;
  6125. var_contents.skip_whitespace();
  6126. if (!expand_variables(element, pseudo_element, property_name, dependencies, var_contents, dest))
  6127. return false;
  6128. }
  6129. }
  6130. return true;
  6131. }
  6132. bool Parser::expand_unresolved_values(DOM::Element& element, StringView property_name, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  6133. {
  6134. while (source.has_next_token()) {
  6135. auto const& value = source.next_token();
  6136. if (value.is_function()) {
  6137. if (value.function().name().equals_ignoring_ascii_case("attr"sv)) {
  6138. if (!substitute_attr_function(element, property_name, value.function(), dest))
  6139. return false;
  6140. continue;
  6141. }
  6142. if (auto maybe_calc_value = parse_calculated_value(value); maybe_calc_value && maybe_calc_value->is_calculated()) {
  6143. auto& calc_value = maybe_calc_value->as_calculated();
  6144. if (calc_value.resolves_to_angle()) {
  6145. auto resolved_value = calc_value.resolve_angle();
  6146. dest.empend(Token::create_dimension(resolved_value->to_degrees(), "deg"_fly_string));
  6147. continue;
  6148. }
  6149. if (calc_value.resolves_to_frequency()) {
  6150. auto resolved_value = calc_value.resolve_frequency();
  6151. dest.empend(Token::create_dimension(resolved_value->to_hertz(), "hz"_fly_string));
  6152. continue;
  6153. }
  6154. if (calc_value.resolves_to_length()) {
  6155. // FIXME: In order to resolve lengths, we need to know the font metrics in case a font-relative unit
  6156. // is used. So... we can't do that until style is computed?
  6157. // This might be easier once we have calc-simplification implemented.
  6158. }
  6159. if (calc_value.resolves_to_percentage()) {
  6160. auto resolved_value = calc_value.resolve_percentage();
  6161. dest.empend(Token::create_percentage(resolved_value.value().value()));
  6162. continue;
  6163. }
  6164. if (calc_value.resolves_to_time()) {
  6165. auto resolved_value = calc_value.resolve_time();
  6166. dest.empend(Token::create_dimension(resolved_value->to_seconds(), "s"_fly_string));
  6167. continue;
  6168. }
  6169. if (calc_value.resolves_to_number()) {
  6170. auto resolved_value = calc_value.resolve_number();
  6171. dest.empend(Token::create_number(resolved_value.value()));
  6172. continue;
  6173. }
  6174. }
  6175. auto const& source_function = value.function();
  6176. Vector<ComponentValue> function_values;
  6177. TokenStream source_function_contents { source_function.values() };
  6178. if (!expand_unresolved_values(element, property_name, source_function_contents, function_values))
  6179. return false;
  6180. NonnullRefPtr<Function> function = Function::create(source_function.name(), move(function_values));
  6181. dest.empend(function);
  6182. continue;
  6183. }
  6184. if (value.is_block()) {
  6185. auto const& source_block = value.block();
  6186. TokenStream source_block_values { source_block.values() };
  6187. Vector<ComponentValue> block_values;
  6188. if (!expand_unresolved_values(element, property_name, source_block_values, block_values))
  6189. return false;
  6190. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  6191. dest.empend(move(block));
  6192. continue;
  6193. }
  6194. dest.empend(value.token());
  6195. }
  6196. return true;
  6197. }
  6198. // https://drafts.csswg.org/css-values-5/#attr-substitution
  6199. bool Parser::substitute_attr_function(DOM::Element& element, StringView property_name, Function const& attr_function, Vector<ComponentValue>& dest)
  6200. {
  6201. // First, parse the arguments to attr():
  6202. // attr() = attr( <q-name> <attr-type>? , <declaration-value>?)
  6203. // <attr-type> = string | url | ident | color | number | percentage | length | angle | time | frequency | flex | <dimension-unit>
  6204. TokenStream attr_contents { attr_function.values() };
  6205. attr_contents.skip_whitespace();
  6206. if (!attr_contents.has_next_token())
  6207. return false;
  6208. // - Attribute name
  6209. // FIXME: Support optional attribute namespace
  6210. if (!attr_contents.peek_token().is(Token::Type::Ident))
  6211. return false;
  6212. auto attribute_name = attr_contents.next_token().token().ident();
  6213. attr_contents.skip_whitespace();
  6214. // - Attribute type (optional)
  6215. auto attribute_type = "string"_fly_string;
  6216. if (attr_contents.peek_token().is(Token::Type::Ident)) {
  6217. attribute_type = attr_contents.next_token().token().ident();
  6218. attr_contents.skip_whitespace();
  6219. }
  6220. // - Comma, then fallback values (optional)
  6221. bool has_fallback_values = false;
  6222. if (attr_contents.has_next_token()) {
  6223. if (!attr_contents.peek_token().is(Token::Type::Comma))
  6224. return false;
  6225. (void)attr_contents.next_token(); // Comma
  6226. has_fallback_values = true;
  6227. }
  6228. // Then, run the substitution algorithm:
  6229. // 1. If the attr() function has a substitution value, replace the attr() function by the substitution value.
  6230. // https://drafts.csswg.org/css-values-5/#attr-types
  6231. if (element.has_attribute(attribute_name)) {
  6232. auto attribute_value = element.get_attribute_value(attribute_name);
  6233. if (attribute_type.equals_ignoring_ascii_case("angle"_fly_string)) {
  6234. // Parse a component value from the attribute’s value.
  6235. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6236. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6237. // Otherwise, there is no substitution value.
  6238. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6239. if (Angle::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6240. dest.append(component_value.release_value());
  6241. return true;
  6242. }
  6243. }
  6244. } else if (attribute_type.equals_ignoring_ascii_case("color"_fly_string)) {
  6245. // Parse a component value from the attribute’s value.
  6246. // If the result is a <hex-color> or a named color ident, the substitution value is that result as a <color>.
  6247. // Otherwise there is no substitution value.
  6248. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6249. if (component_value.has_value()) {
  6250. if ((component_value->is(Token::Type::Hash)
  6251. && Color::from_string(MUST(String::formatted("#{}", component_value->token().hash_value()))).has_value())
  6252. || (component_value->is(Token::Type::Ident)
  6253. && Color::from_string(component_value->token().ident()).has_value())) {
  6254. dest.append(component_value.release_value());
  6255. return true;
  6256. }
  6257. }
  6258. } else if (attribute_type.equals_ignoring_ascii_case("flex"_fly_string)) {
  6259. // Parse a component value from the attribute’s value.
  6260. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6261. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6262. // Otherwise, there is no substitution value.
  6263. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6264. if (Flex::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6265. dest.append(component_value.release_value());
  6266. return true;
  6267. }
  6268. }
  6269. } else if (attribute_type.equals_ignoring_ascii_case("frequency"_fly_string)) {
  6270. // Parse a component value from the attribute’s value.
  6271. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6272. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6273. // Otherwise, there is no substitution value.
  6274. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6275. if (Frequency::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6276. dest.append(component_value.release_value());
  6277. return true;
  6278. }
  6279. }
  6280. } else if (attribute_type.equals_ignoring_ascii_case("ident"_fly_string)) {
  6281. // The substitution value is a CSS <custom-ident>, whose value is the literal value of the attribute,
  6282. // with leading and trailing ASCII whitespace stripped. (No CSS parsing of the value is performed.)
  6283. // If the attribute value, after trimming, is the empty string, there is instead no substitution value.
  6284. // If the <custom-ident>’s value is a CSS-wide keyword or `default`, there is instead no substitution value.
  6285. auto substitution_value = MUST(attribute_value.trim(Infra::ASCII_WHITESPACE));
  6286. if (!substitution_value.is_empty()
  6287. && !substitution_value.equals_ignoring_ascii_case("default"sv)
  6288. && !is_css_wide_keyword(substitution_value)) {
  6289. dest.empend(Token::create_ident(substitution_value));
  6290. return true;
  6291. }
  6292. } else if (attribute_type.equals_ignoring_ascii_case("length"_fly_string)) {
  6293. // Parse a component value from the attribute’s value.
  6294. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6295. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6296. // Otherwise, there is no substitution value.
  6297. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6298. if (Length::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6299. dest.append(component_value.release_value());
  6300. return true;
  6301. }
  6302. }
  6303. } else if (attribute_type.equals_ignoring_ascii_case("number"_fly_string)) {
  6304. // Parse a component value from the attribute’s value.
  6305. // If the result is a <number-token>, the result is the substitution value.
  6306. // Otherwise, there is no substitution value.
  6307. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6308. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  6309. dest.append(component_value.release_value());
  6310. return true;
  6311. }
  6312. } else if (attribute_type.equals_ignoring_ascii_case("percentage"_fly_string)) {
  6313. // Parse a component value from the attribute’s value.
  6314. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6315. // If the result is a <percentage-token>, the result is the substitution value.
  6316. // Otherwise, there is no substitution value.
  6317. if (component_value.has_value() && component_value->is(Token::Type::Percentage)) {
  6318. dest.append(component_value.release_value());
  6319. return true;
  6320. }
  6321. } else if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  6322. // The substitution value is a CSS string, whose value is the literal value of the attribute.
  6323. // (No CSS parsing or "cleanup" of the value is performed.)
  6324. // No value triggers fallback.
  6325. dest.empend(Token::create_string(attribute_value));
  6326. return true;
  6327. } else if (attribute_type.equals_ignoring_ascii_case("time"_fly_string)) {
  6328. // Parse a component value from the attribute’s value.
  6329. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6330. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6331. // Otherwise, there is no substitution value.
  6332. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6333. if (Time::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6334. dest.append(component_value.release_value());
  6335. return true;
  6336. }
  6337. }
  6338. } else if (attribute_type.equals_ignoring_ascii_case("url"_fly_string)) {
  6339. // The substitution value is a CSS <url> value, whose url is the literal value of the attribute.
  6340. // (No CSS parsing or "cleanup" of the value is performed.)
  6341. // No value triggers fallback.
  6342. dest.empend(Token::create_url(attribute_value));
  6343. return true;
  6344. } else {
  6345. // Dimension units
  6346. // Parse a component value from the attribute’s value.
  6347. // If the result is a <number-token>, the substitution value is a dimension with the result’s value, and the given unit.
  6348. // Otherwise, there is no substitution value.
  6349. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6350. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  6351. if (attribute_value == "%"sv) {
  6352. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6353. return true;
  6354. } else if (auto angle_unit = Angle::unit_from_name(attribute_type); angle_unit.has_value()) {
  6355. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6356. return true;
  6357. } else if (auto flex_unit = Flex::unit_from_name(attribute_type); flex_unit.has_value()) {
  6358. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6359. return true;
  6360. } else if (auto frequency_unit = Frequency::unit_from_name(attribute_type); frequency_unit.has_value()) {
  6361. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6362. return true;
  6363. } else if (auto length_unit = Length::unit_from_name(attribute_type); length_unit.has_value()) {
  6364. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6365. return true;
  6366. } else if (auto time_unit = Time::unit_from_name(attribute_type); time_unit.has_value()) {
  6367. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6368. return true;
  6369. } else {
  6370. // Not a dimension unit.
  6371. return false;
  6372. }
  6373. }
  6374. }
  6375. }
  6376. // 2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value.
  6377. // If there are any var() or attr() references in the fallback, substitute them as well.
  6378. if (has_fallback_values)
  6379. return expand_unresolved_values(element, property_name, attr_contents, dest);
  6380. // 3. Otherwise, the property containing the attr() function is invalid at computed-value time.
  6381. return false;
  6382. }
  6383. }