Parser.cpp 305 KB

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