Parser.cpp 321 KB

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