Parser.cpp 360 KB

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