Parser.cpp 299 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064
  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 = ((Token)name_ident).at_keyword();
  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 = ((Token)name_ident).function();
  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 = ((Token)token).ident();
  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<Gfx::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<Gfx::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<Gfx::UnicodeRange> Parser::parse_unicode_range(StringView text)
  1493. {
  1494. auto make_valid_unicode_range = [&](u32 start_value, u32 end_value) -> Optional<Gfx::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 Gfx::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(component_value.token().string().to_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(TokenStream<ComponentValue>& tokens)
  2261. {
  2262. // `auto || <ratio>`
  2263. RefPtr<StyleValue> auto_value;
  2264. RefPtr<StyleValue> ratio_value;
  2265. auto transaction = tokens.begin_transaction();
  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. transaction.commit();
  2286. return StyleValueList::create(
  2287. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  2288. StyleValueList::Separator::Space);
  2289. }
  2290. if (ratio_value) {
  2291. transaction.commit();
  2292. return ratio_value.release_nonnull();
  2293. }
  2294. if (auto_value) {
  2295. transaction.commit();
  2296. return auto_value.release_nonnull();
  2297. }
  2298. return nullptr;
  2299. }
  2300. RefPtr<StyleValue> Parser::parse_background_value(TokenStream<ComponentValue>& tokens)
  2301. {
  2302. auto transaction = tokens.begin_transaction();
  2303. 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) {
  2304. return ShorthandStyleValue::create(PropertyID::Background,
  2305. { PropertyID::BackgroundColor, PropertyID::BackgroundImage, PropertyID::BackgroundPosition, PropertyID::BackgroundSize, PropertyID::BackgroundRepeat, PropertyID::BackgroundAttachment, PropertyID::BackgroundOrigin, PropertyID::BackgroundClip },
  2306. { move(background_color), move(background_image), move(background_position), move(background_size), move(background_repeat), move(background_attachment), move(background_origin), move(background_clip) });
  2307. };
  2308. StyleValueVector background_images;
  2309. StyleValueVector background_positions;
  2310. StyleValueVector background_sizes;
  2311. StyleValueVector background_repeats;
  2312. StyleValueVector background_attachments;
  2313. StyleValueVector background_clips;
  2314. StyleValueVector background_origins;
  2315. RefPtr<StyleValue> background_color;
  2316. auto initial_background_image = property_initial_value(m_context.realm(), PropertyID::BackgroundImage);
  2317. auto initial_background_position = property_initial_value(m_context.realm(), PropertyID::BackgroundPosition);
  2318. auto initial_background_size = property_initial_value(m_context.realm(), PropertyID::BackgroundSize);
  2319. auto initial_background_repeat = property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat);
  2320. auto initial_background_attachment = property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment);
  2321. auto initial_background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
  2322. auto initial_background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
  2323. auto initial_background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
  2324. // Per-layer values
  2325. RefPtr<StyleValue> background_image;
  2326. RefPtr<StyleValue> background_position;
  2327. RefPtr<StyleValue> background_size;
  2328. RefPtr<StyleValue> background_repeat;
  2329. RefPtr<StyleValue> background_attachment;
  2330. RefPtr<StyleValue> background_clip;
  2331. RefPtr<StyleValue> background_origin;
  2332. bool has_multiple_layers = false;
  2333. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  2334. Vector<PropertyID> remaining_layer_properties {
  2335. PropertyID::BackgroundAttachment,
  2336. PropertyID::BackgroundClip,
  2337. PropertyID::BackgroundColor,
  2338. PropertyID::BackgroundImage,
  2339. PropertyID::BackgroundOrigin,
  2340. PropertyID::BackgroundPosition,
  2341. PropertyID::BackgroundRepeat,
  2342. };
  2343. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  2344. if (allow_background_color) {
  2345. if (background_color)
  2346. return true;
  2347. } else {
  2348. if (background_color)
  2349. return false;
  2350. }
  2351. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  2352. };
  2353. auto complete_background_layer = [&]() {
  2354. background_images.append(background_image ? background_image.release_nonnull() : initial_background_image);
  2355. background_positions.append(background_position ? background_position.release_nonnull() : initial_background_position);
  2356. background_sizes.append(background_size ? background_size.release_nonnull() : initial_background_size);
  2357. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat);
  2358. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment);
  2359. if (!background_origin && !background_clip) {
  2360. background_origin = initial_background_origin;
  2361. background_clip = initial_background_clip;
  2362. } else if (!background_clip) {
  2363. background_clip = background_origin;
  2364. }
  2365. background_origins.append(background_origin.release_nonnull());
  2366. background_clips.append(background_clip.release_nonnull());
  2367. background_image = nullptr;
  2368. background_position = nullptr;
  2369. background_size = nullptr;
  2370. background_repeat = nullptr;
  2371. background_attachment = nullptr;
  2372. background_clip = nullptr;
  2373. background_origin = nullptr;
  2374. remaining_layer_properties.clear_with_capacity();
  2375. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  2376. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  2377. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  2378. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  2379. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  2380. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  2381. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  2382. };
  2383. while (tokens.has_next_token()) {
  2384. if (tokens.peek_token().is(Token::Type::Comma)) {
  2385. has_multiple_layers = true;
  2386. if (!background_layer_is_valid(false))
  2387. return nullptr;
  2388. complete_background_layer();
  2389. (void)tokens.next_token();
  2390. continue;
  2391. }
  2392. auto value_and_property = parse_css_value_for_properties(remaining_layer_properties, tokens);
  2393. if (!value_and_property.has_value())
  2394. return nullptr;
  2395. auto& value = value_and_property->style_value;
  2396. remove_property(remaining_layer_properties, value_and_property->property);
  2397. switch (value_and_property->property) {
  2398. case PropertyID::BackgroundAttachment:
  2399. VERIFY(!background_attachment);
  2400. background_attachment = value.release_nonnull();
  2401. continue;
  2402. case PropertyID::BackgroundColor:
  2403. VERIFY(!background_color);
  2404. background_color = value.release_nonnull();
  2405. continue;
  2406. case PropertyID::BackgroundImage:
  2407. VERIFY(!background_image);
  2408. background_image = value.release_nonnull();
  2409. continue;
  2410. case PropertyID::BackgroundClip:
  2411. case PropertyID::BackgroundOrigin: {
  2412. // background-origin and background-clip accept the same values. From the spec:
  2413. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  2414. // If two values are present, then the first sets background-origin and the second background-clip."
  2415. // - https://www.w3.org/TR/css-backgrounds-3/#background
  2416. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  2417. // If we only get one, we copy the value before creating the ShorthandStyleValue.
  2418. if (!background_origin) {
  2419. background_origin = value.release_nonnull();
  2420. } else if (!background_clip) {
  2421. background_clip = value.release_nonnull();
  2422. } else {
  2423. VERIFY_NOT_REACHED();
  2424. }
  2425. continue;
  2426. }
  2427. case PropertyID::BackgroundPosition: {
  2428. VERIFY(!background_position);
  2429. background_position = value.release_nonnull();
  2430. // Attempt to parse `/ <background-size>`
  2431. auto background_size_transaction = tokens.begin_transaction();
  2432. auto& maybe_slash = tokens.next_token();
  2433. if (maybe_slash.is_delim('/')) {
  2434. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  2435. background_size_transaction.commit();
  2436. background_size = maybe_background_size.release_nonnull();
  2437. continue;
  2438. }
  2439. return nullptr;
  2440. }
  2441. continue;
  2442. }
  2443. case PropertyID::BackgroundRepeat: {
  2444. VERIFY(!background_repeat);
  2445. tokens.reconsume_current_input_token();
  2446. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  2447. background_repeat = maybe_repeat.release_nonnull();
  2448. continue;
  2449. }
  2450. return nullptr;
  2451. }
  2452. default:
  2453. VERIFY_NOT_REACHED();
  2454. }
  2455. return nullptr;
  2456. }
  2457. if (!background_layer_is_valid(true))
  2458. return nullptr;
  2459. // We only need to create StyleValueLists if there are multiple layers.
  2460. // Otherwise, we can pass the single StyleValues directly.
  2461. if (has_multiple_layers) {
  2462. complete_background_layer();
  2463. if (!background_color)
  2464. background_color = initial_background_color;
  2465. transaction.commit();
  2466. return make_background_shorthand(
  2467. background_color.release_nonnull(),
  2468. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  2469. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  2470. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  2471. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  2472. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  2473. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  2474. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  2475. }
  2476. if (!background_color)
  2477. background_color = initial_background_color;
  2478. if (!background_image)
  2479. background_image = initial_background_image;
  2480. if (!background_position)
  2481. background_position = initial_background_position;
  2482. if (!background_size)
  2483. background_size = initial_background_size;
  2484. if (!background_repeat)
  2485. background_repeat = initial_background_repeat;
  2486. if (!background_attachment)
  2487. background_attachment = initial_background_attachment;
  2488. if (!background_origin && !background_clip) {
  2489. background_origin = initial_background_origin;
  2490. background_clip = initial_background_clip;
  2491. } else if (!background_clip) {
  2492. background_clip = background_origin;
  2493. }
  2494. transaction.commit();
  2495. return make_background_shorthand(
  2496. background_color.release_nonnull(),
  2497. background_image.release_nonnull(),
  2498. background_position.release_nonnull(),
  2499. background_size.release_nonnull(),
  2500. background_repeat.release_nonnull(),
  2501. background_attachment.release_nonnull(),
  2502. background_origin.release_nonnull(),
  2503. background_clip.release_nonnull());
  2504. }
  2505. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  2506. {
  2507. if (value->is_percentage())
  2508. return LengthPercentage { value->as_percentage().percentage() };
  2509. if (value->is_length())
  2510. return LengthPercentage { value->as_length().length() };
  2511. if (value->is_calculated())
  2512. return LengthPercentage { value->as_calculated() };
  2513. return {};
  2514. }
  2515. RefPtr<StyleValue> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  2516. {
  2517. PositionEdge relative_edge {};
  2518. if (property == PropertyID::BackgroundPositionX) {
  2519. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  2520. relative_edge = PositionEdge::Left;
  2521. } else if (property == PropertyID::BackgroundPositionY) {
  2522. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  2523. relative_edge = PositionEdge::Top;
  2524. } else {
  2525. VERIFY_NOT_REACHED();
  2526. }
  2527. auto transaction = tokens.begin_transaction();
  2528. if (!tokens.has_next_token())
  2529. return nullptr;
  2530. auto value = parse_css_value_for_property(property, tokens);
  2531. if (!value)
  2532. return nullptr;
  2533. if (value->is_identifier()) {
  2534. auto identifier = value->to_identifier();
  2535. if (identifier == ValueID::Center) {
  2536. transaction.commit();
  2537. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  2538. }
  2539. if (auto edge = value_id_to_position_edge(identifier); edge.has_value()) {
  2540. relative_edge = *edge;
  2541. } else {
  2542. return nullptr;
  2543. }
  2544. if (tokens.has_next_token()) {
  2545. value = parse_css_value_for_property(property, tokens);
  2546. if (!value) {
  2547. transaction.commit();
  2548. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  2549. }
  2550. }
  2551. }
  2552. auto offset = style_value_to_length_percentage(value);
  2553. if (offset.has_value()) {
  2554. transaction.commit();
  2555. return EdgeStyleValue::create(relative_edge, *offset);
  2556. }
  2557. // If no offset is provided create this element but with an offset of default value of zero
  2558. transaction.commit();
  2559. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  2560. }
  2561. RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  2562. {
  2563. auto transaction = tokens.begin_transaction();
  2564. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2565. auto value_id = value.to_identifier();
  2566. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2567. };
  2568. auto as_repeat = [](ValueID identifier) -> Optional<Repeat> {
  2569. switch (identifier) {
  2570. case ValueID::NoRepeat:
  2571. return Repeat::NoRepeat;
  2572. case ValueID::Repeat:
  2573. return Repeat::Repeat;
  2574. case ValueID::Round:
  2575. return Repeat::Round;
  2576. case ValueID::Space:
  2577. return Repeat::Space;
  2578. default:
  2579. return {};
  2580. }
  2581. };
  2582. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  2583. if (!maybe_x_value)
  2584. return nullptr;
  2585. auto x_value = maybe_x_value.release_nonnull();
  2586. if (is_directional_repeat(*x_value)) {
  2587. auto value_id = x_value->to_identifier();
  2588. transaction.commit();
  2589. return BackgroundRepeatStyleValue::create(
  2590. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  2591. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  2592. }
  2593. auto x_repeat = as_repeat(x_value->to_identifier());
  2594. if (!x_repeat.has_value())
  2595. return nullptr;
  2596. // See if we have a second value for Y
  2597. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  2598. if (!maybe_y_value) {
  2599. // We don't have a second value, so use x for both
  2600. transaction.commit();
  2601. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  2602. }
  2603. auto y_value = maybe_y_value.release_nonnull();
  2604. if (is_directional_repeat(*y_value))
  2605. return nullptr;
  2606. auto y_repeat = as_repeat(y_value->to_identifier());
  2607. if (!y_repeat.has_value())
  2608. return nullptr;
  2609. transaction.commit();
  2610. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  2611. }
  2612. RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  2613. {
  2614. auto transaction = tokens.begin_transaction();
  2615. auto get_length_percentage = [](StyleValue& style_value) -> Optional<LengthPercentage> {
  2616. if (style_value.has_auto())
  2617. return LengthPercentage { Length::make_auto() };
  2618. if (style_value.is_percentage())
  2619. return LengthPercentage { style_value.as_percentage().percentage() };
  2620. if (style_value.is_length())
  2621. return LengthPercentage { style_value.as_length().length() };
  2622. if (style_value.is_calculated())
  2623. return LengthPercentage { style_value.as_calculated() };
  2624. return {};
  2625. };
  2626. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  2627. if (!maybe_x_value)
  2628. return nullptr;
  2629. auto x_value = maybe_x_value.release_nonnull();
  2630. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain) {
  2631. transaction.commit();
  2632. return x_value;
  2633. }
  2634. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  2635. if (!maybe_y_value) {
  2636. auto y_value = LengthPercentage { Length::make_auto() };
  2637. auto x_size = get_length_percentage(*x_value);
  2638. if (!x_size.has_value())
  2639. return nullptr;
  2640. transaction.commit();
  2641. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  2642. }
  2643. auto y_value = maybe_y_value.release_nonnull();
  2644. auto x_size = get_length_percentage(*x_value);
  2645. auto y_size = get_length_percentage(*y_value);
  2646. if (!x_size.has_value() || !y_size.has_value())
  2647. return nullptr;
  2648. transaction.commit();
  2649. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  2650. }
  2651. RefPtr<StyleValue> Parser::parse_border_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  2652. {
  2653. RefPtr<StyleValue> border_width;
  2654. RefPtr<StyleValue> border_color;
  2655. RefPtr<StyleValue> border_style;
  2656. auto color_property = PropertyID::Invalid;
  2657. auto style_property = PropertyID::Invalid;
  2658. auto width_property = PropertyID::Invalid;
  2659. switch (property_id) {
  2660. case PropertyID::Border:
  2661. color_property = PropertyID::BorderColor;
  2662. style_property = PropertyID::BorderStyle;
  2663. width_property = PropertyID::BorderWidth;
  2664. break;
  2665. case PropertyID::BorderBottom:
  2666. color_property = PropertyID::BorderBottomColor;
  2667. style_property = PropertyID::BorderBottomStyle;
  2668. width_property = PropertyID::BorderBottomWidth;
  2669. break;
  2670. case PropertyID::BorderLeft:
  2671. color_property = PropertyID::BorderLeftColor;
  2672. style_property = PropertyID::BorderLeftStyle;
  2673. width_property = PropertyID::BorderLeftWidth;
  2674. break;
  2675. case PropertyID::BorderRight:
  2676. color_property = PropertyID::BorderRightColor;
  2677. style_property = PropertyID::BorderRightStyle;
  2678. width_property = PropertyID::BorderRightWidth;
  2679. break;
  2680. case PropertyID::BorderTop:
  2681. color_property = PropertyID::BorderTopColor;
  2682. style_property = PropertyID::BorderTopStyle;
  2683. width_property = PropertyID::BorderTopWidth;
  2684. break;
  2685. default:
  2686. VERIFY_NOT_REACHED();
  2687. }
  2688. auto remaining_longhands = Vector { width_property, color_property, style_property };
  2689. auto transaction = tokens.begin_transaction();
  2690. while (tokens.has_next_token()) {
  2691. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  2692. if (!property_and_value.has_value())
  2693. return nullptr;
  2694. auto& value = property_and_value->style_value;
  2695. remove_property(remaining_longhands, property_and_value->property);
  2696. if (property_and_value->property == width_property) {
  2697. VERIFY(!border_width);
  2698. border_width = value.release_nonnull();
  2699. } else if (property_and_value->property == color_property) {
  2700. VERIFY(!border_color);
  2701. border_color = value.release_nonnull();
  2702. } else if (property_and_value->property == style_property) {
  2703. VERIFY(!border_style);
  2704. border_style = value.release_nonnull();
  2705. } else {
  2706. VERIFY_NOT_REACHED();
  2707. }
  2708. }
  2709. if (!border_width)
  2710. border_width = property_initial_value(m_context.realm(), width_property);
  2711. if (!border_style)
  2712. border_style = property_initial_value(m_context.realm(), style_property);
  2713. if (!border_color)
  2714. border_color = property_initial_value(m_context.realm(), color_property);
  2715. transaction.commit();
  2716. return ShorthandStyleValue::create(property_id,
  2717. { width_property, style_property, color_property },
  2718. { border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull() });
  2719. }
  2720. RefPtr<StyleValue> Parser::parse_border_radius_value(TokenStream<ComponentValue>& tokens)
  2721. {
  2722. if (tokens.remaining_token_count() == 2) {
  2723. auto transaction = tokens.begin_transaction();
  2724. auto horizontal = parse_dimension(tokens.next_token());
  2725. auto vertical = parse_dimension(tokens.next_token());
  2726. if (horizontal.has_value() && horizontal->is_length_percentage() && vertical.has_value() && vertical->is_length_percentage()) {
  2727. transaction.commit();
  2728. return BorderRadiusStyleValue::create(horizontal->length_percentage(), vertical->length_percentage());
  2729. }
  2730. }
  2731. if (tokens.remaining_token_count() == 1) {
  2732. auto transaction = tokens.begin_transaction();
  2733. auto radius = parse_dimension(tokens.next_token());
  2734. if (radius.has_value() && radius->is_length_percentage()) {
  2735. transaction.commit();
  2736. return BorderRadiusStyleValue::create(radius->length_percentage(), radius->length_percentage());
  2737. }
  2738. }
  2739. return nullptr;
  2740. }
  2741. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(TokenStream<ComponentValue>& tokens)
  2742. {
  2743. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  2744. auto top_right = [&](Vector<LengthPercentage>& radii) {
  2745. switch (radii.size()) {
  2746. case 4:
  2747. case 3:
  2748. case 2:
  2749. return radii[1];
  2750. case 1:
  2751. return radii[0];
  2752. default:
  2753. VERIFY_NOT_REACHED();
  2754. }
  2755. };
  2756. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  2757. switch (radii.size()) {
  2758. case 4:
  2759. case 3:
  2760. return radii[2];
  2761. case 2:
  2762. case 1:
  2763. return radii[0];
  2764. default:
  2765. VERIFY_NOT_REACHED();
  2766. }
  2767. };
  2768. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  2769. switch (radii.size()) {
  2770. case 4:
  2771. return radii[3];
  2772. case 3:
  2773. case 2:
  2774. return radii[1];
  2775. case 1:
  2776. return radii[0];
  2777. default:
  2778. VERIFY_NOT_REACHED();
  2779. }
  2780. };
  2781. Vector<LengthPercentage> horizontal_radii;
  2782. Vector<LengthPercentage> vertical_radii;
  2783. bool reading_vertical = false;
  2784. auto transaction = tokens.begin_transaction();
  2785. while (tokens.has_next_token()) {
  2786. auto& token = tokens.next_token();
  2787. if (token.is_delim('/')) {
  2788. if (reading_vertical || horizontal_radii.is_empty())
  2789. return nullptr;
  2790. reading_vertical = true;
  2791. continue;
  2792. }
  2793. auto maybe_dimension = parse_dimension(token);
  2794. if (!maybe_dimension.has_value() || !maybe_dimension->is_length_percentage())
  2795. return nullptr;
  2796. if (reading_vertical) {
  2797. vertical_radii.append(maybe_dimension->length_percentage());
  2798. } else {
  2799. horizontal_radii.append(maybe_dimension->length_percentage());
  2800. }
  2801. }
  2802. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2803. || horizontal_radii.is_empty()
  2804. || (reading_vertical && vertical_radii.is_empty()))
  2805. return nullptr;
  2806. auto top_left_radius = BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2807. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii));
  2808. auto top_right_radius = BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2809. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii));
  2810. auto bottom_right_radius = BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2811. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii));
  2812. auto bottom_left_radius = BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2813. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii));
  2814. transaction.commit();
  2815. return ShorthandStyleValue::create(PropertyID::BorderRadius,
  2816. { PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius },
  2817. { move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius) });
  2818. }
  2819. RefPtr<StyleValue> Parser::parse_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  2820. {
  2821. // "none"
  2822. if (contains_single_none_ident(tokens))
  2823. return parse_identifier_value(tokens.next_token());
  2824. return parse_comma_separated_value_list(tokens, [this, allow_inset_keyword](auto& tokens) {
  2825. return parse_single_shadow_value(tokens, allow_inset_keyword);
  2826. });
  2827. }
  2828. RefPtr<StyleValue> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  2829. {
  2830. auto transaction = tokens.begin_transaction();
  2831. Optional<Color> color;
  2832. RefPtr<StyleValue> offset_x;
  2833. RefPtr<StyleValue> offset_y;
  2834. RefPtr<StyleValue> blur_radius;
  2835. RefPtr<StyleValue> spread_distance;
  2836. Optional<ShadowPlacement> placement;
  2837. auto possibly_dynamic_length = [&](ComponentValue const& token) -> RefPtr<StyleValue> {
  2838. if (auto calculated_value = parse_calculated_value(token)) {
  2839. if (!calculated_value->resolves_to_length())
  2840. return nullptr;
  2841. return calculated_value;
  2842. }
  2843. auto maybe_length = parse_length(token);
  2844. if (!maybe_length.has_value())
  2845. return nullptr;
  2846. return LengthStyleValue::create(maybe_length.release_value());
  2847. };
  2848. while (tokens.has_next_token()) {
  2849. auto const& token = tokens.peek_token();
  2850. if (auto maybe_color = parse_color(token); maybe_color.has_value()) {
  2851. if (color.has_value())
  2852. return nullptr;
  2853. color = maybe_color.release_value();
  2854. tokens.next_token();
  2855. continue;
  2856. }
  2857. if (auto maybe_offset_x = possibly_dynamic_length(token); maybe_offset_x) {
  2858. // horizontal offset
  2859. if (offset_x)
  2860. return nullptr;
  2861. offset_x = maybe_offset_x;
  2862. tokens.next_token();
  2863. // vertical offset
  2864. if (!tokens.has_next_token())
  2865. return nullptr;
  2866. auto maybe_offset_y = possibly_dynamic_length(tokens.peek_token());
  2867. if (!maybe_offset_y)
  2868. return nullptr;
  2869. offset_y = maybe_offset_y;
  2870. tokens.next_token();
  2871. // blur radius (optional)
  2872. if (!tokens.has_next_token())
  2873. break;
  2874. auto maybe_blur_radius = possibly_dynamic_length(tokens.peek_token());
  2875. if (!maybe_blur_radius)
  2876. continue;
  2877. blur_radius = maybe_blur_radius;
  2878. tokens.next_token();
  2879. // spread distance (optional)
  2880. if (!tokens.has_next_token())
  2881. break;
  2882. auto maybe_spread_distance = possibly_dynamic_length(tokens.peek_token());
  2883. if (!maybe_spread_distance)
  2884. continue;
  2885. spread_distance = maybe_spread_distance;
  2886. tokens.next_token();
  2887. continue;
  2888. }
  2889. if (allow_inset_keyword == AllowInsetKeyword::Yes && token.is_ident("inset"sv)) {
  2890. if (placement.has_value())
  2891. return nullptr;
  2892. placement = ShadowPlacement::Inner;
  2893. tokens.next_token();
  2894. continue;
  2895. }
  2896. if (token.is(Token::Type::Comma))
  2897. break;
  2898. return nullptr;
  2899. }
  2900. // FIXME: If color is absent, default to `currentColor`
  2901. if (!color.has_value())
  2902. color = Color::NamedColor::Black;
  2903. // x/y offsets are required
  2904. if (!offset_x || !offset_y)
  2905. return nullptr;
  2906. // Other lengths default to 0
  2907. if (!blur_radius)
  2908. blur_radius = LengthStyleValue::create(Length::make_px(0));
  2909. if (!spread_distance)
  2910. spread_distance = LengthStyleValue::create(Length::make_px(0));
  2911. // Placement is outer by default
  2912. if (!placement.has_value())
  2913. placement = ShadowPlacement::Outer;
  2914. transaction.commit();
  2915. 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());
  2916. }
  2917. RefPtr<StyleValue> Parser::parse_content_value(TokenStream<ComponentValue>& tokens)
  2918. {
  2919. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  2920. auto transaction = tokens.begin_transaction();
  2921. auto is_single_value_identifier = [](ValueID identifier) -> bool {
  2922. switch (identifier) {
  2923. case ValueID::None:
  2924. case ValueID::Normal:
  2925. return true;
  2926. default:
  2927. return false;
  2928. }
  2929. };
  2930. if (tokens.remaining_token_count() == 1) {
  2931. if (auto identifier = parse_identifier_value(tokens.peek_token())) {
  2932. if (is_single_value_identifier(identifier->to_identifier())) {
  2933. (void)tokens.next_token();
  2934. transaction.commit();
  2935. return identifier;
  2936. }
  2937. }
  2938. }
  2939. StyleValueVector content_values;
  2940. StyleValueVector alt_text_values;
  2941. bool in_alt_text = false;
  2942. while (tokens.has_next_token()) {
  2943. auto& next = tokens.peek_token();
  2944. if (next.is_delim('/')) {
  2945. if (in_alt_text || content_values.is_empty())
  2946. return nullptr;
  2947. in_alt_text = true;
  2948. (void)tokens.next_token();
  2949. continue;
  2950. }
  2951. if (auto style_value = parse_css_value_for_property(PropertyID::Content, tokens)) {
  2952. if (is_single_value_identifier(style_value->to_identifier()))
  2953. return nullptr;
  2954. if (in_alt_text) {
  2955. alt_text_values.append(style_value.release_nonnull());
  2956. } else {
  2957. content_values.append(style_value.release_nonnull());
  2958. }
  2959. continue;
  2960. }
  2961. return nullptr;
  2962. }
  2963. if (content_values.is_empty())
  2964. return nullptr;
  2965. if (in_alt_text && alt_text_values.is_empty())
  2966. return nullptr;
  2967. RefPtr<StyleValueList> alt_text;
  2968. if (!alt_text_values.is_empty())
  2969. alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);
  2970. transaction.commit();
  2971. return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
  2972. }
  2973. // https://www.w3.org/TR/css-display-3/#the-display-properties
  2974. RefPtr<StyleValue> Parser::parse_display_value(TokenStream<ComponentValue>& tokens)
  2975. {
  2976. auto parse_single_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  2977. auto transaction = tokens.begin_transaction();
  2978. if (auto identifier_value = parse_identifier_value(tokens.next_token())) {
  2979. auto identifier = identifier_value->to_identifier();
  2980. if (identifier == ValueID::ListItem) {
  2981. transaction.commit();
  2982. return Display::from_short(Display::Short::ListItem);
  2983. }
  2984. if (auto display_outside = value_id_to_display_outside(identifier); display_outside.has_value()) {
  2985. transaction.commit();
  2986. switch (display_outside.value()) {
  2987. case DisplayOutside::Block:
  2988. return Display::from_short(Display::Short::Block);
  2989. case DisplayOutside::Inline:
  2990. return Display::from_short(Display::Short::Inline);
  2991. case DisplayOutside::RunIn:
  2992. return Display::from_short(Display::Short::RunIn);
  2993. }
  2994. }
  2995. if (auto display_inside = value_id_to_display_inside(identifier); display_inside.has_value()) {
  2996. transaction.commit();
  2997. switch (display_inside.value()) {
  2998. case DisplayInside::Flow:
  2999. return Display::from_short(Display::Short::Flow);
  3000. case DisplayInside::FlowRoot:
  3001. return Display::from_short(Display::Short::FlowRoot);
  3002. case DisplayInside::Table:
  3003. return Display::from_short(Display::Short::Table);
  3004. case DisplayInside::Flex:
  3005. return Display::from_short(Display::Short::Flex);
  3006. case DisplayInside::Grid:
  3007. return Display::from_short(Display::Short::Grid);
  3008. case DisplayInside::Ruby:
  3009. return Display::from_short(Display::Short::Ruby);
  3010. case DisplayInside::Math:
  3011. return Display::from_short(Display::Short::Math);
  3012. }
  3013. }
  3014. if (auto display_internal = value_id_to_display_internal(identifier); display_internal.has_value()) {
  3015. transaction.commit();
  3016. return Display { display_internal.value() };
  3017. }
  3018. if (auto display_box = value_id_to_display_box(identifier); display_box.has_value()) {
  3019. transaction.commit();
  3020. switch (display_box.value()) {
  3021. case DisplayBox::Contents:
  3022. return Display::from_short(Display::Short::Contents);
  3023. case DisplayBox::None:
  3024. return Display::from_short(Display::Short::None);
  3025. }
  3026. }
  3027. if (auto display_legacy = value_id_to_display_legacy(identifier); display_legacy.has_value()) {
  3028. transaction.commit();
  3029. switch (display_legacy.value()) {
  3030. case DisplayLegacy::InlineBlock:
  3031. return Display::from_short(Display::Short::InlineBlock);
  3032. case DisplayLegacy::InlineTable:
  3033. return Display::from_short(Display::Short::InlineTable);
  3034. case DisplayLegacy::InlineFlex:
  3035. return Display::from_short(Display::Short::InlineFlex);
  3036. case DisplayLegacy::InlineGrid:
  3037. return Display::from_short(Display::Short::InlineGrid);
  3038. }
  3039. }
  3040. }
  3041. return OptionalNone {};
  3042. };
  3043. auto parse_multi_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  3044. auto list_item = Display::ListItem::No;
  3045. Optional<DisplayInside> inside;
  3046. Optional<DisplayOutside> outside;
  3047. auto transaction = tokens.begin_transaction();
  3048. while (tokens.has_next_token()) {
  3049. auto& token = tokens.next_token();
  3050. if (auto value = parse_identifier_value(token)) {
  3051. auto identifier = value->to_identifier();
  3052. if (identifier == ValueID::ListItem) {
  3053. if (list_item == Display::ListItem::Yes)
  3054. return {};
  3055. list_item = Display::ListItem::Yes;
  3056. continue;
  3057. }
  3058. if (auto inside_value = value_id_to_display_inside(identifier); inside_value.has_value()) {
  3059. if (inside.has_value())
  3060. return {};
  3061. inside = inside_value.value();
  3062. continue;
  3063. }
  3064. if (auto outside_value = value_id_to_display_outside(identifier); outside_value.has_value()) {
  3065. if (outside.has_value())
  3066. return {};
  3067. outside = outside_value.value();
  3068. continue;
  3069. }
  3070. }
  3071. // Not a display value, abort.
  3072. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized display value: `{}`", token.to_string());
  3073. return {};
  3074. }
  3075. // The spec does not allow any other inside values to be combined with list-item
  3076. // <display-outside>? && [ flow | flow-root ]? && list-item
  3077. if (list_item == Display::ListItem::Yes && inside.has_value() && inside != DisplayInside::Flow && inside != DisplayInside::FlowRoot)
  3078. return {};
  3079. transaction.commit();
  3080. return Display { outside.value_or(DisplayOutside::Block), inside.value_or(DisplayInside::Flow), list_item };
  3081. };
  3082. Optional<Display> display;
  3083. if (tokens.remaining_token_count() == 1)
  3084. display = parse_single_component_display(tokens);
  3085. else
  3086. display = parse_multi_component_display(tokens);
  3087. if (display.has_value())
  3088. return DisplayStyleValue::create(display.value());
  3089. return nullptr;
  3090. }
  3091. RefPtr<StyleValue> Parser::parse_filter_value_list_value(TokenStream<ComponentValue>& tokens)
  3092. {
  3093. auto transaction = tokens.begin_transaction();
  3094. if (contains_single_none_ident(tokens)) {
  3095. transaction.commit();
  3096. return parse_identifier_value(tokens.next_token());
  3097. }
  3098. // FIXME: <url>s are ignored for now
  3099. // <filter-value-list> = [ <filter-function> | <url> ]+
  3100. enum class FilterToken {
  3101. // Color filters:
  3102. Brightness,
  3103. Contrast,
  3104. Grayscale,
  3105. Invert,
  3106. Opacity,
  3107. Saturate,
  3108. Sepia,
  3109. // Special filters:
  3110. Blur,
  3111. DropShadow,
  3112. HueRotate
  3113. };
  3114. auto filter_token_to_operation = [&](auto filter) {
  3115. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  3116. return static_cast<Filter::Color::Operation>(filter);
  3117. };
  3118. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  3119. if (token.is(Token::Type::Percentage))
  3120. return NumberPercentage(Percentage(token.token().percentage()));
  3121. if (token.is(Token::Type::Number))
  3122. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  3123. return {};
  3124. };
  3125. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  3126. if (name.equals_ignoring_ascii_case("blur"sv))
  3127. return FilterToken::Blur;
  3128. if (name.equals_ignoring_ascii_case("brightness"sv))
  3129. return FilterToken::Brightness;
  3130. if (name.equals_ignoring_ascii_case("contrast"sv))
  3131. return FilterToken::Contrast;
  3132. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  3133. return FilterToken::DropShadow;
  3134. if (name.equals_ignoring_ascii_case("grayscale"sv))
  3135. return FilterToken::Grayscale;
  3136. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  3137. return FilterToken::HueRotate;
  3138. if (name.equals_ignoring_ascii_case("invert"sv))
  3139. return FilterToken::Invert;
  3140. if (name.equals_ignoring_ascii_case("opacity"sv))
  3141. return FilterToken::Opacity;
  3142. if (name.equals_ignoring_ascii_case("saturate"sv))
  3143. return FilterToken::Saturate;
  3144. if (name.equals_ignoring_ascii_case("sepia"sv))
  3145. return FilterToken::Sepia;
  3146. return {};
  3147. };
  3148. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  3149. TokenStream tokens { function_values };
  3150. tokens.skip_whitespace();
  3151. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  3152. tokens.skip_whitespace();
  3153. if (tokens.has_next_token())
  3154. return {};
  3155. return filter;
  3156. };
  3157. if (filter_token == FilterToken::Blur) {
  3158. // blur( <length>? )
  3159. if (!tokens.has_next_token())
  3160. return Filter::Blur {};
  3161. auto blur_radius = parse_length(tokens.next_token());
  3162. if (!blur_radius.has_value())
  3163. return {};
  3164. return if_no_more_tokens_return(Filter::Blur { *blur_radius });
  3165. } else if (filter_token == FilterToken::DropShadow) {
  3166. if (!tokens.has_next_token())
  3167. return {};
  3168. auto next_token = [&]() -> auto& {
  3169. auto& token = tokens.next_token();
  3170. tokens.skip_whitespace();
  3171. return token;
  3172. };
  3173. // drop-shadow( [ <color>? && <length>{2,3} ] )
  3174. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  3175. auto& first_param = next_token();
  3176. Optional<Length> maybe_radius = {};
  3177. auto maybe_color = parse_color(first_param);
  3178. auto x_offset = parse_length(maybe_color.has_value() ? next_token() : first_param);
  3179. if (!x_offset.has_value() || !tokens.has_next_token()) {
  3180. return {};
  3181. }
  3182. auto y_offset = parse_length(next_token());
  3183. if (!y_offset.has_value()) {
  3184. return {};
  3185. }
  3186. if (tokens.has_next_token()) {
  3187. auto& token = next_token();
  3188. maybe_radius = parse_length(token);
  3189. if (!maybe_color.has_value() && (!maybe_radius.has_value() || tokens.has_next_token())) {
  3190. maybe_color = parse_color(!maybe_radius.has_value() ? token : next_token());
  3191. if (!maybe_color.has_value()) {
  3192. return {};
  3193. }
  3194. } else if (!maybe_radius.has_value()) {
  3195. return {};
  3196. }
  3197. }
  3198. return if_no_more_tokens_return(Filter::DropShadow { *x_offset, *y_offset, maybe_radius, maybe_color });
  3199. } else if (filter_token == FilterToken::HueRotate) {
  3200. // hue-rotate( [ <angle> | <zero> ]? )
  3201. if (!tokens.has_next_token())
  3202. return Filter::HueRotate {};
  3203. auto& token = tokens.next_token();
  3204. if (token.is(Token::Type::Number)) {
  3205. // hue-rotate(0)
  3206. auto number = token.token().number();
  3207. if (number.is_integer() && number.integer_value() == 0)
  3208. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  3209. return {};
  3210. }
  3211. if (!token.is(Token::Type::Dimension))
  3212. return {};
  3213. auto angle_value = token.token().dimension_value();
  3214. auto angle_unit_name = token.token().dimension_unit();
  3215. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  3216. if (!angle_unit.has_value())
  3217. return {};
  3218. Angle angle { angle_value, angle_unit.release_value() };
  3219. return if_no_more_tokens_return(Filter::HueRotate { angle });
  3220. } else {
  3221. // Simple filters:
  3222. // brightness( <number-percentage>? )
  3223. // contrast( <number-percentage>? )
  3224. // grayscale( <number-percentage>? )
  3225. // invert( <number-percentage>? )
  3226. // opacity( <number-percentage>? )
  3227. // sepia( <number-percentage>? )
  3228. // saturate( <number-percentage>? )
  3229. if (!tokens.has_next_token())
  3230. return Filter::Color { filter_token_to_operation(filter_token) };
  3231. auto amount = parse_number_percentage(tokens.next_token());
  3232. if (!amount.has_value())
  3233. return {};
  3234. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  3235. }
  3236. };
  3237. Vector<FilterFunction> filter_value_list {};
  3238. while (tokens.has_next_token()) {
  3239. tokens.skip_whitespace();
  3240. if (!tokens.has_next_token())
  3241. break;
  3242. auto& token = tokens.next_token();
  3243. if (!token.is_function())
  3244. return nullptr;
  3245. auto filter_token = parse_filter_function_name(token.function().name());
  3246. if (!filter_token.has_value())
  3247. return nullptr;
  3248. auto filter_function = parse_filter_function(*filter_token, token.function().values());
  3249. if (!filter_function.has_value())
  3250. return nullptr;
  3251. filter_value_list.append(*filter_function);
  3252. }
  3253. if (filter_value_list.is_empty())
  3254. return nullptr;
  3255. transaction.commit();
  3256. return FilterValueListStyleValue::create(move(filter_value_list));
  3257. }
  3258. RefPtr<StyleValue> Parser::parse_flex_value(TokenStream<ComponentValue>& tokens)
  3259. {
  3260. auto transaction = tokens.begin_transaction();
  3261. auto make_flex_shorthand = [&](NonnullRefPtr<StyleValue> flex_grow, NonnullRefPtr<StyleValue> flex_shrink, NonnullRefPtr<StyleValue> flex_basis) {
  3262. transaction.commit();
  3263. return ShorthandStyleValue::create(PropertyID::Flex,
  3264. { PropertyID::FlexGrow, PropertyID::FlexShrink, PropertyID::FlexBasis },
  3265. { move(flex_grow), move(flex_shrink), move(flex_basis) });
  3266. };
  3267. if (tokens.remaining_token_count() == 1) {
  3268. // One-value syntax: <flex-grow> | <flex-basis> | none
  3269. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  3270. auto property_and_value = parse_css_value_for_properties(properties, tokens);
  3271. if (!property_and_value.has_value())
  3272. return nullptr;
  3273. auto& value = property_and_value->style_value;
  3274. switch (property_and_value->property) {
  3275. case PropertyID::FlexGrow: {
  3276. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  3277. // https://github.com/w3c/csswg-drafts/issues/5742
  3278. auto flex_basis = PercentageStyleValue::create(Percentage(0));
  3279. auto one = NumberStyleValue::create(1);
  3280. return make_flex_shorthand(*value, one, flex_basis);
  3281. }
  3282. case PropertyID::FlexBasis: {
  3283. auto one = NumberStyleValue::create(1);
  3284. return make_flex_shorthand(one, one, *value);
  3285. }
  3286. case PropertyID::Flex: {
  3287. if (value->is_identifier() && value->to_identifier() == ValueID::None) {
  3288. auto zero = NumberStyleValue::create(0);
  3289. return make_flex_shorthand(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  3290. }
  3291. break;
  3292. }
  3293. default:
  3294. VERIFY_NOT_REACHED();
  3295. }
  3296. return nullptr;
  3297. }
  3298. RefPtr<StyleValue> flex_grow;
  3299. RefPtr<StyleValue> flex_shrink;
  3300. RefPtr<StyleValue> flex_basis;
  3301. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  3302. // if FlexGrow (along with optional FlexShrink) have already been specified.
  3303. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  3304. while (tokens.has_next_token()) {
  3305. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3306. if (!property_and_value.has_value())
  3307. return nullptr;
  3308. auto& value = property_and_value->style_value;
  3309. remove_property(remaining_longhands, property_and_value->property);
  3310. switch (property_and_value->property) {
  3311. case PropertyID::FlexGrow: {
  3312. VERIFY(!flex_grow);
  3313. flex_grow = value.release_nonnull();
  3314. // Flex-shrink may optionally follow directly after.
  3315. auto maybe_flex_shrink = parse_css_value_for_property(PropertyID::FlexShrink, tokens);
  3316. if (maybe_flex_shrink)
  3317. flex_shrink = maybe_flex_shrink.release_nonnull();
  3318. continue;
  3319. }
  3320. case PropertyID::FlexBasis: {
  3321. VERIFY(!flex_basis);
  3322. flex_basis = value.release_nonnull();
  3323. continue;
  3324. }
  3325. default:
  3326. VERIFY_NOT_REACHED();
  3327. }
  3328. }
  3329. if (!flex_grow)
  3330. flex_grow = property_initial_value(m_context.realm(), PropertyID::FlexGrow);
  3331. if (!flex_shrink)
  3332. flex_shrink = property_initial_value(m_context.realm(), PropertyID::FlexShrink);
  3333. if (!flex_basis) {
  3334. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  3335. // https://github.com/w3c/csswg-drafts/issues/5742
  3336. flex_basis = PercentageStyleValue::create(Percentage(0));
  3337. }
  3338. return make_flex_shorthand(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  3339. }
  3340. RefPtr<StyleValue> Parser::parse_flex_flow_value(TokenStream<ComponentValue>& tokens)
  3341. {
  3342. RefPtr<StyleValue> flex_direction;
  3343. RefPtr<StyleValue> flex_wrap;
  3344. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  3345. auto transaction = tokens.begin_transaction();
  3346. while (tokens.has_next_token()) {
  3347. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3348. if (!property_and_value.has_value())
  3349. return nullptr;
  3350. auto& value = property_and_value->style_value;
  3351. remove_property(remaining_longhands, property_and_value->property);
  3352. switch (property_and_value->property) {
  3353. case PropertyID::FlexDirection:
  3354. VERIFY(!flex_direction);
  3355. flex_direction = value.release_nonnull();
  3356. continue;
  3357. case PropertyID::FlexWrap:
  3358. VERIFY(!flex_wrap);
  3359. flex_wrap = value.release_nonnull();
  3360. continue;
  3361. default:
  3362. VERIFY_NOT_REACHED();
  3363. }
  3364. }
  3365. if (!flex_direction)
  3366. flex_direction = property_initial_value(m_context.realm(), PropertyID::FlexDirection);
  3367. if (!flex_wrap)
  3368. flex_wrap = property_initial_value(m_context.realm(), PropertyID::FlexWrap);
  3369. transaction.commit();
  3370. return ShorthandStyleValue::create(PropertyID::FlexFlow,
  3371. { PropertyID::FlexDirection, PropertyID::FlexWrap },
  3372. { flex_direction.release_nonnull(), flex_wrap.release_nonnull() });
  3373. }
  3374. static bool is_generic_font_family(ValueID identifier)
  3375. {
  3376. switch (identifier) {
  3377. case ValueID::Cursive:
  3378. case ValueID::Fantasy:
  3379. case ValueID::Monospace:
  3380. case ValueID::Serif:
  3381. case ValueID::SansSerif:
  3382. case ValueID::UiMonospace:
  3383. case ValueID::UiRounded:
  3384. case ValueID::UiSerif:
  3385. case ValueID::UiSansSerif:
  3386. return true;
  3387. default:
  3388. return false;
  3389. }
  3390. }
  3391. RefPtr<StyleValue> Parser::parse_font_value(TokenStream<ComponentValue>& tokens)
  3392. {
  3393. RefPtr<StyleValue> font_stretch;
  3394. RefPtr<StyleValue> font_style;
  3395. RefPtr<StyleValue> font_weight;
  3396. RefPtr<StyleValue> font_size;
  3397. RefPtr<StyleValue> line_height;
  3398. RefPtr<StyleValue> font_families;
  3399. RefPtr<StyleValue> font_variant;
  3400. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  3401. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  3402. // So, we have to handle that separately.
  3403. int normal_count = 0;
  3404. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStretch, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight };
  3405. auto transaction = tokens.begin_transaction();
  3406. while (tokens.has_next_token()) {
  3407. auto& peek_token = tokens.peek_token();
  3408. if (peek_token.is_ident("normal"sv)) {
  3409. normal_count++;
  3410. (void)tokens.next_token();
  3411. continue;
  3412. }
  3413. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3414. if (!property_and_value.has_value())
  3415. return nullptr;
  3416. auto& value = property_and_value->style_value;
  3417. remove_property(remaining_longhands, property_and_value->property);
  3418. switch (property_and_value->property) {
  3419. case PropertyID::FontSize: {
  3420. VERIFY(!font_size);
  3421. font_size = value.release_nonnull();
  3422. // Consume `/ line-height` if present
  3423. if (tokens.peek_token().is_delim('/')) {
  3424. (void)tokens.next_token();
  3425. auto maybe_line_height = parse_css_value_for_property(PropertyID::LineHeight, tokens);
  3426. if (!maybe_line_height)
  3427. return nullptr;
  3428. line_height = maybe_line_height.release_nonnull();
  3429. }
  3430. // Consume font-families
  3431. auto maybe_font_families = parse_font_family_value(tokens);
  3432. // font-family comes last, so we must not have any tokens left over.
  3433. if (!maybe_font_families || tokens.has_next_token())
  3434. return nullptr;
  3435. font_families = maybe_font_families.release_nonnull();
  3436. continue;
  3437. }
  3438. case PropertyID::FontStretch: {
  3439. VERIFY(!font_stretch);
  3440. font_stretch = value.release_nonnull();
  3441. continue;
  3442. }
  3443. case PropertyID::FontStyle: {
  3444. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  3445. VERIFY(!font_style);
  3446. font_style = value.release_nonnull();
  3447. continue;
  3448. }
  3449. case PropertyID::FontVariant: {
  3450. VERIFY(!font_variant);
  3451. font_variant = value.release_nonnull();
  3452. continue;
  3453. }
  3454. case PropertyID::FontWeight: {
  3455. VERIFY(!font_weight);
  3456. font_weight = value.release_nonnull();
  3457. continue;
  3458. }
  3459. default:
  3460. VERIFY_NOT_REACHED();
  3461. }
  3462. return nullptr;
  3463. }
  3464. // Since normal is the default value for all the properties that can have it, we don't have to actually
  3465. // set anything to normal here. It'll be set when we create the ShorthandStyleValue below.
  3466. // We just need to make sure we were not given more normals than will fit.
  3467. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1) + (font_variant ? 0 : 1) + (font_stretch ? 0 : 1);
  3468. if (unset_value_count < normal_count)
  3469. return nullptr;
  3470. if (!font_size || !font_families)
  3471. return nullptr;
  3472. if (!font_style)
  3473. font_style = property_initial_value(m_context.realm(), PropertyID::FontStyle);
  3474. if (!font_variant)
  3475. font_variant = property_initial_value(m_context.realm(), PropertyID::FontVariant);
  3476. if (!font_weight)
  3477. font_weight = property_initial_value(m_context.realm(), PropertyID::FontWeight);
  3478. if (!font_stretch)
  3479. font_stretch = property_initial_value(m_context.realm(), PropertyID::FontStretch);
  3480. if (!line_height)
  3481. line_height = property_initial_value(m_context.realm(), PropertyID::LineHeight);
  3482. transaction.commit();
  3483. return ShorthandStyleValue::create(PropertyID::Font,
  3484. { PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontStretch, PropertyID::FontSize, PropertyID::LineHeight, PropertyID::FontFamily },
  3485. { 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() });
  3486. }
  3487. RefPtr<StyleValue> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  3488. {
  3489. auto next_is_comma_or_eof = [&]() -> bool {
  3490. return !tokens.has_next_token() || tokens.peek_token().is(Token::Type::Comma);
  3491. };
  3492. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  3493. // eg, these are equivalent:
  3494. // font-family: my cool font\!, serif;
  3495. // font-family: "my cool font!", serif;
  3496. StyleValueVector font_families;
  3497. Vector<String> current_name_parts;
  3498. while (tokens.has_next_token()) {
  3499. auto const& peek = tokens.peek_token();
  3500. if (peek.is(Token::Type::String)) {
  3501. // `font-family: my cool "font";` is invalid.
  3502. if (!current_name_parts.is_empty())
  3503. return nullptr;
  3504. (void)tokens.next_token(); // String
  3505. if (!next_is_comma_or_eof())
  3506. return nullptr;
  3507. font_families.append(StringStyleValue::create(peek.token().string().to_string()));
  3508. (void)tokens.next_token(); // Comma
  3509. continue;
  3510. }
  3511. if (peek.is(Token::Type::Ident)) {
  3512. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  3513. // CSS-wide keywords are not allowed
  3514. if (auto builtin = parse_builtin_value(peek))
  3515. return nullptr;
  3516. auto maybe_ident = value_id_from_string(peek.token().ident());
  3517. // Can't have a generic-font-name as a token in an unquoted font name.
  3518. if (maybe_ident.has_value() && is_generic_font_family(maybe_ident.value())) {
  3519. if (!current_name_parts.is_empty())
  3520. return nullptr;
  3521. (void)tokens.next_token(); // Ident
  3522. if (!next_is_comma_or_eof())
  3523. return nullptr;
  3524. font_families.append(IdentifierStyleValue::create(maybe_ident.value()));
  3525. (void)tokens.next_token(); // Comma
  3526. continue;
  3527. }
  3528. current_name_parts.append(tokens.next_token().token().ident().to_string());
  3529. continue;
  3530. }
  3531. if (peek.is(Token::Type::Comma)) {
  3532. if (current_name_parts.is_empty())
  3533. return nullptr;
  3534. (void)tokens.next_token(); // Comma
  3535. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  3536. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  3537. current_name_parts.clear();
  3538. // Can't have a trailing comma
  3539. if (!tokens.has_next_token())
  3540. return nullptr;
  3541. continue;
  3542. }
  3543. return nullptr;
  3544. }
  3545. if (!current_name_parts.is_empty()) {
  3546. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  3547. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  3548. current_name_parts.clear();
  3549. }
  3550. if (font_families.is_empty())
  3551. return nullptr;
  3552. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  3553. }
  3554. CSSRule* Parser::parse_font_face_rule(TokenStream<ComponentValue>& tokens)
  3555. {
  3556. auto declarations_and_at_rules = parse_a_list_of_declarations(tokens);
  3557. Optional<FlyString> font_family;
  3558. Vector<FontFace::Source> src;
  3559. Vector<Gfx::UnicodeRange> unicode_range;
  3560. Optional<int> weight;
  3561. Optional<int> slope;
  3562. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  3563. if (declaration_or_at_rule.is_at_rule()) {
  3564. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: CSS at-rules are not allowed in @font-face; discarding.");
  3565. continue;
  3566. }
  3567. auto const& declaration = declaration_or_at_rule.declaration();
  3568. if (declaration.name().equals_ignoring_ascii_case("font-weight"sv)) {
  3569. TokenStream token_stream { declaration.values() };
  3570. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  3571. weight = value.value()->to_font_weight();
  3572. }
  3573. continue;
  3574. }
  3575. if (declaration.name().equals_ignoring_ascii_case("font-style"sv)) {
  3576. TokenStream token_stream { declaration.values() };
  3577. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  3578. slope = value.value()->to_font_slope();
  3579. }
  3580. continue;
  3581. }
  3582. if (declaration.name().equals_ignoring_ascii_case("font-family"sv)) {
  3583. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  3584. // Ideally they could share code.
  3585. Vector<FlyString> font_family_parts;
  3586. bool had_syntax_error = false;
  3587. for (size_t i = 0; i < declaration.values().size(); ++i) {
  3588. auto const& part = declaration.values()[i];
  3589. if (part.is(Token::Type::Whitespace))
  3590. continue;
  3591. if (part.is(Token::Type::String)) {
  3592. if (!font_family_parts.is_empty()) {
  3593. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3594. had_syntax_error = true;
  3595. break;
  3596. }
  3597. font_family_parts.append(part.token().string());
  3598. continue;
  3599. }
  3600. if (part.is(Token::Type::Ident)) {
  3601. if (is_css_wide_keyword(part.token().ident())) {
  3602. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3603. had_syntax_error = true;
  3604. break;
  3605. }
  3606. auto value_id = value_id_from_string(part.token().ident());
  3607. if (value_id.has_value() && is_generic_font_family(value_id.value())) {
  3608. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3609. had_syntax_error = true;
  3610. break;
  3611. }
  3612. font_family_parts.append(part.token().ident());
  3613. continue;
  3614. }
  3615. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  3616. had_syntax_error = true;
  3617. break;
  3618. }
  3619. if (had_syntax_error || font_family_parts.is_empty())
  3620. continue;
  3621. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  3622. continue;
  3623. }
  3624. if (declaration.name().equals_ignoring_ascii_case("src"sv)) {
  3625. TokenStream token_stream { declaration.values() };
  3626. Vector<FontFace::Source> supported_sources = parse_font_face_src(token_stream);
  3627. if (!supported_sources.is_empty())
  3628. src = move(supported_sources);
  3629. continue;
  3630. }
  3631. if (declaration.name().equals_ignoring_ascii_case("unicode-range"sv)) {
  3632. Vector<Gfx::UnicodeRange> unicode_ranges;
  3633. bool unicode_range_invalid = false;
  3634. TokenStream all_tokens { declaration.values() };
  3635. auto range_token_lists = parse_a_comma_separated_list_of_component_values(all_tokens);
  3636. for (auto& range_tokens : range_token_lists) {
  3637. TokenStream range_token_stream { range_tokens };
  3638. auto maybe_unicode_range = parse_unicode_range(range_token_stream);
  3639. if (!maybe_unicode_range.has_value()) {
  3640. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face unicode-range format invalid; discarding.");
  3641. unicode_range_invalid = true;
  3642. break;
  3643. }
  3644. unicode_ranges.append(maybe_unicode_range.release_value());
  3645. }
  3646. if (unicode_range_invalid || unicode_ranges.is_empty())
  3647. continue;
  3648. unicode_range = move(unicode_ranges);
  3649. continue;
  3650. }
  3651. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-face; discarding.", declaration.name());
  3652. }
  3653. if (!font_family.has_value()) {
  3654. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  3655. return {};
  3656. }
  3657. if (unicode_range.is_empty()) {
  3658. unicode_range.empend(0x0u, 0x10FFFFu);
  3659. }
  3660. return CSSFontFaceRule::create(m_context.realm(), FontFace { font_family.release_value(), weight, slope, move(src), move(unicode_range) });
  3661. }
  3662. Vector<FontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values)
  3663. {
  3664. // FIXME: Get this information from the system somehow?
  3665. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  3666. auto font_format_is_supported = [](StringView name) {
  3667. // The spec requires us to treat opentype and truetype as synonymous.
  3668. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv, "woff2"sv))
  3669. return true;
  3670. return false;
  3671. };
  3672. Vector<FontFace::Source> supported_sources;
  3673. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  3674. for (auto const& source_token_list : list_of_source_token_lists) {
  3675. TokenStream source_tokens { source_token_list };
  3676. source_tokens.skip_whitespace();
  3677. auto const& first = source_tokens.next_token();
  3678. // <url> [ format(<font-format>)]?
  3679. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  3680. if (auto maybe_url = parse_url_function(first); maybe_url.has_value()) {
  3681. auto url = maybe_url.release_value();
  3682. if (!url.is_valid()) {
  3683. continue;
  3684. }
  3685. Optional<FlyString> format;
  3686. source_tokens.skip_whitespace();
  3687. if (!source_tokens.has_next_token()) {
  3688. supported_sources.empend(move(url), format);
  3689. continue;
  3690. }
  3691. auto maybe_function = source_tokens.next_token();
  3692. if (!maybe_function.is_function()) {
  3693. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  3694. return {};
  3695. }
  3696. auto const& function = maybe_function.function();
  3697. if (function.name().equals_ignoring_ascii_case("format"sv)) {
  3698. TokenStream format_tokens { function.values() };
  3699. format_tokens.skip_whitespace();
  3700. auto const& format_name_token = format_tokens.next_token();
  3701. StringView format_name;
  3702. if (format_name_token.is(Token::Type::Ident)) {
  3703. format_name = format_name_token.token().ident();
  3704. } else if (format_name_token.is(Token::Type::String)) {
  3705. format_name = format_name_token.token().string();
  3706. } else {
  3707. 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());
  3708. return {};
  3709. }
  3710. if (!font_format_is_supported(format_name)) {
  3711. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  3712. continue;
  3713. }
  3714. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  3715. } else {
  3716. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name());
  3717. return {};
  3718. }
  3719. source_tokens.skip_whitespace();
  3720. if (source_tokens.has_next_token()) {
  3721. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.peek_token().to_debug_string());
  3722. return {};
  3723. }
  3724. supported_sources.empend(move(url), format);
  3725. continue;
  3726. }
  3727. if (first.is_function("local"sv)) {
  3728. if (first.function().values().is_empty()) {
  3729. continue;
  3730. }
  3731. supported_sources.empend(first.function().values().first().to_string(), Optional<FlyString> {});
  3732. continue;
  3733. }
  3734. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  3735. return {};
  3736. }
  3737. return supported_sources;
  3738. }
  3739. RefPtr<StyleValue> Parser::parse_list_style_value(TokenStream<ComponentValue>& tokens)
  3740. {
  3741. RefPtr<StyleValue> list_position;
  3742. RefPtr<StyleValue> list_image;
  3743. RefPtr<StyleValue> list_type;
  3744. int found_nones = 0;
  3745. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  3746. auto transaction = tokens.begin_transaction();
  3747. while (tokens.has_next_token()) {
  3748. if (auto peek = tokens.peek_token(); peek.is_ident("none"sv)) {
  3749. (void)tokens.next_token();
  3750. found_nones++;
  3751. continue;
  3752. }
  3753. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3754. if (!property_and_value.has_value())
  3755. return nullptr;
  3756. auto& value = property_and_value->style_value;
  3757. remove_property(remaining_longhands, property_and_value->property);
  3758. switch (property_and_value->property) {
  3759. case PropertyID::ListStylePosition: {
  3760. VERIFY(!list_position);
  3761. list_position = value.release_nonnull();
  3762. continue;
  3763. }
  3764. case PropertyID::ListStyleImage: {
  3765. VERIFY(!list_image);
  3766. list_image = value.release_nonnull();
  3767. continue;
  3768. }
  3769. case PropertyID::ListStyleType: {
  3770. VERIFY(!list_type);
  3771. list_type = value.release_nonnull();
  3772. continue;
  3773. }
  3774. default:
  3775. VERIFY_NOT_REACHED();
  3776. }
  3777. }
  3778. if (found_nones > 2)
  3779. return nullptr;
  3780. if (found_nones == 2) {
  3781. if (list_image || list_type)
  3782. return nullptr;
  3783. auto none = IdentifierStyleValue::create(ValueID::None);
  3784. list_image = none;
  3785. list_type = none;
  3786. } else if (found_nones == 1) {
  3787. if (list_image && list_type)
  3788. return nullptr;
  3789. auto none = IdentifierStyleValue::create(ValueID::None);
  3790. if (!list_image)
  3791. list_image = none;
  3792. if (!list_type)
  3793. list_type = none;
  3794. }
  3795. if (!list_position)
  3796. list_position = property_initial_value(m_context.realm(), PropertyID::ListStylePosition);
  3797. if (!list_image)
  3798. list_image = property_initial_value(m_context.realm(), PropertyID::ListStyleImage);
  3799. if (!list_type)
  3800. list_type = property_initial_value(m_context.realm(), PropertyID::ListStyleType);
  3801. transaction.commit();
  3802. return ShorthandStyleValue::create(PropertyID::ListStyle,
  3803. { PropertyID::ListStylePosition, PropertyID::ListStyleImage, PropertyID::ListStyleType },
  3804. { list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull() });
  3805. }
  3806. RefPtr<StyleValue> Parser::parse_math_depth_value(TokenStream<ComponentValue>& tokens)
  3807. {
  3808. // https://w3c.github.io/mathml-core/#propdef-math-depth
  3809. // auto-add | add(<integer>) | <integer>
  3810. auto transaction = tokens.begin_transaction();
  3811. auto token = tokens.next_token();
  3812. if (tokens.has_next_token())
  3813. return nullptr;
  3814. // auto-add
  3815. if (token.is_ident("auto-add"sv)) {
  3816. transaction.commit();
  3817. return MathDepthStyleValue::create_auto_add();
  3818. }
  3819. // FIXME: Make it easier to parse "thing that might be <bar> or literally anything that resolves to it" and get rid of this
  3820. auto parse_something_that_resolves_to_integer = [this](ComponentValue& token) -> RefPtr<StyleValue> {
  3821. if (token.is(Token::Type::Number) && token.token().number().is_integer())
  3822. return IntegerStyleValue::create(token.token().to_integer());
  3823. if (auto value = parse_calculated_value(token); value && value->resolves_to_number())
  3824. return value;
  3825. return nullptr;
  3826. };
  3827. // add(<integer>)
  3828. if (token.is_function("add"sv)) {
  3829. auto add_tokens = TokenStream { token.function().values() };
  3830. add_tokens.skip_whitespace();
  3831. auto integer_token = add_tokens.next_token();
  3832. add_tokens.skip_whitespace();
  3833. if (add_tokens.has_next_token())
  3834. return nullptr;
  3835. if (auto integer_value = parse_something_that_resolves_to_integer(integer_token)) {
  3836. transaction.commit();
  3837. return MathDepthStyleValue::create_add(integer_value.release_nonnull());
  3838. }
  3839. return nullptr;
  3840. }
  3841. // <integer>
  3842. if (auto integer_value = parse_something_that_resolves_to_integer(token)) {
  3843. transaction.commit();
  3844. return MathDepthStyleValue::create_integer(integer_value.release_nonnull());
  3845. }
  3846. return nullptr;
  3847. }
  3848. RefPtr<StyleValue> Parser::parse_overflow_value(TokenStream<ComponentValue>& tokens)
  3849. {
  3850. auto transaction = tokens.begin_transaction();
  3851. auto maybe_x_value = parse_css_value_for_property(PropertyID::OverflowX, tokens);
  3852. if (!maybe_x_value)
  3853. return nullptr;
  3854. auto maybe_y_value = parse_css_value_for_property(PropertyID::OverflowY, tokens);
  3855. transaction.commit();
  3856. if (maybe_y_value) {
  3857. return ShorthandStyleValue::create(PropertyID::Overflow,
  3858. { PropertyID::OverflowX, PropertyID::OverflowY },
  3859. { maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull() });
  3860. }
  3861. return ShorthandStyleValue::create(PropertyID::Overflow,
  3862. { PropertyID::OverflowX, PropertyID::OverflowY },
  3863. { *maybe_x_value, *maybe_x_value });
  3864. }
  3865. RefPtr<StyleValue> Parser::parse_place_content_value(TokenStream<ComponentValue>& tokens)
  3866. {
  3867. auto transaction = tokens.begin_transaction();
  3868. auto maybe_align_content_value = parse_css_value_for_property(PropertyID::AlignContent, tokens);
  3869. if (!maybe_align_content_value)
  3870. return nullptr;
  3871. if (!tokens.has_next_token()) {
  3872. if (!property_accepts_identifier(PropertyID::JustifyContent, maybe_align_content_value->to_identifier()))
  3873. return nullptr;
  3874. transaction.commit();
  3875. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  3876. { PropertyID::AlignContent, PropertyID::JustifyContent },
  3877. { *maybe_align_content_value, *maybe_align_content_value });
  3878. }
  3879. auto maybe_justify_content_value = parse_css_value_for_property(PropertyID::JustifyContent, tokens);
  3880. if (!maybe_justify_content_value)
  3881. return nullptr;
  3882. transaction.commit();
  3883. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  3884. { PropertyID::AlignContent, PropertyID::JustifyContent },
  3885. { maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull() });
  3886. }
  3887. RefPtr<StyleValue> Parser::parse_place_items_value(TokenStream<ComponentValue>& tokens)
  3888. {
  3889. auto transaction = tokens.begin_transaction();
  3890. auto maybe_align_items_value = parse_css_value_for_property(PropertyID::AlignItems, tokens);
  3891. if (!maybe_align_items_value)
  3892. return nullptr;
  3893. if (!tokens.has_next_token()) {
  3894. if (!property_accepts_identifier(PropertyID::JustifyItems, maybe_align_items_value->to_identifier()))
  3895. return nullptr;
  3896. transaction.commit();
  3897. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  3898. { PropertyID::AlignItems, PropertyID::JustifyItems },
  3899. { *maybe_align_items_value, *maybe_align_items_value });
  3900. }
  3901. auto maybe_justify_items_value = parse_css_value_for_property(PropertyID::JustifyItems, tokens);
  3902. if (!maybe_justify_items_value)
  3903. return nullptr;
  3904. transaction.commit();
  3905. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  3906. { PropertyID::AlignItems, PropertyID::JustifyItems },
  3907. { *maybe_align_items_value, *maybe_justify_items_value });
  3908. }
  3909. RefPtr<StyleValue> Parser::parse_place_self_value(TokenStream<ComponentValue>& tokens)
  3910. {
  3911. auto transaction = tokens.begin_transaction();
  3912. auto maybe_align_self_value = parse_css_value_for_property(PropertyID::AlignSelf, tokens);
  3913. if (!maybe_align_self_value)
  3914. return nullptr;
  3915. if (!tokens.has_next_token()) {
  3916. if (!property_accepts_identifier(PropertyID::JustifySelf, maybe_align_self_value->to_identifier()))
  3917. return nullptr;
  3918. transaction.commit();
  3919. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  3920. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  3921. { *maybe_align_self_value, *maybe_align_self_value });
  3922. }
  3923. auto maybe_justify_self_value = parse_css_value_for_property(PropertyID::JustifySelf, tokens);
  3924. if (!maybe_justify_self_value)
  3925. return nullptr;
  3926. transaction.commit();
  3927. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  3928. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  3929. { *maybe_align_self_value, *maybe_justify_self_value });
  3930. }
  3931. RefPtr<StyleValue> Parser::parse_quotes_value(TokenStream<ComponentValue>& tokens)
  3932. {
  3933. // https://www.w3.org/TR/css-content-3/#quotes-property
  3934. // auto | none | [ <string> <string> ]+
  3935. auto transaction = tokens.begin_transaction();
  3936. if (tokens.remaining_token_count() == 1) {
  3937. auto identifier = parse_identifier_value(tokens.next_token());
  3938. if (identifier && property_accepts_identifier(PropertyID::Quotes, identifier->to_identifier())) {
  3939. transaction.commit();
  3940. return identifier;
  3941. }
  3942. return nullptr;
  3943. }
  3944. // Parse an even number of <string> values.
  3945. if (tokens.remaining_token_count() % 2 != 0)
  3946. return nullptr;
  3947. StyleValueVector string_values;
  3948. while (tokens.has_next_token()) {
  3949. auto maybe_string = parse_string_value(tokens.next_token());
  3950. if (!maybe_string)
  3951. return nullptr;
  3952. string_values.append(maybe_string.release_nonnull());
  3953. }
  3954. transaction.commit();
  3955. return StyleValueList::create(move(string_values), StyleValueList::Separator::Space);
  3956. }
  3957. RefPtr<StyleValue> Parser::parse_text_decoration_value(Vector<ComponentValue> const& component_values)
  3958. {
  3959. RefPtr<StyleValue> decoration_line;
  3960. RefPtr<StyleValue> decoration_thickness;
  3961. RefPtr<StyleValue> decoration_style;
  3962. RefPtr<StyleValue> decoration_color;
  3963. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  3964. auto tokens = TokenStream { component_values };
  3965. while (tokens.has_next_token()) {
  3966. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3967. if (!property_and_value.has_value())
  3968. return nullptr;
  3969. auto& value = property_and_value->style_value;
  3970. remove_property(remaining_longhands, property_and_value->property);
  3971. switch (property_and_value->property) {
  3972. case PropertyID::TextDecorationColor: {
  3973. VERIFY(!decoration_color);
  3974. decoration_color = value.release_nonnull();
  3975. continue;
  3976. }
  3977. case PropertyID::TextDecorationLine: {
  3978. VERIFY(!decoration_line);
  3979. tokens.reconsume_current_input_token();
  3980. auto parsed_decoration_line = parse_text_decoration_line_value(tokens);
  3981. if (!parsed_decoration_line)
  3982. return nullptr;
  3983. decoration_line = parsed_decoration_line.release_nonnull();
  3984. continue;
  3985. }
  3986. case PropertyID::TextDecorationThickness: {
  3987. VERIFY(!decoration_thickness);
  3988. decoration_thickness = value.release_nonnull();
  3989. continue;
  3990. }
  3991. case PropertyID::TextDecorationStyle: {
  3992. VERIFY(!decoration_style);
  3993. decoration_style = value.release_nonnull();
  3994. continue;
  3995. }
  3996. default:
  3997. VERIFY_NOT_REACHED();
  3998. }
  3999. }
  4000. if (!decoration_line)
  4001. decoration_line = property_initial_value(m_context.realm(), PropertyID::TextDecorationLine);
  4002. if (!decoration_thickness)
  4003. decoration_thickness = property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness);
  4004. if (!decoration_style)
  4005. decoration_style = property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle);
  4006. if (!decoration_color)
  4007. decoration_color = property_initial_value(m_context.realm(), PropertyID::TextDecorationColor);
  4008. return ShorthandStyleValue::create(PropertyID::TextDecoration,
  4009. { PropertyID::TextDecorationLine, PropertyID::TextDecorationThickness, PropertyID::TextDecorationStyle, PropertyID::TextDecorationColor },
  4010. { decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull() });
  4011. }
  4012. RefPtr<StyleValue> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  4013. {
  4014. StyleValueVector style_values;
  4015. while (tokens.has_next_token()) {
  4016. auto maybe_value = parse_css_value_for_property(PropertyID::TextDecorationLine, tokens);
  4017. if (!maybe_value)
  4018. break;
  4019. auto value = maybe_value.release_nonnull();
  4020. if (auto maybe_line = value_id_to_text_decoration_line(value->to_identifier()); maybe_line.has_value()) {
  4021. if (maybe_line == TextDecorationLine::None) {
  4022. if (!style_values.is_empty())
  4023. break;
  4024. return value;
  4025. }
  4026. if (style_values.contains_slow(value))
  4027. break;
  4028. style_values.append(move(value));
  4029. continue;
  4030. }
  4031. break;
  4032. }
  4033. if (style_values.is_empty())
  4034. return nullptr;
  4035. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  4036. }
  4037. RefPtr<StyleValue> Parser::parse_easing_value(TokenStream<ComponentValue>& tokens)
  4038. {
  4039. auto transaction = tokens.begin_transaction();
  4040. tokens.skip_whitespace();
  4041. auto const& part = tokens.next_token();
  4042. StringView name;
  4043. Optional<Vector<ComponentValue> const&> arguments;
  4044. if (part.is(Token::Type::Ident)) {
  4045. name = part.token().ident();
  4046. } else if (part.is_function()) {
  4047. name = part.function().name();
  4048. arguments = part.function().values();
  4049. } else {
  4050. return nullptr;
  4051. }
  4052. auto maybe_function = easing_function_from_string(name);
  4053. if (!maybe_function.has_value())
  4054. return nullptr;
  4055. auto function = maybe_function.release_value();
  4056. auto function_metadata = easing_function_metadata(function);
  4057. if (function_metadata.parameters.is_empty() && arguments.has_value()) {
  4058. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: 0", name);
  4059. return nullptr;
  4060. }
  4061. StyleValueVector values;
  4062. size_t argument_index = 0;
  4063. if (arguments.has_value()) {
  4064. auto argument_tokens = TokenStream { *arguments };
  4065. auto arguments_values = parse_a_comma_separated_list_of_component_values(argument_tokens);
  4066. if (arguments_values.size() > function_metadata.parameters.size()) {
  4067. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", name, function_metadata.parameters.size());
  4068. return nullptr;
  4069. }
  4070. for (auto& argument_values : arguments_values) {
  4071. // Prune any whitespace before and after the actual argument values.
  4072. argument_values.remove_all_matching([](auto& value) { return value.is(Token::Type::Whitespace); });
  4073. if (argument_values.size() != 1) {
  4074. dbgln_if(CSS_PARSER_DEBUG, "Too many values in argument to {}. max: 1", name);
  4075. return nullptr;
  4076. }
  4077. auto& value = argument_values[0];
  4078. switch (function_metadata.parameters[argument_index].type) {
  4079. case EasingFunctionParameterType::Number: {
  4080. if (value.is(Token::Type::Number))
  4081. values.append(NumberStyleValue::create(value.token().number().value()));
  4082. else
  4083. return nullptr;
  4084. break;
  4085. }
  4086. case EasingFunctionParameterType::NumberZeroToOne: {
  4087. if (value.is(Token::Type::Number) && value.token().number_value() >= 0 && value.token().number_value() <= 1)
  4088. values.append(NumberStyleValue::create(value.token().number().value()));
  4089. else
  4090. return nullptr;
  4091. break;
  4092. }
  4093. case EasingFunctionParameterType::Integer: {
  4094. if (value.is(Token::Type::Number) && value.token().number().is_integer())
  4095. values.append(IntegerStyleValue::create(value.token().number().integer_value()));
  4096. else
  4097. return nullptr;
  4098. break;
  4099. }
  4100. case EasingFunctionParameterType::StepPosition: {
  4101. if (!value.is(Token::Type::Ident))
  4102. return nullptr;
  4103. auto ident = parse_identifier_value(value);
  4104. if (!ident)
  4105. return nullptr;
  4106. switch (ident->to_identifier()) {
  4107. case ValueID::JumpStart:
  4108. case ValueID::JumpEnd:
  4109. case ValueID::JumpNone:
  4110. case ValueID::Start:
  4111. case ValueID::End:
  4112. values.append(*ident);
  4113. break;
  4114. default:
  4115. return nullptr;
  4116. }
  4117. }
  4118. }
  4119. ++argument_index;
  4120. }
  4121. }
  4122. if (argument_index < function_metadata.parameters.size() && !function_metadata.parameters[argument_index].is_optional) {
  4123. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  4124. return nullptr;
  4125. }
  4126. transaction.commit();
  4127. return EasingStyleValue::create(function, move(values));
  4128. }
  4129. RefPtr<StyleValue> Parser::parse_transform_value(Vector<ComponentValue> const& component_values)
  4130. {
  4131. StyleValueVector transformations;
  4132. auto tokens = TokenStream { component_values };
  4133. tokens.skip_whitespace();
  4134. while (tokens.has_next_token()) {
  4135. tokens.skip_whitespace();
  4136. auto const& part = tokens.next_token();
  4137. if (part.is_ident("none"sv)) {
  4138. if (!transformations.is_empty())
  4139. return nullptr;
  4140. tokens.skip_whitespace();
  4141. if (tokens.has_next_token())
  4142. return nullptr;
  4143. return IdentifierStyleValue::create(ValueID::None);
  4144. }
  4145. if (!part.is_function())
  4146. return nullptr;
  4147. auto maybe_function = transform_function_from_string(part.function().name());
  4148. if (!maybe_function.has_value())
  4149. return nullptr;
  4150. auto function = maybe_function.release_value();
  4151. auto function_metadata = transform_function_metadata(function);
  4152. StyleValueVector values;
  4153. auto argument_tokens = TokenStream { part.function().values() };
  4154. argument_tokens.skip_whitespace();
  4155. size_t argument_index = 0;
  4156. while (argument_tokens.has_next_token()) {
  4157. if (argument_index == function_metadata.parameters.size()) {
  4158. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name(), function_metadata.parameters.size());
  4159. return nullptr;
  4160. }
  4161. auto const& value = argument_tokens.next_token();
  4162. RefPtr<CalculatedStyleValue> maybe_calc_value = parse_calculated_value(value);
  4163. switch (function_metadata.parameters[argument_index].type) {
  4164. case TransformFunctionParameterType::Angle: {
  4165. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  4166. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  4167. values.append(maybe_calc_value.release_nonnull());
  4168. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  4169. values.append(AngleStyleValue::create(Angle::make_degrees(0)));
  4170. } else {
  4171. auto dimension_value = parse_dimension_value(value);
  4172. if (!dimension_value || !dimension_value->is_angle())
  4173. return nullptr;
  4174. values.append(dimension_value.release_nonnull());
  4175. }
  4176. break;
  4177. }
  4178. case TransformFunctionParameterType::Length: {
  4179. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  4180. values.append(maybe_calc_value.release_nonnull());
  4181. } else {
  4182. auto dimension_value = parse_dimension_value(value);
  4183. if (!dimension_value)
  4184. return nullptr;
  4185. if (dimension_value->is_length())
  4186. values.append(dimension_value.release_nonnull());
  4187. else
  4188. return nullptr;
  4189. }
  4190. break;
  4191. }
  4192. case TransformFunctionParameterType::LengthPercentage: {
  4193. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  4194. values.append(maybe_calc_value.release_nonnull());
  4195. } else {
  4196. auto dimension_value = parse_dimension_value(value);
  4197. if (!dimension_value)
  4198. return nullptr;
  4199. if (dimension_value->is_percentage() || dimension_value->is_length())
  4200. values.append(dimension_value.release_nonnull());
  4201. else
  4202. return nullptr;
  4203. }
  4204. break;
  4205. }
  4206. case TransformFunctionParameterType::Number: {
  4207. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  4208. values.append(maybe_calc_value.release_nonnull());
  4209. } else {
  4210. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  4211. argument_tokens.reconsume_current_input_token();
  4212. auto number = parse_number_value(argument_tokens);
  4213. if (!number)
  4214. return nullptr;
  4215. values.append(number.release_nonnull());
  4216. }
  4217. break;
  4218. }
  4219. }
  4220. argument_tokens.skip_whitespace();
  4221. if (argument_tokens.has_next_token()) {
  4222. // Arguments must be separated by commas.
  4223. if (!argument_tokens.next_token().is(Token::Type::Comma))
  4224. return nullptr;
  4225. argument_tokens.skip_whitespace();
  4226. // If there are no more parameters after the comma, this is invalid.
  4227. if (!argument_tokens.has_next_token())
  4228. return nullptr;
  4229. }
  4230. argument_index++;
  4231. }
  4232. if (argument_index < function_metadata.parameters.size() && function_metadata.parameters[argument_index].required) {
  4233. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", argument_index);
  4234. return nullptr;
  4235. }
  4236. transformations.append(TransformationStyleValue::create(function, move(values)));
  4237. }
  4238. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  4239. }
  4240. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  4241. // FIXME: This only supports a 2D position
  4242. RefPtr<StyleValue> Parser::parse_transform_origin_value(Vector<ComponentValue> const& component_values)
  4243. {
  4244. enum class Axis {
  4245. None,
  4246. X,
  4247. Y,
  4248. };
  4249. struct AxisOffset {
  4250. Axis axis;
  4251. NonnullRefPtr<StyleValue> offset;
  4252. };
  4253. auto to_axis_offset = [](RefPtr<StyleValue> value) -> Optional<AxisOffset> {
  4254. if (!value)
  4255. return OptionalNone {};
  4256. if (value->is_percentage())
  4257. return AxisOffset { Axis::None, value->as_percentage() };
  4258. if (value->is_length())
  4259. return AxisOffset { Axis::None, value->as_length() };
  4260. if (value->is_identifier()) {
  4261. switch (value->to_identifier()) {
  4262. case ValueID::Top:
  4263. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
  4264. case ValueID::Left:
  4265. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
  4266. case ValueID::Center:
  4267. return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
  4268. case ValueID::Bottom:
  4269. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
  4270. case ValueID::Right:
  4271. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
  4272. default:
  4273. return OptionalNone {};
  4274. }
  4275. }
  4276. return OptionalNone {};
  4277. };
  4278. auto make_list = [](NonnullRefPtr<StyleValue> const& x_value, NonnullRefPtr<StyleValue> const& y_value) -> NonnullRefPtr<StyleValueList> {
  4279. StyleValueVector values;
  4280. values.append(x_value);
  4281. values.append(y_value);
  4282. return StyleValueList::create(move(values), StyleValueList::Separator::Space);
  4283. };
  4284. auto tokens = TokenStream { component_values };
  4285. switch (component_values.size()) {
  4286. case 1: {
  4287. auto single_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4288. if (!single_value.has_value())
  4289. return nullptr;
  4290. // If only one value is specified, the second value is assumed to be center.
  4291. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  4292. switch (single_value->axis) {
  4293. case Axis::None:
  4294. case Axis::X:
  4295. return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
  4296. case Axis::Y:
  4297. return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
  4298. }
  4299. VERIFY_NOT_REACHED();
  4300. }
  4301. case 2: {
  4302. auto first_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4303. auto second_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  4304. if (!first_value.has_value() || !second_value.has_value())
  4305. return nullptr;
  4306. RefPtr<StyleValue> x_value;
  4307. RefPtr<StyleValue> y_value;
  4308. if (first_value->axis == Axis::X) {
  4309. x_value = first_value->offset;
  4310. } else if (first_value->axis == Axis::Y) {
  4311. y_value = first_value->offset;
  4312. }
  4313. if (second_value->axis == Axis::X) {
  4314. if (x_value)
  4315. return nullptr;
  4316. x_value = second_value->offset;
  4317. // Put the other in Y since its axis can't have been X
  4318. y_value = first_value->offset;
  4319. } else if (second_value->axis == Axis::Y) {
  4320. if (y_value)
  4321. return nullptr;
  4322. y_value = second_value->offset;
  4323. // Put the other in X since its axis can't have been Y
  4324. x_value = first_value->offset;
  4325. } else {
  4326. if (x_value) {
  4327. VERIFY(!y_value);
  4328. y_value = second_value->offset;
  4329. } else {
  4330. VERIFY(!x_value);
  4331. x_value = second_value->offset;
  4332. }
  4333. }
  4334. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  4335. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  4336. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  4337. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  4338. x_value = first_value->offset;
  4339. y_value = second_value->offset;
  4340. }
  4341. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  4342. }
  4343. }
  4344. return nullptr;
  4345. }
  4346. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  4347. {
  4348. auto component_values = parse_a_list_of_component_values(m_token_stream);
  4349. auto tokens = TokenStream(component_values);
  4350. auto parsed_value = parse_css_value(property_id, tokens);
  4351. if (parsed_value.is_error())
  4352. return nullptr;
  4353. return parsed_value.release_value();
  4354. }
  4355. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  4356. {
  4357. if (component_value.is_function()) {
  4358. if (auto maybe_calculated = parse_calculated_value(component_value)) {
  4359. if (maybe_calculated->resolves_to_length_percentage())
  4360. return GridSize(LengthPercentage(maybe_calculated.release_nonnull()));
  4361. // FIXME: Support calculated <flex>
  4362. }
  4363. return {};
  4364. }
  4365. if (component_value.is_ident("auto"sv))
  4366. return GridSize::make_auto();
  4367. if (component_value.is_ident("max-content"sv))
  4368. return GridSize(GridSize::Type::MaxContent);
  4369. if (component_value.is_ident("min-content"sv))
  4370. return GridSize(GridSize::Type::MinContent);
  4371. auto dimension = parse_dimension(component_value);
  4372. if (!dimension.has_value())
  4373. return {};
  4374. if (dimension->is_length())
  4375. return GridSize(dimension->length());
  4376. else if (dimension->is_percentage())
  4377. return GridSize(dimension->percentage());
  4378. else if (dimension->is_flex())
  4379. return GridSize(dimension->flex());
  4380. return {};
  4381. }
  4382. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  4383. {
  4384. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  4385. // 'minmax(min, max)'
  4386. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  4387. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  4388. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  4389. auto function_tokens = TokenStream(component_values);
  4390. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  4391. if (comma_separated_list.size() != 2)
  4392. return {};
  4393. TokenStream part_one_tokens { comma_separated_list[0] };
  4394. part_one_tokens.skip_whitespace();
  4395. if (!part_one_tokens.has_next_token())
  4396. return {};
  4397. auto current_token = part_one_tokens.next_token();
  4398. auto min_grid_size = parse_grid_size(current_token);
  4399. TokenStream part_two_tokens { comma_separated_list[1] };
  4400. part_two_tokens.skip_whitespace();
  4401. if (!part_two_tokens.has_next_token())
  4402. return {};
  4403. current_token = part_two_tokens.next_token();
  4404. auto max_grid_size = parse_grid_size(current_token);
  4405. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  4406. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  4407. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  4408. if (min_grid_size.value().is_flexible_length())
  4409. return {};
  4410. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  4411. }
  4412. return {};
  4413. }
  4414. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  4415. {
  4416. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  4417. // 7.2.3.1. Syntax of repeat()
  4418. // The generic form of the repeat() syntax is, approximately,
  4419. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  4420. auto is_auto_fill = false;
  4421. auto is_auto_fit = false;
  4422. auto function_tokens = TokenStream(component_values);
  4423. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  4424. if (comma_separated_list.size() != 2)
  4425. return {};
  4426. // The first argument specifies the number of repetitions.
  4427. TokenStream part_one_tokens { comma_separated_list[0] };
  4428. part_one_tokens.skip_whitespace();
  4429. if (!part_one_tokens.has_next_token())
  4430. return {};
  4431. auto& current_token = part_one_tokens.next_token();
  4432. auto repeat_count = 0;
  4433. if (current_token.is(Token::Type::Number) && current_token.token().number().is_integer() && current_token.token().number_value() > 0)
  4434. repeat_count = current_token.token().number_value();
  4435. else if (current_token.is_ident("auto-fill"sv))
  4436. is_auto_fill = true;
  4437. else if (current_token.is_ident("auto-fit"sv))
  4438. is_auto_fit = true;
  4439. // The second argument is a track list, which is repeated that number of times.
  4440. TokenStream part_two_tokens { comma_separated_list[1] };
  4441. part_two_tokens.skip_whitespace();
  4442. if (!part_two_tokens.has_next_token())
  4443. return {};
  4444. Vector<CSS::ExplicitGridTrack> repeat_params;
  4445. Vector<Vector<String>> line_names_list;
  4446. auto last_object_was_line_names = false;
  4447. while (part_two_tokens.has_next_token()) {
  4448. auto token = part_two_tokens.next_token();
  4449. Vector<String> line_names;
  4450. if (token.is_block()) {
  4451. if (last_object_was_line_names)
  4452. return {};
  4453. last_object_was_line_names = true;
  4454. if (!token.block().is_square())
  4455. return {};
  4456. TokenStream block_tokens { token.block().values() };
  4457. while (block_tokens.has_next_token()) {
  4458. auto current_block_token = block_tokens.next_token();
  4459. line_names.append(current_block_token.token().ident().to_string());
  4460. block_tokens.skip_whitespace();
  4461. }
  4462. line_names_list.append(line_names);
  4463. part_two_tokens.skip_whitespace();
  4464. } else {
  4465. last_object_was_line_names = false;
  4466. auto track_sizing_function = parse_track_sizing_function(token);
  4467. if (!track_sizing_function.has_value())
  4468. return {};
  4469. // However, there are some restrictions:
  4470. // The repeat() notation can’t be nested.
  4471. if (track_sizing_function.value().is_repeat())
  4472. return {};
  4473. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  4474. if (track_sizing_function.value().is_default() && track_sizing_function.value().grid_size().is_flexible_length() && (is_auto_fill || is_auto_fit))
  4475. return {};
  4476. repeat_params.append(track_sizing_function.value());
  4477. part_two_tokens.skip_whitespace();
  4478. }
  4479. }
  4480. while (line_names_list.size() <= repeat_params.size())
  4481. line_names_list.append({});
  4482. // Thus the precise syntax of the repeat() notation has several forms:
  4483. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  4484. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  4485. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  4486. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  4487. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  4488. // fixed number of repetitions.
  4489. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  4490. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  4491. // list, but the same track list can also contain <fixed-repeat>s.
  4492. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  4493. // subgrid keyword and cannot specify track sizes, only line names.
  4494. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  4495. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  4496. // 1fr [b a] 1fr [b].
  4497. if (is_auto_fill)
  4498. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFill);
  4499. else if (is_auto_fit)
  4500. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), CSS::GridRepeat::Type::AutoFit);
  4501. else
  4502. return CSS::GridRepeat(CSS::GridTrackSizeList(repeat_params, line_names_list), repeat_count);
  4503. }
  4504. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  4505. {
  4506. if (token.is_function()) {
  4507. auto const& function_token = token.function();
  4508. if (function_token.name().equals_ignoring_ascii_case("repeat"sv)) {
  4509. auto maybe_repeat = parse_repeat(function_token.values());
  4510. if (maybe_repeat.has_value())
  4511. return CSS::ExplicitGridTrack(maybe_repeat.value());
  4512. else
  4513. return {};
  4514. } else if (function_token.name().equals_ignoring_ascii_case("minmax"sv)) {
  4515. auto maybe_min_max_value = parse_min_max(function_token.values());
  4516. if (maybe_min_max_value.has_value())
  4517. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  4518. else
  4519. return {};
  4520. } else if (auto maybe_calculated = parse_calculated_value(token)) {
  4521. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_calculated.release_nonnull())));
  4522. }
  4523. return {};
  4524. } else if (token.is_ident("auto"sv)) {
  4525. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  4526. } else if (token.is_block()) {
  4527. return {};
  4528. } else {
  4529. auto grid_size = parse_grid_size(token);
  4530. if (!grid_size.has_value())
  4531. return {};
  4532. return CSS::ExplicitGridTrack(grid_size.value());
  4533. }
  4534. }
  4535. RefPtr<StyleValue> Parser::parse_grid_track_size_list(Vector<ComponentValue> const& component_values, bool allow_separate_line_name_blocks)
  4536. {
  4537. TokenStream tokens { component_values };
  4538. if (contains_single_none_ident(tokens)) {
  4539. tokens.next_token();
  4540. return GridTrackSizeListStyleValue::make_none();
  4541. }
  4542. Vector<CSS::ExplicitGridTrack> track_list;
  4543. Vector<Vector<String>> line_names_list;
  4544. auto last_object_was_line_names = false;
  4545. while (tokens.has_next_token()) {
  4546. auto token = tokens.next_token();
  4547. if (token.is_block()) {
  4548. if (last_object_was_line_names && !allow_separate_line_name_blocks)
  4549. return GridTrackSizeListStyleValue::make_auto();
  4550. last_object_was_line_names = true;
  4551. Vector<String> line_names;
  4552. if (!token.block().is_square())
  4553. return GridTrackSizeListStyleValue::make_auto();
  4554. TokenStream block_tokens { token.block().values() };
  4555. block_tokens.skip_whitespace();
  4556. while (block_tokens.has_next_token()) {
  4557. auto current_block_token = block_tokens.next_token();
  4558. line_names.append(current_block_token.token().ident().to_string());
  4559. block_tokens.skip_whitespace();
  4560. }
  4561. line_names_list.append(line_names);
  4562. } else {
  4563. last_object_was_line_names = false;
  4564. auto track_sizing_function = parse_track_sizing_function(token);
  4565. if (!track_sizing_function.has_value())
  4566. return GridTrackSizeListStyleValue::make_auto();
  4567. // FIXME: Handle multiple repeat values (should combine them here, or remove
  4568. // any other ones if the first one is auto-fill, etc.)
  4569. track_list.append(track_sizing_function.value());
  4570. }
  4571. }
  4572. while (line_names_list.size() <= track_list.size())
  4573. line_names_list.append({});
  4574. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, line_names_list));
  4575. }
  4576. // https://www.w3.org/TR/css-grid-1/#grid-auto-flow-property
  4577. RefPtr<GridAutoFlowStyleValue> Parser::parse_grid_auto_flow_value(TokenStream<ComponentValue>& tokens)
  4578. {
  4579. // [ row | column ] || dense
  4580. if (!tokens.has_next_token())
  4581. return nullptr;
  4582. auto transaction = tokens.begin_transaction();
  4583. auto parse_axis = [&]() -> Optional<GridAutoFlowStyleValue::Axis> {
  4584. auto transaction = tokens.begin_transaction();
  4585. auto token = tokens.next_token();
  4586. if (!token.is(Token::Type::Ident))
  4587. return {};
  4588. auto const& ident = token.token().ident();
  4589. if (ident.equals_ignoring_ascii_case("row"sv)) {
  4590. transaction.commit();
  4591. return GridAutoFlowStyleValue::Axis::Row;
  4592. } else if (ident.equals_ignoring_ascii_case("column"sv)) {
  4593. transaction.commit();
  4594. return GridAutoFlowStyleValue::Axis::Column;
  4595. }
  4596. return {};
  4597. };
  4598. auto parse_dense = [&]() -> Optional<GridAutoFlowStyleValue::Dense> {
  4599. auto transaction = tokens.begin_transaction();
  4600. auto token = tokens.next_token();
  4601. if (!token.is(Token::Type::Ident))
  4602. return {};
  4603. auto const& ident = token.token().ident();
  4604. if (ident.equals_ignoring_ascii_case("dense"sv)) {
  4605. transaction.commit();
  4606. return GridAutoFlowStyleValue::Dense::Yes;
  4607. }
  4608. return {};
  4609. };
  4610. Optional<GridAutoFlowStyleValue::Axis> axis;
  4611. Optional<GridAutoFlowStyleValue::Dense> dense;
  4612. if (axis = parse_axis(); axis.has_value()) {
  4613. dense = parse_dense();
  4614. } else if (dense = parse_dense(); dense.has_value()) {
  4615. axis = parse_axis();
  4616. }
  4617. if (tokens.has_next_token())
  4618. return nullptr;
  4619. transaction.commit();
  4620. return GridAutoFlowStyleValue::create(axis.value_or(GridAutoFlowStyleValue::Axis::Row), dense.value_or(GridAutoFlowStyleValue::Dense::No));
  4621. }
  4622. RefPtr<StyleValue> Parser::parse_grid_auto_track_sizes(Vector<ComponentValue> const& component_values)
  4623. {
  4624. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  4625. // <track-size>+
  4626. Vector<CSS::ExplicitGridTrack> track_list;
  4627. TokenStream tokens { component_values };
  4628. while (tokens.has_next_token()) {
  4629. auto token = tokens.next_token();
  4630. auto track_sizing_function = parse_track_sizing_function(token);
  4631. if (!track_sizing_function.has_value())
  4632. return GridTrackSizeListStyleValue::make_auto();
  4633. // FIXME: Handle multiple repeat values (should combine them here, or remove
  4634. // any other ones if the first one is auto-fill, etc.)
  4635. track_list.append(track_sizing_function.value());
  4636. }
  4637. return GridTrackSizeListStyleValue::create(CSS::GridTrackSizeList(track_list, {}));
  4638. }
  4639. RefPtr<StyleValue> Parser::parse_grid_track_placement(TokenStream<ComponentValue>& tokens)
  4640. {
  4641. // FIXME: This shouldn't be needed. Right now, the below code returns a StyleValue even if no tokens are consumed!
  4642. if (!tokens.has_next_token())
  4643. return nullptr;
  4644. // https://www.w3.org/TR/css-grid-2/#line-placement
  4645. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  4646. // <grid-line> =
  4647. // auto |
  4648. // <custom-ident> |
  4649. // [ <integer> && <custom-ident>? ] |
  4650. // [ span && [ <integer> || <custom-ident> ] ]
  4651. auto is_valid_integer = [](auto& token) -> bool {
  4652. // An <integer> value of zero makes the declaration invalid.
  4653. if (token.is(Token::Type::Number) && token.token().number().is_integer() && token.token().number_value() != 0)
  4654. return true;
  4655. return false;
  4656. };
  4657. auto is_custom_ident = [](auto& token) -> bool {
  4658. // The <custom-ident> additionally excludes the keywords span and auto.
  4659. if (token.is(Token::Type::Ident) && !token.is_ident("span"sv) && !token.is_ident("auto"sv))
  4660. return true;
  4661. return false;
  4662. };
  4663. auto transaction = tokens.begin_transaction();
  4664. // FIXME: Handle the single-token case inside the loop instead, so that we can more easily call this from
  4665. // `parse_grid_area_shorthand_value()` using a single TokenStream.
  4666. if (tokens.remaining_token_count() == 1) {
  4667. auto& token = tokens.next_token();
  4668. if (token.is_ident("auto"sv)) {
  4669. transaction.commit();
  4670. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto());
  4671. }
  4672. if (token.is_ident("span"sv)) {
  4673. transaction.commit();
  4674. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(1));
  4675. }
  4676. if (is_valid_integer(token)) {
  4677. transaction.commit();
  4678. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(token.token().number_value()), {}));
  4679. }
  4680. if (is_custom_ident(token)) {
  4681. transaction.commit();
  4682. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line({}, token.token().ident().to_string()));
  4683. }
  4684. return nullptr;
  4685. }
  4686. auto span_value = false;
  4687. auto span_or_position_value = 0;
  4688. String identifier_value;
  4689. while (tokens.has_next_token()) {
  4690. auto& token = tokens.peek_token();
  4691. if (token.is_ident("auto"sv))
  4692. return nullptr;
  4693. if (token.is_ident("span"sv)) {
  4694. if (span_value)
  4695. return nullptr;
  4696. (void)tokens.next_token(); // span
  4697. span_value = true;
  4698. continue;
  4699. }
  4700. if (is_valid_integer(token)) {
  4701. if (span_or_position_value != 0)
  4702. return nullptr;
  4703. span_or_position_value = static_cast<int>(tokens.next_token().token().to_integer());
  4704. continue;
  4705. }
  4706. if (is_custom_ident(token)) {
  4707. if (!identifier_value.is_empty())
  4708. return nullptr;
  4709. identifier_value = tokens.next_token().token().ident().to_string();
  4710. continue;
  4711. }
  4712. break;
  4713. }
  4714. // Negative integers or zero are invalid.
  4715. if (span_value && span_or_position_value < 1)
  4716. return nullptr;
  4717. // If the <integer> is omitted, it defaults to 1.
  4718. if (span_or_position_value == 0)
  4719. span_or_position_value = 1;
  4720. transaction.commit();
  4721. if (!identifier_value.is_empty())
  4722. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(span_or_position_value, identifier_value));
  4723. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(span_or_position_value));
  4724. }
  4725. RefPtr<StyleValue> Parser::parse_grid_track_placement_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  4726. {
  4727. auto start_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnStart : PropertyID::GridRowStart;
  4728. auto end_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnEnd : PropertyID::GridRowEnd;
  4729. auto transaction = tokens.begin_transaction();
  4730. auto current_token = tokens.next_token();
  4731. Vector<ComponentValue> track_start_placement_tokens;
  4732. while (true) {
  4733. if (current_token.is_delim('/'))
  4734. break;
  4735. track_start_placement_tokens.append(current_token);
  4736. if (!tokens.has_next_token())
  4737. break;
  4738. current_token = tokens.next_token();
  4739. }
  4740. Vector<ComponentValue> track_end_placement_tokens;
  4741. if (tokens.has_next_token()) {
  4742. current_token = tokens.next_token();
  4743. while (true) {
  4744. track_end_placement_tokens.append(current_token);
  4745. if (!tokens.has_next_token())
  4746. break;
  4747. current_token = tokens.next_token();
  4748. }
  4749. }
  4750. TokenStream track_start_placement_token_stream { track_start_placement_tokens };
  4751. auto parsed_start_value = parse_grid_track_placement(track_start_placement_token_stream);
  4752. if (parsed_start_value && track_end_placement_tokens.is_empty()) {
  4753. transaction.commit();
  4754. return ShorthandStyleValue::create(property_id,
  4755. { start_property, end_property },
  4756. { parsed_start_value.release_nonnull(), GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto()) });
  4757. }
  4758. TokenStream track_end_placement_token_stream { track_end_placement_tokens };
  4759. auto parsed_end_value = parse_grid_track_placement(track_end_placement_token_stream);
  4760. if (parsed_start_value && parsed_end_value) {
  4761. transaction.commit();
  4762. return ShorthandStyleValue::create(property_id,
  4763. { start_property, end_property },
  4764. { parsed_start_value.release_nonnull(), parsed_end_value.release_nonnull() });
  4765. }
  4766. return nullptr;
  4767. }
  4768. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  4769. // 7.4. Explicit Grid Shorthand: the grid-template property
  4770. RefPtr<StyleValue> Parser::parse_grid_track_size_list_shorthand_value(PropertyID property_id, Vector<ComponentValue> const& component_values)
  4771. {
  4772. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  4773. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  4774. // none
  4775. // - Sets all three properties to their initial values (none).
  4776. // <'grid-template-rows'> / <'grid-template-columns'>
  4777. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  4778. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  4779. // - Sets grid-template-areas to the strings listed.
  4780. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  4781. // and splicing in the named lines defined before/after each size.
  4782. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  4783. Vector<ComponentValue> template_rows_tokens;
  4784. Vector<ComponentValue> template_columns_tokens;
  4785. Vector<ComponentValue> template_area_tokens;
  4786. int forward_slash_index = -1;
  4787. for (size_t x = 0; x < component_values.size(); x++) {
  4788. if (component_values[x].is_delim('/')) {
  4789. forward_slash_index = x;
  4790. break;
  4791. }
  4792. }
  4793. for (size_t x = 0; x < (forward_slash_index > -1 ? forward_slash_index : component_values.size()); x++) {
  4794. if (component_values[x].is_token() && component_values[x].token().is(Token::Type::String))
  4795. template_area_tokens.append(component_values[x]);
  4796. else
  4797. template_rows_tokens.append(component_values[x]);
  4798. }
  4799. if (forward_slash_index > -1) {
  4800. for (size_t x = forward_slash_index + 1; x < component_values.size(); x++)
  4801. template_columns_tokens.append(component_values[x]);
  4802. }
  4803. TokenStream template_area_token_stream { template_area_tokens };
  4804. auto parsed_template_areas_values = parse_grid_template_areas_value(template_area_token_stream);
  4805. auto parsed_template_rows_values = parse_grid_track_size_list(template_rows_tokens, true);
  4806. auto parsed_template_columns_values = parse_grid_track_size_list(template_columns_tokens);
  4807. return ShorthandStyleValue::create(property_id,
  4808. { PropertyID::GridTemplateAreas, PropertyID::GridTemplateRows, PropertyID::GridTemplateColumns },
  4809. { parsed_template_areas_values.release_nonnull(), parsed_template_rows_values.release_nonnull(), parsed_template_columns_values.release_nonnull() });
  4810. }
  4811. RefPtr<StyleValue> Parser::parse_grid_area_shorthand_value(TokenStream<ComponentValue>& tokens)
  4812. {
  4813. auto transaction = tokens.begin_transaction();
  4814. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  4815. while (tokens.has_next_token()) {
  4816. auto& current_token = tokens.next_token();
  4817. if (check_for_delimiter && current_token.is_delim('/'))
  4818. break;
  4819. placement_tokens.append(current_token);
  4820. }
  4821. };
  4822. Vector<ComponentValue> row_start_placement_tokens;
  4823. parse_placement_tokens(row_start_placement_tokens);
  4824. Vector<ComponentValue> column_start_placement_tokens;
  4825. if (tokens.has_next_token())
  4826. parse_placement_tokens(column_start_placement_tokens);
  4827. Vector<ComponentValue> row_end_placement_tokens;
  4828. if (tokens.has_next_token())
  4829. parse_placement_tokens(row_end_placement_tokens);
  4830. Vector<ComponentValue> column_end_placement_tokens;
  4831. if (tokens.has_next_token())
  4832. parse_placement_tokens(column_end_placement_tokens, false);
  4833. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  4834. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  4835. // grid-column-end.
  4836. TokenStream row_start_placement_token_stream { row_start_placement_tokens };
  4837. auto row_start_style_value = parse_grid_track_placement(row_start_placement_token_stream);
  4838. if (row_start_placement_token_stream.has_next_token())
  4839. return nullptr;
  4840. TokenStream column_start_placement_token_stream { column_start_placement_tokens };
  4841. auto column_start_style_value = parse_grid_track_placement(column_start_placement_token_stream);
  4842. if (column_start_placement_token_stream.has_next_token())
  4843. return nullptr;
  4844. TokenStream row_end_placement_token_stream { row_end_placement_tokens };
  4845. auto row_end_style_value = parse_grid_track_placement(row_end_placement_token_stream);
  4846. if (row_end_placement_token_stream.has_next_token())
  4847. return nullptr;
  4848. TokenStream column_end_placement_token_stream { column_end_placement_tokens };
  4849. auto column_end_style_value = parse_grid_track_placement(column_end_placement_token_stream);
  4850. if (column_end_placement_token_stream.has_next_token())
  4851. return nullptr;
  4852. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  4853. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  4854. // fourth value.
  4855. auto row_start = GridTrackPlacement::make_auto();
  4856. auto column_start = GridTrackPlacement::make_auto();
  4857. auto row_end = GridTrackPlacement::make_auto();
  4858. auto column_end = GridTrackPlacement::make_auto();
  4859. if (row_start_style_value)
  4860. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4861. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  4862. // that value. Otherwise, it is set to auto.
  4863. if (column_start_style_value)
  4864. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4865. else
  4866. column_start = row_start;
  4867. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  4868. // <custom-ident>; otherwise, it is set to auto.
  4869. if (row_end_style_value)
  4870. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4871. else
  4872. row_end = column_start;
  4873. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  4874. // that <custom-ident>; otherwise, it is set to auto.
  4875. if (column_end_style_value)
  4876. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  4877. else
  4878. column_end = row_end;
  4879. transaction.commit();
  4880. return ShorthandStyleValue::create(PropertyID::GridArea,
  4881. { PropertyID::GridRowStart, PropertyID::GridColumnStart, PropertyID::GridRowEnd, PropertyID::GridColumnEnd },
  4882. { GridTrackPlacementStyleValue::create(row_start), GridTrackPlacementStyleValue::create(column_start), GridTrackPlacementStyleValue::create(row_end), GridTrackPlacementStyleValue::create(column_end) });
  4883. }
  4884. RefPtr<StyleValue> Parser::parse_grid_shorthand_value(Vector<ComponentValue> const& component_value)
  4885. {
  4886. // <'grid-template'> |
  4887. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  4888. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  4889. return parse_grid_track_size_list_shorthand_value(PropertyID::Grid, component_value);
  4890. }
  4891. // https://www.w3.org/TR/css-grid-1/#grid-template-areas-property
  4892. RefPtr<StyleValue> Parser::parse_grid_template_areas_value(TokenStream<ComponentValue>& tokens)
  4893. {
  4894. // none | <string>+
  4895. Vector<Vector<String>> grid_area_rows;
  4896. if (contains_single_none_ident(tokens)) {
  4897. (void)tokens.next_token(); // none
  4898. return GridTemplateAreaStyleValue::create(move(grid_area_rows));
  4899. }
  4900. auto transaction = tokens.begin_transaction();
  4901. while (tokens.has_next_token() && tokens.peek_token().is(Token::Type::String)) {
  4902. Vector<String> grid_area_columns;
  4903. auto const parts = MUST(tokens.next_token().token().string().to_string().split(' '));
  4904. for (auto& part : parts) {
  4905. grid_area_columns.append(part);
  4906. }
  4907. grid_area_rows.append(move(grid_area_columns));
  4908. }
  4909. transaction.commit();
  4910. return GridTemplateAreaStyleValue::create(grid_area_rows);
  4911. }
  4912. static bool block_contains_var_or_attr(Block const& block);
  4913. static bool function_contains_var_or_attr(Function const& function)
  4914. {
  4915. if (function.name().equals_ignoring_ascii_case("var"sv) || function.name().equals_ignoring_ascii_case("attr"sv))
  4916. return true;
  4917. for (auto const& token : function.values()) {
  4918. if (token.is_function() && function_contains_var_or_attr(token.function()))
  4919. return true;
  4920. if (token.is_block() && block_contains_var_or_attr(token.block()))
  4921. return true;
  4922. }
  4923. return false;
  4924. }
  4925. bool block_contains_var_or_attr(Block const& block)
  4926. {
  4927. for (auto const& token : block.values()) {
  4928. if (token.is_function() && function_contains_var_or_attr(token.function()))
  4929. return true;
  4930. if (token.is_block() && block_contains_var_or_attr(token.block()))
  4931. return true;
  4932. }
  4933. return false;
  4934. }
  4935. Parser::ParseErrorOr<NonnullRefPtr<StyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& unprocessed_tokens)
  4936. {
  4937. m_context.set_current_property_id(property_id);
  4938. Vector<ComponentValue> component_values;
  4939. bool contains_var_or_attr = false;
  4940. bool const property_accepts_custom_ident = property_accepts_type(property_id, ValueType::CustomIdent);
  4941. while (unprocessed_tokens.has_next_token()) {
  4942. auto const& token = unprocessed_tokens.next_token();
  4943. if (token.is(Token::Type::Semicolon)) {
  4944. unprocessed_tokens.reconsume_current_input_token();
  4945. break;
  4946. }
  4947. if (property_id != PropertyID::Custom) {
  4948. if (token.is(Token::Type::Whitespace))
  4949. continue;
  4950. if (!property_accepts_custom_ident && token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  4951. return ParseError::IncludesIgnoredVendorPrefix;
  4952. }
  4953. if (!contains_var_or_attr) {
  4954. if (token.is_function() && function_contains_var_or_attr(token.function()))
  4955. contains_var_or_attr = true;
  4956. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  4957. contains_var_or_attr = true;
  4958. }
  4959. component_values.append(token);
  4960. }
  4961. if (property_id == PropertyID::Custom || contains_var_or_attr)
  4962. return UnresolvedStyleValue::create(move(component_values), contains_var_or_attr);
  4963. if (component_values.is_empty())
  4964. return ParseError::SyntaxError;
  4965. if (component_values.size() == 1) {
  4966. if (auto parsed_value = parse_builtin_value(component_values.first()))
  4967. return parsed_value.release_nonnull();
  4968. }
  4969. // Special-case property handling
  4970. auto tokens = TokenStream { component_values };
  4971. switch (property_id) {
  4972. case PropertyID::AspectRatio:
  4973. if (auto parsed_value = parse_aspect_ratio_value(tokens); parsed_value && !tokens.has_next_token())
  4974. return parsed_value.release_nonnull();
  4975. return ParseError::SyntaxError;
  4976. case PropertyID::BackdropFilter:
  4977. if (auto parsed_value = parse_filter_value_list_value(tokens); parsed_value && !tokens.has_next_token())
  4978. return parsed_value.release_nonnull();
  4979. return ParseError::SyntaxError;
  4980. case PropertyID::Background:
  4981. if (auto parsed_value = parse_background_value(tokens); parsed_value && !tokens.has_next_token())
  4982. return parsed_value.release_nonnull();
  4983. return ParseError::SyntaxError;
  4984. case PropertyID::BackgroundAttachment:
  4985. case PropertyID::BackgroundClip:
  4986. case PropertyID::BackgroundImage:
  4987. case PropertyID::BackgroundOrigin:
  4988. if (auto parsed_value = parse_simple_comma_separated_value_list(property_id, tokens))
  4989. return parsed_value.release_nonnull();
  4990. return ParseError::SyntaxError;
  4991. case PropertyID::BackgroundPosition:
  4992. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_position_value(tokens, PositionParsingMode::BackgroundPosition); }))
  4993. return parsed_value.release_nonnull();
  4994. return ParseError::SyntaxError;
  4995. case PropertyID::BackgroundPositionX:
  4996. case PropertyID::BackgroundPositionY:
  4997. 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); }))
  4998. return parsed_value.release_nonnull();
  4999. return ParseError::SyntaxError;
  5000. case PropertyID::BackgroundRepeat:
  5001. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  5002. return parsed_value.release_nonnull();
  5003. return ParseError::SyntaxError;
  5004. case PropertyID::BackgroundSize:
  5005. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  5006. return parsed_value.release_nonnull();
  5007. return ParseError::SyntaxError;
  5008. case PropertyID::Border:
  5009. case PropertyID::BorderBottom:
  5010. case PropertyID::BorderLeft:
  5011. case PropertyID::BorderRight:
  5012. case PropertyID::BorderTop:
  5013. if (auto parsed_value = parse_border_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  5014. return parsed_value.release_nonnull();
  5015. return ParseError::SyntaxError;
  5016. case PropertyID::BorderTopLeftRadius:
  5017. case PropertyID::BorderTopRightRadius:
  5018. case PropertyID::BorderBottomRightRadius:
  5019. case PropertyID::BorderBottomLeftRadius:
  5020. if (auto parsed_value = parse_border_radius_value(tokens); parsed_value && !tokens.has_next_token())
  5021. return parsed_value.release_nonnull();
  5022. return ParseError::SyntaxError;
  5023. case PropertyID::BorderRadius:
  5024. if (auto parsed_value = parse_border_radius_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  5025. return parsed_value.release_nonnull();
  5026. return ParseError::SyntaxError;
  5027. case PropertyID::BoxShadow:
  5028. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::Yes); parsed_value && !tokens.has_next_token())
  5029. return parsed_value.release_nonnull();
  5030. return ParseError::SyntaxError;
  5031. case PropertyID::Content:
  5032. if (auto parsed_value = parse_content_value(tokens); parsed_value && !tokens.has_next_token())
  5033. return parsed_value.release_nonnull();
  5034. return ParseError::SyntaxError;
  5035. case PropertyID::Display:
  5036. if (auto parsed_value = parse_display_value(tokens); parsed_value && !tokens.has_next_token())
  5037. return parsed_value.release_nonnull();
  5038. return ParseError::SyntaxError;
  5039. case PropertyID::Flex:
  5040. if (auto parsed_value = parse_flex_value(tokens); parsed_value && !tokens.has_next_token())
  5041. return parsed_value.release_nonnull();
  5042. return ParseError::SyntaxError;
  5043. case PropertyID::FlexFlow:
  5044. if (auto parsed_value = parse_flex_flow_value(tokens); parsed_value && !tokens.has_next_token())
  5045. return parsed_value.release_nonnull();
  5046. return ParseError::SyntaxError;
  5047. case PropertyID::Font:
  5048. if (auto parsed_value = parse_font_value(tokens); parsed_value && !tokens.has_next_token())
  5049. return parsed_value.release_nonnull();
  5050. return ParseError::SyntaxError;
  5051. case PropertyID::FontFamily:
  5052. if (auto parsed_value = parse_font_family_value(tokens); parsed_value && !tokens.has_next_token())
  5053. return parsed_value.release_nonnull();
  5054. return ParseError::SyntaxError;
  5055. case PropertyID::GridArea:
  5056. if (auto parsed_value = parse_grid_area_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  5057. return parsed_value.release_nonnull();
  5058. return ParseError::SyntaxError;
  5059. case PropertyID::GridAutoFlow:
  5060. if (auto parsed_value = parse_grid_auto_flow_value(tokens); parsed_value && !tokens.has_next_token())
  5061. return parsed_value.release_nonnull();
  5062. return ParseError::SyntaxError;
  5063. case PropertyID::GridColumn:
  5064. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  5065. return parsed_value.release_nonnull();
  5066. return ParseError::SyntaxError;
  5067. case PropertyID::GridColumnEnd:
  5068. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5069. return parsed_value.release_nonnull();
  5070. return ParseError::SyntaxError;
  5071. case PropertyID::GridColumnStart:
  5072. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5073. return parsed_value.release_nonnull();
  5074. return ParseError::SyntaxError;
  5075. case PropertyID::GridRow:
  5076. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  5077. return parsed_value.release_nonnull();
  5078. return ParseError::SyntaxError;
  5079. case PropertyID::GridRowEnd:
  5080. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5081. return parsed_value.release_nonnull();
  5082. return ParseError::SyntaxError;
  5083. case PropertyID::GridRowStart:
  5084. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  5085. return parsed_value.release_nonnull();
  5086. return ParseError::SyntaxError;
  5087. case PropertyID::Grid:
  5088. if (auto parsed_value = parse_grid_shorthand_value(component_values))
  5089. return parsed_value.release_nonnull();
  5090. return ParseError::SyntaxError;
  5091. case PropertyID::GridTemplate:
  5092. if (auto parsed_value = parse_grid_track_size_list_shorthand_value(property_id, component_values))
  5093. return parsed_value.release_nonnull();
  5094. return ParseError::SyntaxError;
  5095. case PropertyID::GridTemplateAreas:
  5096. if (auto parsed_value = parse_grid_template_areas_value(tokens); parsed_value && !tokens.has_next_token())
  5097. return parsed_value.release_nonnull();
  5098. return ParseError::SyntaxError;
  5099. case PropertyID::GridTemplateColumns:
  5100. if (auto parsed_value = parse_grid_track_size_list(component_values))
  5101. return parsed_value.release_nonnull();
  5102. return ParseError::SyntaxError;
  5103. case PropertyID::GridTemplateRows:
  5104. if (auto parsed_value = parse_grid_track_size_list(component_values))
  5105. return parsed_value.release_nonnull();
  5106. return ParseError::SyntaxError;
  5107. case PropertyID::GridAutoColumns:
  5108. if (auto parsed_value = parse_grid_auto_track_sizes(component_values))
  5109. return parsed_value.release_nonnull();
  5110. return ParseError::SyntaxError;
  5111. case PropertyID::GridAutoRows:
  5112. if (auto parsed_value = parse_grid_auto_track_sizes(component_values))
  5113. return parsed_value.release_nonnull();
  5114. return ParseError::SyntaxError;
  5115. case PropertyID::ListStyle:
  5116. if (auto parsed_value = parse_list_style_value(tokens); parsed_value && !tokens.has_next_token())
  5117. return parsed_value.release_nonnull();
  5118. return ParseError::SyntaxError;
  5119. case PropertyID::MathDepth:
  5120. if (auto parsed_value = parse_math_depth_value(tokens); parsed_value && !tokens.has_next_token())
  5121. return parsed_value.release_nonnull();
  5122. return ParseError::SyntaxError;
  5123. case PropertyID::Overflow:
  5124. if (auto parsed_value = parse_overflow_value(tokens); parsed_value && !tokens.has_next_token())
  5125. return parsed_value.release_nonnull();
  5126. return ParseError::SyntaxError;
  5127. case PropertyID::PlaceContent:
  5128. if (auto parsed_value = parse_place_content_value(tokens); parsed_value && !tokens.has_next_token())
  5129. return parsed_value.release_nonnull();
  5130. return ParseError::SyntaxError;
  5131. case PropertyID::PlaceItems:
  5132. if (auto parsed_value = parse_place_items_value(tokens); parsed_value && !tokens.has_next_token())
  5133. return parsed_value.release_nonnull();
  5134. return ParseError::SyntaxError;
  5135. case PropertyID::PlaceSelf:
  5136. if (auto parsed_value = parse_place_self_value(tokens); parsed_value && !tokens.has_next_token())
  5137. return parsed_value.release_nonnull();
  5138. return ParseError::SyntaxError;
  5139. case PropertyID::Quotes:
  5140. if (auto parsed_value = parse_quotes_value(tokens); parsed_value && !tokens.has_next_token())
  5141. return parsed_value.release_nonnull();
  5142. return ParseError::SyntaxError;
  5143. case PropertyID::TextDecoration:
  5144. if (auto parsed_value = parse_text_decoration_value(component_values))
  5145. return parsed_value.release_nonnull();
  5146. return ParseError::SyntaxError;
  5147. case PropertyID::TextDecorationLine: {
  5148. TokenStream value_tokens { component_values };
  5149. auto parsed_value = parse_text_decoration_line_value(value_tokens);
  5150. if (parsed_value && !value_tokens.has_next_token())
  5151. return parsed_value.release_nonnull();
  5152. return ParseError::SyntaxError;
  5153. }
  5154. case PropertyID::TextShadow:
  5155. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::No); parsed_value && !tokens.has_next_token())
  5156. return parsed_value.release_nonnull();
  5157. return ParseError::SyntaxError;
  5158. case PropertyID::Transform:
  5159. if (auto parsed_value = parse_transform_value(component_values))
  5160. return parsed_value.release_nonnull();
  5161. return ParseError::SyntaxError;
  5162. case PropertyID::TransformOrigin:
  5163. if (auto parsed_value = parse_transform_origin_value(component_values))
  5164. return parsed_value.release_nonnull();
  5165. return ParseError ::SyntaxError;
  5166. default:
  5167. break;
  5168. }
  5169. // If there's only 1 ComponentValue, we can only produce a single StyleValue.
  5170. if (component_values.size() == 1) {
  5171. auto stream = TokenStream { component_values };
  5172. if (auto parsed_value = parse_css_value_for_property(property_id, stream))
  5173. return parsed_value.release_nonnull();
  5174. } else {
  5175. StyleValueVector parsed_values;
  5176. auto stream = TokenStream { component_values };
  5177. while (auto parsed_value = parse_css_value_for_property(property_id, stream)) {
  5178. parsed_values.append(parsed_value.release_nonnull());
  5179. if (!stream.has_next_token())
  5180. break;
  5181. }
  5182. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 StyleValue, return it directly.
  5183. if (parsed_values.size() == 1)
  5184. return *parsed_values.take_first();
  5185. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  5186. return StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space);
  5187. }
  5188. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  5189. auto unassigned_properties = longhands_for_shorthand(property_id);
  5190. if (unassigned_properties.is_empty())
  5191. return ParseError::SyntaxError;
  5192. auto stream = TokenStream { component_values };
  5193. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<StyleValue const>>> assigned_values;
  5194. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  5195. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  5196. if (property_and_value.has_value()) {
  5197. auto property = property_and_value->property;
  5198. auto value = property_and_value->style_value;
  5199. auto& values = assigned_values.ensure(to_underlying(property));
  5200. if (values.size() + 1 == property_maximum_value_count(property)) {
  5201. // We're done with this property, move on to the next one.
  5202. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  5203. }
  5204. values.append(value.release_nonnull());
  5205. continue;
  5206. }
  5207. // No property matched, so we're done.
  5208. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.peek_token().to_debug_string());
  5209. for (auto id : unassigned_properties)
  5210. dbgln(" {}", string_from_property_id(id));
  5211. break;
  5212. }
  5213. for (auto& property : unassigned_properties)
  5214. assigned_values.ensure(to_underlying(property)).append(property_initial_value(m_context.realm(), property));
  5215. stream.skip_whitespace();
  5216. if (stream.has_next_token())
  5217. return ParseError::SyntaxError;
  5218. Vector<PropertyID> longhand_properties;
  5219. longhand_properties.ensure_capacity(assigned_values.size());
  5220. for (auto& it : assigned_values)
  5221. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  5222. StyleValueVector longhand_values;
  5223. longhand_values.ensure_capacity(assigned_values.size());
  5224. for (auto& it : assigned_values) {
  5225. if (it.value.size() == 1)
  5226. longhand_values.unchecked_append(it.value.take_first());
  5227. else
  5228. longhand_values.unchecked_append(StyleValueList::create(move(it.value), StyleValueList::Separator::Space));
  5229. }
  5230. return { ShorthandStyleValue::create(property_id, move(longhand_properties), move(longhand_values)) };
  5231. }
  5232. RefPtr<StyleValue> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  5233. {
  5234. return parse_css_value_for_properties({ &property_id, 1 }, tokens)
  5235. .map([](auto& it) { return it.style_value; })
  5236. .value_or(nullptr);
  5237. }
  5238. Optional<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  5239. {
  5240. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  5241. for (auto const& property : property_ids) {
  5242. if (property_accepts_type(property, value_type))
  5243. return property;
  5244. }
  5245. return {};
  5246. };
  5247. auto any_property_accepts_type_percentage = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  5248. for (auto const& property : property_ids) {
  5249. if (property_accepts_type(property, value_type) && property_accepts_type(property, ValueType::Percentage))
  5250. return property;
  5251. }
  5252. return {};
  5253. };
  5254. auto any_property_accepts_identifier = [](ReadonlySpan<PropertyID> property_ids, ValueID identifier) -> Optional<PropertyID> {
  5255. for (auto const& property : property_ids) {
  5256. if (property_accepts_identifier(property, identifier))
  5257. return property;
  5258. }
  5259. return {};
  5260. };
  5261. auto& peek_token = tokens.peek_token();
  5262. if (auto property = any_property_accepts_type(property_ids, ValueType::EasingFunction); property.has_value()) {
  5263. if (auto maybe_easing_function = parse_easing_value(tokens))
  5264. return PropertyAndValue { *property, maybe_easing_function };
  5265. }
  5266. if (peek_token.is(Token::Type::Ident)) {
  5267. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  5268. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  5269. auto ident = value_id_from_string(peek_token.token().ident());
  5270. if (ident.has_value()) {
  5271. if (auto property = any_property_accepts_identifier(property_ids, ident.value()); property.has_value()) {
  5272. (void)tokens.next_token();
  5273. return PropertyAndValue { *property, IdentifierStyleValue::create(ident.value()) };
  5274. }
  5275. }
  5276. // Custom idents
  5277. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  5278. (void)tokens.next_token();
  5279. return PropertyAndValue { *property, CustomIdentStyleValue::create(peek_token.token().ident()) };
  5280. }
  5281. }
  5282. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  5283. if (auto maybe_color = parse_color_value(peek_token)) {
  5284. (void)tokens.next_token();
  5285. return PropertyAndValue { *property, maybe_color };
  5286. }
  5287. }
  5288. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  5289. if (auto maybe_image = parse_image_value(peek_token)) {
  5290. (void)tokens.next_token();
  5291. return PropertyAndValue { *property, maybe_image };
  5292. }
  5293. }
  5294. if (auto property = any_property_accepts_type(property_ids, ValueType::Position); property.has_value()) {
  5295. if (auto maybe_position = parse_position_value(tokens))
  5296. return PropertyAndValue { *property, maybe_position };
  5297. }
  5298. if (auto property = any_property_accepts_type(property_ids, ValueType::BackgroundPosition); property.has_value()) {
  5299. if (auto maybe_position = parse_position_value(tokens, PositionParsingMode::BackgroundPosition))
  5300. return PropertyAndValue { *property, maybe_position };
  5301. }
  5302. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  5303. if (auto maybe_ratio = parse_ratio_value(tokens))
  5304. return PropertyAndValue { *property, maybe_ratio };
  5305. }
  5306. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  5307. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  5308. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  5309. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  5310. if (property_accepting_integer.has_value()) {
  5311. auto transaction = tokens.begin_transaction();
  5312. if (auto integer = parse_integer_value(tokens); integer && property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  5313. transaction.commit();
  5314. return PropertyAndValue { *property_accepting_integer, integer };
  5315. }
  5316. }
  5317. if (property_accepting_number.has_value()) {
  5318. auto transaction = tokens.begin_transaction();
  5319. if (auto number = parse_number_value(tokens); number && property_accepts_number(*property_accepting_number, number->as_number().number())) {
  5320. transaction.commit();
  5321. return PropertyAndValue { *property_accepting_number, number };
  5322. }
  5323. }
  5324. }
  5325. if (peek_token.is(Token::Type::Percentage)) {
  5326. auto percentage = Percentage(peek_token.token().percentage());
  5327. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  5328. (void)tokens.next_token();
  5329. return PropertyAndValue { *property, PercentageStyleValue::create(percentage) };
  5330. }
  5331. }
  5332. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  5333. if (auto maybe_rect = parse_rect_value(peek_token)) {
  5334. (void)tokens.next_token();
  5335. return PropertyAndValue { *property, maybe_rect };
  5336. }
  5337. }
  5338. if (peek_token.is(Token::Type::String)) {
  5339. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  5340. return PropertyAndValue { *property, StringStyleValue::create(tokens.next_token().token().string().to_string()) };
  5341. }
  5342. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  5343. if (auto url = parse_url_value(peek_token)) {
  5344. (void)tokens.next_token();
  5345. return PropertyAndValue { *property, url };
  5346. }
  5347. }
  5348. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  5349. || any_property_accepts_type(property_ids, ValueType::Flex).has_value()
  5350. || any_property_accepts_type(property_ids, ValueType::Frequency).has_value()
  5351. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  5352. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  5353. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  5354. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  5355. if (property_accepts_dimension) {
  5356. if (peek_token.is(Token::Type::Number) && m_context.is_parsing_svg_presentation_attribute()) {
  5357. auto transaction = tokens.begin_transaction();
  5358. auto token = tokens.next_token();
  5359. // https://svgwg.org/svg2-draft/types.html#presentation-attribute-css-value
  5360. // We need to allow <number> in any place that expects a <length> or <angle>.
  5361. // FIXME: How should these numbers be interpreted? https://github.com/w3c/svgwg/issues/792
  5362. // For now: Convert them to px lengths, or deg angles.
  5363. auto angle = Angle::make_degrees(token.token().number_value());
  5364. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  5365. transaction.commit();
  5366. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  5367. }
  5368. auto length = Length::make_px(CSSPixels::nearest_value_for(token.token().number_value()));
  5369. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  5370. transaction.commit();
  5371. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  5372. }
  5373. }
  5374. auto transaction = tokens.begin_transaction();
  5375. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  5376. (void)tokens.next_token();
  5377. auto dimension = maybe_dimension.release_value();
  5378. if (dimension.is_angle()) {
  5379. auto angle = dimension.angle();
  5380. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  5381. transaction.commit();
  5382. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  5383. }
  5384. }
  5385. if (dimension.is_flex()) {
  5386. auto flex = dimension.flex();
  5387. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value() && property_accepts_flex(*property, flex)) {
  5388. transaction.commit();
  5389. return PropertyAndValue { *property, FlexStyleValue::create(flex) };
  5390. }
  5391. }
  5392. if (dimension.is_frequency()) {
  5393. auto frequency = dimension.frequency();
  5394. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  5395. transaction.commit();
  5396. return PropertyAndValue { *property, FrequencyStyleValue::create(frequency) };
  5397. }
  5398. }
  5399. if (dimension.is_length()) {
  5400. auto length = dimension.length();
  5401. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  5402. transaction.commit();
  5403. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  5404. }
  5405. }
  5406. if (dimension.is_resolution()) {
  5407. auto resolution = dimension.resolution();
  5408. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  5409. transaction.commit();
  5410. return PropertyAndValue { *property, ResolutionStyleValue::create(resolution) };
  5411. }
  5412. }
  5413. if (dimension.is_time()) {
  5414. auto time = dimension.time();
  5415. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  5416. transaction.commit();
  5417. return PropertyAndValue { *property, TimeStyleValue::create(time) };
  5418. }
  5419. }
  5420. }
  5421. }
  5422. // In order to not end up parsing `calc()` and other math expressions multiple times,
  5423. // we parse it once, and then see if its resolved type matches what the property accepts.
  5424. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  5425. if (auto maybe_calculated = parse_calculated_value(peek_token); maybe_calculated) {
  5426. (void)tokens.next_token();
  5427. auto& calculated = *maybe_calculated;
  5428. // This is a bit sensitive to ordering: `<foo>` and `<percentage>` have to be checked before `<foo-percentage>`.
  5429. // FIXME: When parsing SVG presentation attributes, <number> is permitted wherever <length>, <length-percentage>, or <angle> are.
  5430. // The specifics are unclear, so I'm ignoring this for calculated values for now.
  5431. // See https://github.com/w3c/svgwg/issues/792
  5432. if (calculated.resolves_to_percentage()) {
  5433. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  5434. return PropertyAndValue { *property, calculated };
  5435. } else if (calculated.resolves_to_angle()) {
  5436. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  5437. return PropertyAndValue { *property, calculated };
  5438. } else if (calculated.resolves_to_angle_percentage()) {
  5439. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Angle); property.has_value())
  5440. return PropertyAndValue { *property, calculated };
  5441. } else if (calculated.resolves_to_flex()) {
  5442. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value())
  5443. return PropertyAndValue { *property, calculated };
  5444. } else if (calculated.resolves_to_frequency()) {
  5445. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  5446. return PropertyAndValue { *property, calculated };
  5447. } else if (calculated.resolves_to_frequency_percentage()) {
  5448. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Frequency); property.has_value())
  5449. return PropertyAndValue { *property, calculated };
  5450. } else if (calculated.resolves_to_number()) {
  5451. if (property_accepts_numeric) {
  5452. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  5453. return PropertyAndValue { property_or_resolved, calculated };
  5454. }
  5455. } else if (calculated.resolves_to_number_percentage()) {
  5456. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Number); property.has_value())
  5457. return PropertyAndValue { *property, calculated };
  5458. } else if (calculated.resolves_to_length()) {
  5459. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  5460. return PropertyAndValue { *property, calculated };
  5461. } else if (calculated.resolves_to_length_percentage()) {
  5462. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Length); property.has_value())
  5463. return PropertyAndValue { *property, calculated };
  5464. } else if (calculated.resolves_to_time()) {
  5465. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  5466. return PropertyAndValue { *property, calculated };
  5467. } else if (calculated.resolves_to_time_percentage()) {
  5468. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Time); property.has_value())
  5469. return PropertyAndValue { *property, calculated };
  5470. }
  5471. }
  5472. }
  5473. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  5474. if (auto value = parse_paint_value(tokens))
  5475. return PropertyAndValue { *property, value.release_nonnull() };
  5476. }
  5477. return OptionalNone {};
  5478. }
  5479. class UnparsedCalculationNode final : public CalculationNode {
  5480. public:
  5481. static NonnullOwnPtr<UnparsedCalculationNode> create(ComponentValue component_value)
  5482. {
  5483. return adopt_own(*new (nothrow) UnparsedCalculationNode(move(component_value)));
  5484. }
  5485. virtual ~UnparsedCalculationNode() = default;
  5486. ComponentValue& component_value() { return m_component_value; }
  5487. virtual String to_string() const override { VERIFY_NOT_REACHED(); }
  5488. virtual Optional<CalculatedStyleValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  5489. virtual Optional<CSSNumericType> determine_type(Web::CSS::PropertyID) const override { VERIFY_NOT_REACHED(); }
  5490. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  5491. virtual CalculatedStyleValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CalculatedStyleValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  5492. virtual void for_each_child_node(AK::Function<void(NonnullOwnPtr<CalculationNode>&)> const&) override { }
  5493. virtual void dump(StringBuilder& builder, int indent) const override
  5494. {
  5495. builder.appendff("{: >{}}UNPARSED({})\n", "", indent, m_component_value.to_debug_string());
  5496. }
  5497. private:
  5498. UnparsedCalculationNode(ComponentValue component_value)
  5499. : CalculationNode(Type::Unparsed)
  5500. , m_component_value(move(component_value))
  5501. {
  5502. }
  5503. ComponentValue m_component_value;
  5504. };
  5505. // https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
  5506. LengthOrCalculated Parser::Parser::parse_as_sizes_attribute()
  5507. {
  5508. // 1. Let unparsed sizes list be the result of parsing a comma-separated list of component values
  5509. // from the value of element's sizes attribute (or the empty string, if the attribute is absent).
  5510. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  5511. // 2. Let size be null.
  5512. Optional<LengthOrCalculated> size;
  5513. // 3. For each unparsed size in unparsed sizes list:
  5514. for (auto& unparsed_size : unparsed_sizes_list) {
  5515. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  5516. // If unparsed size is now empty, that is a parse error; continue.
  5517. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  5518. unparsed_size.take_last();
  5519. if (unparsed_size.is_empty()) {
  5520. log_parse_error();
  5521. continue;
  5522. }
  5523. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  5524. // let size be its value and remove the component value from unparsed size.
  5525. // FIXME: Any CSS function other than the math functions is invalid.
  5526. // Otherwise, there is a parse error; continue.
  5527. if (auto source_size_value = parse_source_size_value(unparsed_size.last()); source_size_value.has_value()) {
  5528. size = source_size_value.value();
  5529. unparsed_size.take_last();
  5530. } else {
  5531. log_parse_error();
  5532. continue;
  5533. }
  5534. // 3. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  5535. while (!unparsed_size.is_empty() && unparsed_size.last().is_token() && unparsed_size.last().token().is(Token::Type::Whitespace))
  5536. unparsed_size.take_last();
  5537. // If unparsed size is now empty, then return size.
  5538. if (unparsed_size.is_empty())
  5539. return size.value();
  5540. // FIXME: If this was not the keyword auto and it was not the last item in unparsed sizes list, that is a parse error.
  5541. // 4. Parse the remaining component values in unparsed size as a <media-condition>.
  5542. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  5543. TokenStream<ComponentValue> token_stream { unparsed_size };
  5544. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  5545. if (media_condition && media_condition->evaluate(*m_context.window()) == MatchResult::True) {
  5546. return size.value();
  5547. } else {
  5548. continue;
  5549. }
  5550. // 5. If size is not auto, then return size.
  5551. if (size.value().is_calculated() || !size.value().value().is_auto())
  5552. return size.value();
  5553. }
  5554. return Length(100, Length::Type::Vw);
  5555. }
  5556. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  5557. OwnPtr<CalculationNode> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  5558. {
  5559. // 1. Discard any <whitespace-token>s from values.
  5560. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  5561. struct Operator {
  5562. char delim;
  5563. };
  5564. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  5565. Vector<Value> values;
  5566. for (auto& value : original_values) {
  5567. if (value.is(Token::Type::Whitespace))
  5568. continue;
  5569. if (value.is(Token::Type::Delim)) {
  5570. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  5571. // NOTE: Sequential operators are invalid syntax.
  5572. if (!values.is_empty() && values.last().has<Operator>())
  5573. return nullptr;
  5574. values.append(Operator { static_cast<char>(value.token().delim()) });
  5575. continue;
  5576. }
  5577. }
  5578. if (value.is(Token::Type::Ident)) {
  5579. auto maybe_constant = CalculationNode::constant_type_from_string(value.token().ident());
  5580. if (maybe_constant.has_value()) {
  5581. values.append({ ConstantCalculationNode::create(maybe_constant.value()) });
  5582. continue;
  5583. }
  5584. }
  5585. if (value.is(Token::Type::Number)) {
  5586. values.append({ NumericCalculationNode::create(value.token().number()) });
  5587. continue;
  5588. }
  5589. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  5590. if (dimension->is_angle())
  5591. values.append({ NumericCalculationNode::create(dimension->angle()) });
  5592. else if (dimension->is_frequency())
  5593. values.append({ NumericCalculationNode::create(dimension->frequency()) });
  5594. else if (dimension->is_length())
  5595. values.append({ NumericCalculationNode::create(dimension->length()) });
  5596. else if (dimension->is_percentage())
  5597. values.append({ NumericCalculationNode::create(dimension->percentage()) });
  5598. // FIXME: Resolutions, once calc() supports them.
  5599. else if (dimension->is_time())
  5600. values.append({ NumericCalculationNode::create(dimension->time()) });
  5601. else if (dimension->is_flex()) {
  5602. // https://www.w3.org/TR/css3-grid-layout/#fr-unit
  5603. // NOTE: <flex> values are not <length>s (nor are they compatible with <length>s, like some <percentage> values),
  5604. // so they cannot be represented in or combined with other unit types in calc() expressions.
  5605. return nullptr;
  5606. } else {
  5607. VERIFY_NOT_REACHED();
  5608. }
  5609. continue;
  5610. }
  5611. values.append({ UnparsedCalculationNode::create(value) });
  5612. }
  5613. // If we have no values, the syntax is invalid.
  5614. if (values.is_empty())
  5615. return nullptr;
  5616. // NOTE: If the first or last value is an operator, the syntax is invalid.
  5617. if (values.first().has<Operator>() || values.last().has<Operator>())
  5618. return nullptr;
  5619. // 3. Collect children into Product and Invert nodes.
  5620. // For every consecutive run of value items in values separated by "*" or "/" operators:
  5621. while (true) {
  5622. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  5623. return item.template has<Operator>()
  5624. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  5625. });
  5626. if (!first_product_operator.has_value())
  5627. break;
  5628. auto start_of_run = first_product_operator.value() - 1;
  5629. auto end_of_run = first_product_operator.value() + 1;
  5630. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  5631. auto& item = values[i];
  5632. if (!item.has<Operator>()) {
  5633. end_of_run = i - 1;
  5634. break;
  5635. }
  5636. auto delim = item.get<Operator>().delim;
  5637. if (!first_is_one_of(delim, '*', '/')) {
  5638. end_of_run = i - 1;
  5639. break;
  5640. }
  5641. }
  5642. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  5643. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  5644. run_values.append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>()));
  5645. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  5646. auto& operator_ = values[i].get<Operator>().delim;
  5647. auto& rhs = values[i + 1];
  5648. if (operator_ == '/') {
  5649. run_values.append(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  5650. continue;
  5651. }
  5652. VERIFY(operator_ == '*');
  5653. run_values.append(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  5654. }
  5655. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  5656. auto product_node = ProductCalculationNode::create(move(run_values));
  5657. values.remove(start_of_run, end_of_run - start_of_run + 1);
  5658. values.insert(start_of_run, { move(product_node) });
  5659. }
  5660. // 4. Collect children into Sum and Negate nodes.
  5661. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  5662. {
  5663. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  5664. for (auto i = 0u; i < values.size(); ++i) {
  5665. auto& maybe_minus_operator = values[i];
  5666. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  5667. continue;
  5668. auto rhs_index = ++i;
  5669. auto& rhs = values[rhs_index];
  5670. NonnullOwnPtr<CalculationNode> negate_node = NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  5671. values.remove(rhs_index);
  5672. values.insert(rhs_index, move(negate_node));
  5673. }
  5674. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  5675. if (values.size() == 1) {
  5676. values.first().visit(
  5677. [&](ComponentValue& component_value) {
  5678. if (component_value.is_block() && component_value.block().is_paren())
  5679. single_value = UnparsedCalculationNode::create(component_value);
  5680. },
  5681. [&](NonnullOwnPtr<CalculationNode>& node) {
  5682. if (node->type() == CalculationNode::Type::Product)
  5683. single_value = move(node);
  5684. },
  5685. [](auto&) {});
  5686. }
  5687. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  5688. if (!single_value.has_value()) {
  5689. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  5690. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  5691. value_items.ensure_capacity(values.size());
  5692. for (auto& value : values) {
  5693. if (value.has<Operator>())
  5694. continue;
  5695. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  5696. }
  5697. single_value = SumCalculationNode::create(move(value_items));
  5698. }
  5699. }
  5700. // 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.
  5701. // For every leaf node leaf in values:
  5702. bool parsing_failed_for_child_node = false;
  5703. single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) {
  5704. if (node->type() != CalculationNode::Type::Unparsed)
  5705. return;
  5706. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  5707. auto& component_value = unparsed_node.component_value();
  5708. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  5709. if (component_value.is_block() && component_value.block().is_paren()) {
  5710. auto leaf_calculation = parse_a_calculation(component_value.block().values());
  5711. if (!leaf_calculation) {
  5712. parsing_failed_for_child_node = true;
  5713. return;
  5714. }
  5715. node = leaf_calculation.release_nonnull();
  5716. return;
  5717. }
  5718. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  5719. // NOTE: All function tokens at this point should be math functions.
  5720. else if (component_value.is_function()) {
  5721. auto& function = component_value.function();
  5722. auto leaf_calculation = parse_a_calc_function_node(function);
  5723. if (!leaf_calculation) {
  5724. parsing_failed_for_child_node = true;
  5725. return;
  5726. }
  5727. node = leaf_calculation.release_nonnull();
  5728. return;
  5729. }
  5730. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  5731. // So, the calc() is invalid.
  5732. 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());
  5733. parsing_failed_for_child_node = true;
  5734. return;
  5735. });
  5736. if (parsing_failed_for_child_node)
  5737. return nullptr;
  5738. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  5739. return single_value.release_value();
  5740. }
  5741. bool Parser::has_ignored_vendor_prefix(StringView string)
  5742. {
  5743. if (!string.starts_with('-'))
  5744. return false;
  5745. if (string.starts_with("--"sv))
  5746. return false;
  5747. if (string.starts_with("-libweb-"sv))
  5748. return false;
  5749. return true;
  5750. }
  5751. NonnullRefPtr<StyleValue> Parser::resolve_unresolved_style_value(Badge<StyleComputer>, ParsingContext const& context, DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  5752. {
  5753. // Unresolved always contains a var() or attr(), unless it is a custom property's value, in which case we shouldn't be trying
  5754. // to produce a different StyleValue from it.
  5755. VERIFY(unresolved.contains_var_or_attr());
  5756. // If the value is invalid, we fall back to `unset`: https://www.w3.org/TR/css-variables-1/#invalid-at-computed-value-time
  5757. auto parser = MUST(Parser::create(context, ""sv));
  5758. return parser.resolve_unresolved_style_value(element, pseudo_element, property_id, unresolved);
  5759. }
  5760. class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> {
  5761. public:
  5762. static NonnullRefPtr<PropertyDependencyNode> create(String name)
  5763. {
  5764. return adopt_ref(*new PropertyDependencyNode(move(name)));
  5765. }
  5766. void add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  5767. {
  5768. for (auto const& child : m_children) {
  5769. if (child->m_name == new_child->m_name)
  5770. return;
  5771. }
  5772. // We detect self-reference already.
  5773. VERIFY(new_child->m_name != m_name);
  5774. m_children.append(move(new_child));
  5775. }
  5776. bool has_cycles()
  5777. {
  5778. if (m_marked)
  5779. return true;
  5780. TemporaryChange change { m_marked, true };
  5781. for (auto& child : m_children) {
  5782. if (child->has_cycles())
  5783. return true;
  5784. }
  5785. return false;
  5786. }
  5787. private:
  5788. explicit PropertyDependencyNode(String name)
  5789. : m_name(move(name))
  5790. {
  5791. }
  5792. String m_name;
  5793. Vector<NonnullRefPtr<PropertyDependencyNode>> m_children;
  5794. bool m_marked { false };
  5795. };
  5796. NonnullRefPtr<StyleValue> Parser::resolve_unresolved_style_value(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  5797. {
  5798. TokenStream unresolved_values_without_variables_expanded { unresolved.values() };
  5799. Vector<ComponentValue> values_with_variables_expanded;
  5800. HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  5801. if (!expand_variables(element, pseudo_element, string_from_property_id(property_id), dependencies, unresolved_values_without_variables_expanded, values_with_variables_expanded))
  5802. return UnsetStyleValue::the();
  5803. TokenStream unresolved_values_with_variables_expanded { values_with_variables_expanded };
  5804. Vector<ComponentValue> expanded_values;
  5805. if (!expand_unresolved_values(element, string_from_property_id(property_id), unresolved_values_with_variables_expanded, expanded_values))
  5806. return UnsetStyleValue::the();
  5807. auto expanded_value_tokens = TokenStream { expanded_values };
  5808. if (auto parsed_value = parse_css_value(property_id, expanded_value_tokens); !parsed_value.is_error())
  5809. return parsed_value.release_value();
  5810. return UnsetStyleValue::the();
  5811. }
  5812. static RefPtr<StyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, FlyString const& custom_property_name)
  5813. {
  5814. if (pseudo_element.has_value()) {
  5815. if (auto it = element.custom_properties(pseudo_element).find(custom_property_name.to_string()); it != element.custom_properties(pseudo_element).end())
  5816. return it->value.value;
  5817. }
  5818. for (auto const* current_element = &element; current_element; current_element = current_element->parent_element()) {
  5819. if (auto it = current_element->custom_properties({}).find(custom_property_name.to_string()); it != current_element->custom_properties({}).end())
  5820. return it->value.value;
  5821. }
  5822. return nullptr;
  5823. }
  5824. bool Parser::expand_variables(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, StringView property_name, HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>>& dependencies, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  5825. {
  5826. // Arbitrary large value chosen to avoid the billion-laughs attack.
  5827. // https://www.w3.org/TR/css-variables-1/#long-variables
  5828. size_t const MAX_VALUE_COUNT = 16384;
  5829. if (source.remaining_token_count() + dest.size() > MAX_VALUE_COUNT) {
  5830. dbgln("Stopped expanding CSS variables: maximum length reached.");
  5831. return false;
  5832. }
  5833. auto get_dependency_node = [&](FlyString name) -> NonnullRefPtr<PropertyDependencyNode> {
  5834. if (auto existing = dependencies.get(name); existing.has_value())
  5835. return *existing.value();
  5836. auto new_node = PropertyDependencyNode::create(name.to_string());
  5837. dependencies.set(name, new_node);
  5838. return new_node;
  5839. };
  5840. while (source.has_next_token()) {
  5841. auto const& value = source.next_token();
  5842. if (value.is_block()) {
  5843. auto const& source_block = value.block();
  5844. Vector<ComponentValue> block_values;
  5845. TokenStream source_block_contents { source_block.values() };
  5846. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_block_contents, block_values))
  5847. return false;
  5848. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  5849. dest.empend(block);
  5850. continue;
  5851. }
  5852. if (!value.is_function()) {
  5853. dest.empend(value);
  5854. continue;
  5855. }
  5856. if (!value.function().name().equals_ignoring_ascii_case("var"sv)) {
  5857. auto const& source_function = value.function();
  5858. Vector<ComponentValue> function_values;
  5859. TokenStream source_function_contents { source_function.values() };
  5860. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_function_contents, function_values))
  5861. return false;
  5862. NonnullRefPtr<Function> function = Function::create(source_function.name(), move(function_values));
  5863. dest.empend(function);
  5864. continue;
  5865. }
  5866. TokenStream var_contents { value.function().values() };
  5867. var_contents.skip_whitespace();
  5868. if (!var_contents.has_next_token())
  5869. return false;
  5870. auto const& custom_property_name_token = var_contents.next_token();
  5871. if (!custom_property_name_token.is(Token::Type::Ident))
  5872. return false;
  5873. auto custom_property_name = custom_property_name_token.token().ident();
  5874. if (!custom_property_name.bytes_as_string_view().starts_with("--"sv))
  5875. return false;
  5876. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  5877. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  5878. // but rebuilding it every time.
  5879. if (custom_property_name == property_name)
  5880. return false;
  5881. auto parent = get_dependency_node(MUST(FlyString::from_utf8(property_name)));
  5882. auto child = get_dependency_node(custom_property_name);
  5883. parent->add_child(child);
  5884. if (parent->has_cycles())
  5885. return false;
  5886. if (auto custom_property_value = get_custom_property(element, pseudo_element, custom_property_name)) {
  5887. VERIFY(custom_property_value->is_unresolved());
  5888. TokenStream custom_property_tokens { custom_property_value->as_unresolved().values() };
  5889. if (!expand_variables(element, pseudo_element, custom_property_name, dependencies, custom_property_tokens, dest))
  5890. return false;
  5891. continue;
  5892. }
  5893. // Use the provided fallback value, if any.
  5894. var_contents.skip_whitespace();
  5895. if (var_contents.has_next_token()) {
  5896. auto const& comma_token = var_contents.next_token();
  5897. if (!comma_token.is(Token::Type::Comma))
  5898. return false;
  5899. var_contents.skip_whitespace();
  5900. if (!expand_variables(element, pseudo_element, property_name, dependencies, var_contents, dest))
  5901. return false;
  5902. }
  5903. }
  5904. return true;
  5905. }
  5906. bool Parser::expand_unresolved_values(DOM::Element& element, StringView property_name, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  5907. {
  5908. while (source.has_next_token()) {
  5909. auto const& value = source.next_token();
  5910. if (value.is_function()) {
  5911. if (value.function().name().equals_ignoring_ascii_case("attr"sv)) {
  5912. if (!substitute_attr_function(element, property_name, value.function(), dest))
  5913. return false;
  5914. continue;
  5915. }
  5916. if (auto maybe_calc_value = parse_calculated_value(value); maybe_calc_value && maybe_calc_value->is_calculated()) {
  5917. auto& calc_value = maybe_calc_value->as_calculated();
  5918. if (calc_value.resolves_to_angle()) {
  5919. auto resolved_value = calc_value.resolve_angle();
  5920. dest.empend(Token::create_dimension(resolved_value->to_degrees(), "deg"_fly_string));
  5921. continue;
  5922. }
  5923. if (calc_value.resolves_to_frequency()) {
  5924. auto resolved_value = calc_value.resolve_frequency();
  5925. dest.empend(Token::create_dimension(resolved_value->to_hertz(), "hz"_fly_string));
  5926. continue;
  5927. }
  5928. if (calc_value.resolves_to_length()) {
  5929. // FIXME: In order to resolve lengths, we need to know the font metrics in case a font-relative unit
  5930. // is used. So... we can't do that until style is computed?
  5931. // This might be easier once we have calc-simplification implemented.
  5932. }
  5933. if (calc_value.resolves_to_percentage()) {
  5934. auto resolved_value = calc_value.resolve_percentage();
  5935. dest.empend(Token::create_percentage(resolved_value.value().value()));
  5936. continue;
  5937. }
  5938. if (calc_value.resolves_to_time()) {
  5939. auto resolved_value = calc_value.resolve_time();
  5940. dest.empend(Token::create_dimension(resolved_value->to_seconds(), "s"_fly_string));
  5941. continue;
  5942. }
  5943. if (calc_value.resolves_to_number()) {
  5944. auto resolved_value = calc_value.resolve_number();
  5945. dest.empend(Token::create_number(resolved_value.value()));
  5946. continue;
  5947. }
  5948. }
  5949. auto const& source_function = value.function();
  5950. Vector<ComponentValue> function_values;
  5951. TokenStream source_function_contents { source_function.values() };
  5952. if (!expand_unresolved_values(element, property_name, source_function_contents, function_values))
  5953. return false;
  5954. NonnullRefPtr<Function> function = Function::create(source_function.name(), move(function_values));
  5955. dest.empend(function);
  5956. continue;
  5957. }
  5958. if (value.is_block()) {
  5959. auto const& source_block = value.block();
  5960. TokenStream source_block_values { source_block.values() };
  5961. Vector<ComponentValue> block_values;
  5962. if (!expand_unresolved_values(element, property_name, source_block_values, block_values))
  5963. return false;
  5964. NonnullRefPtr<Block> block = Block::create(source_block.token(), move(block_values));
  5965. dest.empend(move(block));
  5966. continue;
  5967. }
  5968. dest.empend(value.token());
  5969. }
  5970. return true;
  5971. }
  5972. // https://drafts.csswg.org/css-values-5/#attr-substitution
  5973. bool Parser::substitute_attr_function(DOM::Element& element, StringView property_name, Function const& attr_function, Vector<ComponentValue>& dest)
  5974. {
  5975. // First, parse the arguments to attr():
  5976. // attr() = attr( <q-name> <attr-type>? , <declaration-value>?)
  5977. // <attr-type> = string | url | ident | color | number | percentage | length | angle | time | frequency | flex | <dimension-unit>
  5978. TokenStream attr_contents { attr_function.values() };
  5979. attr_contents.skip_whitespace();
  5980. if (!attr_contents.has_next_token())
  5981. return false;
  5982. // - Attribute name
  5983. // FIXME: Support optional attribute namespace
  5984. if (!attr_contents.peek_token().is(Token::Type::Ident))
  5985. return false;
  5986. auto attribute_name = attr_contents.next_token().token().ident();
  5987. attr_contents.skip_whitespace();
  5988. // - Attribute type (optional)
  5989. auto attribute_type = "string"_fly_string;
  5990. if (attr_contents.peek_token().is(Token::Type::Ident)) {
  5991. attribute_type = attr_contents.next_token().token().ident();
  5992. attr_contents.skip_whitespace();
  5993. }
  5994. // - Comma, then fallback values (optional)
  5995. bool has_fallback_values = false;
  5996. if (attr_contents.has_next_token()) {
  5997. if (!attr_contents.peek_token().is(Token::Type::Comma))
  5998. return false;
  5999. (void)attr_contents.next_token(); // Comma
  6000. has_fallback_values = true;
  6001. }
  6002. // Then, run the substitution algorithm:
  6003. // 1. If the attr() function has a substitution value, replace the attr() function by the substitution value.
  6004. // https://drafts.csswg.org/css-values-5/#attr-types
  6005. if (element.has_attribute(attribute_name)) {
  6006. auto attribute_value = element.get_attribute_value(attribute_name);
  6007. if (attribute_type.equals_ignoring_ascii_case("angle"_fly_string)) {
  6008. // Parse a component value from the attribute’s value.
  6009. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6010. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6011. // Otherwise, there is no substitution value.
  6012. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6013. if (Angle::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6014. dest.append(component_value.release_value());
  6015. return true;
  6016. }
  6017. }
  6018. } else if (attribute_type.equals_ignoring_ascii_case("color"_fly_string)) {
  6019. // Parse a component value from the attribute’s value.
  6020. // If the result is a <hex-color> or a named color ident, the substitution value is that result as a <color>.
  6021. // Otherwise there is no substitution value.
  6022. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6023. if (component_value.has_value()) {
  6024. if ((component_value->is(Token::Type::Hash)
  6025. && Color::from_string(MUST(String::formatted("#{}", component_value->token().hash_value()))).has_value())
  6026. || (component_value->is(Token::Type::Ident)
  6027. && Color::from_string(component_value->token().ident()).has_value())) {
  6028. dest.append(component_value.release_value());
  6029. return true;
  6030. }
  6031. }
  6032. } else if (attribute_type.equals_ignoring_ascii_case("flex"_fly_string)) {
  6033. // Parse a component value from the attribute’s value.
  6034. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6035. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6036. // Otherwise, there is no substitution value.
  6037. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6038. if (Flex::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6039. dest.append(component_value.release_value());
  6040. return true;
  6041. }
  6042. }
  6043. } else if (attribute_type.equals_ignoring_ascii_case("frequency"_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 <dimension-token> whose unit matches the given type, the result is the substitution value.
  6047. // Otherwise, there is no substitution value.
  6048. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6049. if (Frequency::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6050. dest.append(component_value.release_value());
  6051. return true;
  6052. }
  6053. }
  6054. } else if (attribute_type.equals_ignoring_ascii_case("ident"_fly_string)) {
  6055. // The substitution value is a CSS <custom-ident>, whose value is the literal value of the attribute,
  6056. // with leading and trailing ASCII whitespace stripped. (No CSS parsing of the value is performed.)
  6057. // If the attribute value, after trimming, is the empty string, there is instead no substitution value.
  6058. // If the <custom-ident>’s value is a CSS-wide keyword or `default`, there is instead no substitution value.
  6059. auto substitution_value = attribute_value.trim_whitespace();
  6060. if (!substitution_value.is_empty()
  6061. && !substitution_value.equals_ignoring_ascii_case("default"sv)
  6062. && !is_css_wide_keyword(substitution_value)) {
  6063. dest.empend(Token::create_ident(MUST(FlyString::from_deprecated_fly_string(substitution_value))));
  6064. return true;
  6065. }
  6066. } else if (attribute_type.equals_ignoring_ascii_case("length"_fly_string)) {
  6067. // Parse a component value from the attribute’s value.
  6068. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6069. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6070. // Otherwise, there is no substitution value.
  6071. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6072. if (Length::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6073. dest.append(component_value.release_value());
  6074. return true;
  6075. }
  6076. }
  6077. } else if (attribute_type.equals_ignoring_ascii_case("number"_fly_string)) {
  6078. // Parse a component value from the attribute’s value.
  6079. // If the result is a <number-token>, the result is the substitution value.
  6080. // Otherwise, there is no substitution value.
  6081. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6082. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  6083. dest.append(component_value.release_value());
  6084. return true;
  6085. }
  6086. } else if (attribute_type.equals_ignoring_ascii_case("percentage"_fly_string)) {
  6087. // Parse a component value from the attribute’s value.
  6088. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6089. // If the result is a <percentage-token>, the result is the substitution value.
  6090. // Otherwise, there is no substitution value.
  6091. if (component_value.has_value() && component_value->is(Token::Type::Percentage)) {
  6092. dest.append(component_value.release_value());
  6093. return true;
  6094. }
  6095. } else if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  6096. // The substitution value is a CSS string, whose value is the literal value of the attribute.
  6097. // (No CSS parsing or "cleanup" of the value is performed.)
  6098. // No value triggers fallback.
  6099. dest.empend(Token::create_string(MUST(FlyString::from_deprecated_fly_string(attribute_value))));
  6100. return true;
  6101. } else if (attribute_type.equals_ignoring_ascii_case("time"_fly_string)) {
  6102. // Parse a component value from the attribute’s value.
  6103. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6104. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  6105. // Otherwise, there is no substitution value.
  6106. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  6107. if (Time::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  6108. dest.append(component_value.release_value());
  6109. return true;
  6110. }
  6111. }
  6112. } else if (attribute_type.equals_ignoring_ascii_case("url"_fly_string)) {
  6113. // The substitution value is a CSS <url> value, whose url is the literal value of the attribute.
  6114. // (No CSS parsing or "cleanup" of the value is performed.)
  6115. // No value triggers fallback.
  6116. dest.empend(Token::create_url(MUST(FlyString::from_deprecated_fly_string(attribute_value))));
  6117. return true;
  6118. } else {
  6119. // Dimension units
  6120. // Parse a component value from the attribute’s value.
  6121. // If the result is a <number-token>, the substitution value is a dimension with the result’s value, and the given unit.
  6122. // Otherwise, there is no substitution value.
  6123. auto component_value = MUST(Parser::Parser::create(m_context, attribute_value)).parse_as_component_value();
  6124. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  6125. if (attribute_value == "%"sv) {
  6126. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6127. return true;
  6128. } else if (auto angle_unit = Angle::unit_from_name(attribute_type); angle_unit.has_value()) {
  6129. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6130. return true;
  6131. } else if (auto flex_unit = Flex::unit_from_name(attribute_type); flex_unit.has_value()) {
  6132. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6133. return true;
  6134. } else if (auto frequency_unit = Frequency::unit_from_name(attribute_type); frequency_unit.has_value()) {
  6135. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6136. return true;
  6137. } else if (auto length_unit = Length::unit_from_name(attribute_type); length_unit.has_value()) {
  6138. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6139. return true;
  6140. } else if (auto time_unit = Time::unit_from_name(attribute_type); time_unit.has_value()) {
  6141. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  6142. return true;
  6143. } else {
  6144. // Not a dimension unit.
  6145. return false;
  6146. }
  6147. }
  6148. }
  6149. }
  6150. // 2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value.
  6151. // If there are any var() or attr() references in the fallback, substitute them as well.
  6152. if (has_fallback_values)
  6153. return expand_unresolved_values(element, property_name, attr_contents, dest);
  6154. // 3. Otherwise, the property containing the attr() function is invalid at computed-value time.
  6155. return false;
  6156. }
  6157. }