Parser.cpp 347 KB

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