Parser.cpp 378 KB

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