Parser.cpp 311 KB

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