Parser.cpp 346 KB

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