Parser.cpp 301 KB

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