Parser.cpp 298 KB

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