Parser.cpp 312 KB

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