Parser.cpp 356 KB

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