Parser.cpp 301 KB

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