Parser.cpp 364 KB

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