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