Parser.cpp 311 KB

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