Parser.cpp 300 KB

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