Parser.cpp 306 KB

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