Parser.cpp 366 KB

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