Parser.cpp 338 KB

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