Parser.cpp 377 KB

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