Parser.cpp 349 KB

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