Parser.cpp 380 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285
  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<OwnPtr<CalculationNode>> Parser::parse_mod_function(Function const& function)
  3437. {
  3438. TokenStream stream { function.values() };
  3439. auto parameters = parse_a_comma_separated_list_of_component_values(stream);
  3440. if (parameters.size() != 2) {
  3441. dbgln_if(CSS_PARSER_DEBUG, "mod() must have exactly two parameters"sv);
  3442. return nullptr;
  3443. }
  3444. auto node_a = TRY(parse_a_calculation(parameters[0]));
  3445. auto node_b = TRY(parse_a_calculation(parameters[1]));
  3446. if (!node_a || !node_b) {
  3447. dbgln_if(CSS_PARSER_DEBUG, "mod() parameters must be valid calculations"sv);
  3448. return nullptr;
  3449. }
  3450. auto node_a_maybe_parameter_type = node_a->resolved_type();
  3451. if (!node_a_maybe_parameter_type.has_value()) {
  3452. dbgln_if(CSS_PARSER_DEBUG, "Failed to resolve type for mod() parameter 1"sv);
  3453. return nullptr;
  3454. }
  3455. auto node_b_maybe_parameter_type = node_b->resolved_type();
  3456. if (!node_b_maybe_parameter_type.has_value()) {
  3457. dbgln_if(CSS_PARSER_DEBUG, "Failed to resolve type for mod() parameter 2"sv);
  3458. return nullptr;
  3459. }
  3460. auto node_a_resolved_type = node_a_maybe_parameter_type.value();
  3461. auto node_b_resolved_type = node_b_maybe_parameter_type.value();
  3462. if (node_a_resolved_type != node_b_resolved_type) {
  3463. dbgln_if(CSS_PARSER_DEBUG, "mod() parameters must all be of the same type"sv);
  3464. return nullptr;
  3465. }
  3466. return TRY(ModCalculationNode::create(node_a.release_nonnull(), node_b.release_nonnull()));
  3467. }
  3468. ErrorOr<OwnPtr<CalculationNode>> Parser::parse_rem_function(Function const& function)
  3469. {
  3470. TokenStream stream { function.values() };
  3471. auto parameters = parse_a_comma_separated_list_of_component_values(stream);
  3472. if (parameters.size() != 2) {
  3473. dbgln_if(CSS_PARSER_DEBUG, "rem() must have exactly two parameters"sv);
  3474. return nullptr;
  3475. }
  3476. auto node_a = TRY(parse_a_calculation(parameters[0]));
  3477. auto node_b = TRY(parse_a_calculation(parameters[1]));
  3478. if (!node_a || !node_b) {
  3479. dbgln_if(CSS_PARSER_DEBUG, "rem() parameters must be valid calculations"sv);
  3480. return nullptr;
  3481. }
  3482. auto node_a_maybe_parameter_type = node_a->resolved_type();
  3483. if (!node_a_maybe_parameter_type.has_value()) {
  3484. dbgln_if(CSS_PARSER_DEBUG, "Failed to resolve type for rem() parameter 1"sv);
  3485. return nullptr;
  3486. }
  3487. auto node_b_maybe_parameter_type = node_b->resolved_type();
  3488. if (!node_b_maybe_parameter_type.has_value()) {
  3489. dbgln_if(CSS_PARSER_DEBUG, "Failed to resolve type for rem() parameter 2"sv);
  3490. return nullptr;
  3491. }
  3492. auto node_a_resolved_type = node_a_maybe_parameter_type.value();
  3493. auto node_b_resolved_type = node_b_maybe_parameter_type.value();
  3494. if (node_a_resolved_type != node_b_resolved_type) {
  3495. dbgln_if(CSS_PARSER_DEBUG, "rem() parameters must all be of the same type"sv);
  3496. return nullptr;
  3497. }
  3498. return TRY(RemCalculationNode::create(node_a.release_nonnull(), node_b.release_nonnull()));
  3499. }
  3500. ErrorOr<RefPtr<StyleValue>> Parser::parse_dynamic_value(ComponentValue const& component_value)
  3501. {
  3502. if (component_value.is_function()) {
  3503. auto const& function = component_value.function();
  3504. if (function.name().equals_ignoring_ascii_case("var"sv)) {
  3505. // Declarations using `var()` should already be parsed as an UnresolvedStyleValue before this point.
  3506. VERIFY_NOT_REACHED();
  3507. }
  3508. auto function_node = TRY(parse_a_calc_function_node(function));
  3509. if (!function_node)
  3510. return nullptr;
  3511. auto function_type = function_node->resolved_type();
  3512. if (!function_type.has_value())
  3513. return nullptr;
  3514. return CalculatedStyleValue::create(function_node.release_nonnull(), function_type.release_value());
  3515. }
  3516. return nullptr;
  3517. }
  3518. ErrorOr<OwnPtr<CalculationNode>> Parser::parse_a_calc_function_node(Function const& function)
  3519. {
  3520. if (function.name().equals_ignoring_ascii_case("calc"sv))
  3521. return TRY(parse_a_calculation(function.values()));
  3522. if (function.name().equals_ignoring_ascii_case("min"sv))
  3523. return TRY(parse_min_function(function));
  3524. if (function.name().equals_ignoring_ascii_case("max"sv))
  3525. return TRY(parse_max_function(function));
  3526. if (function.name().equals_ignoring_ascii_case("clamp"sv))
  3527. return TRY(parse_clamp_function(function));
  3528. if (function.name().equals_ignoring_ascii_case("abs"sv))
  3529. return TRY(parse_abs_function(function));
  3530. if (function.name().equals_ignoring_ascii_case("sign"sv))
  3531. return TRY(parse_sign_function(function));
  3532. if (function.name().equals_ignoring_ascii_case("sin"sv))
  3533. return TRY(parse_sin_function(function));
  3534. if (function.name().equals_ignoring_ascii_case("cos"sv))
  3535. return TRY(parse_cos_function(function));
  3536. if (function.name().equals_ignoring_ascii_case("tan"sv))
  3537. return TRY(parse_tan_function(function));
  3538. if (function.name().equals_ignoring_ascii_case("asin"sv))
  3539. return TRY(parse_asin_function(function));
  3540. if (function.name().equals_ignoring_ascii_case("acos"sv))
  3541. return TRY(parse_acos_function(function));
  3542. if (function.name().equals_ignoring_ascii_case("atan"sv))
  3543. return TRY(parse_atan_function(function));
  3544. if (function.name().equals_ignoring_ascii_case("atan2"sv))
  3545. return TRY(parse_atan2_function(function));
  3546. if (function.name().equals_ignoring_ascii_case("pow"sv))
  3547. return TRY(parse_pow_function(function));
  3548. if (function.name().equals_ignoring_ascii_case("sqrt"sv))
  3549. return TRY(parse_sqrt_function(function));
  3550. if (function.name().equals_ignoring_ascii_case("hypot"sv))
  3551. return TRY(parse_hypot_function(function));
  3552. if (function.name().equals_ignoring_ascii_case("log"sv))
  3553. return TRY(parse_log_function(function));
  3554. if (function.name().equals_ignoring_ascii_case("exp"sv))
  3555. return TRY(parse_exp_function(function));
  3556. if (function.name().equals_ignoring_ascii_case("round"sv))
  3557. return TRY(parse_round_function(function));
  3558. if (function.name().equals_ignoring_ascii_case("mod"sv))
  3559. return TRY(parse_mod_function(function));
  3560. if (function.name().equals_ignoring_ascii_case("rem"sv))
  3561. return TRY(parse_rem_function(function));
  3562. dbgln_if(CSS_PARSER_DEBUG, "We didn't implement `{}` function yet", function.name());
  3563. return nullptr;
  3564. }
  3565. Optional<Parser::Dimension> Parser::parse_dimension(ComponentValue const& component_value)
  3566. {
  3567. if (component_value.is(Token::Type::Dimension)) {
  3568. float numeric_value = component_value.token().dimension_value();
  3569. auto unit_string = component_value.token().dimension_unit();
  3570. if (auto length_type = Length::unit_from_name(unit_string); length_type.has_value())
  3571. return Length { numeric_value, length_type.release_value() };
  3572. if (auto angle_type = Angle::unit_from_name(unit_string); angle_type.has_value())
  3573. return Angle { numeric_value, angle_type.release_value() };
  3574. if (auto frequency_type = Frequency::unit_from_name(unit_string); frequency_type.has_value())
  3575. return Frequency { numeric_value, frequency_type.release_value() };
  3576. if (auto resolution_type = Resolution::unit_from_name(unit_string); resolution_type.has_value())
  3577. return Resolution { numeric_value, resolution_type.release_value() };
  3578. if (auto time_type = Time::unit_from_name(unit_string); time_type.has_value())
  3579. return Time { numeric_value, time_type.release_value() };
  3580. }
  3581. if (component_value.is(Token::Type::Percentage))
  3582. return Percentage { static_cast<float>(component_value.token().percentage()) };
  3583. if (component_value.is(Token::Type::Number)) {
  3584. float numeric_value = component_value.token().number_value();
  3585. if (numeric_value == 0)
  3586. return Length::make_px(0);
  3587. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  3588. // https://quirks.spec.whatwg.org/#quirky-length-value
  3589. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  3590. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  3591. // expression, and must not be supported in the supports() static method of the CSS interface."
  3592. return Length::make_px(numeric_value);
  3593. }
  3594. }
  3595. return {};
  3596. }
  3597. Optional<Length> Parser::parse_length(ComponentValue const& component_value)
  3598. {
  3599. auto dimension = parse_dimension(component_value);
  3600. if (!dimension.has_value())
  3601. return {};
  3602. if (dimension->is_length())
  3603. return dimension->length();
  3604. return {};
  3605. }
  3606. Optional<Ratio> Parser::parse_ratio(TokenStream<ComponentValue>& tokens)
  3607. {
  3608. auto transaction = tokens.begin_transaction();
  3609. tokens.skip_whitespace();
  3610. auto read_number_value = [this](ComponentValue const& component_value) -> Optional<float> {
  3611. if (component_value.is(Token::Type::Number)) {
  3612. return component_value.token().number_value();
  3613. } else if (component_value.is_function()) {
  3614. auto maybe_calc = parse_dynamic_value(component_value).release_value_but_fixme_should_propagate_errors();
  3615. if (!maybe_calc || !maybe_calc->is_calculated() || !maybe_calc->as_calculated().resolves_to_number())
  3616. return {};
  3617. if (auto resolved_number = maybe_calc->as_calculated().resolve_number(); resolved_number.has_value() && resolved_number.value() >= 0) {
  3618. return resolved_number.value();
  3619. }
  3620. }
  3621. return {};
  3622. };
  3623. // `<ratio> = <number [0,∞]> [ / <number [0,∞]> ]?`
  3624. auto maybe_numerator = read_number_value(tokens.next_token());
  3625. if (!maybe_numerator.has_value() || maybe_numerator.value() < 0)
  3626. return {};
  3627. auto numerator = maybe_numerator.value();
  3628. {
  3629. auto two_value_transaction = tokens.begin_transaction();
  3630. tokens.skip_whitespace();
  3631. auto solidus = tokens.next_token();
  3632. tokens.skip_whitespace();
  3633. auto maybe_denominator = read_number_value(tokens.next_token());
  3634. if (solidus.is_delim('/') && maybe_denominator.has_value() && maybe_denominator.value() >= 0) {
  3635. auto denominator = maybe_denominator.value();
  3636. // Two-value ratio
  3637. two_value_transaction.commit();
  3638. transaction.commit();
  3639. return Ratio { numerator, denominator };
  3640. }
  3641. }
  3642. // Single-value ratio
  3643. transaction.commit();
  3644. return Ratio { numerator };
  3645. }
  3646. // https://www.w3.org/TR/css-syntax-3/#urange-syntax
  3647. Optional<UnicodeRange> Parser::parse_unicode_range(TokenStream<ComponentValue>& tokens)
  3648. {
  3649. auto transaction = tokens.begin_transaction();
  3650. tokens.skip_whitespace();
  3651. // <urange> =
  3652. // u '+' <ident-token> '?'* |
  3653. // u <dimension-token> '?'* |
  3654. // u <number-token> '?'* |
  3655. // u <number-token> <dimension-token> |
  3656. // u <number-token> <number-token> |
  3657. // u '+' '?'+
  3658. // (All with no whitespace in between tokens.)
  3659. // NOTE: Parsing this is different from usual. We take these steps:
  3660. // 1. Match the grammar above against the tokens, concatenating them into a string using their original representation.
  3661. // 2. Then, parse that string according to the spec algorithm.
  3662. // Step 2 is performed by calling the other parse_unicode_range() overload.
  3663. auto is_ending_token = [](ComponentValue const& component_value) {
  3664. return component_value.is(Token::Type::EndOfFile)
  3665. || component_value.is(Token::Type::Comma)
  3666. || component_value.is(Token::Type::Semicolon)
  3667. || component_value.is(Token::Type::Whitespace);
  3668. };
  3669. auto create_unicode_range = [&](StringView text, auto& local_transaction) -> Optional<UnicodeRange> {
  3670. auto maybe_unicode_range = parse_unicode_range(text);
  3671. if (maybe_unicode_range.has_value()) {
  3672. local_transaction.commit();
  3673. transaction.commit();
  3674. }
  3675. return maybe_unicode_range;
  3676. };
  3677. // All options start with 'u'/'U'.
  3678. auto const& u = tokens.next_token();
  3679. if (!(u.is(Token::Type::Ident) && u.token().ident().equals_ignoring_ascii_case("u"sv))) {
  3680. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> does not start with 'u'");
  3681. return {};
  3682. }
  3683. auto const& second_token = tokens.next_token();
  3684. // u '+' <ident-token> '?'* |
  3685. // u '+' '?'+
  3686. if (second_token.is_delim('+')) {
  3687. auto local_transaction = tokens.begin_transaction();
  3688. StringBuilder string_builder;
  3689. string_builder.append(second_token.token().representation());
  3690. auto const& third_token = tokens.next_token();
  3691. if (third_token.is(Token::Type::Ident) || third_token.is_delim('?')) {
  3692. string_builder.append(third_token.token().representation());
  3693. while (tokens.peek_token().is_delim('?'))
  3694. string_builder.append(tokens.next_token().token().representation());
  3695. if (is_ending_token(tokens.peek_token()))
  3696. return create_unicode_range(string_builder.string_view(), local_transaction);
  3697. }
  3698. }
  3699. // u <dimension-token> '?'*
  3700. if (second_token.is(Token::Type::Dimension)) {
  3701. auto local_transaction = tokens.begin_transaction();
  3702. StringBuilder string_builder;
  3703. string_builder.append(second_token.token().representation());
  3704. while (tokens.peek_token().is_delim('?'))
  3705. string_builder.append(tokens.next_token().token().representation());
  3706. if (is_ending_token(tokens.peek_token()))
  3707. return create_unicode_range(string_builder.string_view(), local_transaction);
  3708. }
  3709. // u <number-token> '?'* |
  3710. // u <number-token> <dimension-token> |
  3711. // u <number-token> <number-token>
  3712. if (second_token.is(Token::Type::Number)) {
  3713. auto local_transaction = tokens.begin_transaction();
  3714. StringBuilder string_builder;
  3715. string_builder.append(second_token.token().representation());
  3716. if (is_ending_token(tokens.peek_token()))
  3717. return create_unicode_range(string_builder.string_view(), local_transaction);
  3718. auto const& third_token = tokens.next_token();
  3719. if (third_token.is_delim('?')) {
  3720. string_builder.append(third_token.token().representation());
  3721. while (tokens.peek_token().is_delim('?'))
  3722. string_builder.append(tokens.next_token().token().representation());
  3723. if (is_ending_token(tokens.peek_token()))
  3724. return create_unicode_range(string_builder.string_view(), local_transaction);
  3725. } else if (third_token.is(Token::Type::Dimension)) {
  3726. string_builder.append(third_token.token().representation());
  3727. if (is_ending_token(tokens.peek_token()))
  3728. return create_unicode_range(string_builder.string_view(), local_transaction);
  3729. } else if (third_token.is(Token::Type::Number)) {
  3730. string_builder.append(third_token.token().representation());
  3731. if (is_ending_token(tokens.peek_token()))
  3732. return create_unicode_range(string_builder.string_view(), local_transaction);
  3733. }
  3734. }
  3735. if constexpr (CSS_PARSER_DEBUG) {
  3736. dbgln("CSSParser: Tokens did not match <urange> grammar.");
  3737. tokens.dump_all_tokens();
  3738. }
  3739. return {};
  3740. }
  3741. Optional<UnicodeRange> Parser::parse_unicode_range(StringView text)
  3742. {
  3743. auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<UnicodeRange> {
  3744. // https://www.w3.org/TR/css-syntax-3/#maximum-allowed-code-point
  3745. constexpr u32 maximum_allowed_code_point = 0x10FFFF;
  3746. // To determine what codepoints the <urange> represents:
  3747. // 1. If end value is greater than the maximum allowed code point,
  3748. // the <urange> is invalid and a syntax error.
  3749. if (end_value > maximum_allowed_code_point) {
  3750. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: end_value ({}) > maximum ({})", end_value, maximum_allowed_code_point);
  3751. return {};
  3752. }
  3753. // 2. If start value is greater than end value, the <urange> is invalid and a syntax error.
  3754. if (start_value > end_value) {
  3755. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Invalid <urange>: start_value ({}) > end_value ({})", start_value, end_value);
  3756. return {};
  3757. }
  3758. // 3. Otherwise, the <urange> represents a contiguous range of codepoints from start value to end value, inclusive.
  3759. return UnicodeRange { start_value, end_value };
  3760. };
  3761. // 1. Skipping the first u token, concatenate the representations of all the tokens in the production together.
  3762. // Let this be text.
  3763. // NOTE: The concatenation is already done by the caller.
  3764. GenericLexer lexer { text };
  3765. // 2. If the first character of text is U+002B PLUS SIGN, consume it.
  3766. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  3767. if (lexer.next_is('+')) {
  3768. lexer.consume();
  3769. } else {
  3770. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Second character of <urange> was not '+'; got: '{}'", lexer.consume());
  3771. return {};
  3772. }
  3773. // 3. Consume as many hex digits from text as possible.
  3774. // then consume as many U+003F QUESTION MARK (?) code points as possible.
  3775. auto hex_digits = lexer.consume_while(is_ascii_hex_digit);
  3776. auto question_marks = lexer.consume_while([](auto it) { return it == '?'; });
  3777. // If zero code points were consumed, or more than six code points were consumed,
  3778. // this is an invalid <urange>, and this algorithm must exit.
  3779. size_t consumed_code_points = hex_digits.length() + question_marks.length();
  3780. if (consumed_code_points == 0 || consumed_code_points > 6) {
  3781. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value had {} digits/?s, expected between 1 and 6.", consumed_code_points);
  3782. return {};
  3783. }
  3784. StringView start_value_code_points { hex_digits.characters_without_null_termination(), consumed_code_points };
  3785. // If any U+003F QUESTION MARK (?) code points were consumed, then:
  3786. if (question_marks.length() > 0) {
  3787. // 1. If there are any code points left in text, this is an invalid <urange>,
  3788. // and this algorithm must exit.
  3789. if (lexer.tell_remaining() != 0) {
  3790. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  3791. return {};
  3792. }
  3793. // 2. Interpret the consumed code points as a hexadecimal number,
  3794. // with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
  3795. // This is the start value.
  3796. auto start_value_string = start_value_code_points.replace("?"sv, "0"sv, ReplaceMode::All);
  3797. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
  3798. if (!maybe_start_value.has_value()) {
  3799. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
  3800. return {};
  3801. }
  3802. u32 start_value = maybe_start_value.release_value();
  3803. // 3. Interpret the consumed code points as a hexadecimal number again,
  3804. // with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
  3805. // This is the end value.
  3806. auto end_value_string = start_value_code_points.replace("?"sv, "F"sv, ReplaceMode::All);
  3807. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
  3808. if (!maybe_end_value.has_value()) {
  3809. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");
  3810. return {};
  3811. }
  3812. u32 end_value = maybe_end_value.release_value();
  3813. // 4. Exit this algorithm.
  3814. return make_valid_unicode_range(start_value, end_value);
  3815. }
  3816. // Otherwise, interpret the consumed code points as a hexadecimal number. This is the start value.
  3817. auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_code_points);
  3818. if (!maybe_start_value.has_value()) {
  3819. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start value did not parse as hex number.");
  3820. return {};
  3821. }
  3822. u32 start_value = maybe_start_value.release_value();
  3823. // 4. If there are no code points left in text, The end value is the same as the start value.
  3824. // Exit this algorithm.
  3825. if (lexer.tell_remaining() == 0)
  3826. return make_valid_unicode_range(start_value, start_value);
  3827. // 5. If the next code point in text is U+002D HYPHEN-MINUS (-), consume it.
  3828. if (lexer.next_is('-')) {
  3829. lexer.consume();
  3830. }
  3831. // Otherwise, this is an invalid <urange>, and this algorithm must exit.
  3832. else {
  3833. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> start and end values not separated by '-'.");
  3834. return {};
  3835. }
  3836. // 6. Consume as many hex digits as possible from text.
  3837. auto end_hex_digits = lexer.consume_while(is_ascii_hex_digit);
  3838. // If zero hex digits were consumed, or more than 6 hex digits were consumed,
  3839. // this is an invalid <urange>, and this algorithm must exit.
  3840. if (end_hex_digits.length() == 0 || end_hex_digits.length() > 6) {
  3841. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value had {} digits, expected between 1 and 6.", end_hex_digits.length());
  3842. return {};
  3843. }
  3844. // If there are any code points left in text, this is an invalid <urange>, and this algorithm must exit.
  3845. if (lexer.tell_remaining() != 0) {
  3846. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> invalid; had {} code points left over.", lexer.tell_remaining());
  3847. return {};
  3848. }
  3849. // 7. Interpret the consumed code points as a hexadecimal number. This is the end value.
  3850. auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_hex_digits);
  3851. if (!maybe_end_value.has_value()) {
  3852. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> end value did not parse as hex number.");
  3853. return {};
  3854. }
  3855. u32 end_value = maybe_end_value.release_value();
  3856. return make_valid_unicode_range(start_value, end_value);
  3857. }
  3858. ErrorOr<RefPtr<StyleValue>> Parser::parse_dimension_value(ComponentValue const& component_value)
  3859. {
  3860. // Numbers with no units can be lengths, in two situations:
  3861. // 1) We're in quirks mode, and it's an integer.
  3862. // 2) It's a 0.
  3863. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  3864. 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)))
  3865. return nullptr;
  3866. auto dimension = parse_dimension(component_value);
  3867. if (!dimension.has_value())
  3868. return nullptr;
  3869. if (dimension->is_angle())
  3870. return AngleStyleValue::create(dimension->angle());
  3871. if (dimension->is_frequency())
  3872. return FrequencyStyleValue::create(dimension->frequency());
  3873. if (dimension->is_length())
  3874. return LengthStyleValue::create(dimension->length());
  3875. if (dimension->is_percentage())
  3876. return PercentageStyleValue::create(dimension->percentage());
  3877. if (dimension->is_resolution())
  3878. return ResolutionStyleValue::create(dimension->resolution());
  3879. if (dimension->is_time())
  3880. return TimeStyleValue::create(dimension->time());
  3881. VERIFY_NOT_REACHED();
  3882. }
  3883. ErrorOr<RefPtr<StyleValue>> Parser::parse_integer_value(TokenStream<ComponentValue>& tokens)
  3884. {
  3885. auto peek_token = tokens.peek_token();
  3886. if (peek_token.is(Token::Type::Number) && peek_token.token().number().is_integer()) {
  3887. (void)tokens.next_token();
  3888. return IntegerStyleValue::create(peek_token.token().number().integer_value());
  3889. }
  3890. return nullptr;
  3891. }
  3892. ErrorOr<RefPtr<StyleValue>> Parser::parse_number_value(TokenStream<ComponentValue>& tokens)
  3893. {
  3894. auto peek_token = tokens.peek_token();
  3895. if (peek_token.is(Token::Type::Number)) {
  3896. (void)tokens.next_token();
  3897. return NumberStyleValue::create(peek_token.token().number().value());
  3898. }
  3899. return nullptr;
  3900. }
  3901. ErrorOr<RefPtr<StyleValue>> Parser::parse_identifier_value(ComponentValue const& component_value)
  3902. {
  3903. if (component_value.is(Token::Type::Ident)) {
  3904. auto value_id = value_id_from_string(component_value.token().ident());
  3905. if (value_id.has_value())
  3906. return IdentifierStyleValue::create(value_id.value());
  3907. }
  3908. return nullptr;
  3909. }
  3910. Optional<Color> Parser::parse_rgb_or_hsl_color(StringView function_name, Vector<ComponentValue> const& component_values)
  3911. {
  3912. Token params[4];
  3913. bool legacy_syntax = false;
  3914. auto tokens = TokenStream { component_values };
  3915. tokens.skip_whitespace();
  3916. auto const& component1 = tokens.next_token();
  3917. if (!component1.is(Token::Type::Number)
  3918. && !component1.is(Token::Type::Percentage)
  3919. && !component1.is(Token::Type::Dimension))
  3920. return {};
  3921. params[0] = component1.token();
  3922. tokens.skip_whitespace();
  3923. if (tokens.peek_token().is(Token::Type::Comma)) {
  3924. legacy_syntax = true;
  3925. tokens.next_token();
  3926. }
  3927. tokens.skip_whitespace();
  3928. auto const& component2 = tokens.next_token();
  3929. if (!component2.is(Token::Type::Number) && !component2.is(Token::Type::Percentage))
  3930. return {};
  3931. params[1] = component2.token();
  3932. tokens.skip_whitespace();
  3933. if (legacy_syntax && !tokens.next_token().is(Token::Type::Comma))
  3934. return {};
  3935. tokens.skip_whitespace();
  3936. auto const& component3 = tokens.next_token();
  3937. if (!component3.is(Token::Type::Number) && !component3.is(Token::Type::Percentage))
  3938. return {};
  3939. params[2] = component3.token();
  3940. tokens.skip_whitespace();
  3941. auto const& alpha_separator = tokens.peek_token();
  3942. bool has_comma = alpha_separator.is(Token::Type::Comma);
  3943. bool has_slash = alpha_separator.is_delim('/');
  3944. if (legacy_syntax ? has_comma : has_slash) {
  3945. tokens.next_token();
  3946. tokens.skip_whitespace();
  3947. auto const& component4 = tokens.next_token();
  3948. if (!component4.is(Token::Type::Number) && !component4.is(Token::Type::Percentage))
  3949. return {};
  3950. params[3] = component4.token();
  3951. }
  3952. tokens.skip_whitespace();
  3953. if (tokens.has_next_token())
  3954. return {};
  3955. if (function_name.equals_ignoring_ascii_case("rgb"sv)
  3956. || function_name.equals_ignoring_ascii_case("rgba"sv)) {
  3957. // https://www.w3.org/TR/css-color-4/#rgb-functions
  3958. u8 a_val = 255;
  3959. if (params[3].is(Token::Type::Number))
  3960. a_val = clamp(lroundf(params[3].number_value() * 255.0f), 0, 255);
  3961. else if (params[3].is(Token::Type::Percentage))
  3962. a_val = clamp(lroundf(params[3].percentage() * 2.55f), 0, 255);
  3963. if (params[0].is(Token::Type::Number)
  3964. && params[1].is(Token::Type::Number)
  3965. && params[2].is(Token::Type::Number)) {
  3966. u8 r_val = clamp(llroundf(params[0].number_value()), 0, 255);
  3967. u8 g_val = clamp(llroundf(params[1].number_value()), 0, 255);
  3968. u8 b_val = clamp(llroundf(params[2].number_value()), 0, 255);
  3969. return Color(r_val, g_val, b_val, a_val);
  3970. }
  3971. if (params[0].is(Token::Type::Percentage)
  3972. && params[1].is(Token::Type::Percentage)
  3973. && params[2].is(Token::Type::Percentage)) {
  3974. u8 r_val = lroundf(clamp(params[0].percentage() * 2.55f, 0, 255));
  3975. u8 g_val = lroundf(clamp(params[1].percentage() * 2.55f, 0, 255));
  3976. u8 b_val = lroundf(clamp(params[2].percentage() * 2.55f, 0, 255));
  3977. return Color(r_val, g_val, b_val, a_val);
  3978. }
  3979. } else if (function_name.equals_ignoring_ascii_case("hsl"sv)
  3980. || function_name.equals_ignoring_ascii_case("hsla"sv)) {
  3981. // https://www.w3.org/TR/css-color-4/#the-hsl-notation
  3982. float a_val = 1.0f;
  3983. if (params[3].is(Token::Type::Number))
  3984. a_val = params[3].number_value();
  3985. else if (params[3].is(Token::Type::Percentage))
  3986. a_val = params[3].percentage() / 100.0f;
  3987. if (params[0].is(Token::Type::Dimension)
  3988. && params[1].is(Token::Type::Percentage)
  3989. && params[2].is(Token::Type::Percentage)) {
  3990. float numeric_value = params[0].dimension_value();
  3991. auto unit_string = params[0].dimension_unit();
  3992. auto angle_type = Angle::unit_from_name(unit_string);
  3993. if (!angle_type.has_value())
  3994. return {};
  3995. auto angle = Angle { numeric_value, angle_type.release_value() };
  3996. float h_val = fmodf(angle.to_degrees(), 360.0f);
  3997. float s_val = params[1].percentage() / 100.0f;
  3998. float l_val = params[2].percentage() / 100.0f;
  3999. return Color::from_hsla(h_val, s_val, l_val, a_val);
  4000. }
  4001. if (params[0].is(Token::Type::Number)
  4002. && params[1].is(Token::Type::Percentage)
  4003. && params[2].is(Token::Type::Percentage)) {
  4004. float h_val = fmodf(params[0].number_value(), 360.0f);
  4005. float s_val = params[1].percentage() / 100.0f;
  4006. float l_val = params[2].percentage() / 100.0f;
  4007. return Color::from_hsla(h_val, s_val, l_val, a_val);
  4008. }
  4009. }
  4010. return {};
  4011. }
  4012. // https://www.w3.org/TR/CSS2/visufx.html#value-def-shape
  4013. ErrorOr<RefPtr<StyleValue>> Parser::parse_rect_value(ComponentValue const& component_value)
  4014. {
  4015. if (!component_value.is_function())
  4016. return nullptr;
  4017. auto const& function = component_value.function();
  4018. if (!function.name().equals_ignoring_ascii_case("rect"sv))
  4019. return nullptr;
  4020. Vector<Length, 4> params;
  4021. auto tokens = TokenStream { function.values() };
  4022. enum class CommaRequirement {
  4023. Unknown,
  4024. RequiresCommas,
  4025. RequiresNoCommas
  4026. };
  4027. enum class Side {
  4028. Top = 0,
  4029. Right = 1,
  4030. Bottom = 2,
  4031. Left = 3
  4032. };
  4033. auto comma_requirement = CommaRequirement::Unknown;
  4034. // In CSS 2.1, the only valid <shape> value is: rect(<top>, <right>, <bottom>, <left>) where
  4035. // <top> and <bottom> specify offsets from the top border edge of the box, and <right>, and
  4036. // <left> specify offsets from the left border edge of the box.
  4037. for (size_t side = 0; side < 4; side++) {
  4038. tokens.skip_whitespace();
  4039. // <top>, <right>, <bottom>, and <left> may either have a <length> value or 'auto'.
  4040. // Negative lengths are permitted.
  4041. auto current_token = tokens.next_token().token();
  4042. if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto"sv)) {
  4043. params.append(Length::make_auto());
  4044. } else {
  4045. auto maybe_length = parse_length(current_token);
  4046. if (!maybe_length.has_value())
  4047. return nullptr;
  4048. params.append(maybe_length.value());
  4049. }
  4050. tokens.skip_whitespace();
  4051. // The last side, should be no more tokens following it.
  4052. if (static_cast<Side>(side) == Side::Left) {
  4053. if (tokens.has_next_token())
  4054. return nullptr;
  4055. break;
  4056. }
  4057. bool next_is_comma = tokens.peek_token().is(Token::Type::Comma);
  4058. // Authors should separate offset values with commas. User agents must support separation
  4059. // with commas, but may also support separation without commas (but not a combination),
  4060. // because a previous revision of this specification was ambiguous in this respect.
  4061. if (comma_requirement == CommaRequirement::Unknown)
  4062. comma_requirement = next_is_comma ? CommaRequirement::RequiresCommas : CommaRequirement::RequiresNoCommas;
  4063. if (comma_requirement == CommaRequirement::RequiresCommas) {
  4064. if (next_is_comma)
  4065. tokens.next_token();
  4066. else
  4067. return nullptr;
  4068. } else if (comma_requirement == CommaRequirement::RequiresNoCommas) {
  4069. if (next_is_comma)
  4070. return nullptr;
  4071. } else {
  4072. VERIFY_NOT_REACHED();
  4073. }
  4074. }
  4075. return RectStyleValue::create(EdgeRect { params[0], params[1], params[2], params[3] });
  4076. }
  4077. Optional<Color> Parser::parse_color(ComponentValue const& component_value)
  4078. {
  4079. // https://www.w3.org/TR/css-color-4/
  4080. if (component_value.is(Token::Type::Ident)) {
  4081. auto ident = component_value.token().ident();
  4082. auto color = Color::from_string(ident);
  4083. if (color.has_value())
  4084. return color;
  4085. } else if (component_value.is(Token::Type::Hash)) {
  4086. auto color = Color::from_string(DeprecatedString::formatted("#{}", component_value.token().hash_value()));
  4087. if (color.has_value())
  4088. return color;
  4089. return {};
  4090. } else if (component_value.is_function()) {
  4091. auto const& function = component_value.function();
  4092. auto const& values = function.values();
  4093. return parse_rgb_or_hsl_color(function.name(), values);
  4094. }
  4095. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  4096. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  4097. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  4098. // aborting on the first step that returns a value:
  4099. // 1. Let cv be the component value.
  4100. auto const& cv = component_value;
  4101. DeprecatedString serialization;
  4102. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  4103. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  4104. // 1. If cv’s type flag is not "integer", return an error.
  4105. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  4106. if (!cv.token().number().is_integer())
  4107. return {};
  4108. // 2. If cv’s value is less than zero, return an error.
  4109. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  4110. if (value < 0)
  4111. return {};
  4112. // 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.
  4113. StringBuilder serialization_builder;
  4114. serialization_builder.appendff("{}", value);
  4115. // 4. If cv is a <dimension-token>, append the unit to serialization.
  4116. if (cv.is(Token::Type::Dimension))
  4117. serialization_builder.append(cv.token().dimension_unit());
  4118. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  4119. serialization = serialization_builder.to_deprecated_string();
  4120. if (serialization_builder.length() < 6) {
  4121. StringBuilder builder;
  4122. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  4123. builder.append('0');
  4124. builder.append(serialization_builder.string_view());
  4125. serialization = builder.to_deprecated_string();
  4126. }
  4127. }
  4128. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  4129. else {
  4130. if (!cv.is(Token::Type::Ident))
  4131. return {};
  4132. serialization = cv.token().ident();
  4133. }
  4134. // 4. If serialization does not consist of three or six characters, return an error.
  4135. if (serialization.length() != 3 && serialization.length() != 6)
  4136. return {};
  4137. // 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.
  4138. for (auto c : serialization) {
  4139. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  4140. return {};
  4141. }
  4142. // 6. Return the concatenation of "#" (U+0023) and serialization.
  4143. DeprecatedString concatenation = DeprecatedString::formatted("#{}", serialization);
  4144. return Color::from_string(concatenation);
  4145. }
  4146. return {};
  4147. }
  4148. ErrorOr<RefPtr<StyleValue>> Parser::parse_color_value(ComponentValue const& component_value)
  4149. {
  4150. auto color = parse_color(component_value);
  4151. if (color.has_value())
  4152. return ColorStyleValue::create(color.value());
  4153. if (component_value.is(Token::Type::Ident)) {
  4154. if (auto ident = value_id_from_string(component_value.token().ident()); ident.has_value()) {
  4155. switch (ident.value()) {
  4156. case ValueID::Currentcolor:
  4157. case ValueID::LibwebLink:
  4158. case ValueID::LibwebPaletteActiveLink:
  4159. case ValueID::LibwebPaletteActiveWindowBorder1:
  4160. case ValueID::LibwebPaletteActiveWindowBorder2:
  4161. case ValueID::LibwebPaletteActiveWindowTitle:
  4162. case ValueID::LibwebPaletteBase:
  4163. case ValueID::LibwebPaletteBaseText:
  4164. case ValueID::LibwebPaletteButton:
  4165. case ValueID::LibwebPaletteButtonText:
  4166. case ValueID::LibwebPaletteDesktopBackground:
  4167. case ValueID::LibwebPaletteFocusOutline:
  4168. case ValueID::LibwebPaletteHighlightWindowBorder1:
  4169. case ValueID::LibwebPaletteHighlightWindowBorder2:
  4170. case ValueID::LibwebPaletteHighlightWindowTitle:
  4171. case ValueID::LibwebPaletteHoverHighlight:
  4172. case ValueID::LibwebPaletteInactiveSelection:
  4173. case ValueID::LibwebPaletteInactiveSelectionText:
  4174. case ValueID::LibwebPaletteInactiveWindowBorder1:
  4175. case ValueID::LibwebPaletteInactiveWindowBorder2:
  4176. case ValueID::LibwebPaletteInactiveWindowTitle:
  4177. case ValueID::LibwebPaletteLink:
  4178. case ValueID::LibwebPaletteMenuBase:
  4179. case ValueID::LibwebPaletteMenuBaseText:
  4180. case ValueID::LibwebPaletteMenuSelection:
  4181. case ValueID::LibwebPaletteMenuSelectionText:
  4182. case ValueID::LibwebPaletteMenuStripe:
  4183. case ValueID::LibwebPaletteMovingWindowBorder1:
  4184. case ValueID::LibwebPaletteMovingWindowBorder2:
  4185. case ValueID::LibwebPaletteMovingWindowTitle:
  4186. case ValueID::LibwebPaletteRubberBandBorder:
  4187. case ValueID::LibwebPaletteRubberBandFill:
  4188. case ValueID::LibwebPaletteRuler:
  4189. case ValueID::LibwebPaletteRulerActiveText:
  4190. case ValueID::LibwebPaletteRulerBorder:
  4191. case ValueID::LibwebPaletteRulerInactiveText:
  4192. case ValueID::LibwebPaletteSelection:
  4193. case ValueID::LibwebPaletteSelectionText:
  4194. case ValueID::LibwebPaletteSyntaxComment:
  4195. case ValueID::LibwebPaletteSyntaxControlKeyword:
  4196. case ValueID::LibwebPaletteSyntaxIdentifier:
  4197. case ValueID::LibwebPaletteSyntaxKeyword:
  4198. case ValueID::LibwebPaletteSyntaxNumber:
  4199. case ValueID::LibwebPaletteSyntaxOperator:
  4200. case ValueID::LibwebPaletteSyntaxPreprocessorStatement:
  4201. case ValueID::LibwebPaletteSyntaxPreprocessorValue:
  4202. case ValueID::LibwebPaletteSyntaxPunctuation:
  4203. case ValueID::LibwebPaletteSyntaxString:
  4204. case ValueID::LibwebPaletteSyntaxType:
  4205. case ValueID::LibwebPaletteTextCursor:
  4206. case ValueID::LibwebPaletteThreedHighlight:
  4207. case ValueID::LibwebPaletteThreedShadow1:
  4208. case ValueID::LibwebPaletteThreedShadow2:
  4209. case ValueID::LibwebPaletteVisitedLink:
  4210. case ValueID::LibwebPaletteWindow:
  4211. case ValueID::LibwebPaletteWindowText:
  4212. return IdentifierStyleValue::create(ident.value());
  4213. default:
  4214. break;
  4215. }
  4216. }
  4217. }
  4218. return nullptr;
  4219. }
  4220. ErrorOr<RefPtr<StyleValue>> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  4221. {
  4222. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  4223. return RatioStyleValue::create(ratio.release_value());
  4224. return nullptr;
  4225. }
  4226. ErrorOr<RefPtr<StyleValue>> Parser::parse_string_value(ComponentValue const& component_value)
  4227. {
  4228. if (component_value.is(Token::Type::String))
  4229. return StringStyleValue::create(TRY(String::from_utf8(component_value.token().string())));
  4230. return nullptr;
  4231. }
  4232. ErrorOr<RefPtr<StyleValue>> Parser::parse_image_value(ComponentValue const& component_value)
  4233. {
  4234. auto url = parse_url_function(component_value, AllowedDataUrlType::Image);
  4235. if (url.has_value())
  4236. return ImageStyleValue::create(url.value());
  4237. auto linear_gradient = TRY(parse_linear_gradient_function(component_value));
  4238. if (linear_gradient)
  4239. return linear_gradient;
  4240. auto conic_gradient = TRY(parse_conic_gradient_function(component_value));
  4241. if (conic_gradient)
  4242. return conic_gradient;
  4243. return parse_radial_gradient_function(component_value);
  4244. }
  4245. // https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint
  4246. ErrorOr<RefPtr<StyleValue>> Parser::parse_paint_value(TokenStream<ComponentValue>& tokens)
  4247. {
  4248. // `<paint> = none | <color> | <url> [none | <color>]? | context-fill | context-stroke`
  4249. if (auto color = TRY(parse_color_value(tokens.peek_token()))) {
  4250. (void)tokens.next_token();
  4251. return color;
  4252. }
  4253. if (auto url = TRY(parse_url_value(tokens.peek_token(), AllowedDataUrlType::Image))) {
  4254. // FIXME: Accept `[none | <color>]?`
  4255. (void)tokens.next_token();
  4256. return url;
  4257. }
  4258. // NOTE: <color> also accepts identifiers, so we do this identifier check last.
  4259. if (tokens.peek_token().is(Token::Type::Ident)) {
  4260. auto maybe_ident = value_id_from_string(tokens.peek_token().token().ident());
  4261. if (maybe_ident.has_value()) {
  4262. // FIXME: Accept `context-fill` and `context-stroke`
  4263. switch (*maybe_ident) {
  4264. case ValueID::None:
  4265. (void)tokens.next_token();
  4266. return IdentifierStyleValue::create(*maybe_ident);
  4267. default:
  4268. return nullptr;
  4269. }
  4270. }
  4271. }
  4272. return nullptr;
  4273. }
  4274. template<typename ParseFunction>
  4275. ErrorOr<RefPtr<StyleValue>> Parser::parse_comma_separated_value_list(Vector<ComponentValue> const& component_values, ParseFunction parse_one_value)
  4276. {
  4277. auto tokens = TokenStream { component_values };
  4278. auto first = TRY(parse_one_value(tokens));
  4279. if (!first || !tokens.has_next_token())
  4280. return first;
  4281. StyleValueVector values;
  4282. values.append(first.release_nonnull());
  4283. while (tokens.has_next_token()) {
  4284. if (!tokens.next_token().is(Token::Type::Comma))
  4285. return nullptr;
  4286. if (auto maybe_value = TRY(parse_one_value(tokens))) {
  4287. values.append(maybe_value.release_nonnull());
  4288. continue;
  4289. }
  4290. return nullptr;
  4291. }
  4292. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  4293. }
  4294. ErrorOr<RefPtr<StyleValue>> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, Vector<ComponentValue> const& component_values)
  4295. {
  4296. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> ErrorOr<RefPtr<StyleValue>> {
  4297. if (auto value = TRY(parse_css_value_for_property(property_id, tokens)))
  4298. return value;
  4299. tokens.reconsume_current_input_token();
  4300. return nullptr;
  4301. });
  4302. }
  4303. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  4304. {
  4305. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  4306. }
  4307. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  4308. ErrorOr<RefPtr<StyleValue>> Parser::parse_aspect_ratio_value(Vector<ComponentValue> const& component_values)
  4309. {
  4310. // `auto || <ratio>`
  4311. RefPtr<StyleValue> auto_value;
  4312. RefPtr<StyleValue> ratio_value;
  4313. auto tokens = TokenStream { component_values };
  4314. while (tokens.has_next_token()) {
  4315. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::AspectRatio, tokens));
  4316. if (!maybe_value)
  4317. return nullptr;
  4318. if (maybe_value->is_ratio()) {
  4319. if (ratio_value)
  4320. return nullptr;
  4321. ratio_value = maybe_value.release_nonnull();
  4322. continue;
  4323. }
  4324. if (maybe_value->is_identifier() && maybe_value->as_identifier().id() == ValueID::Auto) {
  4325. if (auto_value)
  4326. return nullptr;
  4327. auto_value = maybe_value.release_nonnull();
  4328. continue;
  4329. }
  4330. return nullptr;
  4331. }
  4332. if (auto_value && ratio_value) {
  4333. return TRY(StyleValueList::create(
  4334. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  4335. StyleValueList::Separator::Space));
  4336. }
  4337. if (ratio_value)
  4338. return ratio_value.release_nonnull();
  4339. if (auto_value)
  4340. return auto_value.release_nonnull();
  4341. return nullptr;
  4342. }
  4343. ErrorOr<RefPtr<StyleValue>> Parser::parse_background_value(Vector<ComponentValue> const& component_values)
  4344. {
  4345. StyleValueVector background_images;
  4346. StyleValueVector background_positions;
  4347. StyleValueVector background_sizes;
  4348. StyleValueVector background_repeats;
  4349. StyleValueVector background_attachments;
  4350. StyleValueVector background_clips;
  4351. StyleValueVector background_origins;
  4352. RefPtr<StyleValue> background_color;
  4353. auto initial_background_image = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundImage));
  4354. auto initial_background_position = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundPosition));
  4355. auto initial_background_size = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundSize));
  4356. auto initial_background_repeat = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat));
  4357. auto initial_background_attachment = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment));
  4358. auto initial_background_clip = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundClip));
  4359. auto initial_background_origin = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin));
  4360. auto initial_background_color = TRY(property_initial_value(m_context.realm(), PropertyID::BackgroundColor));
  4361. // Per-layer values
  4362. RefPtr<StyleValue> background_image;
  4363. RefPtr<StyleValue> background_position;
  4364. RefPtr<StyleValue> background_size;
  4365. RefPtr<StyleValue> background_repeat;
  4366. RefPtr<StyleValue> background_attachment;
  4367. RefPtr<StyleValue> background_clip;
  4368. RefPtr<StyleValue> background_origin;
  4369. bool has_multiple_layers = false;
  4370. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  4371. Vector<PropertyID> remaining_layer_properties {
  4372. PropertyID::BackgroundAttachment,
  4373. PropertyID::BackgroundClip,
  4374. PropertyID::BackgroundColor,
  4375. PropertyID::BackgroundImage,
  4376. PropertyID::BackgroundOrigin,
  4377. PropertyID::BackgroundPosition,
  4378. PropertyID::BackgroundRepeat,
  4379. };
  4380. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  4381. if (allow_background_color) {
  4382. if (background_color)
  4383. return true;
  4384. } else {
  4385. if (background_color)
  4386. return false;
  4387. }
  4388. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  4389. };
  4390. auto complete_background_layer = [&]() -> ErrorOr<void> {
  4391. TRY(background_images.try_append(background_image ? background_image.release_nonnull() : initial_background_image));
  4392. TRY(background_positions.try_append(background_position ? background_position.release_nonnull() : initial_background_position));
  4393. TRY(background_sizes.try_append(background_size ? background_size.release_nonnull() : initial_background_size));
  4394. TRY(background_repeats.try_append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat));
  4395. TRY(background_attachments.try_append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment));
  4396. if (!background_origin && !background_clip) {
  4397. background_origin = initial_background_origin;
  4398. background_clip = initial_background_clip;
  4399. } else if (!background_clip) {
  4400. background_clip = background_origin;
  4401. }
  4402. TRY(background_origins.try_append(background_origin.release_nonnull()));
  4403. TRY(background_clips.try_append(background_clip.release_nonnull()));
  4404. background_image = nullptr;
  4405. background_position = nullptr;
  4406. background_size = nullptr;
  4407. background_repeat = nullptr;
  4408. background_attachment = nullptr;
  4409. background_clip = nullptr;
  4410. background_origin = nullptr;
  4411. remaining_layer_properties.clear_with_capacity();
  4412. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  4413. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  4414. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  4415. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  4416. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  4417. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  4418. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  4419. return {};
  4420. };
  4421. auto tokens = TokenStream { component_values };
  4422. while (tokens.has_next_token()) {
  4423. if (tokens.peek_token().is(Token::Type::Comma)) {
  4424. has_multiple_layers = true;
  4425. if (!background_layer_is_valid(false))
  4426. return nullptr;
  4427. TRY(complete_background_layer());
  4428. (void)tokens.next_token();
  4429. continue;
  4430. }
  4431. auto value_and_property = TRY(parse_css_value_for_properties(remaining_layer_properties, tokens));
  4432. if (!value_and_property.style_value)
  4433. return nullptr;
  4434. auto& value = value_and_property.style_value;
  4435. remove_property(remaining_layer_properties, value_and_property.property);
  4436. switch (value_and_property.property) {
  4437. case PropertyID::BackgroundAttachment:
  4438. VERIFY(!background_attachment);
  4439. background_attachment = value.release_nonnull();
  4440. continue;
  4441. case PropertyID::BackgroundColor:
  4442. VERIFY(!background_color);
  4443. background_color = value.release_nonnull();
  4444. continue;
  4445. case PropertyID::BackgroundImage:
  4446. VERIFY(!background_image);
  4447. background_image = value.release_nonnull();
  4448. continue;
  4449. case PropertyID::BackgroundClip:
  4450. case PropertyID::BackgroundOrigin: {
  4451. // background-origin and background-clip accept the same values. From the spec:
  4452. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  4453. // If two values are present, then the first sets background-origin and the second background-clip."
  4454. // - https://www.w3.org/TR/css-backgrounds-3/#background
  4455. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  4456. // If we only get one, we copy the value before creating the BackgroundStyleValue.
  4457. if (!background_origin) {
  4458. background_origin = value.release_nonnull();
  4459. } else if (!background_clip) {
  4460. background_clip = value.release_nonnull();
  4461. } else {
  4462. VERIFY_NOT_REACHED();
  4463. }
  4464. continue;
  4465. }
  4466. case PropertyID::BackgroundPosition: {
  4467. VERIFY(!background_position);
  4468. tokens.reconsume_current_input_token();
  4469. if (auto maybe_background_position = TRY(parse_single_background_position_value(tokens))) {
  4470. background_position = maybe_background_position.release_nonnull();
  4471. // Attempt to parse `/ <background-size>`
  4472. auto transaction = tokens.begin_transaction();
  4473. auto& maybe_slash = tokens.next_token();
  4474. if (maybe_slash.is_delim('/')) {
  4475. if (auto maybe_background_size = TRY(parse_single_background_size_value(tokens))) {
  4476. transaction.commit();
  4477. background_size = maybe_background_size.release_nonnull();
  4478. continue;
  4479. }
  4480. return nullptr;
  4481. }
  4482. continue;
  4483. }
  4484. return nullptr;
  4485. }
  4486. case PropertyID::BackgroundRepeat: {
  4487. VERIFY(!background_repeat);
  4488. tokens.reconsume_current_input_token();
  4489. if (auto maybe_repeat = TRY(parse_single_background_repeat_value(tokens))) {
  4490. background_repeat = maybe_repeat.release_nonnull();
  4491. continue;
  4492. }
  4493. return nullptr;
  4494. }
  4495. default:
  4496. VERIFY_NOT_REACHED();
  4497. }
  4498. return nullptr;
  4499. }
  4500. if (!background_layer_is_valid(true))
  4501. return nullptr;
  4502. // We only need to create StyleValueLists if there are multiple layers.
  4503. // Otherwise, we can pass the single StyleValues directly.
  4504. if (has_multiple_layers) {
  4505. TRY(complete_background_layer());
  4506. if (!background_color)
  4507. background_color = initial_background_color;
  4508. return BackgroundStyleValue::create(
  4509. background_color.release_nonnull(),
  4510. TRY(StyleValueList::create(move(background_images), StyleValueList::Separator::Comma)),
  4511. TRY(StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma)),
  4512. TRY(StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma)),
  4513. TRY(StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma)),
  4514. TRY(StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma)),
  4515. TRY(StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma)),
  4516. TRY(StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma)));
  4517. }
  4518. if (!background_color)
  4519. background_color = initial_background_color;
  4520. if (!background_image)
  4521. background_image = initial_background_image;
  4522. if (!background_position)
  4523. background_position = initial_background_position;
  4524. if (!background_size)
  4525. background_size = initial_background_size;
  4526. if (!background_repeat)
  4527. background_repeat = initial_background_repeat;
  4528. if (!background_attachment)
  4529. background_attachment = initial_background_attachment;
  4530. if (!background_origin && !background_clip) {
  4531. background_origin = initial_background_origin;
  4532. background_clip = initial_background_clip;
  4533. } else if (!background_clip) {
  4534. background_clip = background_origin;
  4535. }
  4536. return BackgroundStyleValue::create(
  4537. background_color.release_nonnull(),
  4538. background_image.release_nonnull(),
  4539. background_position.release_nonnull(),
  4540. background_size.release_nonnull(),
  4541. background_repeat.release_nonnull(),
  4542. background_attachment.release_nonnull(),
  4543. background_origin.release_nonnull(),
  4544. background_clip.release_nonnull());
  4545. }
  4546. static Optional<PositionEdge> identifier_to_edge(ValueID identifier)
  4547. {
  4548. switch (identifier) {
  4549. case ValueID::Top:
  4550. return PositionEdge::Top;
  4551. case ValueID::Bottom:
  4552. return PositionEdge::Bottom;
  4553. case ValueID::Left:
  4554. return PositionEdge::Left;
  4555. case ValueID::Right:
  4556. return PositionEdge::Right;
  4557. default:
  4558. return {};
  4559. }
  4560. };
  4561. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  4562. {
  4563. if (value->is_percentage())
  4564. return LengthPercentage { value->as_percentage().percentage() };
  4565. if (value->is_length())
  4566. return LengthPercentage { value->as_length().length() };
  4567. if (value->is_calculated())
  4568. return LengthPercentage { value->as_calculated() };
  4569. return {};
  4570. };
  4571. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_position_value(TokenStream<ComponentValue>& tokens)
  4572. {
  4573. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  4574. // "Note: The background-position property also accepts a three-value syntax.
  4575. // This has been disallowed generically because it creates parsing ambiguities
  4576. // when combined with other length or percentage components in a property value."
  4577. // - https://www.w3.org/TR/css-values-4/#typedef-position
  4578. // So, we'll need a separate function to parse <position> later.
  4579. auto transaction = tokens.begin_transaction();
  4580. auto is_horizontal = [](ValueID identifier) -> bool {
  4581. switch (identifier) {
  4582. case ValueID::Left:
  4583. case ValueID::Right:
  4584. return true;
  4585. default:
  4586. return false;
  4587. }
  4588. };
  4589. auto is_vertical = [](ValueID identifier) -> bool {
  4590. switch (identifier) {
  4591. case ValueID::Top:
  4592. case ValueID::Bottom:
  4593. return true;
  4594. default:
  4595. return false;
  4596. }
  4597. };
  4598. struct EdgeOffset {
  4599. PositionEdge edge;
  4600. LengthPercentage offset;
  4601. bool edge_provided;
  4602. bool offset_provided;
  4603. };
  4604. Optional<EdgeOffset> horizontal;
  4605. Optional<EdgeOffset> vertical;
  4606. bool found_center = false;
  4607. auto const center_offset = Percentage { 50 };
  4608. auto const zero_offset = Length::make_px(0);
  4609. while (tokens.has_next_token()) {
  4610. // Check if we're done
  4611. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  4612. if (seen_items == 2)
  4613. break;
  4614. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::BackgroundPosition, tokens));
  4615. if (!maybe_value)
  4616. break;
  4617. auto value = maybe_value.release_nonnull();
  4618. if (auto offset = style_value_to_length_percentage(value); offset.has_value()) {
  4619. if (!horizontal.has_value()) {
  4620. horizontal = EdgeOffset { PositionEdge::Left, *offset, false, true };
  4621. } else if (!vertical.has_value()) {
  4622. vertical = EdgeOffset { PositionEdge::Top, *offset, false, true };
  4623. } else {
  4624. return nullptr;
  4625. }
  4626. continue;
  4627. }
  4628. auto try_parse_offset = [&](bool& offset_provided) -> ErrorOr<LengthPercentage> {
  4629. auto transaction = tokens.begin_transaction();
  4630. if (tokens.has_next_token()) {
  4631. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::BackgroundPosition, tokens));
  4632. if (!maybe_value)
  4633. return zero_offset;
  4634. auto offset = style_value_to_length_percentage(maybe_value.release_nonnull());
  4635. if (offset.has_value()) {
  4636. offset_provided = true;
  4637. transaction.commit();
  4638. return *offset;
  4639. }
  4640. }
  4641. return zero_offset;
  4642. };
  4643. if (value->is_identifier()) {
  4644. auto identifier = value->to_identifier();
  4645. if (is_horizontal(identifier)) {
  4646. bool offset_provided = false;
  4647. auto offset = TRY(try_parse_offset(offset_provided));
  4648. horizontal = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  4649. } else if (is_vertical(identifier)) {
  4650. bool offset_provided = false;
  4651. auto offset = TRY(try_parse_offset(offset_provided));
  4652. vertical = EdgeOffset { *identifier_to_edge(identifier), offset, true, offset_provided };
  4653. } else if (identifier == ValueID::Center) {
  4654. found_center = true;
  4655. } else {
  4656. return nullptr;
  4657. }
  4658. continue;
  4659. }
  4660. tokens.reconsume_current_input_token();
  4661. break;
  4662. }
  4663. if (found_center) {
  4664. if (horizontal.has_value() && vertical.has_value())
  4665. return nullptr;
  4666. if (!horizontal.has_value())
  4667. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  4668. if (!vertical.has_value())
  4669. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  4670. }
  4671. if (!horizontal.has_value() && !vertical.has_value())
  4672. return nullptr;
  4673. // Unpack `<edge> <length>`:
  4674. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  4675. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  4676. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  4677. // Split into `x y`
  4678. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  4679. horizontal->offset = zero_offset;
  4680. horizontal->offset_provided = false;
  4681. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  4682. // `y`, reconsume
  4683. vertical->offset = zero_offset;
  4684. vertical->offset_provided = false;
  4685. tokens.reconsume_current_input_token();
  4686. }
  4687. // If only one value is specified, the second value is assumed to be center.
  4688. if (!horizontal.has_value())
  4689. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  4690. if (!vertical.has_value())
  4691. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  4692. transaction.commit();
  4693. return PositionStyleValue::create(
  4694. TRY(EdgeStyleValue::create(horizontal->edge, horizontal->offset)),
  4695. TRY(EdgeStyleValue::create(vertical->edge, vertical->offset)));
  4696. }
  4697. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  4698. {
  4699. PositionEdge relative_edge {};
  4700. if (property == PropertyID::BackgroundPositionX) {
  4701. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  4702. relative_edge = PositionEdge::Left;
  4703. } else if (property == PropertyID::BackgroundPositionY) {
  4704. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  4705. relative_edge = PositionEdge::Top;
  4706. } else {
  4707. VERIFY_NOT_REACHED();
  4708. }
  4709. auto transaction = tokens.begin_transaction();
  4710. if (!tokens.has_next_token())
  4711. return nullptr;
  4712. auto value = TRY(parse_css_value_for_property(property, tokens));
  4713. if (!value)
  4714. return nullptr;
  4715. if (value->is_identifier()) {
  4716. auto identifier = value->to_identifier();
  4717. if (identifier == ValueID::Center) {
  4718. transaction.commit();
  4719. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  4720. }
  4721. if (auto edge = identifier_to_edge(identifier); edge.has_value()) {
  4722. relative_edge = *edge;
  4723. } else {
  4724. return nullptr;
  4725. }
  4726. if (tokens.has_next_token()) {
  4727. value = TRY(parse_css_value_for_property(property, tokens));
  4728. if (!value) {
  4729. transaction.commit();
  4730. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  4731. }
  4732. }
  4733. }
  4734. auto offset = style_value_to_length_percentage(value);
  4735. if (offset.has_value()) {
  4736. transaction.commit();
  4737. return EdgeStyleValue::create(relative_edge, *offset);
  4738. }
  4739. return nullptr;
  4740. }
  4741. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  4742. {
  4743. auto transaction = tokens.begin_transaction();
  4744. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  4745. auto value_id = value.to_identifier();
  4746. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  4747. };
  4748. auto as_repeat = [](ValueID identifier) -> Optional<Repeat> {
  4749. switch (identifier) {
  4750. case ValueID::NoRepeat:
  4751. return Repeat::NoRepeat;
  4752. case ValueID::Repeat:
  4753. return Repeat::Repeat;
  4754. case ValueID::Round:
  4755. return Repeat::Round;
  4756. case ValueID::Space:
  4757. return Repeat::Space;
  4758. default:
  4759. return {};
  4760. }
  4761. };
  4762. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens));
  4763. if (!maybe_x_value)
  4764. return nullptr;
  4765. auto x_value = maybe_x_value.release_nonnull();
  4766. if (is_directional_repeat(*x_value)) {
  4767. auto value_id = x_value->to_identifier();
  4768. transaction.commit();
  4769. return BackgroundRepeatStyleValue::create(
  4770. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  4771. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  4772. }
  4773. auto x_repeat = as_repeat(x_value->to_identifier());
  4774. if (!x_repeat.has_value())
  4775. return nullptr;
  4776. // See if we have a second value for Y
  4777. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens));
  4778. if (!maybe_y_value) {
  4779. // We don't have a second value, so use x for both
  4780. transaction.commit();
  4781. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  4782. }
  4783. auto y_value = maybe_y_value.release_nonnull();
  4784. if (is_directional_repeat(*y_value))
  4785. return nullptr;
  4786. auto y_repeat = as_repeat(y_value->to_identifier());
  4787. if (!y_repeat.has_value())
  4788. return nullptr;
  4789. transaction.commit();
  4790. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  4791. }
  4792. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  4793. {
  4794. auto transaction = tokens.begin_transaction();
  4795. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  4796. if (style_value.has_auto())
  4797. return LengthPercentage { Length::make_auto() };
  4798. if (style_value.is_percentage())
  4799. return LengthPercentage { style_value.as_percentage().percentage() };
  4800. if (style_value.is_length())
  4801. return LengthPercentage { style_value.as_length().length() };
  4802. return {};
  4803. };
  4804. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::BackgroundSize, tokens));
  4805. if (!maybe_x_value)
  4806. return nullptr;
  4807. auto x_value = maybe_x_value.release_nonnull();
  4808. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain) {
  4809. transaction.commit();
  4810. return x_value;
  4811. }
  4812. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::BackgroundSize, tokens));
  4813. if (!maybe_y_value) {
  4814. auto y_value = LengthPercentage { Length::make_auto() };
  4815. auto x_size = get_length_percentage(*x_value);
  4816. if (!x_size.has_value())
  4817. return nullptr;
  4818. transaction.commit();
  4819. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  4820. }
  4821. auto y_value = maybe_y_value.release_nonnull();
  4822. auto x_size = get_length_percentage(*x_value);
  4823. auto y_size = get_length_percentage(*y_value);
  4824. if (!x_size.has_value() || !y_size.has_value())
  4825. return nullptr;
  4826. transaction.commit();
  4827. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  4828. }
  4829. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_value(Vector<ComponentValue> const& component_values)
  4830. {
  4831. if (component_values.size() > 3)
  4832. return nullptr;
  4833. RefPtr<StyleValue> border_width;
  4834. RefPtr<StyleValue> border_color;
  4835. RefPtr<StyleValue> border_style;
  4836. auto remaining_longhands = Vector { PropertyID::BorderWidth, PropertyID::BorderColor, PropertyID::BorderStyle };
  4837. auto tokens = TokenStream { component_values };
  4838. while (tokens.has_next_token()) {
  4839. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  4840. if (!property_and_value.style_value)
  4841. return nullptr;
  4842. auto& value = property_and_value.style_value;
  4843. remove_property(remaining_longhands, property_and_value.property);
  4844. switch (property_and_value.property) {
  4845. case PropertyID::BorderWidth: {
  4846. VERIFY(!border_width);
  4847. border_width = value.release_nonnull();
  4848. continue;
  4849. }
  4850. case PropertyID::BorderColor: {
  4851. VERIFY(!border_color);
  4852. border_color = value.release_nonnull();
  4853. continue;
  4854. }
  4855. case PropertyID::BorderStyle: {
  4856. VERIFY(!border_style);
  4857. border_style = value.release_nonnull();
  4858. continue;
  4859. }
  4860. default:
  4861. VERIFY_NOT_REACHED();
  4862. }
  4863. }
  4864. if (!border_width)
  4865. border_width = TRY(property_initial_value(m_context.realm(), PropertyID::BorderWidth));
  4866. if (!border_style)
  4867. border_style = TRY(property_initial_value(m_context.realm(), PropertyID::BorderStyle));
  4868. if (!border_color)
  4869. border_color = TRY(property_initial_value(m_context.realm(), PropertyID::BorderColor));
  4870. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  4871. }
  4872. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_radius_value(Vector<ComponentValue> const& component_values)
  4873. {
  4874. if (component_values.size() == 2) {
  4875. auto horizontal = parse_dimension(component_values[0]);
  4876. auto vertical = parse_dimension(component_values[1]);
  4877. if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage())
  4878. return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());
  4879. return nullptr;
  4880. }
  4881. if (component_values.size() == 1) {
  4882. auto radius = parse_dimension(component_values[0]);
  4883. if (radius.has_value() && radius->is_length_percentage())
  4884. return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
  4885. return nullptr;
  4886. }
  4887. return nullptr;
  4888. }
  4889. ErrorOr<RefPtr<StyleValue>> Parser::parse_border_radius_shorthand_value(Vector<ComponentValue> const& component_values)
  4890. {
  4891. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  4892. auto top_right = [&](Vector<LengthPercentage>& radii) {
  4893. switch (radii.size()) {
  4894. case 4:
  4895. case 3:
  4896. case 2:
  4897. return radii[1];
  4898. case 1:
  4899. return radii[0];
  4900. default:
  4901. VERIFY_NOT_REACHED();
  4902. }
  4903. };
  4904. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  4905. switch (radii.size()) {
  4906. case 4:
  4907. case 3:
  4908. return radii[2];
  4909. case 2:
  4910. case 1:
  4911. return radii[0];
  4912. default:
  4913. VERIFY_NOT_REACHED();
  4914. }
  4915. };
  4916. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  4917. switch (radii.size()) {
  4918. case 4:
  4919. return radii[3];
  4920. case 3:
  4921. case 2:
  4922. return radii[1];
  4923. case 1:
  4924. return radii[0];
  4925. default:
  4926. VERIFY_NOT_REACHED();
  4927. }
  4928. };
  4929. Vector<LengthPercentage> horizontal_radii;
  4930. Vector<LengthPercentage> vertical_radii;
  4931. bool reading_vertical = false;
  4932. for (auto const& value : component_values) {
  4933. if (value.is_delim('/')) {
  4934. if (reading_vertical || horizontal_radii.is_empty())
  4935. return nullptr;
  4936. reading_vertical = true;
  4937. continue;
  4938. }
  4939. auto maybe_dimension = parse_dimension(value);
  4940. if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
  4941. return nullptr;
  4942. if (reading_vertical) {
  4943. vertical_radii.append(maybe_dimension->length_percentage());
  4944. } else {
  4945. horizontal_radii.append(maybe_dimension->length_percentage());
  4946. }
  4947. }
  4948. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  4949. || horizontal_radii.is_empty()
  4950. || (reading_vertical && vertical_radii.is_empty()))
  4951. return nullptr;
  4952. auto top_left_radius = TRY(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  4953. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  4954. auto top_right_radius = TRY(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  4955. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  4956. auto bottom_right_radius = TRY(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  4957. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  4958. auto bottom_left_radius = TRY(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  4959. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  4960. return BorderRadiusShorthandStyleValue::create(move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius));
  4961. }
  4962. ErrorOr<RefPtr<StyleValue>> Parser::parse_shadow_value(Vector<ComponentValue> const& component_values, AllowInsetKeyword allow_inset_keyword)
  4963. {
  4964. // "none"
  4965. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  4966. auto ident = TRY(parse_identifier_value(component_values.first()));
  4967. if (ident && ident->to_identifier() == ValueID::None)
  4968. return ident;
  4969. }
  4970. return parse_comma_separated_value_list(component_values, [this, allow_inset_keyword](auto& tokens) {
  4971. return parse_single_shadow_value(tokens, allow_inset_keyword);
  4972. });
  4973. }
  4974. ErrorOr<RefPtr<StyleValue>> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  4975. {
  4976. auto transaction = tokens.begin_transaction();
  4977. Optional<Color> color;
  4978. Optional<Length> offset_x;
  4979. Optional<Length> offset_y;
  4980. Optional<Length> blur_radius;
  4981. Optional<Length> spread_distance;
  4982. Optional<ShadowPlacement> placement;
  4983. while (tokens.has_next_token()) {
  4984. auto const& token = tokens.peek_token();
  4985. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  4986. if (color.has_value())
  4987. return nullptr;
  4988. color = maybe_color.release_value();
  4989. tokens.next_token();
  4990. continue;
  4991. }
  4992. if (auto maybe_offset_x = parse_length(token); maybe_offset_x.has_value()) {
  4993. // horizontal offset
  4994. if (offset_x.has_value())
  4995. return nullptr;
  4996. offset_x = maybe_offset_x.release_value();
  4997. tokens.next_token();
  4998. // vertical offset
  4999. if (!tokens.has_next_token())
  5000. return nullptr;
  5001. auto maybe_offset_y = parse_length(tokens.peek_token());
  5002. if (!maybe_offset_y.has_value())
  5003. return nullptr;
  5004. offset_y = maybe_offset_y.release_value();
  5005. tokens.next_token();
  5006. // blur radius (optional)
  5007. if (!tokens.has_next_token())
  5008. break;
  5009. auto maybe_blur_radius = parse_length(tokens.peek_token());
  5010. if (!maybe_blur_radius.has_value())
  5011. continue;
  5012. blur_radius = maybe_blur_radius.release_value();
  5013. tokens.next_token();
  5014. // spread distance (optional)
  5015. if (!tokens.has_next_token())
  5016. break;
  5017. auto maybe_spread_distance = parse_length(tokens.peek_token());
  5018. if (!maybe_spread_distance.has_value())
  5019. continue;
  5020. spread_distance = maybe_spread_distance.release_value();
  5021. tokens.next_token();
  5022. continue;
  5023. }
  5024. if (allow_inset_keyword == AllowInsetKeyword::Yes
  5025. && token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("inset"sv)) {
  5026. if (placement.has_value())
  5027. return nullptr;
  5028. placement = ShadowPlacement::Inner;
  5029. tokens.next_token();
  5030. continue;
  5031. }
  5032. if (token.is(Token::Type::Comma))
  5033. break;
  5034. return nullptr;
  5035. }
  5036. // FIXME: If color is absent, default to `currentColor`
  5037. if (!color.has_value())
  5038. color = Color::NamedColor::Black;
  5039. // x/y offsets are required
  5040. if (!offset_x.has_value() || !offset_y.has_value())
  5041. return nullptr;
  5042. // Other lengths default to 0
  5043. if (!blur_radius.has_value())
  5044. blur_radius = Length::make_px(0);
  5045. if (!spread_distance.has_value())
  5046. spread_distance = Length::make_px(0);
  5047. // Placement is outer by default
  5048. if (!placement.has_value())
  5049. placement = ShadowPlacement::Outer;
  5050. transaction.commit();
  5051. 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());
  5052. }
  5053. ErrorOr<RefPtr<StyleValue>> Parser::parse_content_value(Vector<ComponentValue> const& component_values)
  5054. {
  5055. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  5056. auto is_single_value_identifier = [](ValueID identifier) -> bool {
  5057. switch (identifier) {
  5058. case ValueID::None:
  5059. case ValueID::Normal:
  5060. return true;
  5061. default:
  5062. return false;
  5063. }
  5064. };
  5065. if (component_values.size() == 1) {
  5066. if (auto identifier = TRY(parse_identifier_value(component_values.first()))) {
  5067. if (is_single_value_identifier(identifier->to_identifier()))
  5068. return identifier;
  5069. }
  5070. }
  5071. StyleValueVector content_values;
  5072. StyleValueVector alt_text_values;
  5073. bool in_alt_text = false;
  5074. auto tokens = TokenStream { component_values };
  5075. while (tokens.has_next_token()) {
  5076. auto& next = tokens.peek_token();
  5077. if (next.is_delim('/')) {
  5078. if (in_alt_text || content_values.is_empty())
  5079. return nullptr;
  5080. in_alt_text = true;
  5081. (void)tokens.next_token();
  5082. continue;
  5083. }
  5084. if (auto style_value = TRY(parse_css_value_for_property(PropertyID::Content, tokens))) {
  5085. if (is_single_value_identifier(style_value->to_identifier()))
  5086. return nullptr;
  5087. if (in_alt_text) {
  5088. TRY(alt_text_values.try_append(style_value.release_nonnull()));
  5089. } else {
  5090. TRY(content_values.try_append(style_value.release_nonnull()));
  5091. }
  5092. continue;
  5093. }
  5094. return nullptr;
  5095. }
  5096. if (content_values.is_empty())
  5097. return nullptr;
  5098. if (in_alt_text && alt_text_values.is_empty())
  5099. return nullptr;
  5100. RefPtr<StyleValueList> alt_text;
  5101. if (!alt_text_values.is_empty())
  5102. alt_text = TRY(StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space));
  5103. return ContentStyleValue::create(TRY(StyleValueList::create(move(content_values), StyleValueList::Separator::Space)), move(alt_text));
  5104. }
  5105. // https://www.w3.org/TR/css-display-3/#the-display-properties
  5106. ErrorOr<RefPtr<StyleValue>> Parser::parse_display_value(Vector<ComponentValue> const& component_values)
  5107. {
  5108. auto parse_inside = [](ValueID identifier) -> Optional<Display::Inside> {
  5109. switch (identifier) {
  5110. case ValueID::Flow:
  5111. return Display::Inside::Flow;
  5112. case ValueID::FlowRoot:
  5113. return Display::Inside::FlowRoot;
  5114. case ValueID::Table:
  5115. return Display::Inside::Table;
  5116. case ValueID::Flex:
  5117. return Display::Inside::Flex;
  5118. case ValueID::Grid:
  5119. return Display::Inside::Grid;
  5120. case ValueID::Ruby:
  5121. return Display::Inside::Ruby;
  5122. default:
  5123. return {};
  5124. }
  5125. };
  5126. auto parse_outside = [](ValueID identifier) -> Optional<Display::Outside> {
  5127. switch (identifier) {
  5128. case ValueID::Block:
  5129. return Display::Outside::Block;
  5130. case ValueID::Inline:
  5131. return Display::Outside::Inline;
  5132. case ValueID::RunIn:
  5133. return Display::Outside::RunIn;
  5134. default:
  5135. return {};
  5136. }
  5137. };
  5138. auto parse_single_component_display = [&](Vector<ComponentValue> const& component_values) -> ErrorOr<Optional<Display>> {
  5139. if (auto identifier = TRY(parse_identifier_value(component_values.first()))) {
  5140. switch (identifier->to_identifier()) {
  5141. // display-outside
  5142. case ValueID::Block:
  5143. return Display::from_short(Display::Short::Block);
  5144. case ValueID::Inline:
  5145. return Display::from_short(Display::Short::Inline);
  5146. case ValueID::RunIn:
  5147. return Display::from_short(Display::Short::RunIn);
  5148. // display-inside
  5149. case ValueID::Flow:
  5150. return Display::from_short(Display::Short::Flow);
  5151. case ValueID::FlowRoot:
  5152. return Display::from_short(Display::Short::FlowRoot);
  5153. case ValueID::Table:
  5154. return Display::from_short(Display::Short::Table);
  5155. case ValueID::Flex:
  5156. return Display::from_short(Display::Short::Flex);
  5157. case ValueID::Grid:
  5158. return Display::from_short(Display::Short::Grid);
  5159. case ValueID::Ruby:
  5160. return Display::from_short(Display::Short::Ruby);
  5161. // display-listitem
  5162. case ValueID::ListItem:
  5163. return Display::from_short(Display::Short::ListItem);
  5164. // display-internal
  5165. case ValueID::TableRowGroup:
  5166. return Display { Display::Internal::TableRowGroup };
  5167. case ValueID::TableHeaderGroup:
  5168. return Display { Display::Internal::TableHeaderGroup };
  5169. case ValueID::TableFooterGroup:
  5170. return Display { Display::Internal::TableFooterGroup };
  5171. case ValueID::TableRow:
  5172. return Display { Display::Internal::TableRow };
  5173. case ValueID::TableCell:
  5174. return Display { Display::Internal::TableCell };
  5175. case ValueID::TableColumnGroup:
  5176. return Display { Display::Internal::TableColumnGroup };
  5177. case ValueID::TableColumn:
  5178. return Display { Display::Internal::TableColumn };
  5179. case ValueID::TableCaption:
  5180. return Display { Display::Internal::TableCaption };
  5181. case ValueID::RubyBase:
  5182. return Display { Display::Internal::RubyBase };
  5183. case ValueID::RubyText:
  5184. return Display { Display::Internal::RubyText };
  5185. case ValueID::RubyBaseContainer:
  5186. return Display { Display::Internal::RubyBaseContainer };
  5187. case ValueID::RubyTextContainer:
  5188. return Display { Display::Internal::RubyTextContainer };
  5189. // display-box
  5190. case ValueID::Contents:
  5191. // FIXME this should be Display::Short::Contents but contents is currently not implemented
  5192. return Display::from_short(Display::Short::Flow);
  5193. case ValueID::None:
  5194. return Display::from_short(Display::Short::None);
  5195. // display-legacy
  5196. case ValueID::InlineBlock:
  5197. return Display::from_short(Display::Short::InlineBlock);
  5198. case ValueID::InlineTable:
  5199. return Display::from_short(Display::Short::InlineTable);
  5200. case ValueID::InlineFlex:
  5201. return Display::from_short(Display::Short::InlineFlex);
  5202. case ValueID::InlineGrid:
  5203. return Display::from_short(Display::Short::InlineGrid);
  5204. default:
  5205. return OptionalNone {};
  5206. }
  5207. }
  5208. return OptionalNone {};
  5209. };
  5210. auto parse_multi_component_display = [&](Vector<ComponentValue> const& component_values) -> ErrorOr<Optional<Display>> {
  5211. auto list_item = Display::ListItem::No;
  5212. Display::Inside inside = Display::Inside::Flow;
  5213. Display::Outside outside = Display::Outside::Block;
  5214. for (size_t i = 0; i < component_values.size(); ++i) {
  5215. if (auto value = TRY(parse_identifier_value(component_values[i]))) {
  5216. auto identifier = value->to_identifier();
  5217. if (ValueID::ListItem == identifier) {
  5218. list_item = Display::ListItem::Yes;
  5219. continue;
  5220. }
  5221. auto inside_value = parse_inside(identifier);
  5222. if (inside_value.has_value()) {
  5223. inside = inside_value.value();
  5224. continue;
  5225. }
  5226. auto outside_value = parse_outside(identifier);
  5227. if (outside_value.has_value()) {
  5228. outside = outside_value.value();
  5229. }
  5230. }
  5231. }
  5232. // The spec does not allow any other inside values to be combined with list-item
  5233. // <display-outside>? && [ flow | flow-root ]? && list-item
  5234. if (list_item == Display::ListItem::Yes && inside != Display::Inside::Flow && inside != Display::Inside::FlowRoot)
  5235. return OptionalNone {};
  5236. return Display { outside, inside, list_item };
  5237. };
  5238. Optional<Display> display;
  5239. if (component_values.size() == 1)
  5240. display = TRY(parse_single_component_display(component_values));
  5241. else
  5242. display = TRY(parse_multi_component_display(component_values));
  5243. if (display.has_value())
  5244. return DisplayStyleValue::create(display.value());
  5245. return nullptr;
  5246. }
  5247. ErrorOr<RefPtr<StyleValue>> Parser::parse_filter_value_list_value(Vector<ComponentValue> const& component_values)
  5248. {
  5249. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  5250. auto ident = TRY(parse_identifier_value(component_values.first()));
  5251. if (ident && ident->to_identifier() == ValueID::None)
  5252. return ident;
  5253. }
  5254. TokenStream tokens { component_values };
  5255. // FIXME: <url>s are ignored for now
  5256. // <filter-value-list> = [ <filter-function> | <url> ]+
  5257. enum class FilterToken {
  5258. // Color filters:
  5259. Brightness,
  5260. Contrast,
  5261. Grayscale,
  5262. Invert,
  5263. Opacity,
  5264. Saturate,
  5265. Sepia,
  5266. // Special filters:
  5267. Blur,
  5268. DropShadow,
  5269. HueRotate
  5270. };
  5271. auto filter_token_to_operation = [&](auto filter) {
  5272. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  5273. return static_cast<Filter::Color::Operation>(filter);
  5274. };
  5275. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  5276. if (token.is(Token::Type::Percentage))
  5277. return NumberPercentage(Percentage(token.token().percentage()));
  5278. if (token.is(Token::Type::Number))
  5279. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  5280. return {};
  5281. };
  5282. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  5283. if (name.equals_ignoring_ascii_case("blur"sv))
  5284. return FilterToken::Blur;
  5285. if (name.equals_ignoring_ascii_case("brightness"sv))
  5286. return FilterToken::Brightness;
  5287. if (name.equals_ignoring_ascii_case("contrast"sv))
  5288. return FilterToken::Contrast;
  5289. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  5290. return FilterToken::DropShadow;
  5291. if (name.equals_ignoring_ascii_case("grayscale"sv))
  5292. return FilterToken::Grayscale;
  5293. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  5294. return FilterToken::HueRotate;
  5295. if (name.equals_ignoring_ascii_case("invert"sv))
  5296. return FilterToken::Invert;
  5297. if (name.equals_ignoring_ascii_case("opacity"sv))
  5298. return FilterToken::Opacity;
  5299. if (name.equals_ignoring_ascii_case("saturate"sv))
  5300. return FilterToken::Saturate;
  5301. if (name.equals_ignoring_ascii_case("sepia"sv))
  5302. return FilterToken::Sepia;
  5303. return {};
  5304. };
  5305. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  5306. TokenStream tokens { function_values };
  5307. tokens.skip_whitespace();
  5308. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  5309. tokens.skip_whitespace();
  5310. if (tokens.has_next_token())
  5311. return {};
  5312. return filter;
  5313. };
  5314. if (filter_token == FilterToken::Blur) {
  5315. // blur( <length>? )
  5316. if (!tokens.has_next_token())
  5317. return Filter::Blur {};
  5318. auto blur_radius = parse_length(tokens.next_token());
  5319. if (!blur_radius.has_value())
  5320. return {};
  5321. return if_no_more_tokens_return(Filter::Blur { *blur_radius });
  5322. } else if (filter_token == FilterToken::DropShadow) {
  5323. if (!tokens.has_next_token())
  5324. return {};
  5325. auto next_token = [&]() -> auto&
  5326. {
  5327. auto& token = tokens.next_token();
  5328. tokens.skip_whitespace();
  5329. return token;
  5330. };
  5331. // drop-shadow( [ <color>? && <length>{2,3} ] )
  5332. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  5333. auto& first_param = next_token();
  5334. Optional<Length> maybe_radius = {};
  5335. auto maybe_color = parse_color(first_param);
  5336. auto x_offset = parse_length(maybe_color.has_value() ? next_token() : first_param);
  5337. if (!x_offset.has_value() || !tokens.has_next_token()) {
  5338. return {};
  5339. }
  5340. auto y_offset = parse_length(next_token());
  5341. if (!y_offset.has_value()) {
  5342. return {};
  5343. }
  5344. if (tokens.has_next_token()) {
  5345. auto& token = next_token();
  5346. maybe_radius = parse_length(token);
  5347. if (!maybe_color.has_value() && (!maybe_radius.has_value() || tokens.has_next_token())) {
  5348. maybe_color = parse_color(!maybe_radius.has_value() ? token : next_token());
  5349. if (!maybe_color.has_value()) {
  5350. return {};
  5351. }
  5352. } else if (!maybe_radius.has_value()) {
  5353. return {};
  5354. }
  5355. }
  5356. return if_no_more_tokens_return(Filter::DropShadow { *x_offset, *y_offset, maybe_radius, maybe_color });
  5357. } else if (filter_token == FilterToken::HueRotate) {
  5358. // hue-rotate( [ <angle> | <zero> ]? )
  5359. if (!tokens.has_next_token())
  5360. return Filter::HueRotate {};
  5361. auto& token = tokens.next_token();
  5362. if (token.is(Token::Type::Number)) {
  5363. // hue-rotate(0)
  5364. auto number = token.token().number();
  5365. if (number.is_integer() && number.integer_value() == 0)
  5366. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  5367. return {};
  5368. }
  5369. if (!token.is(Token::Type::Dimension))
  5370. return {};
  5371. float angle_value = token.token().dimension_value();
  5372. auto angle_unit_name = token.token().dimension_unit();
  5373. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  5374. if (!angle_unit.has_value())
  5375. return {};
  5376. Angle angle { angle_value, angle_unit.release_value() };
  5377. return if_no_more_tokens_return(Filter::HueRotate { angle });
  5378. } else {
  5379. // Simple filters:
  5380. // brightness( <number-percentage>? )
  5381. // contrast( <number-percentage>? )
  5382. // grayscale( <number-percentage>? )
  5383. // invert( <number-percentage>? )
  5384. // opacity( <number-percentage>? )
  5385. // sepia( <number-percentage>? )
  5386. // saturate( <number-percentage>? )
  5387. if (!tokens.has_next_token())
  5388. return Filter::Color { filter_token_to_operation(filter_token) };
  5389. auto amount = parse_number_percentage(tokens.next_token());
  5390. if (!amount.has_value())
  5391. return {};
  5392. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  5393. }
  5394. };
  5395. Vector<FilterFunction> filter_value_list {};
  5396. while (tokens.has_next_token()) {
  5397. tokens.skip_whitespace();
  5398. if (!tokens.has_next_token())
  5399. break;
  5400. auto& token = tokens.next_token();
  5401. if (!token.is_function())
  5402. return nullptr;
  5403. auto filter_token = parse_filter_function_name(token.function().name());
  5404. if (!filter_token.has_value())
  5405. return nullptr;
  5406. auto filter_function = parse_filter_function(*filter_token, token.function().values());
  5407. if (!filter_function.has_value())
  5408. return nullptr;
  5409. filter_value_list.append(*filter_function);
  5410. }
  5411. if (filter_value_list.is_empty())
  5412. return nullptr;
  5413. return FilterValueListStyleValue::create(move(filter_value_list));
  5414. }
  5415. ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_value(Vector<ComponentValue> const& component_values)
  5416. {
  5417. auto tokens = TokenStream { component_values };
  5418. if (component_values.size() == 1) {
  5419. // One-value syntax: <flex-grow> | <flex-basis> | none
  5420. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  5421. auto property_and_value = TRY(parse_css_value_for_properties(properties, tokens));
  5422. if (!property_and_value.style_value)
  5423. return nullptr;
  5424. auto& value = property_and_value.style_value;
  5425. switch (property_and_value.property) {
  5426. case PropertyID::FlexGrow: {
  5427. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  5428. // https://github.com/w3c/csswg-drafts/issues/5742
  5429. auto flex_basis = TRY(PercentageStyleValue::create(Percentage(0)));
  5430. auto one = TRY(NumberStyleValue::create(1));
  5431. return FlexStyleValue::create(*value, one, flex_basis);
  5432. }
  5433. case PropertyID::FlexBasis: {
  5434. auto one = TRY(NumberStyleValue::create(1));
  5435. return FlexStyleValue::create(one, one, *value);
  5436. }
  5437. case PropertyID::Flex: {
  5438. if (value->is_identifier() && value->to_identifier() == ValueID::None) {
  5439. auto zero = TRY(NumberStyleValue::create(0));
  5440. return FlexStyleValue::create(zero, zero, TRY(IdentifierStyleValue::create(ValueID::Auto)));
  5441. }
  5442. break;
  5443. }
  5444. default:
  5445. VERIFY_NOT_REACHED();
  5446. }
  5447. return nullptr;
  5448. }
  5449. RefPtr<StyleValue> flex_grow;
  5450. RefPtr<StyleValue> flex_shrink;
  5451. RefPtr<StyleValue> flex_basis;
  5452. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  5453. // if FlexGrow (along with optional FlexShrink) have already been specified.
  5454. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  5455. while (tokens.has_next_token()) {
  5456. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5457. if (!property_and_value.style_value)
  5458. return nullptr;
  5459. auto& value = property_and_value.style_value;
  5460. remove_property(remaining_longhands, property_and_value.property);
  5461. switch (property_and_value.property) {
  5462. case PropertyID::FlexGrow: {
  5463. VERIFY(!flex_grow);
  5464. flex_grow = value.release_nonnull();
  5465. // Flex-shrink may optionally follow directly after.
  5466. auto maybe_flex_shrink = TRY(parse_css_value_for_property(PropertyID::FlexShrink, tokens));
  5467. if (maybe_flex_shrink)
  5468. flex_shrink = maybe_flex_shrink.release_nonnull();
  5469. continue;
  5470. }
  5471. case PropertyID::FlexBasis: {
  5472. VERIFY(!flex_basis);
  5473. flex_basis = value.release_nonnull();
  5474. continue;
  5475. }
  5476. default:
  5477. VERIFY_NOT_REACHED();
  5478. }
  5479. }
  5480. if (!flex_grow)
  5481. flex_grow = TRY(property_initial_value(m_context.realm(), PropertyID::FlexGrow));
  5482. if (!flex_shrink)
  5483. flex_shrink = TRY(property_initial_value(m_context.realm(), PropertyID::FlexShrink));
  5484. if (!flex_basis) {
  5485. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  5486. // https://github.com/w3c/csswg-drafts/issues/5742
  5487. flex_basis = TRY(PercentageStyleValue::create(Percentage(0)));
  5488. }
  5489. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  5490. }
  5491. ErrorOr<RefPtr<StyleValue>> Parser::parse_flex_flow_value(Vector<ComponentValue> const& component_values)
  5492. {
  5493. if (component_values.size() > 2)
  5494. return nullptr;
  5495. RefPtr<StyleValue> flex_direction;
  5496. RefPtr<StyleValue> flex_wrap;
  5497. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  5498. auto tokens = TokenStream { component_values };
  5499. while (tokens.has_next_token()) {
  5500. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5501. if (!property_and_value.style_value)
  5502. return nullptr;
  5503. auto& value = property_and_value.style_value;
  5504. remove_property(remaining_longhands, property_and_value.property);
  5505. switch (property_and_value.property) {
  5506. case PropertyID::FlexDirection:
  5507. VERIFY(!flex_direction);
  5508. flex_direction = value.release_nonnull();
  5509. continue;
  5510. case PropertyID::FlexWrap:
  5511. VERIFY(!flex_wrap);
  5512. flex_wrap = value.release_nonnull();
  5513. continue;
  5514. default:
  5515. VERIFY_NOT_REACHED();
  5516. }
  5517. }
  5518. if (!flex_direction)
  5519. flex_direction = TRY(property_initial_value(m_context.realm(), PropertyID::FlexDirection));
  5520. if (!flex_wrap)
  5521. flex_wrap = TRY(property_initial_value(m_context.realm(), PropertyID::FlexWrap));
  5522. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  5523. }
  5524. static bool is_generic_font_family(ValueID identifier)
  5525. {
  5526. switch (identifier) {
  5527. case ValueID::Cursive:
  5528. case ValueID::Fantasy:
  5529. case ValueID::Monospace:
  5530. case ValueID::Serif:
  5531. case ValueID::SansSerif:
  5532. case ValueID::UiMonospace:
  5533. case ValueID::UiRounded:
  5534. case ValueID::UiSerif:
  5535. case ValueID::UiSansSerif:
  5536. return true;
  5537. default:
  5538. return false;
  5539. }
  5540. }
  5541. ErrorOr<RefPtr<StyleValue>> Parser::parse_font_value(Vector<ComponentValue> const& component_values)
  5542. {
  5543. RefPtr<StyleValue> font_stretch;
  5544. RefPtr<StyleValue> font_style;
  5545. RefPtr<StyleValue> font_weight;
  5546. RefPtr<StyleValue> font_size;
  5547. RefPtr<StyleValue> line_height;
  5548. RefPtr<StyleValue> font_families;
  5549. RefPtr<StyleValue> font_variant;
  5550. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  5551. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  5552. // So, we have to handle that separately.
  5553. int normal_count = 0;
  5554. auto tokens = TokenStream { component_values };
  5555. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStretch, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight };
  5556. while (tokens.has_next_token()) {
  5557. auto& peek_token = tokens.peek_token();
  5558. if (peek_token.is(Token::Type::Ident) && value_id_from_string(peek_token.token().ident()) == ValueID::Normal) {
  5559. normal_count++;
  5560. (void)tokens.next_token();
  5561. continue;
  5562. }
  5563. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5564. if (!property_and_value.style_value)
  5565. return nullptr;
  5566. auto& value = property_and_value.style_value;
  5567. remove_property(remaining_longhands, property_and_value.property);
  5568. switch (property_and_value.property) {
  5569. case PropertyID::FontSize: {
  5570. VERIFY(!font_size);
  5571. font_size = value.release_nonnull();
  5572. // Consume `/ line-height` if present
  5573. if (tokens.peek_token().is_delim('/')) {
  5574. (void)tokens.next_token();
  5575. auto maybe_line_height = TRY(parse_css_value_for_property(PropertyID::LineHeight, tokens));
  5576. if (!maybe_line_height)
  5577. return nullptr;
  5578. line_height = maybe_line_height.release_nonnull();
  5579. }
  5580. // Consume font-families
  5581. auto maybe_font_families = TRY(parse_font_family_value(tokens));
  5582. // font-family comes last, so we must not have any tokens left over.
  5583. if (!maybe_font_families || tokens.has_next_token())
  5584. return nullptr;
  5585. font_families = maybe_font_families.release_nonnull();
  5586. continue;
  5587. }
  5588. case PropertyID::FontStretch: {
  5589. VERIFY(!font_stretch);
  5590. font_stretch = value.release_nonnull();
  5591. continue;
  5592. }
  5593. case PropertyID::FontStyle: {
  5594. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  5595. VERIFY(!font_style);
  5596. font_style = value.release_nonnull();
  5597. continue;
  5598. }
  5599. case PropertyID::FontVariant: {
  5600. VERIFY(!font_variant);
  5601. font_variant = value.release_nonnull();
  5602. continue;
  5603. }
  5604. case PropertyID::FontWeight: {
  5605. VERIFY(!font_weight);
  5606. font_weight = value.release_nonnull();
  5607. continue;
  5608. }
  5609. default:
  5610. VERIFY_NOT_REACHED();
  5611. }
  5612. return nullptr;
  5613. }
  5614. // Since normal is the default value for all the properties that can have it, we don't have to actually
  5615. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  5616. // We just need to make sure we were not given more normals than will fit.
  5617. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  5618. if (unset_value_count < normal_count)
  5619. return nullptr;
  5620. if (!font_size || !font_families)
  5621. return nullptr;
  5622. if (!font_stretch)
  5623. font_stretch = TRY(property_initial_value(m_context.realm(), PropertyID::FontStretch));
  5624. if (!font_style)
  5625. font_style = TRY(property_initial_value(m_context.realm(), PropertyID::FontStyle));
  5626. if (!font_weight)
  5627. font_weight = TRY(property_initial_value(m_context.realm(), PropertyID::FontWeight));
  5628. if (!line_height)
  5629. line_height = TRY(property_initial_value(m_context.realm(), PropertyID::LineHeight));
  5630. 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());
  5631. }
  5632. ErrorOr<RefPtr<StyleValue>> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  5633. {
  5634. auto next_is_comma_or_eof = [&]() -> bool {
  5635. return !tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma);
  5636. };
  5637. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  5638. // eg, these are equivalent:
  5639. // font-family: my cool font\!, serif;
  5640. // font-family: "my cool font!", serif;
  5641. StyleValueVector font_families;
  5642. Vector<DeprecatedString> current_name_parts;
  5643. while (tokens.has_next_token()) {
  5644. auto const& peek = tokens.peek_token();
  5645. if (peek.is(Token::Type::String)) {
  5646. // `font-family: my cool "font";` is invalid.
  5647. if (!current_name_parts.is_empty())
  5648. return nullptr;
  5649. (void)tokens.next_token(); // String
  5650. if (!next_is_comma_or_eof())
  5651. return nullptr;
  5652. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::from_utf8(peek.token().string()))))));
  5653. (void)tokens.next_token(); // Comma
  5654. continue;
  5655. }
  5656. if (peek.is(Token::Type::Ident)) {
  5657. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  5658. // CSS-wide keywords are not allowed
  5659. if (auto builtin = TRY(parse_builtin_value(peek)))
  5660. return nullptr;
  5661. auto maybe_ident = value_id_from_string(peek.token().ident());
  5662. // Can't have a generic-font-name as a token in an unquoted font name.
  5663. if (maybe_ident.has_value() && is_generic_font_family(maybe_ident.value())) {
  5664. if (!current_name_parts.is_empty())
  5665. return nullptr;
  5666. (void)tokens.next_token(); // Ident
  5667. if (!next_is_comma_or_eof())
  5668. return nullptr;
  5669. TRY(font_families.try_append(TRY(IdentifierStyleValue::create(maybe_ident.value()))));
  5670. (void)tokens.next_token(); // Comma
  5671. continue;
  5672. }
  5673. TRY(current_name_parts.try_append(tokens.next_token().token().ident()));
  5674. continue;
  5675. }
  5676. if (peek.is(Token::Type::Comma)) {
  5677. if (current_name_parts.is_empty())
  5678. return nullptr;
  5679. (void)tokens.next_token(); // Comma
  5680. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::join(' ', current_name_parts))))));
  5681. current_name_parts.clear();
  5682. // Can't have a trailing comma
  5683. if (!tokens.has_next_token())
  5684. return nullptr;
  5685. continue;
  5686. }
  5687. return nullptr;
  5688. }
  5689. if (!current_name_parts.is_empty()) {
  5690. TRY(font_families.try_append(TRY(StringStyleValue::create(TRY(String::join(' ', current_name_parts))))));
  5691. current_name_parts.clear();
  5692. }
  5693. if (font_families.is_empty())
  5694. return nullptr;
  5695. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  5696. }
  5697. CSSRule* Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
  5698. {
  5699. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  5700. Optional<FlyString> font_family;
  5701. Vector<FontFace::Source> src;
  5702. Vector<UnicodeRange> unicode_range;
  5703. Optional<int> weight;
  5704. Optional<int> slope;
  5705. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  5706. if (declaration_or_at_rule.is_at_rule()) {
  5707. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-family; discarding.");
  5708. continue;
  5709. }
  5710. auto const& declaration = declaration_or_at_rule.declaration();
  5711. if (declaration.name().equals_ignoring_ascii_case("font-weight"sv)) {
  5712. TokenStream token_stream { declaration.values() };
  5713. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  5714. weight = value.value()->to_font_weight();
  5715. }
  5716. continue;
  5717. }
  5718. if (declaration.name().equals_ignoring_ascii_case("font-style"sv)) {
  5719. TokenStream token_stream { declaration.values() };
  5720. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  5721. slope = value.value()->to_font_slope();
  5722. }
  5723. continue;
  5724. }
  5725. if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
  5726. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  5727. // Ideally they could share code.
  5728. Vector<DeprecatedString> font_family_parts;
  5729. bool had_syntax_error = false;
  5730. for (size_t i = 0; i < declaration.values().size(); ++i) {
  5731. auto const& part = declaration.values()[i];
  5732. if (part.is(Token::Type::Whitespace))
  5733. continue;
  5734. if (part.is(Token::Type::String)) {
  5735. if (!font_family_parts.is_empty()) {
  5736. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5737. had_syntax_error = true;
  5738. break;
  5739. }
  5740. font_family_parts.append(part.token().string());
  5741. continue;
  5742. }
  5743. if (part.is(Token::Type::Ident)) {
  5744. if (is_builtin(part.token().ident())) {
  5745. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5746. had_syntax_error = true;
  5747. break;
  5748. }
  5749. auto value_id = value_id_from_string(part.token().ident());
  5750. if (value_id.has_value() && is_generic_font_family(value_id.value())) {
  5751. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5752. had_syntax_error = true;
  5753. break;
  5754. }
  5755. font_family_parts.append(part.token().ident());
  5756. continue;
  5757. }
  5758. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5759. had_syntax_error = true;
  5760. break;
  5761. }
  5762. if (had_syntax_error || font_family_parts.is_empty())
  5763. continue;
  5764. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  5765. continue;
  5766. }
  5767. if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
  5768. TokenStream token_stream { declaration.values() };
  5769. Vector<FontFace::Source> supported_sources = parse_font_face_src(token_stream);
  5770. if (!supported_sources.is_empty())
  5771. src = move(supported_sources);
  5772. continue;
  5773. }
  5774. if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
  5775. Vector<UnicodeRange> unicode_ranges;
  5776. bool unicode_range_invalid = false;
  5777. TokenStream all_tokens { declaration.values() };
  5778. auto range_token_lists = parse_a_comma_separated_list_of_component_values(all_tokens);
  5779. for (auto& range_tokens : range_token_lists) {
  5780. TokenStream range_token_stream { range_tokens };
  5781. auto maybe_unicode_range = parse_unicode_range(range_token_stream);
  5782. if (!maybe_unicode_range.has_value()) {
  5783. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face unicode-range format invalid; discarding.");
  5784. unicode_range_invalid = true;
  5785. break;
  5786. }
  5787. unicode_ranges.append(maybe_unicode_range.release_value());
  5788. }
  5789. if (unicode_range_invalid || unicode_ranges.is_empty())
  5790. continue;
  5791. unicode_range = move(unicode_ranges);
  5792. continue;
  5793. }
  5794. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-family; discarding.", declaration.name());
  5795. }
  5796. if (!font_family.has_value()) {
  5797. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  5798. return {};
  5799. }
  5800. if (unicode_range.is_empty()) {
  5801. unicode_range.empend(0x0u, 0x10FFFFu);
  5802. }
  5803. 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();
  5804. }
  5805. Vector<FontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values)
  5806. {
  5807. // FIXME: Get this information from the system somehow?
  5808. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  5809. auto font_format_is_supported = [](StringView name) {
  5810. // The spec requires us to treat opentype and truetype as synonymous.
  5811. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv))
  5812. return true;
  5813. return false;
  5814. };
  5815. Vector<FontFace::Source> supported_sources;
  5816. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  5817. for (auto const& source_token_list : list_of_source_token_lists) {
  5818. TokenStream source_tokens { source_token_list };
  5819. source_tokens.skip_whitespace();
  5820. auto const& first = source_tokens.next_token();
  5821. // <url> [ format(<font-format>)]?
  5822. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  5823. if (auto maybe_url = parse_url_function(first, AllowedDataUrlType::Font); maybe_url.has_value()) {
  5824. auto url = maybe_url.release_value();
  5825. if (!url.is_valid()) {
  5826. continue;
  5827. }
  5828. Optional<FlyString> format;
  5829. source_tokens.skip_whitespace();
  5830. if (!source_tokens.has_next_token()) {
  5831. supported_sources.empend(move(url), format);
  5832. continue;
  5833. }
  5834. auto maybe_function = source_tokens.next_token();
  5835. if (!maybe_function.is_function()) {
  5836. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  5837. return {};
  5838. }
  5839. auto const& function = maybe_function.function();
  5840. if (function.name().equals_ignoring_ascii_case("format"sv)) {
  5841. TokenStream format_tokens { function.values() };
  5842. format_tokens.skip_whitespace();
  5843. auto const& format_name_token = format_tokens.next_token();
  5844. StringView format_name;
  5845. if (format_name_token.is(Token::Type::Ident)) {
  5846. format_name = format_name_token.token().ident();
  5847. } else if (format_name_token.is(Token::Type::String)) {
  5848. format_name = format_name_token.token().string();
  5849. } else {
  5850. 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());
  5851. return {};
  5852. }
  5853. if (!font_format_is_supported(format_name)) {
  5854. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  5855. continue;
  5856. }
  5857. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  5858. } else {
  5859. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
  5860. return {};
  5861. }
  5862. source_tokens.skip_whitespace();
  5863. if (source_tokens.has_next_token()) {
  5864. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
  5865. return {};
  5866. }
  5867. supported_sources.empend(move(url), format);
  5868. continue;
  5869. }
  5870. // FIXME: Implement `local()`.
  5871. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  5872. return {};
  5873. }
  5874. return supported_sources;
  5875. }
  5876. ErrorOr<RefPtr<StyleValue>> Parser::parse_list_style_value(Vector<ComponentValue> const& component_values)
  5877. {
  5878. if (component_values.size() > 3)
  5879. return nullptr;
  5880. RefPtr<StyleValue> list_position;
  5881. RefPtr<StyleValue> list_image;
  5882. RefPtr<StyleValue> list_type;
  5883. int found_nones = 0;
  5884. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  5885. auto tokens = TokenStream { component_values };
  5886. while (tokens.has_next_token()) {
  5887. if (auto peek = tokens.peek_token(); peek.is(Token::Type::Ident) && peek.token().ident().equals_ignoring_ascii_case("none"sv)) {
  5888. (void)tokens.next_token();
  5889. found_nones++;
  5890. continue;
  5891. }
  5892. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5893. if (!property_and_value.style_value)
  5894. return nullptr;
  5895. auto& value = property_and_value.style_value;
  5896. remove_property(remaining_longhands, property_and_value.property);
  5897. switch (property_and_value.property) {
  5898. case PropertyID::ListStylePosition: {
  5899. VERIFY(!list_position);
  5900. list_position = value.release_nonnull();
  5901. continue;
  5902. }
  5903. case PropertyID::ListStyleImage: {
  5904. VERIFY(!list_image);
  5905. list_image = value.release_nonnull();
  5906. continue;
  5907. }
  5908. case PropertyID::ListStyleType: {
  5909. VERIFY(!list_type);
  5910. list_type = value.release_nonnull();
  5911. continue;
  5912. }
  5913. default:
  5914. VERIFY_NOT_REACHED();
  5915. }
  5916. }
  5917. if (found_nones > 2)
  5918. return nullptr;
  5919. if (found_nones == 2) {
  5920. if (list_image || list_type)
  5921. return nullptr;
  5922. auto none = TRY(IdentifierStyleValue::create(ValueID::None));
  5923. list_image = none;
  5924. list_type = none;
  5925. } else if (found_nones == 1) {
  5926. if (list_image && list_type)
  5927. return nullptr;
  5928. auto none = TRY(IdentifierStyleValue::create(ValueID::None));
  5929. if (!list_image)
  5930. list_image = none;
  5931. if (!list_type)
  5932. list_type = none;
  5933. }
  5934. if (!list_position)
  5935. list_position = TRY(property_initial_value(m_context.realm(), PropertyID::ListStylePosition));
  5936. if (!list_image)
  5937. list_image = TRY(property_initial_value(m_context.realm(), PropertyID::ListStyleImage));
  5938. if (!list_type)
  5939. list_type = TRY(property_initial_value(m_context.realm(), PropertyID::ListStyleType));
  5940. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  5941. }
  5942. ErrorOr<RefPtr<StyleValue>> Parser::parse_overflow_value(Vector<ComponentValue> const& component_values)
  5943. {
  5944. auto tokens = TokenStream { component_values };
  5945. if (component_values.size() == 1) {
  5946. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::Overflow, tokens));
  5947. if (!maybe_value)
  5948. return nullptr;
  5949. return OverflowStyleValue::create(*maybe_value, *maybe_value);
  5950. }
  5951. if (component_values.size() == 2) {
  5952. auto maybe_x_value = TRY(parse_css_value_for_property(PropertyID::OverflowX, tokens));
  5953. auto maybe_y_value = TRY(parse_css_value_for_property(PropertyID::OverflowY, tokens));
  5954. if (!maybe_x_value || !maybe_y_value)
  5955. return nullptr;
  5956. return OverflowStyleValue::create(maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull());
  5957. }
  5958. return nullptr;
  5959. }
  5960. ErrorOr<RefPtr<StyleValue>> Parser::parse_place_content_value(Vector<ComponentValue> const& component_values)
  5961. {
  5962. if (component_values.size() > 2)
  5963. return nullptr;
  5964. auto tokens = TokenStream { component_values };
  5965. auto maybe_align_content_value = TRY(parse_css_value_for_property(PropertyID::AlignContent, tokens));
  5966. if (!maybe_align_content_value)
  5967. return nullptr;
  5968. if (component_values.size() == 1) {
  5969. if (!property_accepts_identifier(PropertyID::JustifyContent, maybe_align_content_value->to_identifier()))
  5970. return nullptr;
  5971. return PlaceContentStyleValue::create(*maybe_align_content_value, *maybe_align_content_value);
  5972. }
  5973. auto maybe_justify_content_value = TRY(parse_css_value_for_property(PropertyID::JustifyContent, tokens));
  5974. if (!maybe_justify_content_value)
  5975. return nullptr;
  5976. return PlaceContentStyleValue::create(maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull());
  5977. }
  5978. ErrorOr<RefPtr<StyleValue>> Parser::parse_text_decoration_value(Vector<ComponentValue> const& component_values)
  5979. {
  5980. RefPtr<StyleValue> decoration_line;
  5981. RefPtr<StyleValue> decoration_thickness;
  5982. RefPtr<StyleValue> decoration_style;
  5983. RefPtr<StyleValue> decoration_color;
  5984. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  5985. auto tokens = TokenStream { component_values };
  5986. while (tokens.has_next_token()) {
  5987. auto property_and_value = TRY(parse_css_value_for_properties(remaining_longhands, tokens));
  5988. if (!property_and_value.style_value)
  5989. return nullptr;
  5990. auto& value = property_and_value.style_value;
  5991. remove_property(remaining_longhands, property_and_value.property);
  5992. switch (property_and_value.property) {
  5993. case PropertyID::TextDecorationColor: {
  5994. VERIFY(!decoration_color);
  5995. decoration_color = value.release_nonnull();
  5996. continue;
  5997. }
  5998. case PropertyID::TextDecorationLine: {
  5999. VERIFY(!decoration_line);
  6000. tokens.reconsume_current_input_token();
  6001. auto parsed_decoration_line = TRY(parse_text_decoration_line_value(tokens));
  6002. if (!parsed_decoration_line)
  6003. return nullptr;
  6004. decoration_line = parsed_decoration_line.release_nonnull();
  6005. continue;
  6006. }
  6007. case PropertyID::TextDecorationThickness: {
  6008. VERIFY(!decoration_thickness);
  6009. decoration_thickness = value.release_nonnull();
  6010. continue;
  6011. }
  6012. case PropertyID::TextDecorationStyle: {
  6013. VERIFY(!decoration_style);
  6014. decoration_style = value.release_nonnull();
  6015. continue;
  6016. }
  6017. default:
  6018. VERIFY_NOT_REACHED();
  6019. }
  6020. }
  6021. if (!decoration_line)
  6022. decoration_line = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationLine));
  6023. if (!decoration_thickness)
  6024. decoration_thickness = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness));
  6025. if (!decoration_style)
  6026. decoration_style = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle));
  6027. if (!decoration_color)
  6028. decoration_color = TRY(property_initial_value(m_context.realm(), PropertyID::TextDecorationColor));
  6029. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  6030. }
  6031. ErrorOr<RefPtr<StyleValue>> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  6032. {
  6033. StyleValueVector style_values;
  6034. while (tokens.has_next_token()) {
  6035. auto maybe_value = TRY(parse_css_value_for_property(PropertyID::TextDecorationLine, tokens));
  6036. if (!maybe_value)
  6037. break;
  6038. auto value = maybe_value.release_nonnull();
  6039. if (auto maybe_line = value_id_to_text_decoration_line(value->to_identifier()); maybe_line.has_value()) {
  6040. if (maybe_line == TextDecorationLine::None) {
  6041. if (!style_values.is_empty())
  6042. break;
  6043. return value;
  6044. }
  6045. if (style_values.contains_slow(value))
  6046. break;
  6047. TRY(style_values.try_append(move(value)));
  6048. continue;
  6049. }
  6050. break;
  6051. }
  6052. if (style_values.is_empty())
  6053. return nullptr;
  6054. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  6055. }
  6056. ErrorOr<RefPtr<StyleValue>> Parser::parse_transform_value(Vector<ComponentValue> const& component_values)
  6057. {
  6058. StyleValueVector transformations;
  6059. auto tokens = TokenStream { component_values };
  6060. tokens.skip_whitespace();
  6061. while (tokens.has_next_token()) {
  6062. tokens.skip_whitespace();
  6063. auto const& part = tokens.next_token();
  6064. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_ascii_case("none"sv)) {
  6065. if (!transformations.is_empty())
  6066. return nullptr;
  6067. tokens.skip_whitespace();
  6068. if (tokens.has_next_token())
  6069. return nullptr;
  6070. return IdentifierStyleValue::create(ValueID::None);
  6071. }
  6072. if (!part.is_function())
  6073. return nullptr;
  6074. auto maybe_function = transform_function_from_string(part.function().name());
  6075. if (!maybe_function.has_value())
  6076. return nullptr;
  6077. auto function = maybe_function.release_value();
  6078. auto function_metadata = transform_function_metadata(function);
  6079. StyleValueVector values;
  6080. auto argument_tokens = TokenStream { part.function().values() };
  6081. argument_tokens.skip_whitespace();
  6082. size_t argument_index = 0;
  6083. while (argument_tokens.has_next_token()) {
  6084. if (argument_index == function_metadata.parameters.size()) {
  6085. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
  6086. return nullptr;
  6087. }
  6088. auto const& value = argument_tokens.next_token();
  6089. RefPtr<CalculatedStyleValue> maybe_calc_value;
  6090. if (auto maybe_dynamic_value = TRY(parse_dynamic_value(value))) {
  6091. // TODO: calc() is the only dynamic value we support for now, but more will come later.
  6092. // FIXME: Actually, calc() should probably be parsed inside parse_dimension_value() etc,
  6093. // so that it affects every use instead of us having to manually implement it.
  6094. VERIFY(maybe_dynamic_value->is_calculated());
  6095. maybe_calc_value = maybe_dynamic_value->as_calculated();
  6096. }
  6097. switch (function_metadata.parameters[argument_index].type) {
  6098. case TransformFunctionParameterType::Angle: {
  6099. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  6100. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  6101. values.append(maybe_calc_value.release_nonnull());
  6102. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  6103. values.append(TRY(AngleStyleValue::create(Angle::make_degrees(0))));
  6104. } else {
  6105. auto dimension_value = TRY(parse_dimension_value(value));
  6106. if (!dimension_value || !dimension_value->is_angle())
  6107. return nullptr;
  6108. values.append(dimension_value.release_nonnull());
  6109. }
  6110. break;
  6111. }
  6112. case TransformFunctionParameterType::Length: {
  6113. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  6114. values.append(maybe_calc_value.release_nonnull());
  6115. } else {
  6116. auto dimension_value = TRY(parse_dimension_value(value));
  6117. if (!dimension_value)
  6118. return nullptr;
  6119. if (dimension_value->is_length())
  6120. values.append(dimension_value.release_nonnull());
  6121. else
  6122. return nullptr;
  6123. }
  6124. break;
  6125. }
  6126. case TransformFunctionParameterType::LengthPercentage: {
  6127. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  6128. values.append(maybe_calc_value.release_nonnull());
  6129. } else {
  6130. auto dimension_value = TRY(parse_dimension_value(value));
  6131. if (!dimension_value)
  6132. return nullptr;
  6133. if (dimension_value->is_percentage() || dimension_value->is_length())
  6134. values.append(dimension_value.release_nonnull());
  6135. else
  6136. return nullptr;
  6137. }
  6138. break;
  6139. }
  6140. case TransformFunctionParameterType::Number: {
  6141. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  6142. values.append(maybe_calc_value.release_nonnull());
  6143. } else {
  6144. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  6145. argument_tokens.reconsume_current_input_token();
  6146. auto number = TRY(parse_number_value(argument_tokens));
  6147. if (!number)
  6148. return nullptr;
  6149. values.append(number.release_nonnull());
  6150. }
  6151. break;
  6152. }
  6153. }
  6154. argument_tokens.skip_whitespace();
  6155. if (argument_tokens.has_next_token()) {
  6156. // Arguments must be separated by commas.
  6157. if (!argument_tokens.next_token().is(Token::Type::Comma))
  6158. return nullptr;
  6159. argument_tokens.skip_whitespace();
  6160. // If there are no more parameters after the comma, this is invalid.
  6161. if (!argument_tokens.has_next_token())
  6162. return nullptr;
  6163. }
  6164. argument_index++;
  6165. }
  6166. if (argument_index < function_metadata.parameters.size() && function_metadata.parameters[argument_index].required) {
  6167. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  6168. return nullptr;
  6169. }
  6170. transformations.append(TRY(TransformationStyleValue::create(function, move(values))));
  6171. }
  6172. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  6173. }
  6174. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  6175. // FIXME: This only supports a 2D position
  6176. ErrorOr<RefPtr<StyleValue>> Parser::parse_transform_origin_value(Vector<ComponentValue> const& component_values)
  6177. {
  6178. enum class Axis {
  6179. None,
  6180. X,
  6181. Y,
  6182. };
  6183. struct AxisOffset {
  6184. Axis axis;
  6185. NonnullRefPtr<StyleValue> offset;
  6186. };
  6187. auto to_axis_offset = [](RefPtr<StyleValue> value) -> ErrorOr<Optional<AxisOffset>> {
  6188. if (value->is_percentage())
  6189. return AxisOffset { Axis::None, value->as_percentage() };
  6190. if (value->is_length())
  6191. return AxisOffset { Axis::None, value->as_length() };
  6192. if (value->is_identifier()) {
  6193. switch (value->to_identifier()) {
  6194. case ValueID::Top:
  6195. return AxisOffset { Axis::Y, TRY(PercentageStyleValue::create(Percentage(0))) };
  6196. case ValueID::Left:
  6197. return AxisOffset { Axis::X, TRY(PercentageStyleValue::create(Percentage(0))) };
  6198. case ValueID::Center:
  6199. return AxisOffset { Axis::None, TRY(PercentageStyleValue::create(Percentage(50))) };
  6200. case ValueID::Bottom:
  6201. return AxisOffset { Axis::Y, TRY(PercentageStyleValue::create(Percentage(100))) };
  6202. case ValueID::Right:
  6203. return AxisOffset { Axis::X, TRY(PercentageStyleValue::create(Percentage(100))) };
  6204. default:
  6205. return OptionalNone {};
  6206. }
  6207. }
  6208. return OptionalNone {};
  6209. };
  6210. auto make_list = [](NonnullRefPtr<StyleValue> const& x_value, NonnullRefPtr<StyleValue> const& y_value) -> ErrorOr<NonnullRefPtr<StyleValueList>> {
  6211. StyleValueVector values;
  6212. values.append(x_value);
  6213. values.append(y_value);
  6214. return StyleValueList::create(move(values), StyleValueList::Separator::Space);
  6215. };
  6216. auto tokens = TokenStream { component_values };
  6217. switch (component_values.size()) {
  6218. case 1: {
  6219. auto single_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  6220. if (!single_value.has_value())
  6221. return nullptr;
  6222. // If only one value is specified, the second value is assumed to be center.
  6223. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  6224. switch (single_value->axis) {
  6225. case Axis::None:
  6226. case Axis::X:
  6227. return make_list(single_value->offset, TRY(PercentageStyleValue::create(Percentage(50))));
  6228. case Axis::Y:
  6229. return make_list(TRY(PercentageStyleValue::create(Percentage(50))), single_value->offset);
  6230. }
  6231. VERIFY_NOT_REACHED();
  6232. }
  6233. case 2: {
  6234. auto first_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  6235. auto second_value = TRY(to_axis_offset(TRY(parse_css_value_for_property(PropertyID::TransformOrigin, tokens))));
  6236. if (!first_value.has_value() || !second_value.has_value())
  6237. return nullptr;
  6238. RefPtr<StyleValue> x_value;
  6239. RefPtr<StyleValue> y_value;
  6240. if (first_value->axis == Axis::X) {
  6241. x_value = first_value->offset;
  6242. } else if (first_value->axis == Axis::Y) {
  6243. y_value = first_value->offset;
  6244. }
  6245. if (second_value->axis == Axis::X) {
  6246. if (x_value)
  6247. return nullptr;
  6248. x_value = second_value->offset;
  6249. // Put the other in Y since its axis can't have been X
  6250. y_value = first_value->offset;
  6251. } else if (second_value->axis == Axis::Y) {
  6252. if (y_value)
  6253. return nullptr;
  6254. y_value = second_value->offset;
  6255. // Put the other in X since its axis can't have been Y
  6256. x_value = first_value->offset;
  6257. } else {
  6258. if (x_value) {
  6259. VERIFY(!y_value);
  6260. y_value = second_value->offset;
  6261. } else {
  6262. VERIFY(!x_value);
  6263. x_value = second_value->offset;
  6264. }
  6265. }
  6266. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  6267. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  6268. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  6269. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  6270. x_value = first_value->offset;
  6271. y_value = second_value->offset;
  6272. }
  6273. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  6274. }
  6275. }
  6276. return nullptr;
  6277. }
  6278. ErrorOr<RefPtr<StyleValue>> Parser::parse_as_css_value(PropertyID property_id)
  6279. {
  6280. auto component_values = parse_a_list_of_component_values(m_token_stream);
  6281. auto tokens = TokenStream(component_values);
  6282. auto parsed_value = parse_css_value(property_id, tokens);
  6283. if (parsed_value.is_error())
  6284. return nullptr;
  6285. return parsed_value.release_value();
  6286. }
  6287. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  6288. {
  6289. if (component_value.is_function()) {
  6290. auto const& function = component_value.function();
  6291. if (function.name().equals_ignoring_ascii_case("calc"sv)) {
  6292. auto calculated_style_value = parse_calculated_value(function.values());
  6293. if (calculated_style_value.is_error() || calculated_style_value.value().is_null()) {
  6294. // FIXME: Propagate error
  6295. return {};
  6296. }
  6297. return GridSize(LengthPercentage { *calculated_style_value.release_value() });
  6298. }
  6299. return {};
  6300. }
  6301. auto token = component_value.token();
  6302. if (token.is(Token::Type::Dimension) && token.dimension_unit().equals_ignoring_ascii_case("fr"sv)) {
  6303. float numeric_value = token.dimension_value();
  6304. if (numeric_value)
  6305. return GridSize(numeric_value);
  6306. }
  6307. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  6308. return GridSize::make_auto();
  6309. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("max-content"sv))
  6310. return GridSize(GridSize::Type::MaxContent);
  6311. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("min-content"sv))
  6312. return GridSize(GridSize::Type::MinContent);
  6313. auto dimension = parse_dimension(token);
  6314. if (!dimension.has_value())
  6315. return {};
  6316. if (dimension->is_length())
  6317. return GridSize(dimension->length());
  6318. else if (dimension->is_percentage())
  6319. return GridSize(dimension->percentage());
  6320. return {};
  6321. }
  6322. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  6323. {
  6324. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  6325. // 'minmax(min, max)'
  6326. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  6327. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  6328. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  6329. auto function_tokens = TokenStream(component_values);
  6330. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  6331. if (comma_separated_list.size() != 2)
  6332. return {};
  6333. TokenStream part_one_tokens { comma_separated_list[0] };
  6334. part_one_tokens.skip_whitespace();
  6335. if (!part_one_tokens.has_next_token())
  6336. return {};
  6337. auto current_token = part_one_tokens.next_token();
  6338. auto min_grid_size = parse_grid_size(current_token);
  6339. TokenStream part_two_tokens { comma_separated_list[1] };
  6340. part_two_tokens.skip_whitespace();
  6341. if (!part_two_tokens.has_next_token())
  6342. return {};
  6343. current_token = part_two_tokens.next_token();
  6344. auto max_grid_size = parse_grid_size(current_token);
  6345. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  6346. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  6347. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  6348. if (min_grid_size.value().is_flexible_length())
  6349. return {};
  6350. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  6351. }
  6352. return {};
  6353. }
  6354. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  6355. {
  6356. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  6357. // 7.2.3.1. Syntax of repeat()
  6358. // The generic form of the repeat() syntax is, approximately,
  6359. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  6360. auto is_auto_fill = false;
  6361. auto is_auto_fit = false;
  6362. auto function_tokens = TokenStream(component_values);
  6363. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  6364. if (comma_separated_list.size() != 2)
  6365. return {};
  6366. // The first argument specifies the number of repetitions.
  6367. TokenStream part_one_tokens { comma_separated_list[0] };
  6368. part_one_tokens.skip_whitespace();
  6369. if (!part_one_tokens.has_next_token())
  6370. return {};
  6371. auto current_token = part_one_tokens.next_token().token();
  6372. auto repeat_count = 0;
  6373. if (current_token.is(Token::Type::Number) && current_token.number().is_integer() && current_token.number_value() > 0)
  6374. repeat_count = current_token.number_value();
  6375. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fill"sv))
  6376. is_auto_fill = true;
  6377. else if (current_token.is(Token::Type::Ident) && current_token.ident().equals_ignoring_ascii_case("auto-fit"sv))
  6378. is_auto_fit = true;
  6379. // The second argument is a track list, which is repeated that number of times.
  6380. TokenStream part_two_tokens { comma_separated_list[1] };
  6381. part_two_tokens.skip_whitespace();
  6382. if (!part_two_tokens.has_next_token())
  6383. return {};
  6384. Vector<CSS::ExplicitGridTrack> repeat_params;
  6385. Vector<Vector<String>> line_names_list;
  6386. auto last_object_was_line_names = false;
  6387. while (part_two_tokens.has_next_token()) {
  6388. auto token = part_two_tokens.next_token();
  6389. Vector<String> line_names;
  6390. if (token.is_block()) {
  6391. if (last_object_was_line_names)
  6392. return {};
  6393. last_object_was_line_names = true;
  6394. if (!token.block().is_square())
  6395. return {};
  6396. TokenStream block_tokens { token.block().values() };
  6397. while (block_tokens.has_next_token()) {
  6398. auto current_block_token = block_tokens.next_token();
  6399. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  6400. if (maybe_string.is_error())
  6401. return {};
  6402. line_names.append(maybe_string.value());
  6403. block_tokens.skip_whitespace();
  6404. }
  6405. line_names_list.append(line_names);
  6406. part_two_tokens.skip_whitespace();
  6407. } else {
  6408. last_object_was_line_names = false;
  6409. auto track_sizing_function = parse_track_sizing_function(token);
  6410. if (!track_sizing_function.has_value())
  6411. return {};
  6412. // However, there are some restrictions:
  6413. // The repeat() notation can’t be nested.
  6414. if (track_sizing_function.value().is_repeat())
  6415. return {};
  6416. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  6417. if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit))
  6418. return {};
  6419. repeat_params.append(track_sizing_function.value());
  6420. part_two_tokens.skip_whitespace();
  6421. }
  6422. }
  6423. while (line_names_list.size() <= repeat_params.size())
  6424. line_names_list.append({});
  6425. // Thus the precise syntax of the repeat() notation has several forms:
  6426. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  6427. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  6428. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  6429. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  6430. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  6431. // fixed number of repetitions.
  6432. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  6433. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  6434. // list, but the same track list can also contain <fixed-repeat>s.
  6435. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  6436. // subgrid keyword and cannot specify track sizes, only line names.
  6437. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  6438. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  6439. // 1fr [b a] 1fr [b].
  6440. if (is_auto_fill)
  6441. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFill);
  6442. else if (is_auto_fit)
  6443. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFit);
  6444. else
  6445. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), repeat_count);
  6446. }
  6447. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  6448. {
  6449. if (token.is_function()) {
  6450. auto const& function_token = token.function();
  6451. if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
  6452. auto maybe_repeat = parse_repeat(function_token.values());
  6453. if (maybe_repeat.has_value())
  6454. return CSS::ExplicitGridTrack(maybe_repeat.value());
  6455. else
  6456. return {};
  6457. } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
  6458. auto maybe_min_max_value = parse_min_max(function_token.values());
  6459. if (maybe_min_max_value.has_value())
  6460. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  6461. else
  6462. return {};
  6463. } else if (auto maybe_dynamic = parse_dynamic_value(token); !maybe_dynamic.is_error() && maybe_dynamic.value()) {
  6464. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_dynamic.release_value()->as_calculated())));
  6465. }
  6466. return {};
  6467. } else if (token.is(Token::Type::Ident) && token.token().ident().equals_ignoring_ascii_case("auto"sv)) {
  6468. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  6469. } else if (token.is_block()) {
  6470. return {};
  6471. } else {
  6472. auto grid_size = parse_grid_size(token);
  6473. if (!grid_size.has_value())
  6474. return {};
  6475. return CSS::ExplicitGridTrack(grid_size.value());
  6476. }
  6477. }
  6478. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_size_list(Vector<ComponentValue> const& component_values, bool allow_separate_line_name_blocks)
  6479. {
  6480. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  6481. auto ident = TRY(parse_identifier_value(component_values.first()));
  6482. if (ident && ident->to_identifier() == ValueID::None) {
  6483. return GridTrackSizeListStyleValue::make_none();
  6484. }
  6485. }
  6486. Vector<CSS::ExplicitGridTrack> track_list;
  6487. Vector<Vector<String>> line_names_list;
  6488. auto last_object_was_line_names = false;
  6489. TokenStream tokens { component_values };
  6490. while (tokens.has_next_token()) {
  6491. auto token = tokens.next_token();
  6492. if (token.is_block()) {
  6493. if (last_object_was_line_names && !allow_separate_line_name_blocks)
  6494. return GridTrackSizeListStyleValue::make_auto();
  6495. last_object_was_line_names = true;
  6496. Vector<String> line_names;
  6497. if (!token.block().is_square())
  6498. return GridTrackSizeListStyleValue::make_auto();
  6499. TokenStream block_tokens { token.block().values() };
  6500. block_tokens.skip_whitespace();
  6501. while (block_tokens.has_next_token()) {
  6502. auto current_block_token = block_tokens.next_token();
  6503. auto maybe_string = String::from_utf8(current_block_token.token().ident());
  6504. if (maybe_string.is_error())
  6505. return nullptr;
  6506. line_names.append(maybe_string.value());
  6507. block_tokens.skip_whitespace();
  6508. }
  6509. line_names_list.append(line_names);
  6510. } else {
  6511. last_object_was_line_names = false;
  6512. auto track_sizing_function = parse_track_sizing_function(token);
  6513. if (!track_sizing_function.has_value())
  6514. return GridTrackSizeListStyleValue::make_auto();
  6515. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6516. // any other ones if the first one is auto-fill, etc.)
  6517. track_list.append(track_sizing_function.value());
  6518. }
  6519. }
  6520. while (line_names_list.size() <= track_list.size())
  6521. line_names_list.append({});
  6522. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
  6523. }
  6524. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_auto_track_sizes(Vector<ComponentValue> const& component_values)
  6525. {
  6526. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  6527. // <track-size>+
  6528. Vector<CSS::ExplicitGridTrack> track_list;
  6529. TokenStream tokens { component_values };
  6530. while (tokens.has_next_token()) {
  6531. auto token = tokens.next_token();
  6532. auto track_sizing_function = parse_track_sizing_function(token);
  6533. if (!track_sizing_function.has_value())
  6534. return GridTrackSizeListStyleValue::make_auto();
  6535. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6536. // any other ones if the first one is auto-fill, etc.)
  6537. track_list.append(track_sizing_function.value());
  6538. }
  6539. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, {}));
  6540. }
  6541. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_placement(Vector<ComponentValue> const& component_values)
  6542. {
  6543. // https://www.w3.org/TR/css-grid-2/#line-placement
  6544. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  6545. // <grid-line> =
  6546. // auto |
  6547. // <custom-ident> |
  6548. // [ <integer> && <custom-ident>? ] |
  6549. // [ span && [ <integer> || <custom-ident> ] ]
  6550. auto is_auto = [](Token token) -> bool {
  6551. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("auto"sv))
  6552. return true;
  6553. return false;
  6554. };
  6555. auto is_span = [](Token token) -> bool {
  6556. if (token.is(Token::Type::Ident) && token.ident().equals_ignoring_ascii_case("span"sv))
  6557. return true;
  6558. return false;
  6559. };
  6560. auto is_valid_integer = [](Token token) -> bool {
  6561. // An <integer> value of zero makes the declaration invalid.
  6562. if (token.is(Token::Type::Number) && token.number().is_integer() && token.number_value() != 0)
  6563. return true;
  6564. return false;
  6565. };
  6566. auto is_line_name = [](Token token) -> bool {
  6567. // The <custom-ident> additionally excludes the keywords span and auto.
  6568. if (token.is(Token::Type::Ident) && !token.ident().equals_ignoring_ascii_case("span"sv) && !token.ident().equals_ignoring_ascii_case("auto"sv))
  6569. return true;
  6570. return false;
  6571. };
  6572. auto tokens = TokenStream { component_values };
  6573. tokens.skip_whitespace();
  6574. auto current_token = tokens.next_token().token();
  6575. if (!tokens.has_next_token()) {
  6576. if (is_auto(current_token))
  6577. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement());
  6578. if (is_span(current_token))
  6579. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(1, true));
  6580. if (is_valid_integer(current_token))
  6581. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(static_cast<int>(current_token.number_value())));
  6582. if (is_line_name(current_token)) {
  6583. auto maybe_string = String::from_utf8(current_token.ident());
  6584. if (!maybe_string.is_error())
  6585. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(maybe_string.value()));
  6586. }
  6587. return nullptr;
  6588. }
  6589. auto span_value = false;
  6590. auto span_or_position_value = 0;
  6591. String line_name_value;
  6592. while (true) {
  6593. if (is_auto(current_token))
  6594. return nullptr;
  6595. if (is_span(current_token)) {
  6596. if (span_value == false)
  6597. span_value = true;
  6598. else
  6599. return nullptr;
  6600. }
  6601. if (is_valid_integer(current_token)) {
  6602. if (span_or_position_value == 0)
  6603. span_or_position_value = static_cast<int>(current_token.number_value());
  6604. else
  6605. return nullptr;
  6606. }
  6607. if (is_line_name(current_token)) {
  6608. if (line_name_value.is_empty()) {
  6609. auto maybe_string = String::from_utf8(current_token.ident());
  6610. if (maybe_string.is_error())
  6611. return nullptr;
  6612. line_name_value = maybe_string.release_value();
  6613. } else {
  6614. return nullptr;
  6615. }
  6616. }
  6617. tokens.skip_whitespace();
  6618. if (tokens.has_next_token())
  6619. current_token = tokens.next_token().token();
  6620. else
  6621. break;
  6622. }
  6623. // Negative integers or zero are invalid.
  6624. if (span_value && span_or_position_value < 1)
  6625. return nullptr;
  6626. // If the <integer> is omitted, it defaults to 1.
  6627. if (span_or_position_value == 0)
  6628. span_or_position_value = 1;
  6629. if (!line_name_value.is_empty())
  6630. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(line_name_value, span_or_position_value, span_value));
  6631. return GridTrackPlacementStyleValue::create(CSS::GridTrackPlacement(span_or_position_value, span_value));
  6632. }
  6633. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_placement_shorthand_value(Vector<ComponentValue> const& component_values)
  6634. {
  6635. auto tokens = TokenStream { component_values };
  6636. auto current_token = tokens.next_token().token();
  6637. Vector<ComponentValue> track_start_placement_tokens;
  6638. while (true) {
  6639. if (current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  6640. break;
  6641. track_start_placement_tokens.append(current_token);
  6642. if (!tokens.has_next_token())
  6643. break;
  6644. current_token = tokens.next_token().token();
  6645. }
  6646. Vector<ComponentValue> track_end_placement_tokens;
  6647. if (tokens.has_next_token()) {
  6648. current_token = tokens.next_token().token();
  6649. while (true) {
  6650. track_end_placement_tokens.append(current_token);
  6651. if (!tokens.has_next_token())
  6652. break;
  6653. current_token = tokens.next_token().token();
  6654. }
  6655. }
  6656. auto parsed_start_value = TRY(parse_grid_track_placement(track_start_placement_tokens));
  6657. if (parsed_start_value && track_end_placement_tokens.is_empty())
  6658. return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement().grid_track_placement());
  6659. auto parsed_end_value = TRY(parse_grid_track_placement(track_end_placement_tokens));
  6660. if (parsed_start_value && parsed_end_value)
  6661. return GridTrackPlacementShorthandStyleValue::create(parsed_start_value.release_nonnull()->as_grid_track_placement(), parsed_end_value.release_nonnull()->as_grid_track_placement());
  6662. return nullptr;
  6663. }
  6664. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  6665. // 7.4. Explicit Grid Shorthand: the grid-template property
  6666. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_track_size_list_shorthand_value(Vector<ComponentValue> const& component_values)
  6667. {
  6668. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  6669. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  6670. // none
  6671. // - Sets all three properties to their initial values (none).
  6672. // <'grid-template-rows'> / <'grid-template-columns'>
  6673. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  6674. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  6675. // - Sets grid-template-areas to the strings listed.
  6676. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  6677. // and splicing in the named lines defined before/after each size.
  6678. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  6679. Vector<ComponentValue> template_rows_tokens;
  6680. Vector<ComponentValue> template_columns_tokens;
  6681. Vector<ComponentValue> template_area_tokens;
  6682. int forward_slash_index = -1;
  6683. for (size_t x = 0; x < component_values.size(); x++) {
  6684. if (component_values[x].is_delim('/')) {
  6685. forward_slash_index = x;
  6686. break;
  6687. }
  6688. }
  6689. for (size_t x = 0; x < (forward_slash_index > -1 ? forward_slash_index : component_values.size()); x++) {
  6690. if (component_values[x].is_token() && component_values[x].token().is(Token::Type::String))
  6691. template_area_tokens.append(component_values[x]);
  6692. else
  6693. template_rows_tokens.append(component_values[x]);
  6694. }
  6695. if (forward_slash_index > -1) {
  6696. for (size_t x = forward_slash_index + 1; x < component_values.size(); x++)
  6697. template_columns_tokens.append(component_values[x]);
  6698. }
  6699. auto parsed_template_areas_values = TRY(parse_grid_template_areas_value(template_area_tokens));
  6700. auto parsed_template_rows_values = TRY(parse_grid_track_size_list(template_rows_tokens, true));
  6701. auto parsed_template_columns_values = TRY(parse_grid_track_size_list(template_columns_tokens));
  6702. return GridTrackSizeListShorthandStyleValue::create(
  6703. parsed_template_areas_values.release_nonnull()->as_grid_template_area(),
  6704. parsed_template_rows_values.release_nonnull()->as_grid_track_size_list(),
  6705. parsed_template_columns_values.release_nonnull()->as_grid_track_size_list());
  6706. }
  6707. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_area_shorthand_value(Vector<ComponentValue> const& component_values)
  6708. {
  6709. auto tokens = TokenStream { component_values };
  6710. Token current_token;
  6711. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  6712. current_token = tokens.next_token().token();
  6713. while (true) {
  6714. if (check_for_delimiter && current_token.is(Token::Type::Delim) && current_token.delim() == "/"sv)
  6715. break;
  6716. placement_tokens.append(current_token);
  6717. tokens.skip_whitespace();
  6718. if (!tokens.has_next_token())
  6719. break;
  6720. current_token = tokens.next_token().token();
  6721. }
  6722. };
  6723. Vector<ComponentValue> row_start_placement_tokens;
  6724. parse_placement_tokens(row_start_placement_tokens);
  6725. Vector<ComponentValue> column_start_placement_tokens;
  6726. if (tokens.has_next_token())
  6727. parse_placement_tokens(column_start_placement_tokens);
  6728. Vector<ComponentValue> row_end_placement_tokens;
  6729. if (tokens.has_next_token())
  6730. parse_placement_tokens(row_end_placement_tokens);
  6731. Vector<ComponentValue> column_end_placement_tokens;
  6732. if (tokens.has_next_token())
  6733. parse_placement_tokens(column_end_placement_tokens, false);
  6734. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  6735. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  6736. // grid-column-end.
  6737. auto row_start_style_value = TRY(parse_grid_track_placement(row_start_placement_tokens));
  6738. auto column_start_style_value = TRY(parse_grid_track_placement(column_start_placement_tokens));
  6739. auto row_end_style_value = TRY(parse_grid_track_placement(row_end_placement_tokens));
  6740. auto column_end_style_value = TRY(parse_grid_track_placement(column_end_placement_tokens));
  6741. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  6742. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  6743. // fourth value.
  6744. auto row_start = GridTrackPlacement::make_auto();
  6745. auto column_start = GridTrackPlacement::make_auto();
  6746. auto row_end = GridTrackPlacement::make_auto();
  6747. auto column_end = GridTrackPlacement::make_auto();
  6748. if (row_start_style_value)
  6749. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6750. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  6751. // that value. Otherwise, it is set to auto.
  6752. if (column_start_style_value)
  6753. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6754. else
  6755. column_start = row_start;
  6756. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  6757. // <custom-ident>; otherwise, it is set to auto.
  6758. if (row_end_style_value)
  6759. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6760. else
  6761. row_end = column_start;
  6762. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  6763. // that <custom-ident>; otherwise, it is set to auto.
  6764. if (column_end_style_value)
  6765. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6766. else
  6767. column_end = row_end;
  6768. return GridAreaShorthandStyleValue::create(row_start, column_start, row_end, column_end);
  6769. }
  6770. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_shorthand_value(Vector<ComponentValue> const& component_value)
  6771. {
  6772. // <'grid-template'> |
  6773. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  6774. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  6775. return parse_grid_track_size_list_shorthand_value(component_value);
  6776. }
  6777. ErrorOr<RefPtr<StyleValue>> Parser::parse_grid_template_areas_value(Vector<ComponentValue> const& component_values)
  6778. {
  6779. Vector<Vector<String>> grid_area_rows;
  6780. for (auto& component_value : component_values) {
  6781. Vector<String> grid_area_columns;
  6782. if (component_value.is(Token::Type::String)) {
  6783. auto const parts = TRY(TRY(String::from_utf8(component_value.token().string())).split(' '));
  6784. for (auto& part : parts) {
  6785. grid_area_columns.append(part);
  6786. }
  6787. }
  6788. grid_area_rows.append(move(grid_area_columns));
  6789. }
  6790. return GridTemplateAreaStyleValue::create(grid_area_rows);
  6791. }
  6792. static bool block_contains_var_or_attr(Block const& block);
  6793. static bool function_contains_var_or_attr(Function const& function)
  6794. {
  6795. if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
  6796. return true;
  6797. for (auto const& token : function.values()) {
  6798. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6799. return true;
  6800. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6801. return true;
  6802. }
  6803. return false;
  6804. }
  6805. bool block_contains_var_or_attr(Block const& block)
  6806. {
  6807. for (auto const& token : block.values()) {
  6808. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6809. return true;
  6810. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6811. return true;
  6812. }
  6813. return false;
  6814. };
  6815. Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6816. {
  6817. // FIXME: This is a hack. Until we can reasonably combine the error types, just log the error
  6818. // and return ParseError::InternalError if we get an AK::Error result.
  6819. #define FIXME_TRY(expression) \
  6820. ({ \
  6821. /* Ignore -Wshadow to allow nesting the macro. */ \
  6822. AK_IGNORE_DIAGNOSTIC("-Wshadow", \
  6823. auto&& _temporary_result = (expression)); \
  6824. if (_temporary_result.is_error()) [[unlikely]] { \
  6825. dbgln("System error when parsing style value: {}", _temporary_result.release_error()); \
  6826. return ParseError::InternalError; \
  6827. } \
  6828. _temporary_result.release_value(); \
  6829. })
  6830. m_context.set_current_property_id(property_id);
  6831. Vector<ComponentValue> component_values;
  6832. bool contains_var_or_attr = false;
  6833. while (tokens.has_next_token()) {
  6834. auto const& token = tokens.next_token();
  6835. if (token.is(Token::Type::Semicolon)) {
  6836. tokens.reconsume_current_input_token();
  6837. break;
  6838. }
  6839. if (property_id != PropertyID::Custom) {
  6840. if (token.is(Token::Type::Whitespace))
  6841. continue;
  6842. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  6843. return ParseError::IncludesIgnoredVendorPrefix;
  6844. }
  6845. if (!contains_var_or_attr) {
  6846. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6847. contains_var_or_attr = true;
  6848. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  6849. contains_var_or_attr = true;
  6850. }
  6851. component_values.append(token);
  6852. }
  6853. if (property_id == PropertyID::Custom || contains_var_or_attr)
  6854. return FIXME_TRY(UnresolvedStyleValue::create(move(component_values), contains_var_or_attr));
  6855. if (component_values.is_empty())
  6856. return ParseError::SyntaxError;
  6857. if (component_values.size() == 1) {
  6858. if (auto parsed_value = FIXME_TRY(parse_builtin_value(component_values.first())))
  6859. return parsed_value.release_nonnull();
  6860. }
  6861. // Special-case property handling
  6862. switch (property_id) {
  6863. case PropertyID::AspectRatio:
  6864. if (auto parsed_value = FIXME_TRY(parse_aspect_ratio_value(component_values)))
  6865. return parsed_value.release_nonnull();
  6866. return ParseError::SyntaxError;
  6867. case PropertyID::BackdropFilter:
  6868. if (auto parsed_value = FIXME_TRY(parse_filter_value_list_value(component_values)))
  6869. return parsed_value.release_nonnull();
  6870. return ParseError::SyntaxError;
  6871. case PropertyID::Background:
  6872. if (auto parsed_value = FIXME_TRY(parse_background_value(component_values)))
  6873. return parsed_value.release_nonnull();
  6874. return ParseError::SyntaxError;
  6875. case PropertyID::BackgroundAttachment:
  6876. case PropertyID::BackgroundClip:
  6877. case PropertyID::BackgroundImage:
  6878. case PropertyID::BackgroundOrigin:
  6879. if (auto parsed_value = FIXME_TRY(parse_simple_comma_separated_value_list(property_id, component_values)))
  6880. return parsed_value.release_nonnull();
  6881. return ParseError::SyntaxError;
  6882. case PropertyID::BackgroundPosition:
  6883. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); })))
  6884. return parsed_value.release_nonnull();
  6885. return ParseError::SyntaxError;
  6886. case PropertyID::BackgroundPositionX:
  6887. case PropertyID::BackgroundPositionY:
  6888. 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); })))
  6889. return parsed_value.release_nonnull();
  6890. return ParseError::SyntaxError;
  6891. case PropertyID::BackgroundRepeat:
  6892. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); })))
  6893. return parsed_value.release_nonnull();
  6894. return ParseError::SyntaxError;
  6895. case PropertyID::BackgroundSize:
  6896. if (auto parsed_value = FIXME_TRY(parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); })))
  6897. return parsed_value.release_nonnull();
  6898. return ParseError::SyntaxError;
  6899. case PropertyID::Border:
  6900. case PropertyID::BorderBottom:
  6901. case PropertyID::BorderLeft:
  6902. case PropertyID::BorderRight:
  6903. case PropertyID::BorderTop:
  6904. if (auto parsed_value = FIXME_TRY(parse_border_value(component_values)))
  6905. return parsed_value.release_nonnull();
  6906. return ParseError::SyntaxError;
  6907. case PropertyID::BorderTopLeftRadius:
  6908. case PropertyID::BorderTopRightRadius:
  6909. case PropertyID::BorderBottomRightRadius:
  6910. case PropertyID::BorderBottomLeftRadius:
  6911. if (auto parsed_value = FIXME_TRY(parse_border_radius_value(component_values)))
  6912. return parsed_value.release_nonnull();
  6913. return ParseError::SyntaxError;
  6914. case PropertyID::BorderRadius:
  6915. if (auto parsed_value = FIXME_TRY(parse_border_radius_shorthand_value(component_values)))
  6916. return parsed_value.release_nonnull();
  6917. return ParseError::SyntaxError;
  6918. case PropertyID::BoxShadow:
  6919. if (auto parsed_value = FIXME_TRY(parse_shadow_value(component_values, AllowInsetKeyword::Yes)))
  6920. return parsed_value.release_nonnull();
  6921. return ParseError::SyntaxError;
  6922. case PropertyID::Content:
  6923. if (auto parsed_value = FIXME_TRY(parse_content_value(component_values)))
  6924. return parsed_value.release_nonnull();
  6925. return ParseError::SyntaxError;
  6926. case PropertyID::Display:
  6927. if (auto parsed_value = FIXME_TRY(parse_display_value(component_values)))
  6928. return parsed_value.release_nonnull();
  6929. return ParseError::SyntaxError;
  6930. case PropertyID::Flex:
  6931. if (auto parsed_value = FIXME_TRY(parse_flex_value(component_values)))
  6932. return parsed_value.release_nonnull();
  6933. return ParseError::SyntaxError;
  6934. case PropertyID::FlexFlow:
  6935. if (auto parsed_value = FIXME_TRY(parse_flex_flow_value(component_values)))
  6936. return parsed_value.release_nonnull();
  6937. return ParseError::SyntaxError;
  6938. case PropertyID::Font:
  6939. if (auto parsed_value = FIXME_TRY(parse_font_value(component_values)))
  6940. return parsed_value.release_nonnull();
  6941. return ParseError::SyntaxError;
  6942. case PropertyID::FontFamily: {
  6943. auto tokens_without_whitespace = TokenStream { component_values };
  6944. if (auto parsed_value = FIXME_TRY(parse_font_family_value(tokens_without_whitespace)))
  6945. return parsed_value.release_nonnull();
  6946. return ParseError::SyntaxError;
  6947. }
  6948. case PropertyID::GridColumn:
  6949. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement_shorthand_value(component_values)))
  6950. return parsed_value.release_nonnull();
  6951. return ParseError::SyntaxError;
  6952. case PropertyID::GridArea:
  6953. if (auto parsed_value = FIXME_TRY(parse_grid_area_shorthand_value(component_values)))
  6954. return parsed_value.release_nonnull();
  6955. return ParseError::SyntaxError;
  6956. case PropertyID::GridTemplateAreas:
  6957. if (auto parsed_value = FIXME_TRY(parse_grid_template_areas_value(component_values)))
  6958. return parsed_value.release_nonnull();
  6959. return ParseError::SyntaxError;
  6960. case PropertyID::GridColumnEnd:
  6961. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6962. return parsed_value.release_nonnull();
  6963. return ParseError::SyntaxError;
  6964. case PropertyID::GridColumnStart:
  6965. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6966. return parsed_value.release_nonnull();
  6967. return ParseError::SyntaxError;
  6968. case PropertyID::GridRow:
  6969. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement_shorthand_value(component_values)))
  6970. return parsed_value.release_nonnull();
  6971. return ParseError::SyntaxError;
  6972. case PropertyID::GridRowEnd:
  6973. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6974. return parsed_value.release_nonnull();
  6975. return ParseError::SyntaxError;
  6976. case PropertyID::GridRowStart:
  6977. if (auto parsed_value = FIXME_TRY(parse_grid_track_placement(component_values)))
  6978. return parsed_value.release_nonnull();
  6979. return ParseError::SyntaxError;
  6980. case PropertyID::Grid:
  6981. if (auto parsed_value = FIXME_TRY(parse_grid_shorthand_value(component_values)))
  6982. return parsed_value.release_nonnull();
  6983. return ParseError::SyntaxError;
  6984. case PropertyID::GridTemplate:
  6985. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list_shorthand_value(component_values)))
  6986. return parsed_value.release_nonnull();
  6987. return ParseError::SyntaxError;
  6988. case PropertyID::GridTemplateColumns:
  6989. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list(component_values)))
  6990. return parsed_value.release_nonnull();
  6991. return ParseError::SyntaxError;
  6992. case PropertyID::GridTemplateRows:
  6993. if (auto parsed_value = FIXME_TRY(parse_grid_track_size_list(component_values)))
  6994. return parsed_value.release_nonnull();
  6995. return ParseError::SyntaxError;
  6996. case PropertyID::GridAutoColumns:
  6997. if (auto parsed_value = FIXME_TRY(parse_grid_auto_track_sizes(component_values)))
  6998. return parsed_value.release_nonnull();
  6999. return ParseError::SyntaxError;
  7000. case PropertyID::GridAutoRows:
  7001. if (auto parsed_value = FIXME_TRY(parse_grid_auto_track_sizes(component_values)))
  7002. return parsed_value.release_nonnull();
  7003. return ParseError::SyntaxError;
  7004. case PropertyID::ListStyle:
  7005. if (auto parsed_value = FIXME_TRY(parse_list_style_value(component_values)))
  7006. return parsed_value.release_nonnull();
  7007. return ParseError::SyntaxError;
  7008. case PropertyID::Overflow:
  7009. if (auto parsed_value = FIXME_TRY(parse_overflow_value(component_values)))
  7010. return parsed_value.release_nonnull();
  7011. return ParseError::SyntaxError;
  7012. case PropertyID::PlaceContent:
  7013. if (auto parsed_value = FIXME_TRY(parse_place_content_value(component_values)))
  7014. return parsed_value.release_nonnull();
  7015. return ParseError::SyntaxError;
  7016. case PropertyID::TextDecoration:
  7017. if (auto parsed_value = FIXME_TRY(parse_text_decoration_value(component_values)))
  7018. return parsed_value.release_nonnull();
  7019. return ParseError::SyntaxError;
  7020. case PropertyID::TextDecorationLine: {
  7021. TokenStream value_tokens { component_values };
  7022. auto parsed_value = FIXME_TRY(parse_text_decoration_line_value(value_tokens));
  7023. if (parsed_value && !value_tokens.has_next_token())
  7024. return parsed_value.release_nonnull();
  7025. return ParseError::SyntaxError;
  7026. }
  7027. case PropertyID::TextShadow:
  7028. if (auto parsed_value = FIXME_TRY(parse_shadow_value(component_values, AllowInsetKeyword::No)))
  7029. return parsed_value.release_nonnull();
  7030. return ParseError::SyntaxError;
  7031. case PropertyID::Transform:
  7032. if (auto parsed_value = FIXME_TRY(parse_transform_value(component_values)))
  7033. return parsed_value.release_nonnull();
  7034. return ParseError::SyntaxError;
  7035. case PropertyID::TransformOrigin:
  7036. if (auto parsed_value = FIXME_TRY(parse_transform_origin_value(component_values)))
  7037. return parsed_value.release_nonnull();
  7038. return ParseError ::SyntaxError;
  7039. default:
  7040. break;
  7041. }
  7042. // If there's only 1 ComponentValue, we can only produce a single StyleValue.
  7043. if (component_values.size() == 1) {
  7044. auto stream = TokenStream { component_values };
  7045. if (auto parsed_value = FIXME_TRY(parse_css_value_for_property(property_id, stream)))
  7046. return parsed_value.release_nonnull();
  7047. return ParseError::SyntaxError;
  7048. }
  7049. // Multiple ComponentValues will usually produce multiple StyleValues, so make a StyleValueList.
  7050. {
  7051. StyleValueVector parsed_values;
  7052. auto stream = TokenStream { component_values };
  7053. while (auto parsed_value = FIXME_TRY(parse_css_value_for_property(property_id, stream))) {
  7054. FIXME_TRY(parsed_values.try_append(parsed_value.release_nonnull()));
  7055. if (!stream.has_next_token())
  7056. break;
  7057. }
  7058. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 StyleValue, return it directly.
  7059. if (parsed_values.size() == 1)
  7060. return *parsed_values.take_first();
  7061. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  7062. return FIXME_TRY(StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space));
  7063. }
  7064. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  7065. auto unassigned_properties = longhands_for_shorthand(property_id);
  7066. if (unassigned_properties.is_empty())
  7067. return ParseError::SyntaxError;
  7068. auto stream = TokenStream { component_values };
  7069. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<StyleValue const>>> assigned_values;
  7070. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  7071. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  7072. if (!property_and_value.is_error() && property_and_value.value().style_value) {
  7073. auto property = property_and_value.value().property;
  7074. auto value = property_and_value.release_value().style_value;
  7075. auto& values = assigned_values.ensure(to_underlying(property));
  7076. if (values.size() + 1 == property_maximum_value_count(property)) {
  7077. // We're done with this property, move on to the next one.
  7078. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  7079. }
  7080. values.append(value.release_nonnull());
  7081. continue;
  7082. }
  7083. // No property matched, so we're done.
  7084. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.peek_token().to_debug_string());
  7085. for (auto id : unassigned_properties)
  7086. dbgln(" {}", string_from_property_id(id));
  7087. break;
  7088. }
  7089. for (auto& property : unassigned_properties)
  7090. assigned_values.ensure(to_underlying(property)).append(FIXME_TRY(property_initial_value(m_context.realm(), property)));
  7091. stream.skip_whitespace();
  7092. if (stream.has_next_token())
  7093. return ParseError::SyntaxError;
  7094. Vector<PropertyID> longhand_properties;
  7095. longhand_properties.ensure_capacity(assigned_values.size());
  7096. for (auto& it : assigned_values)
  7097. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  7098. StyleValueVector longhand_values;
  7099. longhand_values.ensure_capacity(assigned_values.size());
  7100. for (auto& it : assigned_values) {
  7101. if (it.value.size() == 1)
  7102. longhand_values.unchecked_append(it.value.take_first());
  7103. else
  7104. longhand_values.unchecked_append(FIXME_TRY(StyleValueList::create(move(it.value), StyleValueList::Separator::Space)));
  7105. }
  7106. return { FIXME_TRY(CompositeStyleValue::create(move(longhand_properties), move(longhand_values))) };
  7107. #undef FIXME_TRY
  7108. }
  7109. ErrorOr<RefPtr<StyleValue>> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  7110. {
  7111. auto result = parse_css_value_for_properties({ &property_id, 1 }, tokens);
  7112. if (result.is_error())
  7113. return result.release_error();
  7114. return result.value().style_value;
  7115. }
  7116. ErrorOr<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  7117. {
  7118. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  7119. for (auto const& property : property_ids) {
  7120. if (property_accepts_type(property, value_type))
  7121. return property;
  7122. }
  7123. return {};
  7124. };
  7125. auto any_property_accepts_identifier = [](ReadonlySpan<PropertyID> property_ids, ValueID identifier) -> Optional<PropertyID> {
  7126. for (auto const& property : property_ids) {
  7127. if (property_accepts_identifier(property, identifier))
  7128. return property;
  7129. }
  7130. return {};
  7131. };
  7132. auto& peek_token = tokens.peek_token();
  7133. if (peek_token.is(Token::Type::Ident)) {
  7134. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  7135. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  7136. auto ident = value_id_from_string(peek_token.token().ident());
  7137. if (ident.has_value()) {
  7138. if (auto property = any_property_accepts_identifier(property_ids, ident.value()); property.has_value()) {
  7139. (void)tokens.next_token();
  7140. return PropertyAndValue { *property, TRY(IdentifierStyleValue::create(ident.value())) };
  7141. }
  7142. }
  7143. // Custom idents
  7144. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  7145. (void)tokens.next_token();
  7146. return PropertyAndValue { *property, TRY(CustomIdentStyleValue::create(TRY(FlyString::from_utf8(peek_token.token().ident())))) };
  7147. }
  7148. }
  7149. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  7150. if (auto maybe_color = TRY(parse_color_value(peek_token))) {
  7151. (void)tokens.next_token();
  7152. return PropertyAndValue { *property, maybe_color };
  7153. }
  7154. }
  7155. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  7156. if (auto maybe_image = TRY(parse_image_value(peek_token))) {
  7157. (void)tokens.next_token();
  7158. return PropertyAndValue { *property, maybe_image };
  7159. }
  7160. }
  7161. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  7162. if (auto maybe_ratio = TRY(parse_ratio_value(tokens)))
  7163. return PropertyAndValue { *property, maybe_ratio };
  7164. }
  7165. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  7166. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  7167. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  7168. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  7169. if (property_accepting_integer.has_value()) {
  7170. auto transaction = tokens.begin_transaction();
  7171. if (auto integer = TRY(parse_integer_value(tokens)); integer && property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  7172. transaction.commit();
  7173. return PropertyAndValue { *property_accepting_integer, integer };
  7174. }
  7175. }
  7176. if (property_accepting_number.has_value()) {
  7177. auto transaction = tokens.begin_transaction();
  7178. if (auto number = TRY(parse_number_value(tokens)); number && property_accepts_number(*property_accepting_number, number->as_number().number())) {
  7179. transaction.commit();
  7180. return PropertyAndValue { *property_accepting_number, number };
  7181. }
  7182. }
  7183. }
  7184. if (peek_token.is(Token::Type::Percentage)) {
  7185. auto percentage = Percentage(peek_token.token().percentage());
  7186. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  7187. (void)tokens.next_token();
  7188. return PropertyAndValue { *property, TRY(PercentageStyleValue::create(percentage)) };
  7189. }
  7190. }
  7191. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  7192. if (auto maybe_rect = TRY(parse_rect_value(peek_token))) {
  7193. (void)tokens.next_token();
  7194. return PropertyAndValue { *property, maybe_rect };
  7195. }
  7196. }
  7197. if (peek_token.is(Token::Type::String)) {
  7198. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  7199. return PropertyAndValue { *property, TRY(StringStyleValue::create(TRY(String::from_utf8(tokens.next_token().token().string())))) };
  7200. }
  7201. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  7202. if (auto url = TRY(parse_url_value(peek_token))) {
  7203. (void)tokens.next_token();
  7204. return PropertyAndValue { *property, url };
  7205. }
  7206. }
  7207. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  7208. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  7209. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  7210. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  7211. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  7212. if (property_accepts_dimension) {
  7213. auto transaction = tokens.begin_transaction();
  7214. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  7215. (void)tokens.next_token();
  7216. auto dimension = maybe_dimension.release_value();
  7217. if (dimension.is_angle()) {
  7218. auto angle = dimension.angle();
  7219. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  7220. transaction.commit();
  7221. return PropertyAndValue { *property, TRY(AngleStyleValue::create(angle)) };
  7222. }
  7223. }
  7224. if (dimension.is_frequency()) {
  7225. auto frequency = dimension.frequency();
  7226. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  7227. transaction.commit();
  7228. return PropertyAndValue { *property, TRY(FrequencyStyleValue::create(frequency)) };
  7229. }
  7230. }
  7231. if (dimension.is_length()) {
  7232. auto length = dimension.length();
  7233. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  7234. transaction.commit();
  7235. return PropertyAndValue { *property, TRY(LengthStyleValue::create(length)) };
  7236. }
  7237. }
  7238. if (dimension.is_resolution()) {
  7239. auto resolution = dimension.resolution();
  7240. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  7241. transaction.commit();
  7242. return PropertyAndValue { *property, TRY(ResolutionStyleValue::create(resolution)) };
  7243. }
  7244. }
  7245. if (dimension.is_time()) {
  7246. auto time = dimension.time();
  7247. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  7248. transaction.commit();
  7249. return PropertyAndValue { *property, TRY(TimeStyleValue::create(time)) };
  7250. }
  7251. }
  7252. }
  7253. }
  7254. // In order to not end up parsing `calc()` and other math expressions multiple times,
  7255. // we parse it once, and then see if its resolved type matches what the property accepts.
  7256. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  7257. if (auto maybe_dynamic = TRY(parse_dynamic_value(peek_token)); maybe_dynamic && maybe_dynamic->is_calculated()) {
  7258. (void)tokens.next_token();
  7259. auto& calculated = maybe_dynamic->as_calculated();
  7260. switch (calculated.resolved_type()) {
  7261. case CalculatedStyleValue::ResolvedType::Angle:
  7262. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  7263. return PropertyAndValue { *property, calculated };
  7264. break;
  7265. case CalculatedStyleValue::ResolvedType::Frequency:
  7266. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  7267. return PropertyAndValue { *property, calculated };
  7268. break;
  7269. case CalculatedStyleValue::ResolvedType::Integer:
  7270. case CalculatedStyleValue::ResolvedType::Number:
  7271. if (property_accepts_numeric) {
  7272. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  7273. return PropertyAndValue { property_or_resolved, calculated };
  7274. }
  7275. break;
  7276. case CalculatedStyleValue::ResolvedType::Length:
  7277. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  7278. return PropertyAndValue { *property, calculated };
  7279. break;
  7280. case CalculatedStyleValue::ResolvedType::Percentage:
  7281. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  7282. return PropertyAndValue { *property, calculated };
  7283. break;
  7284. case CalculatedStyleValue::ResolvedType::Time:
  7285. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  7286. return PropertyAndValue { *property, calculated };
  7287. break;
  7288. }
  7289. }
  7290. }
  7291. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  7292. if (auto value = TRY(parse_paint_value(tokens)))
  7293. return PropertyAndValue { *property, value.release_nonnull() };
  7294. }
  7295. return PropertyAndValue { property_ids.first(), nullptr };
  7296. }
  7297. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<ComponentValue>& values)
  7298. {
  7299. auto transaction = values.begin_transaction();
  7300. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  7301. if constexpr (CSS_PARSER_DEBUG) {
  7302. dbgln_if(CSS_PARSER_DEBUG, "Invalid An+B value:");
  7303. values.dump_all_tokens();
  7304. }
  7305. return {};
  7306. };
  7307. auto is_n = [](ComponentValue const& value) -> bool {
  7308. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n"sv);
  7309. };
  7310. auto is_ndash = [](ComponentValue const& value) -> bool {
  7311. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("n-"sv);
  7312. };
  7313. auto is_dashn = [](ComponentValue const& value) -> bool {
  7314. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n"sv);
  7315. };
  7316. auto is_dashndash = [](ComponentValue const& value) -> bool {
  7317. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_ascii_case("-n-"sv);
  7318. };
  7319. auto is_sign = [](ComponentValue const& value) -> bool {
  7320. return value.is(Token::Type::Delim) && (value.token().delim() == '+' || value.token().delim() == '-');
  7321. };
  7322. auto is_n_dimension = [](ComponentValue const& value) -> bool {
  7323. if (!value.is(Token::Type::Dimension))
  7324. return false;
  7325. if (!value.token().number().is_integer())
  7326. return false;
  7327. if (!value.token().dimension_unit().equals_ignoring_ascii_case("n"sv))
  7328. return false;
  7329. return true;
  7330. };
  7331. auto is_ndash_dimension = [](ComponentValue const& value) -> bool {
  7332. if (!value.is(Token::Type::Dimension))
  7333. return false;
  7334. if (!value.token().number().is_integer())
  7335. return false;
  7336. if (!value.token().dimension_unit().equals_ignoring_ascii_case("n-"sv))
  7337. return false;
  7338. return true;
  7339. };
  7340. auto is_ndashdigit_dimension = [](ComponentValue const& value) -> bool {
  7341. if (!value.is(Token::Type::Dimension))
  7342. return false;
  7343. if (!value.token().number().is_integer())
  7344. return false;
  7345. auto dimension_unit = value.token().dimension_unit();
  7346. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  7347. return false;
  7348. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  7349. if (!is_ascii_digit(dimension_unit[i]))
  7350. return false;
  7351. }
  7352. return true;
  7353. };
  7354. auto is_ndashdigit_ident = [](ComponentValue const& value) -> bool {
  7355. if (!value.is(Token::Type::Ident))
  7356. return false;
  7357. auto ident = value.token().ident();
  7358. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  7359. return false;
  7360. for (size_t i = 2; i < ident.length(); ++i) {
  7361. if (!is_ascii_digit(ident[i]))
  7362. return false;
  7363. }
  7364. return true;
  7365. };
  7366. auto is_dashndashdigit_ident = [](ComponentValue const& value) -> bool {
  7367. if (!value.is(Token::Type::Ident))
  7368. return false;
  7369. auto ident = value.token().ident();
  7370. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  7371. return false;
  7372. if (ident.length() == 3)
  7373. return false;
  7374. for (size_t i = 3; i < ident.length(); ++i) {
  7375. if (!is_ascii_digit(ident[i]))
  7376. return false;
  7377. }
  7378. return true;
  7379. };
  7380. auto is_integer = [](ComponentValue const& value) -> bool {
  7381. return value.is(Token::Type::Number) && value.token().number().is_integer();
  7382. };
  7383. auto is_signed_integer = [](ComponentValue const& value) -> bool {
  7384. return value.is(Token::Type::Number) && value.token().number().is_integer_with_explicit_sign();
  7385. };
  7386. auto is_signless_integer = [](ComponentValue const& value) -> bool {
  7387. return value.is(Token::Type::Number) && !value.token().number().is_integer_with_explicit_sign();
  7388. };
  7389. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  7390. // Unfortunately these can't be in the same order as in the spec.
  7391. values.skip_whitespace();
  7392. auto const& first_value = values.next_token();
  7393. // odd | even
  7394. if (first_value.is(Token::Type::Ident)) {
  7395. auto ident = first_value.token().ident();
  7396. if (ident.equals_ignoring_ascii_case("odd"sv)) {
  7397. transaction.commit();
  7398. return Selector::SimpleSelector::ANPlusBPattern { 2, 1 };
  7399. }
  7400. if (ident.equals_ignoring_ascii_case("even"sv)) {
  7401. transaction.commit();
  7402. return Selector::SimpleSelector::ANPlusBPattern { 2, 0 };
  7403. }
  7404. }
  7405. // <integer>
  7406. if (is_integer(first_value)) {
  7407. int b = first_value.token().to_integer();
  7408. transaction.commit();
  7409. return Selector::SimpleSelector::ANPlusBPattern { 0, b };
  7410. }
  7411. // <n-dimension>
  7412. // <n-dimension> <signed-integer>
  7413. // <n-dimension> ['+' | '-'] <signless-integer>
  7414. if (is_n_dimension(first_value)) {
  7415. int a = first_value.token().dimension_value_int();
  7416. values.skip_whitespace();
  7417. // <n-dimension> <signed-integer>
  7418. if (is_signed_integer(values.peek_token())) {
  7419. int b = values.next_token().token().to_integer();
  7420. transaction.commit();
  7421. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  7422. }
  7423. // <n-dimension> ['+' | '-'] <signless-integer>
  7424. {
  7425. auto child_transaction = transaction.create_child();
  7426. auto const& second_value = values.next_token();
  7427. values.skip_whitespace();
  7428. auto const& third_value = values.next_token();
  7429. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7430. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7431. child_transaction.commit();
  7432. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  7433. }
  7434. }
  7435. // <n-dimension>
  7436. transaction.commit();
  7437. return Selector::SimpleSelector::ANPlusBPattern { a, 0 };
  7438. }
  7439. // <ndash-dimension> <signless-integer>
  7440. if (is_ndash_dimension(first_value)) {
  7441. values.skip_whitespace();
  7442. auto const& second_value = values.next_token();
  7443. if (is_signless_integer(second_value)) {
  7444. int a = first_value.token().dimension_value_int();
  7445. int b = -second_value.token().to_integer();
  7446. transaction.commit();
  7447. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  7448. }
  7449. return syntax_error();
  7450. }
  7451. // <ndashdigit-dimension>
  7452. if (is_ndashdigit_dimension(first_value)) {
  7453. auto const& dimension = first_value.token();
  7454. int a = dimension.dimension_value_int();
  7455. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  7456. if (maybe_b.has_value()) {
  7457. transaction.commit();
  7458. return Selector::SimpleSelector::ANPlusBPattern { a, maybe_b.value() };
  7459. }
  7460. return syntax_error();
  7461. }
  7462. // <dashndashdigit-ident>
  7463. if (is_dashndashdigit_ident(first_value)) {
  7464. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  7465. if (maybe_b.has_value()) {
  7466. transaction.commit();
  7467. return Selector::SimpleSelector::ANPlusBPattern { -1, maybe_b.value() };
  7468. }
  7469. return syntax_error();
  7470. }
  7471. // -n
  7472. // -n <signed-integer>
  7473. // -n ['+' | '-'] <signless-integer>
  7474. if (is_dashn(first_value)) {
  7475. values.skip_whitespace();
  7476. // -n <signed-integer>
  7477. if (is_signed_integer(values.peek_token())) {
  7478. int b = values.next_token().token().to_integer();
  7479. transaction.commit();
  7480. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7481. }
  7482. // -n ['+' | '-'] <signless-integer>
  7483. {
  7484. auto child_transaction = transaction.create_child();
  7485. auto const& second_value = values.next_token();
  7486. values.skip_whitespace();
  7487. auto const& third_value = values.next_token();
  7488. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7489. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7490. child_transaction.commit();
  7491. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7492. }
  7493. }
  7494. // -n
  7495. transaction.commit();
  7496. return Selector::SimpleSelector::ANPlusBPattern { -1, 0 };
  7497. }
  7498. // -n- <signless-integer>
  7499. if (is_dashndash(first_value)) {
  7500. values.skip_whitespace();
  7501. auto const& second_value = values.next_token();
  7502. if (is_signless_integer(second_value)) {
  7503. int b = -second_value.token().to_integer();
  7504. transaction.commit();
  7505. return Selector::SimpleSelector::ANPlusBPattern { -1, b };
  7506. }
  7507. return syntax_error();
  7508. }
  7509. // All that's left now are these:
  7510. // '+'?† n
  7511. // '+'?† n <signed-integer>
  7512. // '+'?† n ['+' | '-'] <signless-integer>
  7513. // '+'?† n- <signless-integer>
  7514. // '+'?† <ndashdigit-ident>
  7515. // In all of these cases, the + is optional, and has no effect.
  7516. // So, we just skip the +, and carry on.
  7517. if (!first_value.is_delim('+')) {
  7518. values.reconsume_current_input_token();
  7519. // We do *not* skip whitespace here.
  7520. }
  7521. auto const& first_after_plus = values.next_token();
  7522. // '+'?† n
  7523. // '+'?† n <signed-integer>
  7524. // '+'?† n ['+' | '-'] <signless-integer>
  7525. if (is_n(first_after_plus)) {
  7526. values.skip_whitespace();
  7527. // '+'?† n <signed-integer>
  7528. if (is_signed_integer(values.peek_token())) {
  7529. int b = values.next_token().token().to_integer();
  7530. transaction.commit();
  7531. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7532. }
  7533. // '+'?† n ['+' | '-'] <signless-integer>
  7534. {
  7535. auto child_transaction = transaction.create_child();
  7536. auto const& second_value = values.next_token();
  7537. values.skip_whitespace();
  7538. auto const& third_value = values.next_token();
  7539. if (is_sign(second_value) && is_signless_integer(third_value)) {
  7540. int b = third_value.token().to_integer() * (second_value.is_delim('+') ? 1 : -1);
  7541. child_transaction.commit();
  7542. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7543. }
  7544. }
  7545. // '+'?† n
  7546. transaction.commit();
  7547. return Selector::SimpleSelector::ANPlusBPattern { 1, 0 };
  7548. }
  7549. // '+'?† n- <signless-integer>
  7550. if (is_ndash(first_after_plus)) {
  7551. values.skip_whitespace();
  7552. auto const& second_value = values.next_token();
  7553. if (is_signless_integer(second_value)) {
  7554. int b = -second_value.token().to_integer();
  7555. transaction.commit();
  7556. return Selector::SimpleSelector::ANPlusBPattern { 1, b };
  7557. }
  7558. return syntax_error();
  7559. }
  7560. // '+'?† <ndashdigit-ident>
  7561. if (is_ndashdigit_ident(first_after_plus)) {
  7562. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  7563. if (maybe_b.has_value()) {
  7564. transaction.commit();
  7565. return Selector::SimpleSelector::ANPlusBPattern { 1, maybe_b.value() };
  7566. }
  7567. return syntax_error();
  7568. }
  7569. return syntax_error();
  7570. }
  7571. class UnparsedCalculationNode final : public CalculationNode {
  7572. public:
  7573. static ErrorOr<NonnullOwnPtr<UnparsedCalculationNode>> create(ComponentValue component_value)
  7574. {
  7575. return adopt_nonnull_own_or_enomem(new (nothrow) UnparsedCalculationNode(move(component_value)));
  7576. }
  7577. virtual ~UnparsedCalculationNode() = default;
  7578. ComponentValue& component_value() { return m_component_value; }
  7579. virtual ErrorOr<String> to_string() const override { VERIFY_NOT_REACHED(); }
  7580. virtual Optional<CalculatedStyleValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  7581. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  7582. virtual CalculatedStyleValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  7583. virtual ErrorOr<void> dump(StringBuilder& builder, int indent) const override
  7584. {
  7585. return builder.try_appendff("{: >{}}UNPARSED({})\n", "", indent, TRY(m_component_value.to_debug_string()));
  7586. }
  7587. private:
  7588. UnparsedCalculationNode(ComponentValue component_value)
  7589. : CalculationNode(Type::Unparsed)
  7590. , m_component_value(move(component_value))
  7591. {
  7592. }
  7593. ComponentValue m_component_value;
  7594. };
  7595. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  7596. ErrorOr<OwnPtr<CalculationNode>> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  7597. {
  7598. // 1. Discard any <whitespace-token>s from values.
  7599. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  7600. struct Operator {
  7601. char delim;
  7602. };
  7603. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  7604. Vector<Value> values;
  7605. for (auto& value : original_values) {
  7606. if (value.is(Token::Type::Whitespace))
  7607. continue;
  7608. if (value.is(Token::Type::Delim)) {
  7609. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  7610. // NOTE: Sequential operators are invalid syntax.
  7611. if (!values.is_empty() && values.last().has<Operator>())
  7612. return nullptr;
  7613. TRY(values.try_append(Operator { static_cast<char>(value.token().delim()) }));
  7614. continue;
  7615. }
  7616. }
  7617. if (value.is(Token::Type::Ident)) {
  7618. if (value.token().ident().equals_ignoring_ascii_case("e"sv)) {
  7619. TRY(values.try_append({ TRY(ConstantCalculationNode::create(CalculationNode::ConstantType::E)) }));
  7620. continue;
  7621. }
  7622. if (value.token().ident().equals_ignoring_ascii_case("pi"sv)) {
  7623. TRY(values.try_append({ TRY(ConstantCalculationNode::create(CalculationNode::ConstantType::PI)) }));
  7624. continue;
  7625. }
  7626. if (value.token().ident().equals_ignoring_ascii_case("infinity"sv)) {
  7627. TRY(values.try_append({ TRY(ConstantCalculationNode::create(CalculationNode::ConstantType::Infinity)) }));
  7628. continue;
  7629. }
  7630. if (value.token().ident().equals_ignoring_ascii_case("-infinity"sv)) {
  7631. TRY(values.try_append({ TRY(ConstantCalculationNode::create(CalculationNode::ConstantType::MinusInfinity)) }));
  7632. continue;
  7633. }
  7634. if (value.token().ident().equals_ignoring_ascii_case("NaN"sv)) {
  7635. TRY(values.try_append({ TRY(ConstantCalculationNode::create(CalculationNode::ConstantType::NaN)) }));
  7636. continue;
  7637. }
  7638. }
  7639. if (value.is(Token::Type::Number)) {
  7640. TRY(values.try_append({ TRY(NumericCalculationNode::create(value.token().number())) }));
  7641. continue;
  7642. }
  7643. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  7644. if (dimension->is_angle())
  7645. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->angle())) }));
  7646. else if (dimension->is_frequency())
  7647. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->frequency())) }));
  7648. else if (dimension->is_length())
  7649. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->length())) }));
  7650. else if (dimension->is_percentage())
  7651. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->percentage())) }));
  7652. // FIXME: Resolutions, once calc() supports them.
  7653. else if (dimension->is_time())
  7654. TRY(values.try_append({ TRY(NumericCalculationNode::create(dimension->time())) }));
  7655. else
  7656. VERIFY_NOT_REACHED();
  7657. continue;
  7658. }
  7659. TRY(values.try_append({ TRY(UnparsedCalculationNode::create(value)) }));
  7660. }
  7661. // If we have no values, the syntax is invalid.
  7662. if (values.is_empty())
  7663. return nullptr;
  7664. // NOTE: If the first or last value is an operator, the syntax is invalid.
  7665. if (values.first().has<Operator>() || values.last().has<Operator>())
  7666. return nullptr;
  7667. // 3. Collect children into Product and Invert nodes.
  7668. // For every consecutive run of value items in values separated by "*" or "/" operators:
  7669. while (true) {
  7670. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  7671. return item.template has<Operator>()
  7672. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  7673. });
  7674. if (!first_product_operator.has_value())
  7675. break;
  7676. auto start_of_run = first_product_operator.value() - 1;
  7677. auto end_of_run = first_product_operator.value() + 1;
  7678. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  7679. auto& item = values[i];
  7680. if (!item.has<Operator>()) {
  7681. end_of_run = i - 1;
  7682. break;
  7683. }
  7684. auto delim = item.get<Operator>().delim;
  7685. if (!first_is_one_of(delim, '*', '/')) {
  7686. end_of_run = i - 1;
  7687. break;
  7688. }
  7689. }
  7690. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  7691. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  7692. TRY(run_values.try_append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>())));
  7693. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  7694. auto& operator_ = values[i].get<Operator>().delim;
  7695. auto& rhs = values[i + 1];
  7696. if (operator_ == '/') {
  7697. TRY(run_values.try_append(TRY(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())))));
  7698. continue;
  7699. }
  7700. VERIFY(operator_ == '*');
  7701. TRY(run_values.try_append(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7702. }
  7703. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  7704. auto product_node = TRY(ProductCalculationNode::create(move(run_values)));
  7705. values.remove(start_of_run, end_of_run - start_of_run + 1);
  7706. TRY(values.try_insert(start_of_run, { move(product_node) }));
  7707. }
  7708. // 4. Collect children into Sum and Negate nodes.
  7709. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  7710. {
  7711. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  7712. for (auto i = 0u; i < values.size(); ++i) {
  7713. auto& maybe_minus_operator = values[i];
  7714. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  7715. continue;
  7716. auto rhs_index = ++i;
  7717. auto& rhs = values[rhs_index];
  7718. NonnullOwnPtr<CalculationNode> negate_node = TRY(NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7719. values.remove(rhs_index);
  7720. values.insert(rhs_index, move(negate_node));
  7721. }
  7722. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  7723. if (values.size() == 1) {
  7724. TRY(values.first().visit(
  7725. [&](ComponentValue& component_value) -> ErrorOr<void> {
  7726. if (component_value.is_block() && component_value.block().is_paren())
  7727. single_value = TRY(UnparsedCalculationNode::create(component_value));
  7728. return {};
  7729. },
  7730. [&](NonnullOwnPtr<CalculationNode>& node) -> ErrorOr<void> {
  7731. if (node->type() == CalculationNode::Type::Product)
  7732. single_value = move(node);
  7733. return {};
  7734. },
  7735. [](auto&) -> ErrorOr<void> { return {}; }));
  7736. }
  7737. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  7738. if (!single_value.has_value()) {
  7739. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  7740. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  7741. TRY(value_items.try_ensure_capacity(values.size()));
  7742. for (auto& value : values) {
  7743. if (value.has<Operator>())
  7744. continue;
  7745. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  7746. }
  7747. single_value = TRY(SumCalculationNode::create(move(value_items)));
  7748. }
  7749. }
  7750. // 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.
  7751. // For every leaf node leaf in values:
  7752. bool parsing_failed_for_child_node = false;
  7753. TRY(single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) -> ErrorOr<void> {
  7754. if (node->type() != CalculationNode::Type::Unparsed)
  7755. return {};
  7756. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  7757. auto& component_value = unparsed_node.component_value();
  7758. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  7759. if (component_value.is_block() && component_value.block().is_paren()) {
  7760. auto leaf_calculation = TRY(parse_a_calculation(component_value.block().values()));
  7761. if (!leaf_calculation) {
  7762. parsing_failed_for_child_node = true;
  7763. return {};
  7764. }
  7765. node = leaf_calculation.release_nonnull();
  7766. return {};
  7767. }
  7768. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  7769. // NOTE: All function tokens at this point should be math functions.
  7770. else if (component_value.is_function()) {
  7771. auto& function = component_value.function();
  7772. auto leaf_calculation = TRY(parse_a_calc_function_node(function));
  7773. if (!leaf_calculation) {
  7774. parsing_failed_for_child_node = true;
  7775. return {};
  7776. }
  7777. node = leaf_calculation.release_nonnull();
  7778. return {};
  7779. }
  7780. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  7781. // So, the calc() is invalid.
  7782. 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());
  7783. parsing_failed_for_child_node = true;
  7784. return {};
  7785. }));
  7786. if (parsing_failed_for_child_node)
  7787. return nullptr;
  7788. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  7789. return single_value.release_value();
  7790. }
  7791. bool Parser::has_ignored_vendor_prefix(StringView string)
  7792. {
  7793. if (!string.starts_with('-'))
  7794. return false;
  7795. if (string.starts_with("--"sv))
  7796. return false;
  7797. if (string.starts_with("-libweb-"sv))
  7798. return false;
  7799. return true;
  7800. }
  7801. bool Parser::is_builtin(StringView name)
  7802. {
  7803. return name.equals_ignoring_ascii_case("inherit"sv)
  7804. || name.equals_ignoring_ascii_case("initial"sv)
  7805. || name.equals_ignoring_ascii_case("unset"sv);
  7806. }
  7807. ErrorOr<RefPtr<CalculatedStyleValue>> Parser::parse_calculated_value(Badge<StyleComputer>, ParsingContext const& context, Vector<ComponentValue> const& tokens)
  7808. {
  7809. if (tokens.is_empty())
  7810. return nullptr;
  7811. auto parser = TRY(Parser::create(context, ""sv));
  7812. return parser.parse_calculated_value(tokens);
  7813. }
  7814. ErrorOr<RefPtr<StyleValue>> Parser::parse_css_value(Badge<StyleComputer>, ParsingContext const& context, PropertyID property_id, Vector<ComponentValue> const& tokens)
  7815. {
  7816. if (tokens.is_empty() || property_id == CSS::PropertyID::Invalid || property_id == CSS::PropertyID::Custom)
  7817. return nullptr;
  7818. auto parser = TRY(Parser::create(context, ""sv));
  7819. TokenStream<ComponentValue> token_stream { tokens };
  7820. auto result = parser.parse_css_value(property_id, token_stream);
  7821. if (result.is_error())
  7822. return nullptr;
  7823. return result.release_value();
  7824. }
  7825. bool Parser::Dimension::is_angle() const
  7826. {
  7827. return m_value.has<Angle>();
  7828. }
  7829. Angle Parser::Dimension::angle() const
  7830. {
  7831. return m_value.get<Angle>();
  7832. }
  7833. bool Parser::Dimension::is_angle_percentage() const
  7834. {
  7835. return is_angle() || is_percentage();
  7836. }
  7837. AnglePercentage Parser::Dimension::angle_percentage() const
  7838. {
  7839. if (is_angle())
  7840. return angle();
  7841. if (is_percentage())
  7842. return percentage();
  7843. VERIFY_NOT_REACHED();
  7844. }
  7845. bool Parser::Dimension::is_frequency() const
  7846. {
  7847. return m_value.has<Frequency>();
  7848. }
  7849. Frequency Parser::Dimension::frequency() const
  7850. {
  7851. return m_value.get<Frequency>();
  7852. }
  7853. bool Parser::Dimension::is_frequency_percentage() const
  7854. {
  7855. return is_frequency() || is_percentage();
  7856. }
  7857. FrequencyPercentage Parser::Dimension::frequency_percentage() const
  7858. {
  7859. if (is_frequency())
  7860. return frequency();
  7861. if (is_percentage())
  7862. return percentage();
  7863. VERIFY_NOT_REACHED();
  7864. }
  7865. bool Parser::Dimension::is_length() const
  7866. {
  7867. return m_value.has<Length>();
  7868. }
  7869. Length Parser::Dimension::length() const
  7870. {
  7871. return m_value.get<Length>();
  7872. }
  7873. bool Parser::Dimension::is_length_percentage() const
  7874. {
  7875. return is_length() || is_percentage();
  7876. }
  7877. LengthPercentage Parser::Dimension::length_percentage() const
  7878. {
  7879. if (is_length())
  7880. return length();
  7881. if (is_percentage())
  7882. return percentage();
  7883. VERIFY_NOT_REACHED();
  7884. }
  7885. bool Parser::Dimension::is_percentage() const
  7886. {
  7887. return m_value.has<Percentage>();
  7888. }
  7889. Percentage Parser::Dimension::percentage() const
  7890. {
  7891. return m_value.get<Percentage>();
  7892. }
  7893. bool Parser::Dimension::is_resolution() const
  7894. {
  7895. return m_value.has<Resolution>();
  7896. }
  7897. Resolution Parser::Dimension::resolution() const
  7898. {
  7899. return m_value.get<Resolution>();
  7900. }
  7901. bool Parser::Dimension::is_time() const
  7902. {
  7903. return m_value.has<Time>();
  7904. }
  7905. Time Parser::Dimension::time() const
  7906. {
  7907. return m_value.get<Time>();
  7908. }
  7909. bool Parser::Dimension::is_time_percentage() const
  7910. {
  7911. return is_time() || is_percentage();
  7912. }
  7913. TimePercentage Parser::Dimension::time_percentage() const
  7914. {
  7915. if (is_time())
  7916. return time();
  7917. if (is_percentage())
  7918. return percentage();
  7919. VERIFY_NOT_REACHED();
  7920. }
  7921. }
  7922. namespace Web {
  7923. CSS::CSSStyleSheet* parse_css_stylesheet(CSS::Parser::ParsingContext const& context, StringView css, Optional<AK::URL> location)
  7924. {
  7925. if (css.is_empty()) {
  7926. auto rule_list = CSS::CSSRuleList::create_empty(context.realm()).release_value_but_fixme_should_propagate_errors();
  7927. auto media_list = CSS::MediaList::create(context.realm(), {}).release_value_but_fixme_should_propagate_errors();
  7928. return CSS::CSSStyleSheet::create(context.realm(), rule_list, media_list, location).release_value_but_fixme_should_propagate_errors();
  7929. }
  7930. auto parser = CSS::Parser::Parser::create(context, css).release_value_but_fixme_should_propagate_errors();
  7931. return parser.parse_as_css_stylesheet(location);
  7932. }
  7933. CSS::ElementInlineCSSStyleDeclaration* parse_css_style_attribute(CSS::Parser::ParsingContext const& context, StringView css, DOM::Element& element)
  7934. {
  7935. if (css.is_empty())
  7936. return CSS::ElementInlineCSSStyleDeclaration::create(element, {}, {}).release_value_but_fixme_should_propagate_errors();
  7937. auto parser = CSS::Parser::Parser::create(context, css).release_value_but_fixme_should_propagate_errors();
  7938. return parser.parse_as_style_attribute(element);
  7939. }
  7940. ErrorOr<RefPtr<CSS::StyleValue>> parse_css_value(CSS::Parser::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
  7941. {
  7942. if (string.is_empty())
  7943. return nullptr;
  7944. auto parser = TRY(CSS::Parser::Parser::create(context, string));
  7945. return parser.parse_as_css_value(property_id);
  7946. }
  7947. CSS::CSSRule* parse_css_rule(CSS::Parser::ParsingContext const& context, StringView css_text)
  7948. {
  7949. auto parser = CSS::Parser::Parser::create(context, css_text).release_value_but_fixme_should_propagate_errors();
  7950. return parser.parse_as_css_rule();
  7951. }
  7952. Optional<CSS::SelectorList> parse_selector(CSS::Parser::ParsingContext const& context, StringView selector_text)
  7953. {
  7954. auto parser = CSS::Parser::Parser::create(context, selector_text).release_value_but_fixme_should_propagate_errors();
  7955. return parser.parse_as_selector();
  7956. }
  7957. RefPtr<CSS::MediaQuery> parse_media_query(CSS::Parser::ParsingContext const& context, StringView string)
  7958. {
  7959. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7960. return parser.parse_as_media_query();
  7961. }
  7962. Vector<NonnullRefPtr<CSS::MediaQuery>> parse_media_query_list(CSS::Parser::ParsingContext const& context, StringView string)
  7963. {
  7964. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7965. return parser.parse_as_media_query_list();
  7966. }
  7967. RefPtr<CSS::Supports> parse_css_supports(CSS::Parser::ParsingContext const& context, StringView string)
  7968. {
  7969. if (string.is_empty())
  7970. return {};
  7971. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7972. return parser.parse_as_supports();
  7973. }
  7974. Optional<CSS::StyleProperty> parse_css_supports_condition(CSS::Parser::ParsingContext const& context, StringView string)
  7975. {
  7976. if (string.is_empty())
  7977. return {};
  7978. auto parser = CSS::Parser::Parser::create(context, string).release_value_but_fixme_should_propagate_errors();
  7979. return parser.parse_as_supports_condition();
  7980. }
  7981. // https://html.spec.whatwg.org/multipage/images.html#parse-a-srcset-attribute
  7982. CSS::Length CSS::Parser::Parser::parse_as_sizes_attribute()
  7983. {
  7984. Optional<CSS::Length> size;
  7985. // When asked to parse a sizes attribute from an element,
  7986. // parse a comma-separated list of component values from the value of the element's sizes attribute
  7987. // (or the empty string, if the attribute is absent), and let unparsed sizes list be the result.
  7988. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  7989. // For each unparsed size in unparsed sizes list:
  7990. for (auto& unparsed_size : unparsed_sizes_list) {
  7991. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7992. // If unparsed size is now empty, that is a parse error; continue.
  7993. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  7994. unparsed_size.take_last();
  7995. if (unparsed_size.is_empty())
  7996. continue;
  7997. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  7998. // let size be its value and remove the component value from unparsed size.
  7999. // FIXME: Any CSS function other than the math functions is invalid.
  8000. // Otherwise, there is a parse error; continue.
  8001. auto length = parse_length(unparsed_size.last());
  8002. if (length.has_value() && length.value().raw_value() >= 0) {
  8003. size = length.value();
  8004. unparsed_size.take_last();
  8005. } else {
  8006. continue;
  8007. }
  8008. // 3. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  8009. // If unparsed size is now empty, return size and exit this algorithm.
  8010. // If this was not the last item in unparsed sizes list, that is a parse error.
  8011. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  8012. unparsed_size.take_last();
  8013. if (unparsed_size.is_empty())
  8014. return size.value();
  8015. // 4. Parse the remaining component values in unparsed size as a <media-condition>.
  8016. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  8017. TokenStream<ComponentValue> token_stream { unparsed_size };
  8018. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  8019. if (media_condition && media_condition->evaluate(m_context.document()->window()) == CSS::MatchResult::True) {
  8020. return size.value();
  8021. } else {
  8022. continue;
  8023. }
  8024. }
  8025. return CSS::Length(100, CSS::Length::Type::Vw);
  8026. }
  8027. }