Parser.cpp 298 KB

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