Parser.cpp 298 KB

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