Parser.cpp 297 KB

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