Parser.cpp 341 KB

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