Parser.cpp 379 KB

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