Parser.cpp 296 KB

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