Parser.cpp 295 KB

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