Parser.cpp 403 KB

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