Parser.cpp 385 KB

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