Parser.cpp 305 KB

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