Parser.cpp 348 KB

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