Parser.cpp 273 KB

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