Parser.cpp 395 KB

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