Parser.cpp 293 KB

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