Parser.cpp 360 KB

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