Parser.cpp 297 KB

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