Parser.cpp 360 KB

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