Parser.cpp 334 KB

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