Parser.cpp 314 KB

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