Parser.cpp 377 KB

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