Parser.cpp 341 KB

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