Parser.cpp 366 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927
  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. // The parser has consumed a comma, so the alpha value is now required
  2424. if (!alpha)
  2425. return {};
  2426. inner_tokens.discard_whitespace();
  2427. if (inner_tokens.has_next_token())
  2428. return {};
  2429. }
  2430. } else {
  2431. // Modern syntax
  2432. // [<hue> | none]
  2433. // [<percentage> | <number> | none]
  2434. // [<percentage> | <number> | none]
  2435. // [ / [<alpha-value> | none] ]?
  2436. s = parse_number_percentage_value(inner_tokens);
  2437. if (!s)
  2438. return {};
  2439. inner_tokens.discard_whitespace();
  2440. l = parse_number_percentage_value(inner_tokens);
  2441. if (!l)
  2442. return {};
  2443. inner_tokens.discard_whitespace();
  2444. if (inner_tokens.has_next_token()) {
  2445. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2446. if (!alpha || inner_tokens.has_next_token())
  2447. return {};
  2448. }
  2449. }
  2450. if (!alpha)
  2451. alpha = NumberStyleValue::create(1);
  2452. transaction.commit();
  2453. return CSSHSL::create(h.release_nonnull(), s.release_nonnull(), l.release_nonnull(), alpha.release_nonnull());
  2454. }
  2455. // https://www.w3.org/TR/css-color-4/#funcdef-hwb
  2456. RefPtr<CSSStyleValue> Parser::parse_hwb_color_value(TokenStream<ComponentValue>& outer_tokens)
  2457. {
  2458. // hwb() = hwb(
  2459. // [<hue> | none]
  2460. // [<percentage> | <number> | none]
  2461. // [<percentage> | <number> | none]
  2462. // [ / [<alpha-value> | none] ]? )
  2463. auto transaction = outer_tokens.begin_transaction();
  2464. outer_tokens.discard_whitespace();
  2465. auto& function_token = outer_tokens.consume_a_token();
  2466. if (!function_token.is_function("hwb"sv))
  2467. return {};
  2468. RefPtr<CSSStyleValue> h;
  2469. RefPtr<CSSStyleValue> w;
  2470. RefPtr<CSSStyleValue> b;
  2471. RefPtr<CSSStyleValue> alpha;
  2472. auto inner_tokens = TokenStream { function_token.function().value };
  2473. inner_tokens.discard_whitespace();
  2474. h = parse_hue_value(inner_tokens);
  2475. if (!h)
  2476. return {};
  2477. inner_tokens.discard_whitespace();
  2478. w = parse_number_percentage_value(inner_tokens);
  2479. if (!w)
  2480. return {};
  2481. inner_tokens.discard_whitespace();
  2482. b = parse_number_percentage_value(inner_tokens);
  2483. if (!b)
  2484. return {};
  2485. inner_tokens.discard_whitespace();
  2486. if (inner_tokens.has_next_token()) {
  2487. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2488. if (!alpha || inner_tokens.has_next_token())
  2489. return {};
  2490. }
  2491. if (!alpha)
  2492. alpha = NumberStyleValue::create(1);
  2493. transaction.commit();
  2494. return CSSHWB::create(h.release_nonnull(), w.release_nonnull(), b.release_nonnull(), alpha.release_nonnull());
  2495. }
  2496. Optional<Array<RefPtr<CSSStyleValue>, 4>> Parser::parse_lab_like_color_value(TokenStream<ComponentValue>& outer_tokens, StringView function_name)
  2497. {
  2498. // This helper is designed to be compatible with lab and oklab and parses a function with a form like:
  2499. // f() = f( [ <percentage> | <number> | none]
  2500. // [ <percentage> | <number> | none]
  2501. // [ <percentage> | <number> | none]
  2502. // [ / [<alpha-value> | none] ]? )
  2503. auto transaction = outer_tokens.begin_transaction();
  2504. outer_tokens.discard_whitespace();
  2505. auto& function_token = outer_tokens.consume_a_token();
  2506. if (!function_token.is_function(function_name))
  2507. return OptionalNone {};
  2508. RefPtr<CSSStyleValue> l;
  2509. RefPtr<CSSStyleValue> a;
  2510. RefPtr<CSSStyleValue> b;
  2511. RefPtr<CSSStyleValue> alpha;
  2512. auto inner_tokens = TokenStream { function_token.function().value };
  2513. inner_tokens.discard_whitespace();
  2514. l = parse_number_percentage_value(inner_tokens);
  2515. if (!l)
  2516. return OptionalNone {};
  2517. inner_tokens.discard_whitespace();
  2518. a = parse_number_percentage_value(inner_tokens);
  2519. if (!a)
  2520. return OptionalNone {};
  2521. inner_tokens.discard_whitespace();
  2522. b = parse_number_percentage_value(inner_tokens);
  2523. if (!b)
  2524. return OptionalNone {};
  2525. inner_tokens.discard_whitespace();
  2526. if (inner_tokens.has_next_token()) {
  2527. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2528. if (!alpha || inner_tokens.has_next_token())
  2529. return OptionalNone {};
  2530. }
  2531. if (!alpha)
  2532. alpha = NumberStyleValue::create(1);
  2533. transaction.commit();
  2534. return Array { move(l), move(a), move(b), move(alpha) };
  2535. }
  2536. // https://www.w3.org/TR/css-color-4/#funcdef-lab
  2537. RefPtr<CSSStyleValue> Parser::parse_lab_color_value(TokenStream<ComponentValue>& outer_tokens)
  2538. {
  2539. // lab() = lab( [<percentage> | <number> | none]
  2540. // [ <percentage> | <number> | none]
  2541. // [ <percentage> | <number> | none]
  2542. // [ / [<alpha-value> | none] ]? )
  2543. auto maybe_color_values = parse_lab_like_color_value(outer_tokens, "lab"sv);
  2544. if (!maybe_color_values.has_value())
  2545. return {};
  2546. auto& color_values = *maybe_color_values;
  2547. return CSSLabLike::create<CSSLab>(color_values[0].release_nonnull(),
  2548. color_values[1].release_nonnull(),
  2549. color_values[2].release_nonnull(),
  2550. color_values[3].release_nonnull());
  2551. }
  2552. // https://www.w3.org/TR/css-color-4/#funcdef-oklab
  2553. RefPtr<CSSStyleValue> Parser::parse_oklab_color_value(TokenStream<ComponentValue>& outer_tokens)
  2554. {
  2555. // oklab() = oklab( [ <percentage> | <number> | none]
  2556. // [ <percentage> | <number> | none]
  2557. // [ <percentage> | <number> | none]
  2558. // [ / [<alpha-value> | none] ]? )
  2559. auto maybe_color_values = parse_lab_like_color_value(outer_tokens, "oklab"sv);
  2560. if (!maybe_color_values.has_value())
  2561. return {};
  2562. auto& color_values = *maybe_color_values;
  2563. return CSSLabLike::create<CSSOKLab>(color_values[0].release_nonnull(),
  2564. color_values[1].release_nonnull(),
  2565. color_values[2].release_nonnull(),
  2566. color_values[3].release_nonnull());
  2567. }
  2568. Optional<Array<RefPtr<CSSStyleValue>, 4>> Parser::parse_lch_like_color_value(TokenStream<ComponentValue>& outer_tokens, StringView function_name)
  2569. {
  2570. // This helper is designed to be compatible with lch and oklch and parses a function with a form like:
  2571. // f() = f( [<percentage> | <number> | none]
  2572. // [ <percentage> | <number> | none]
  2573. // [ <hue> | none]
  2574. // [ / [<alpha-value> | none] ]? )
  2575. auto transaction = outer_tokens.begin_transaction();
  2576. outer_tokens.discard_whitespace();
  2577. auto const& function_token = outer_tokens.consume_a_token();
  2578. if (!function_token.is_function(function_name))
  2579. return OptionalNone {};
  2580. auto inner_tokens = TokenStream { function_token.function().value };
  2581. inner_tokens.discard_whitespace();
  2582. auto l = parse_number_percentage_value(inner_tokens);
  2583. if (!l)
  2584. return OptionalNone {};
  2585. inner_tokens.discard_whitespace();
  2586. auto c = parse_number_percentage_value(inner_tokens);
  2587. if (!c)
  2588. return OptionalNone {};
  2589. inner_tokens.discard_whitespace();
  2590. auto h = parse_hue_value(inner_tokens);
  2591. if (!h)
  2592. return OptionalNone {};
  2593. inner_tokens.discard_whitespace();
  2594. RefPtr<CSSStyleValue> alpha;
  2595. if (inner_tokens.has_next_token()) {
  2596. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2597. if (!alpha || inner_tokens.has_next_token())
  2598. return OptionalNone {};
  2599. }
  2600. if (!alpha)
  2601. alpha = NumberStyleValue::create(1);
  2602. transaction.commit();
  2603. return Array { move(l), move(c), move(h), move(alpha) };
  2604. }
  2605. // https://www.w3.org/TR/css-color-4/#funcdef-lch
  2606. RefPtr<CSSStyleValue> Parser::parse_lch_color_value(TokenStream<ComponentValue>& outer_tokens)
  2607. {
  2608. // lch() = lch( [<percentage> | <number> | none]
  2609. // [ <percentage> | <number> | none]
  2610. // [ <hue> | none]
  2611. // [ / [<alpha-value> | none] ]? )
  2612. auto maybe_color_values = parse_lch_like_color_value(outer_tokens, "lch"sv);
  2613. if (!maybe_color_values.has_value())
  2614. return {};
  2615. auto& color_values = *maybe_color_values;
  2616. return CSSLCHLike::create<CSSLCH>(color_values[0].release_nonnull(),
  2617. color_values[1].release_nonnull(),
  2618. color_values[2].release_nonnull(),
  2619. color_values[3].release_nonnull());
  2620. }
  2621. // https://www.w3.org/TR/css-color-4/#funcdef-oklch
  2622. RefPtr<CSSStyleValue> Parser::parse_oklch_color_value(TokenStream<ComponentValue>& outer_tokens)
  2623. {
  2624. // oklch() = oklch( [ <percentage> | <number> | none]
  2625. // [ <percentage> | <number> | none]
  2626. // [ <hue> | none]
  2627. // [ / [<alpha-value> | none] ]? )
  2628. auto maybe_color_values = parse_lch_like_color_value(outer_tokens, "oklch"sv);
  2629. if (!maybe_color_values.has_value())
  2630. return {};
  2631. auto& color_values = *maybe_color_values;
  2632. return CSSLCHLike::create<CSSOKLCH>(color_values[0].release_nonnull(),
  2633. color_values[1].release_nonnull(),
  2634. color_values[2].release_nonnull(),
  2635. color_values[3].release_nonnull());
  2636. }
  2637. // https://www.w3.org/TR/css-color-4/#funcdef-color
  2638. RefPtr<CSSStyleValue> Parser::parse_color_function(TokenStream<ComponentValue>& outer_tokens)
  2639. {
  2640. // color() = color( <colorspace-params> [ / [ <alpha-value> | none ] ]? )
  2641. // <colorspace-params> = [ <predefined-rgb-params> | <xyz-params>]
  2642. // <predefined-rgb-params> = <predefined-rgb> [ <number> | <percentage> | none ]{3}
  2643. // <predefined-rgb> = srgb | srgb-linear | display-p3 | a98-rgb | prophoto-rgb | rec2020
  2644. // <xyz-params> = <xyz-space> [ <number> | <percentage> | none ]{3}
  2645. // <xyz-space> = xyz | xyz-d50 | xyz-d65
  2646. auto transaction = outer_tokens.begin_transaction();
  2647. outer_tokens.discard_whitespace();
  2648. auto const& function_token = outer_tokens.consume_a_token();
  2649. if (!function_token.is_function("color"sv))
  2650. return {};
  2651. auto inner_tokens = TokenStream { function_token.function().value };
  2652. inner_tokens.discard_whitespace();
  2653. auto maybe_color_space = inner_tokens.consume_a_token();
  2654. inner_tokens.discard_whitespace();
  2655. if (!any_of(CSSColor::s_supported_color_space, [&](auto supported) { return maybe_color_space.is_ident(supported); }))
  2656. return {};
  2657. auto const& color_space = maybe_color_space.token().ident();
  2658. auto c1 = parse_number_percentage_value(inner_tokens);
  2659. if (!c1)
  2660. return {};
  2661. inner_tokens.discard_whitespace();
  2662. auto c2 = parse_number_percentage_value(inner_tokens);
  2663. if (!c2)
  2664. return {};
  2665. inner_tokens.discard_whitespace();
  2666. auto c3 = parse_number_percentage_value(inner_tokens);
  2667. if (!c3)
  2668. return {};
  2669. inner_tokens.discard_whitespace();
  2670. RefPtr<CSSStyleValue> alpha;
  2671. if (inner_tokens.has_next_token()) {
  2672. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2673. if (!alpha || inner_tokens.has_next_token())
  2674. return {};
  2675. }
  2676. if (!alpha)
  2677. alpha = NumberStyleValue::create(1);
  2678. transaction.commit();
  2679. return CSSColor::create(color_space.to_ascii_lowercase(),
  2680. c1.release_nonnull(),
  2681. c2.release_nonnull(),
  2682. c3.release_nonnull(),
  2683. alpha.release_nonnull());
  2684. }
  2685. // https://www.w3.org/TR/css-color-4/#color-syntax
  2686. RefPtr<CSSStyleValue> Parser::parse_color_value(TokenStream<ComponentValue>& tokens)
  2687. {
  2688. // Keywords: <system-color> | <deprecated-color> | currentColor
  2689. {
  2690. auto transaction = tokens.begin_transaction();
  2691. if (auto keyword = parse_keyword_value(tokens); keyword && keyword->has_color()) {
  2692. transaction.commit();
  2693. return keyword;
  2694. }
  2695. }
  2696. // Functions
  2697. if (auto color = parse_color_function(tokens))
  2698. return color;
  2699. if (auto rgb = parse_rgb_color_value(tokens))
  2700. return rgb;
  2701. if (auto hsl = parse_hsl_color_value(tokens))
  2702. return hsl;
  2703. if (auto hwb = parse_hwb_color_value(tokens))
  2704. return hwb;
  2705. if (auto lab = parse_lab_color_value(tokens))
  2706. return lab;
  2707. if (auto lch = parse_lch_color_value(tokens))
  2708. return lch;
  2709. if (auto oklab = parse_oklab_color_value(tokens))
  2710. return oklab;
  2711. if (auto oklch = parse_oklch_color_value(tokens))
  2712. return oklch;
  2713. auto transaction = tokens.begin_transaction();
  2714. tokens.discard_whitespace();
  2715. auto component_value = tokens.consume_a_token();
  2716. if (component_value.is(Token::Type::Ident)) {
  2717. auto ident = component_value.token().ident();
  2718. auto color = Color::from_string(ident);
  2719. if (color.has_value()) {
  2720. transaction.commit();
  2721. return CSSColorValue::create_from_color(color.release_value());
  2722. }
  2723. // Otherwise, fall through to the hashless-hex-color case
  2724. }
  2725. if (component_value.is(Token::Type::Hash)) {
  2726. auto color = Color::from_string(MUST(String::formatted("#{}", component_value.token().hash_value())));
  2727. if (color.has_value()) {
  2728. transaction.commit();
  2729. return CSSColorValue::create_from_color(color.release_value());
  2730. }
  2731. return {};
  2732. }
  2733. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  2734. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  2735. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  2736. // aborting on the first step that returns a value:
  2737. // 1. Let cv be the component value.
  2738. auto const& cv = component_value;
  2739. String serialization;
  2740. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  2741. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  2742. // 1. If cv’s type flag is not "integer", return an error.
  2743. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  2744. if (!cv.token().number().is_integer())
  2745. return {};
  2746. // 2. If cv’s value is less than zero, return an error.
  2747. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  2748. if (value < 0)
  2749. return {};
  2750. // 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.
  2751. StringBuilder serialization_builder;
  2752. serialization_builder.appendff("{}", value);
  2753. // 4. If cv is a <dimension-token>, append the unit to serialization.
  2754. if (cv.is(Token::Type::Dimension))
  2755. serialization_builder.append(cv.token().dimension_unit());
  2756. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  2757. serialization = MUST(serialization_builder.to_string());
  2758. if (serialization_builder.length() < 6) {
  2759. StringBuilder builder;
  2760. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  2761. builder.append('0');
  2762. builder.append(serialization_builder.string_view());
  2763. serialization = MUST(builder.to_string());
  2764. }
  2765. }
  2766. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  2767. else {
  2768. if (!cv.is(Token::Type::Ident))
  2769. return {};
  2770. serialization = cv.token().ident().to_string();
  2771. }
  2772. // 4. If serialization does not consist of three or six characters, return an error.
  2773. if (serialization.bytes().size() != 3 && serialization.bytes().size() != 6)
  2774. return {};
  2775. // 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.
  2776. for (auto c : serialization.bytes_as_string_view()) {
  2777. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  2778. return {};
  2779. }
  2780. // 6. Return the concatenation of "#" (U+0023) and serialization.
  2781. auto color = Color::from_string(MUST(String::formatted("#{}", serialization)));
  2782. if (color.has_value()) {
  2783. transaction.commit();
  2784. return CSSColorValue::create_from_color(color.release_value());
  2785. }
  2786. }
  2787. return {};
  2788. }
  2789. // https://drafts.csswg.org/css-lists-3/#counter-functions
  2790. RefPtr<CSSStyleValue> Parser::parse_counter_value(TokenStream<ComponentValue>& tokens)
  2791. {
  2792. auto parse_counter_name = [this](TokenStream<ComponentValue>& tokens) -> Optional<FlyString> {
  2793. // https://drafts.csswg.org/css-lists-3/#typedef-counter-name
  2794. // Counters are referred to in CSS syntax using the <counter-name> type, which represents
  2795. // their name as a <custom-ident>. A <counter-name> name cannot match the keyword none;
  2796. // such an identifier is invalid as a <counter-name>.
  2797. auto transaction = tokens.begin_transaction();
  2798. tokens.discard_whitespace();
  2799. auto counter_name = parse_custom_ident_value(tokens, { "none"sv });
  2800. if (!counter_name)
  2801. return {};
  2802. tokens.discard_whitespace();
  2803. if (tokens.has_next_token())
  2804. return {};
  2805. transaction.commit();
  2806. return counter_name->custom_ident();
  2807. };
  2808. auto parse_counter_style = [this](TokenStream<ComponentValue>& tokens) -> RefPtr<CSSStyleValue> {
  2809. // https://drafts.csswg.org/css-counter-styles-3/#typedef-counter-style
  2810. // <counter-style> = <counter-style-name> | <symbols()>
  2811. // For now we just support <counter-style-name>, found here:
  2812. // https://drafts.csswg.org/css-counter-styles-3/#typedef-counter-style-name
  2813. // <counter-style-name> is a <custom-ident> that is not an ASCII case-insensitive match for none.
  2814. auto transaction = tokens.begin_transaction();
  2815. tokens.discard_whitespace();
  2816. auto counter_style_name = parse_custom_ident_value(tokens, { "none"sv });
  2817. if (!counter_style_name)
  2818. return {};
  2819. tokens.discard_whitespace();
  2820. if (tokens.has_next_token())
  2821. return {};
  2822. transaction.commit();
  2823. return counter_style_name.release_nonnull();
  2824. };
  2825. auto transaction = tokens.begin_transaction();
  2826. auto token = tokens.consume_a_token();
  2827. if (token.is_function("counter"sv)) {
  2828. // counter() = counter( <counter-name>, <counter-style>? )
  2829. auto& function = token.function();
  2830. TokenStream function_tokens { function.value };
  2831. auto function_values = parse_a_comma_separated_list_of_component_values(function_tokens);
  2832. if (function_values.is_empty() || function_values.size() > 2)
  2833. return nullptr;
  2834. TokenStream name_tokens { function_values[0] };
  2835. auto counter_name = parse_counter_name(name_tokens);
  2836. if (!counter_name.has_value())
  2837. return nullptr;
  2838. RefPtr<CSSStyleValue> counter_style;
  2839. if (function_values.size() > 1) {
  2840. TokenStream counter_style_tokens { function_values[1] };
  2841. counter_style = parse_counter_style(counter_style_tokens);
  2842. if (!counter_style)
  2843. return nullptr;
  2844. } else {
  2845. // In both cases, if the <counter-style> argument is omitted it defaults to `decimal`.
  2846. counter_style = CustomIdentStyleValue::create("decimal"_fly_string);
  2847. }
  2848. transaction.commit();
  2849. return CounterStyleValue::create_counter(counter_name.release_value(), counter_style.release_nonnull());
  2850. }
  2851. if (token.is_function("counters"sv)) {
  2852. // counters() = counters( <counter-name>, <string>, <counter-style>? )
  2853. auto& function = token.function();
  2854. TokenStream function_tokens { function.value };
  2855. auto function_values = parse_a_comma_separated_list_of_component_values(function_tokens);
  2856. if (function_values.size() < 2 || function_values.size() > 3)
  2857. return nullptr;
  2858. TokenStream name_tokens { function_values[0] };
  2859. auto counter_name = parse_counter_name(name_tokens);
  2860. if (!counter_name.has_value())
  2861. return nullptr;
  2862. TokenStream string_tokens { function_values[1] };
  2863. string_tokens.discard_whitespace();
  2864. auto join_string = parse_string_value(string_tokens);
  2865. string_tokens.discard_whitespace();
  2866. if (!join_string || string_tokens.has_next_token())
  2867. return nullptr;
  2868. RefPtr<CSSStyleValue> counter_style;
  2869. if (function_values.size() > 2) {
  2870. TokenStream counter_style_tokens { function_values[2] };
  2871. counter_style = parse_counter_style(counter_style_tokens);
  2872. if (!counter_style)
  2873. return nullptr;
  2874. } else {
  2875. // In both cases, if the <counter-style> argument is omitted it defaults to `decimal`.
  2876. counter_style = CustomIdentStyleValue::create("decimal"_fly_string);
  2877. }
  2878. transaction.commit();
  2879. return CounterStyleValue::create_counters(counter_name.release_value(), join_string->string_value(), counter_style.release_nonnull());
  2880. }
  2881. return nullptr;
  2882. }
  2883. RefPtr<CSSStyleValue> Parser::parse_counter_definitions_value(TokenStream<ComponentValue>& tokens, AllowReversed allow_reversed, i32 default_value_if_not_reversed)
  2884. {
  2885. // If AllowReversed is Yes, parses:
  2886. // [ <counter-name> <integer>? | <reversed-counter-name> <integer>? ]+
  2887. // Otherwise parses:
  2888. // [ <counter-name> <integer>? ]+
  2889. // FIXME: This disabled parsing of `reversed()` counters. Remove this line once they're supported.
  2890. allow_reversed = AllowReversed::No;
  2891. auto transaction = tokens.begin_transaction();
  2892. tokens.discard_whitespace();
  2893. Vector<CounterDefinition> counter_definitions;
  2894. while (tokens.has_next_token()) {
  2895. auto per_item_transaction = tokens.begin_transaction();
  2896. CounterDefinition definition {};
  2897. // <counter-name> | <reversed-counter-name>
  2898. auto& token = tokens.consume_a_token();
  2899. if (token.is(Token::Type::Ident)) {
  2900. definition.name = token.token().ident();
  2901. definition.is_reversed = false;
  2902. } else if (allow_reversed == AllowReversed::Yes && token.is_function("reversed"sv)) {
  2903. TokenStream function_tokens { token.function().value };
  2904. function_tokens.discard_whitespace();
  2905. auto& name_token = function_tokens.consume_a_token();
  2906. if (!name_token.is(Token::Type::Ident))
  2907. break;
  2908. function_tokens.discard_whitespace();
  2909. if (function_tokens.has_next_token())
  2910. break;
  2911. definition.name = name_token.token().ident();
  2912. definition.is_reversed = true;
  2913. } else {
  2914. break;
  2915. }
  2916. tokens.discard_whitespace();
  2917. // <integer>?
  2918. definition.value = parse_integer_value(tokens);
  2919. if (!definition.value && !definition.is_reversed)
  2920. definition.value = IntegerStyleValue::create(default_value_if_not_reversed);
  2921. counter_definitions.append(move(definition));
  2922. tokens.discard_whitespace();
  2923. per_item_transaction.commit();
  2924. }
  2925. if (counter_definitions.is_empty())
  2926. return {};
  2927. transaction.commit();
  2928. return CounterDefinitionsStyleValue::create(move(counter_definitions));
  2929. }
  2930. RefPtr<CSSStyleValue> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  2931. {
  2932. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  2933. return RatioStyleValue::create(ratio.release_value());
  2934. return nullptr;
  2935. }
  2936. RefPtr<StringStyleValue> Parser::parse_string_value(TokenStream<ComponentValue>& tokens)
  2937. {
  2938. auto peek = tokens.next_token();
  2939. if (peek.is(Token::Type::String)) {
  2940. tokens.discard_a_token();
  2941. return StringStyleValue::create(peek.token().string());
  2942. }
  2943. return nullptr;
  2944. }
  2945. RefPtr<CSSStyleValue> Parser::parse_image_value(TokenStream<ComponentValue>& tokens)
  2946. {
  2947. if (auto url = parse_url_function(tokens); url.has_value())
  2948. return ImageStyleValue::create(url.value());
  2949. if (auto linear_gradient = parse_linear_gradient_function(tokens))
  2950. return linear_gradient;
  2951. if (auto conic_gradient = parse_conic_gradient_function(tokens))
  2952. return conic_gradient;
  2953. if (auto radial_gradient = parse_radial_gradient_function(tokens))
  2954. return radial_gradient;
  2955. return nullptr;
  2956. }
  2957. // https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint
  2958. RefPtr<CSSStyleValue> Parser::parse_paint_value(TokenStream<ComponentValue>& tokens)
  2959. {
  2960. // `<paint> = none | <color> | <url> [none | <color>]? | context-fill | context-stroke`
  2961. auto parse_color_or_none = [&]() -> Optional<RefPtr<CSSStyleValue>> {
  2962. if (auto color = parse_color_value(tokens))
  2963. return color;
  2964. // NOTE: <color> also accepts identifiers, so we do this identifier check last.
  2965. if (tokens.next_token().is(Token::Type::Ident)) {
  2966. auto maybe_keyword = keyword_from_string(tokens.next_token().token().ident());
  2967. if (maybe_keyword.has_value()) {
  2968. // FIXME: Accept `context-fill` and `context-stroke`
  2969. switch (*maybe_keyword) {
  2970. case Keyword::None:
  2971. tokens.discard_a_token();
  2972. return CSSKeywordValue::create(*maybe_keyword);
  2973. default:
  2974. return nullptr;
  2975. }
  2976. }
  2977. }
  2978. return OptionalNone {};
  2979. };
  2980. // FIMXE: Allow context-fill/context-stroke here
  2981. if (auto color_or_none = parse_color_or_none(); color_or_none.has_value())
  2982. return *color_or_none;
  2983. if (auto url = parse_url_value(tokens)) {
  2984. tokens.discard_whitespace();
  2985. if (auto color_or_none = parse_color_or_none(); color_or_none == nullptr) {
  2986. // Fail to parse if the fallback is invalid, but otherwise ignore it.
  2987. // FIXME: Use fallback color
  2988. return nullptr;
  2989. }
  2990. return url;
  2991. }
  2992. return nullptr;
  2993. }
  2994. // https://www.w3.org/TR/css-values-4/#position
  2995. RefPtr<PositionStyleValue> Parser::parse_position_value(TokenStream<ComponentValue>& tokens, PositionParsingMode position_parsing_mode)
  2996. {
  2997. auto parse_position_edge = [](ComponentValue const& token) -> Optional<PositionEdge> {
  2998. if (!token.is(Token::Type::Ident))
  2999. return {};
  3000. auto keyword = keyword_from_string(token.token().ident());
  3001. if (!keyword.has_value())
  3002. return {};
  3003. return keyword_to_position_edge(*keyword);
  3004. };
  3005. auto parse_length_percentage = [&](ComponentValue const& token) -> Optional<LengthPercentage> {
  3006. if (token.is(Token::Type::EndOfFile))
  3007. return {};
  3008. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  3009. if (dimension->is_length_percentage())
  3010. return dimension->length_percentage();
  3011. return {};
  3012. }
  3013. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length_percentage())
  3014. return LengthPercentage { calc.release_nonnull() };
  3015. return {};
  3016. };
  3017. auto is_horizontal = [](PositionEdge edge, bool accept_center) -> bool {
  3018. switch (edge) {
  3019. case PositionEdge::Left:
  3020. case PositionEdge::Right:
  3021. return true;
  3022. case PositionEdge::Center:
  3023. return accept_center;
  3024. default:
  3025. return false;
  3026. }
  3027. };
  3028. auto is_vertical = [](PositionEdge edge, bool accept_center) -> bool {
  3029. switch (edge) {
  3030. case PositionEdge::Top:
  3031. case PositionEdge::Bottom:
  3032. return true;
  3033. case PositionEdge::Center:
  3034. return accept_center;
  3035. default:
  3036. return false;
  3037. }
  3038. };
  3039. auto make_edge_style_value = [](PositionEdge position_edge, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  3040. if (position_edge == PositionEdge::Center)
  3041. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  3042. return EdgeStyleValue::create(position_edge, Length::make_px(0));
  3043. };
  3044. // <position> = [
  3045. // [ left | center | right | top | bottom | <length-percentage> ]
  3046. // |
  3047. // [ left | center | right ] && [ top | center | bottom ]
  3048. // |
  3049. // [ left | center | right | <length-percentage> ]
  3050. // [ top | center | bottom | <length-percentage> ]
  3051. // |
  3052. // [ [ left | right ] <length-percentage> ] &&
  3053. // [ [ top | bottom ] <length-percentage> ]
  3054. // ]
  3055. // [ left | center | right | top | bottom | <length-percentage> ]
  3056. auto alternative_1 = [&]() -> RefPtr<PositionStyleValue> {
  3057. auto transaction = tokens.begin_transaction();
  3058. tokens.discard_whitespace();
  3059. auto const& token = tokens.consume_a_token();
  3060. // [ left | center | right | top | bottom ]
  3061. if (auto maybe_edge = parse_position_edge(token); maybe_edge.has_value()) {
  3062. auto edge = maybe_edge.release_value();
  3063. transaction.commit();
  3064. // [ left | right ]
  3065. if (is_horizontal(edge, false))
  3066. return PositionStyleValue::create(make_edge_style_value(edge, true), make_edge_style_value(PositionEdge::Center, false));
  3067. // [ top | bottom ]
  3068. if (is_vertical(edge, false))
  3069. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(edge, false));
  3070. // [ center ]
  3071. VERIFY(edge == PositionEdge::Center);
  3072. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(PositionEdge::Center, false));
  3073. }
  3074. // [ <length-percentage> ]
  3075. if (auto maybe_percentage = parse_length_percentage(token); maybe_percentage.has_value()) {
  3076. transaction.commit();
  3077. return PositionStyleValue::create(EdgeStyleValue::create(PositionEdge::Left, *maybe_percentage), make_edge_style_value(PositionEdge::Center, false));
  3078. }
  3079. return nullptr;
  3080. };
  3081. // [ left | center | right ] && [ top | center | bottom ]
  3082. auto alternative_2 = [&]() -> RefPtr<PositionStyleValue> {
  3083. auto transaction = tokens.begin_transaction();
  3084. tokens.discard_whitespace();
  3085. // Parse out two position edges
  3086. auto maybe_first_edge = parse_position_edge(tokens.consume_a_token());
  3087. if (!maybe_first_edge.has_value())
  3088. return nullptr;
  3089. auto first_edge = maybe_first_edge.release_value();
  3090. tokens.discard_whitespace();
  3091. auto maybe_second_edge = parse_position_edge(tokens.consume_a_token());
  3092. if (!maybe_second_edge.has_value())
  3093. return nullptr;
  3094. auto second_edge = maybe_second_edge.release_value();
  3095. // If 'left' or 'right' is given, that position is X and the other is Y.
  3096. // Conversely -
  3097. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  3098. if (is_vertical(first_edge, false) || is_horizontal(second_edge, false))
  3099. swap(first_edge, second_edge);
  3100. // [ left | center | right ] [ top | bottom | center ]
  3101. if (is_horizontal(first_edge, true) && is_vertical(second_edge, true)) {
  3102. transaction.commit();
  3103. return PositionStyleValue::create(make_edge_style_value(first_edge, true), make_edge_style_value(second_edge, false));
  3104. }
  3105. return nullptr;
  3106. };
  3107. // [ left | center | right | <length-percentage> ]
  3108. // [ top | center | bottom | <length-percentage> ]
  3109. auto alternative_3 = [&]() -> RefPtr<PositionStyleValue> {
  3110. auto transaction = tokens.begin_transaction();
  3111. auto parse_position_or_length = [&](bool as_horizontal) -> RefPtr<EdgeStyleValue> {
  3112. tokens.discard_whitespace();
  3113. auto const& token = tokens.consume_a_token();
  3114. if (auto maybe_position = parse_position_edge(token); maybe_position.has_value()) {
  3115. auto position = maybe_position.release_value();
  3116. bool valid = as_horizontal ? is_horizontal(position, true) : is_vertical(position, true);
  3117. if (!valid)
  3118. return nullptr;
  3119. return make_edge_style_value(position, as_horizontal);
  3120. }
  3121. auto maybe_length = parse_length_percentage(token);
  3122. if (!maybe_length.has_value())
  3123. return nullptr;
  3124. return EdgeStyleValue::create(as_horizontal ? PositionEdge::Left : PositionEdge::Top, maybe_length.release_value());
  3125. };
  3126. // [ left | center | right | <length-percentage> ]
  3127. auto horizontal_edge = parse_position_or_length(true);
  3128. if (!horizontal_edge)
  3129. return nullptr;
  3130. // [ top | center | bottom | <length-percentage> ]
  3131. auto vertical_edge = parse_position_or_length(false);
  3132. if (!vertical_edge)
  3133. return nullptr;
  3134. transaction.commit();
  3135. return PositionStyleValue::create(horizontal_edge.release_nonnull(), vertical_edge.release_nonnull());
  3136. };
  3137. // [ [ left | right ] <length-percentage> ] &&
  3138. // [ [ top | bottom ] <length-percentage> ]
  3139. auto alternative_4 = [&]() -> RefPtr<PositionStyleValue> {
  3140. struct PositionAndLength {
  3141. PositionEdge position;
  3142. LengthPercentage length;
  3143. };
  3144. auto parse_position_and_length = [&]() -> Optional<PositionAndLength> {
  3145. tokens.discard_whitespace();
  3146. auto maybe_position = parse_position_edge(tokens.consume_a_token());
  3147. if (!maybe_position.has_value())
  3148. return {};
  3149. tokens.discard_whitespace();
  3150. auto maybe_length = parse_length_percentage(tokens.consume_a_token());
  3151. if (!maybe_length.has_value())
  3152. return {};
  3153. return PositionAndLength {
  3154. .position = maybe_position.release_value(),
  3155. .length = maybe_length.release_value(),
  3156. };
  3157. };
  3158. auto transaction = tokens.begin_transaction();
  3159. auto maybe_group1 = parse_position_and_length();
  3160. if (!maybe_group1.has_value())
  3161. return nullptr;
  3162. auto maybe_group2 = parse_position_and_length();
  3163. if (!maybe_group2.has_value())
  3164. return nullptr;
  3165. auto group1 = maybe_group1.release_value();
  3166. auto group2 = maybe_group2.release_value();
  3167. // [ [ left | right ] <length-percentage> ] [ [ top | bottom ] <length-percentage> ]
  3168. if (is_horizontal(group1.position, false) && is_vertical(group2.position, false)) {
  3169. transaction.commit();
  3170. return PositionStyleValue::create(EdgeStyleValue::create(group1.position, group1.length), EdgeStyleValue::create(group2.position, group2.length));
  3171. }
  3172. // [ [ top | bottom ] <length-percentage> ] [ [ left | right ] <length-percentage> ]
  3173. if (is_vertical(group1.position, false) && is_horizontal(group2.position, false)) {
  3174. transaction.commit();
  3175. return PositionStyleValue::create(EdgeStyleValue::create(group2.position, group2.length), EdgeStyleValue::create(group1.position, group1.length));
  3176. }
  3177. return nullptr;
  3178. };
  3179. // The extra 3-value syntax that's allowed for background-position:
  3180. // [ center | [ left | right ] <length-percentage>? ] &&
  3181. // [ center | [ top | bottom ] <length-percentage>? ]
  3182. auto alternative_5_for_background_position = [&]() -> RefPtr<PositionStyleValue> {
  3183. auto transaction = tokens.begin_transaction();
  3184. struct PositionAndMaybeLength {
  3185. PositionEdge position;
  3186. Optional<LengthPercentage> length;
  3187. };
  3188. // [ <position> <length-percentage>? ]
  3189. auto parse_position_and_maybe_length = [&]() -> Optional<PositionAndMaybeLength> {
  3190. tokens.discard_whitespace();
  3191. auto maybe_position = parse_position_edge(tokens.consume_a_token());
  3192. if (!maybe_position.has_value())
  3193. return {};
  3194. tokens.discard_whitespace();
  3195. auto maybe_length = parse_length_percentage(tokens.next_token());
  3196. if (maybe_length.has_value()) {
  3197. // 'center' cannot be followed by a <length-percentage>
  3198. if (maybe_position.value() == PositionEdge::Center && maybe_length.has_value())
  3199. return {};
  3200. tokens.discard_a_token();
  3201. }
  3202. return PositionAndMaybeLength {
  3203. .position = maybe_position.release_value(),
  3204. .length = move(maybe_length),
  3205. };
  3206. };
  3207. auto maybe_group1 = parse_position_and_maybe_length();
  3208. if (!maybe_group1.has_value())
  3209. return nullptr;
  3210. auto maybe_group2 = parse_position_and_maybe_length();
  3211. if (!maybe_group2.has_value())
  3212. return nullptr;
  3213. auto group1 = maybe_group1.release_value();
  3214. auto group2 = maybe_group2.release_value();
  3215. // 2-value or 4-value if both <length-percentage>s are present or missing.
  3216. if (group1.length.has_value() == group2.length.has_value())
  3217. return nullptr;
  3218. // If 'left' or 'right' is given, that position is X and the other is Y.
  3219. // Conversely -
  3220. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  3221. if (is_vertical(group1.position, false) || is_horizontal(group2.position, false))
  3222. swap(group1, group2);
  3223. // [ center | [ left | right ] ]
  3224. if (!is_horizontal(group1.position, true))
  3225. return nullptr;
  3226. // [ center | [ top | bottom ] ]
  3227. if (!is_vertical(group2.position, true))
  3228. return nullptr;
  3229. auto to_style_value = [&](PositionAndMaybeLength const& group, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  3230. if (group.position == PositionEdge::Center)
  3231. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  3232. return EdgeStyleValue::create(group.position, group.length.value_or(Length::make_px(0)));
  3233. };
  3234. transaction.commit();
  3235. return PositionStyleValue::create(to_style_value(group1, true), to_style_value(group2, false));
  3236. };
  3237. // Note: The alternatives must be attempted in this order since shorter alternatives can match a prefix of longer ones.
  3238. if (auto position = alternative_4())
  3239. return position;
  3240. if (position_parsing_mode == PositionParsingMode::BackgroundPosition) {
  3241. if (auto position = alternative_5_for_background_position())
  3242. return position;
  3243. }
  3244. if (auto position = alternative_3())
  3245. return position;
  3246. if (auto position = alternative_2())
  3247. return position;
  3248. if (auto position = alternative_1())
  3249. return position;
  3250. return nullptr;
  3251. }
  3252. template<typename ParseFunction>
  3253. RefPtr<CSSStyleValue> Parser::parse_comma_separated_value_list(TokenStream<ComponentValue>& tokens, ParseFunction parse_one_value)
  3254. {
  3255. auto first = parse_one_value(tokens);
  3256. if (!first || !tokens.has_next_token())
  3257. return first;
  3258. StyleValueVector values;
  3259. values.append(first.release_nonnull());
  3260. while (tokens.has_next_token()) {
  3261. if (!tokens.consume_a_token().is(Token::Type::Comma))
  3262. return nullptr;
  3263. if (auto maybe_value = parse_one_value(tokens)) {
  3264. values.append(maybe_value.release_nonnull());
  3265. continue;
  3266. }
  3267. return nullptr;
  3268. }
  3269. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  3270. }
  3271. RefPtr<CSSStyleValue> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  3272. {
  3273. return parse_comma_separated_value_list(tokens, [this, property_id](auto& tokens) -> RefPtr<CSSStyleValue> {
  3274. if (auto value = parse_css_value_for_property(property_id, tokens))
  3275. return value;
  3276. tokens.reconsume_current_input_token();
  3277. return nullptr;
  3278. });
  3279. }
  3280. RefPtr<CSSStyleValue> Parser::parse_all_as_single_keyword_value(TokenStream<ComponentValue>& tokens, Keyword keyword)
  3281. {
  3282. auto transaction = tokens.begin_transaction();
  3283. tokens.discard_whitespace();
  3284. auto keyword_value = parse_keyword_value(tokens);
  3285. tokens.discard_whitespace();
  3286. if (tokens.has_next_token() || !keyword_value || keyword_value->to_keyword() != keyword)
  3287. return {};
  3288. transaction.commit();
  3289. return keyword_value;
  3290. }
  3291. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  3292. {
  3293. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  3294. }
  3295. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  3296. RefPtr<CSSStyleValue> Parser::parse_aspect_ratio_value(TokenStream<ComponentValue>& tokens)
  3297. {
  3298. // `auto || <ratio>`
  3299. RefPtr<CSSStyleValue> auto_value;
  3300. RefPtr<CSSStyleValue> ratio_value;
  3301. auto transaction = tokens.begin_transaction();
  3302. while (tokens.has_next_token()) {
  3303. auto maybe_value = parse_css_value_for_property(PropertyID::AspectRatio, tokens);
  3304. if (!maybe_value)
  3305. return nullptr;
  3306. if (maybe_value->is_ratio()) {
  3307. if (ratio_value)
  3308. return nullptr;
  3309. ratio_value = maybe_value.release_nonnull();
  3310. continue;
  3311. }
  3312. if (maybe_value->is_keyword() && maybe_value->as_keyword().keyword() == Keyword::Auto) {
  3313. if (auto_value)
  3314. return nullptr;
  3315. auto_value = maybe_value.release_nonnull();
  3316. continue;
  3317. }
  3318. return nullptr;
  3319. }
  3320. if (auto_value && ratio_value) {
  3321. transaction.commit();
  3322. return StyleValueList::create(
  3323. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  3324. StyleValueList::Separator::Space);
  3325. }
  3326. if (ratio_value) {
  3327. transaction.commit();
  3328. return ratio_value.release_nonnull();
  3329. }
  3330. if (auto_value) {
  3331. transaction.commit();
  3332. return auto_value.release_nonnull();
  3333. }
  3334. return nullptr;
  3335. }
  3336. RefPtr<CSSStyleValue> Parser::parse_background_value(TokenStream<ComponentValue>& tokens)
  3337. {
  3338. auto transaction = tokens.begin_transaction();
  3339. 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) {
  3340. return ShorthandStyleValue::create(PropertyID::Background,
  3341. { PropertyID::BackgroundColor, PropertyID::BackgroundImage, PropertyID::BackgroundPosition, PropertyID::BackgroundSize, PropertyID::BackgroundRepeat, PropertyID::BackgroundAttachment, PropertyID::BackgroundOrigin, PropertyID::BackgroundClip },
  3342. { move(background_color), move(background_image), move(background_position), move(background_size), move(background_repeat), move(background_attachment), move(background_origin), move(background_clip) });
  3343. };
  3344. StyleValueVector background_images;
  3345. StyleValueVector background_positions;
  3346. StyleValueVector background_sizes;
  3347. StyleValueVector background_repeats;
  3348. StyleValueVector background_attachments;
  3349. StyleValueVector background_clips;
  3350. StyleValueVector background_origins;
  3351. RefPtr<CSSStyleValue> background_color;
  3352. auto initial_background_image = property_initial_value(m_context.realm(), PropertyID::BackgroundImage);
  3353. auto initial_background_position = property_initial_value(m_context.realm(), PropertyID::BackgroundPosition);
  3354. auto initial_background_size = property_initial_value(m_context.realm(), PropertyID::BackgroundSize);
  3355. auto initial_background_repeat = property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat);
  3356. auto initial_background_attachment = property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment);
  3357. auto initial_background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
  3358. auto initial_background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
  3359. auto initial_background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
  3360. // Per-layer values
  3361. RefPtr<CSSStyleValue> background_image;
  3362. RefPtr<CSSStyleValue> background_position;
  3363. RefPtr<CSSStyleValue> background_size;
  3364. RefPtr<CSSStyleValue> background_repeat;
  3365. RefPtr<CSSStyleValue> background_attachment;
  3366. RefPtr<CSSStyleValue> background_clip;
  3367. RefPtr<CSSStyleValue> background_origin;
  3368. bool has_multiple_layers = false;
  3369. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  3370. Vector<PropertyID> remaining_layer_properties {
  3371. PropertyID::BackgroundAttachment,
  3372. PropertyID::BackgroundClip,
  3373. PropertyID::BackgroundColor,
  3374. PropertyID::BackgroundImage,
  3375. PropertyID::BackgroundOrigin,
  3376. PropertyID::BackgroundPosition,
  3377. PropertyID::BackgroundRepeat,
  3378. };
  3379. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  3380. if (allow_background_color) {
  3381. if (background_color)
  3382. return true;
  3383. } else {
  3384. if (background_color)
  3385. return false;
  3386. }
  3387. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  3388. };
  3389. auto complete_background_layer = [&]() {
  3390. background_images.append(background_image ? background_image.release_nonnull() : initial_background_image);
  3391. background_positions.append(background_position ? background_position.release_nonnull() : initial_background_position);
  3392. background_sizes.append(background_size ? background_size.release_nonnull() : initial_background_size);
  3393. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat);
  3394. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment);
  3395. if (!background_origin && !background_clip) {
  3396. background_origin = initial_background_origin;
  3397. background_clip = initial_background_clip;
  3398. } else if (!background_clip) {
  3399. background_clip = background_origin;
  3400. }
  3401. background_origins.append(background_origin.release_nonnull());
  3402. background_clips.append(background_clip.release_nonnull());
  3403. background_image = nullptr;
  3404. background_position = nullptr;
  3405. background_size = nullptr;
  3406. background_repeat = nullptr;
  3407. background_attachment = nullptr;
  3408. background_clip = nullptr;
  3409. background_origin = nullptr;
  3410. remaining_layer_properties.clear_with_capacity();
  3411. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  3412. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  3413. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  3414. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  3415. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  3416. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  3417. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  3418. };
  3419. while (tokens.has_next_token()) {
  3420. if (tokens.next_token().is(Token::Type::Comma)) {
  3421. has_multiple_layers = true;
  3422. if (!background_layer_is_valid(false))
  3423. return nullptr;
  3424. complete_background_layer();
  3425. tokens.discard_a_token();
  3426. continue;
  3427. }
  3428. auto value_and_property = parse_css_value_for_properties(remaining_layer_properties, tokens);
  3429. if (!value_and_property.has_value())
  3430. return nullptr;
  3431. auto& value = value_and_property->style_value;
  3432. remove_property(remaining_layer_properties, value_and_property->property);
  3433. switch (value_and_property->property) {
  3434. case PropertyID::BackgroundAttachment:
  3435. VERIFY(!background_attachment);
  3436. background_attachment = value.release_nonnull();
  3437. continue;
  3438. case PropertyID::BackgroundColor:
  3439. VERIFY(!background_color);
  3440. background_color = value.release_nonnull();
  3441. continue;
  3442. case PropertyID::BackgroundImage:
  3443. VERIFY(!background_image);
  3444. background_image = value.release_nonnull();
  3445. continue;
  3446. case PropertyID::BackgroundClip:
  3447. case PropertyID::BackgroundOrigin: {
  3448. // background-origin and background-clip accept the same values. From the spec:
  3449. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  3450. // If two values are present, then the first sets background-origin and the second background-clip."
  3451. // - https://www.w3.org/TR/css-backgrounds-3/#background
  3452. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  3453. // If we only get one, we copy the value before creating the ShorthandStyleValue.
  3454. if (!background_origin) {
  3455. background_origin = value.release_nonnull();
  3456. } else if (!background_clip) {
  3457. background_clip = value.release_nonnull();
  3458. } else {
  3459. VERIFY_NOT_REACHED();
  3460. }
  3461. continue;
  3462. }
  3463. case PropertyID::BackgroundPosition: {
  3464. VERIFY(!background_position);
  3465. background_position = value.release_nonnull();
  3466. // Attempt to parse `/ <background-size>`
  3467. auto background_size_transaction = tokens.begin_transaction();
  3468. auto& maybe_slash = tokens.consume_a_token();
  3469. if (maybe_slash.is_delim('/')) {
  3470. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  3471. background_size_transaction.commit();
  3472. background_size = maybe_background_size.release_nonnull();
  3473. continue;
  3474. }
  3475. return nullptr;
  3476. }
  3477. continue;
  3478. }
  3479. case PropertyID::BackgroundRepeat: {
  3480. VERIFY(!background_repeat);
  3481. tokens.reconsume_current_input_token();
  3482. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  3483. background_repeat = maybe_repeat.release_nonnull();
  3484. continue;
  3485. }
  3486. return nullptr;
  3487. }
  3488. default:
  3489. VERIFY_NOT_REACHED();
  3490. }
  3491. return nullptr;
  3492. }
  3493. if (!background_layer_is_valid(true))
  3494. return nullptr;
  3495. // We only need to create StyleValueLists if there are multiple layers.
  3496. // Otherwise, we can pass the single StyleValues directly.
  3497. if (has_multiple_layers) {
  3498. complete_background_layer();
  3499. if (!background_color)
  3500. background_color = initial_background_color;
  3501. transaction.commit();
  3502. return make_background_shorthand(
  3503. background_color.release_nonnull(),
  3504. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  3505. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  3506. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  3507. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  3508. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  3509. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  3510. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  3511. }
  3512. if (!background_color)
  3513. background_color = initial_background_color;
  3514. if (!background_image)
  3515. background_image = initial_background_image;
  3516. if (!background_position)
  3517. background_position = initial_background_position;
  3518. if (!background_size)
  3519. background_size = initial_background_size;
  3520. if (!background_repeat)
  3521. background_repeat = initial_background_repeat;
  3522. if (!background_attachment)
  3523. background_attachment = initial_background_attachment;
  3524. if (!background_origin && !background_clip) {
  3525. background_origin = initial_background_origin;
  3526. background_clip = initial_background_clip;
  3527. } else if (!background_clip) {
  3528. background_clip = background_origin;
  3529. }
  3530. transaction.commit();
  3531. return make_background_shorthand(
  3532. background_color.release_nonnull(),
  3533. background_image.release_nonnull(),
  3534. background_position.release_nonnull(),
  3535. background_size.release_nonnull(),
  3536. background_repeat.release_nonnull(),
  3537. background_attachment.release_nonnull(),
  3538. background_origin.release_nonnull(),
  3539. background_clip.release_nonnull());
  3540. }
  3541. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  3542. {
  3543. if (value->is_percentage())
  3544. return LengthPercentage { value->as_percentage().percentage() };
  3545. if (value->is_length())
  3546. return LengthPercentage { value->as_length().length() };
  3547. if (value->is_math())
  3548. return LengthPercentage { value->as_math() };
  3549. return {};
  3550. }
  3551. RefPtr<CSSStyleValue> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  3552. {
  3553. PositionEdge relative_edge {};
  3554. if (property == PropertyID::BackgroundPositionX) {
  3555. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  3556. relative_edge = PositionEdge::Left;
  3557. } else if (property == PropertyID::BackgroundPositionY) {
  3558. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  3559. relative_edge = PositionEdge::Top;
  3560. } else {
  3561. VERIFY_NOT_REACHED();
  3562. }
  3563. auto transaction = tokens.begin_transaction();
  3564. if (!tokens.has_next_token())
  3565. return nullptr;
  3566. auto value = parse_css_value_for_property(property, tokens);
  3567. if (!value)
  3568. return nullptr;
  3569. if (value->is_keyword()) {
  3570. auto keyword = value->to_keyword();
  3571. if (keyword == Keyword::Center) {
  3572. transaction.commit();
  3573. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  3574. }
  3575. if (auto edge = keyword_to_position_edge(keyword); edge.has_value()) {
  3576. relative_edge = *edge;
  3577. } else {
  3578. return nullptr;
  3579. }
  3580. if (tokens.has_next_token()) {
  3581. value = parse_css_value_for_property(property, tokens);
  3582. if (!value) {
  3583. transaction.commit();
  3584. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  3585. }
  3586. }
  3587. }
  3588. auto offset = style_value_to_length_percentage(value);
  3589. if (offset.has_value()) {
  3590. transaction.commit();
  3591. return EdgeStyleValue::create(relative_edge, *offset);
  3592. }
  3593. // If no offset is provided create this element but with an offset of default value of zero
  3594. transaction.commit();
  3595. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  3596. }
  3597. RefPtr<CSSStyleValue> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  3598. {
  3599. auto transaction = tokens.begin_transaction();
  3600. auto is_directional_repeat = [](CSSStyleValue const& value) -> bool {
  3601. auto keyword = value.to_keyword();
  3602. return keyword == Keyword::RepeatX || keyword == Keyword::RepeatY;
  3603. };
  3604. auto as_repeat = [](Keyword keyword) -> Optional<Repeat> {
  3605. switch (keyword) {
  3606. case Keyword::NoRepeat:
  3607. return Repeat::NoRepeat;
  3608. case Keyword::Repeat:
  3609. return Repeat::Repeat;
  3610. case Keyword::Round:
  3611. return Repeat::Round;
  3612. case Keyword::Space:
  3613. return Repeat::Space;
  3614. default:
  3615. return {};
  3616. }
  3617. };
  3618. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  3619. if (!maybe_x_value)
  3620. return nullptr;
  3621. auto x_value = maybe_x_value.release_nonnull();
  3622. if (is_directional_repeat(*x_value)) {
  3623. auto keyword = x_value->to_keyword();
  3624. transaction.commit();
  3625. return BackgroundRepeatStyleValue::create(
  3626. keyword == Keyword::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  3627. keyword == Keyword::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  3628. }
  3629. auto x_repeat = as_repeat(x_value->to_keyword());
  3630. if (!x_repeat.has_value())
  3631. return nullptr;
  3632. // See if we have a second value for Y
  3633. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  3634. if (!maybe_y_value) {
  3635. // We don't have a second value, so use x for both
  3636. transaction.commit();
  3637. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  3638. }
  3639. auto y_value = maybe_y_value.release_nonnull();
  3640. if (is_directional_repeat(*y_value))
  3641. return nullptr;
  3642. auto y_repeat = as_repeat(y_value->to_keyword());
  3643. if (!y_repeat.has_value())
  3644. return nullptr;
  3645. transaction.commit();
  3646. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  3647. }
  3648. RefPtr<CSSStyleValue> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  3649. {
  3650. auto transaction = tokens.begin_transaction();
  3651. auto get_length_percentage = [](CSSStyleValue& style_value) -> Optional<LengthPercentage> {
  3652. if (style_value.has_auto())
  3653. return LengthPercentage { Length::make_auto() };
  3654. if (style_value.is_percentage())
  3655. return LengthPercentage { style_value.as_percentage().percentage() };
  3656. if (style_value.is_length())
  3657. return LengthPercentage { style_value.as_length().length() };
  3658. if (style_value.is_math())
  3659. return LengthPercentage { style_value.as_math() };
  3660. return {};
  3661. };
  3662. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  3663. if (!maybe_x_value)
  3664. return nullptr;
  3665. auto x_value = maybe_x_value.release_nonnull();
  3666. if (x_value->to_keyword() == Keyword::Cover || x_value->to_keyword() == Keyword::Contain) {
  3667. transaction.commit();
  3668. return x_value;
  3669. }
  3670. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  3671. if (!maybe_y_value) {
  3672. auto y_value = LengthPercentage { Length::make_auto() };
  3673. auto x_size = get_length_percentage(*x_value);
  3674. if (!x_size.has_value())
  3675. return nullptr;
  3676. transaction.commit();
  3677. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  3678. }
  3679. auto y_value = maybe_y_value.release_nonnull();
  3680. auto x_size = get_length_percentage(*x_value);
  3681. auto y_size = get_length_percentage(*y_value);
  3682. if (!x_size.has_value() || !y_size.has_value())
  3683. return nullptr;
  3684. transaction.commit();
  3685. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  3686. }
  3687. RefPtr<CSSStyleValue> Parser::parse_border_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  3688. {
  3689. RefPtr<CSSStyleValue> border_width;
  3690. RefPtr<CSSStyleValue> border_color;
  3691. RefPtr<CSSStyleValue> border_style;
  3692. auto color_property = PropertyID::Invalid;
  3693. auto style_property = PropertyID::Invalid;
  3694. auto width_property = PropertyID::Invalid;
  3695. switch (property_id) {
  3696. case PropertyID::Border:
  3697. color_property = PropertyID::BorderColor;
  3698. style_property = PropertyID::BorderStyle;
  3699. width_property = PropertyID::BorderWidth;
  3700. break;
  3701. case PropertyID::BorderBottom:
  3702. color_property = PropertyID::BorderBottomColor;
  3703. style_property = PropertyID::BorderBottomStyle;
  3704. width_property = PropertyID::BorderBottomWidth;
  3705. break;
  3706. case PropertyID::BorderLeft:
  3707. color_property = PropertyID::BorderLeftColor;
  3708. style_property = PropertyID::BorderLeftStyle;
  3709. width_property = PropertyID::BorderLeftWidth;
  3710. break;
  3711. case PropertyID::BorderRight:
  3712. color_property = PropertyID::BorderRightColor;
  3713. style_property = PropertyID::BorderRightStyle;
  3714. width_property = PropertyID::BorderRightWidth;
  3715. break;
  3716. case PropertyID::BorderTop:
  3717. color_property = PropertyID::BorderTopColor;
  3718. style_property = PropertyID::BorderTopStyle;
  3719. width_property = PropertyID::BorderTopWidth;
  3720. break;
  3721. default:
  3722. VERIFY_NOT_REACHED();
  3723. }
  3724. auto remaining_longhands = Vector { width_property, color_property, style_property };
  3725. auto transaction = tokens.begin_transaction();
  3726. while (tokens.has_next_token()) {
  3727. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3728. if (!property_and_value.has_value())
  3729. return nullptr;
  3730. auto& value = property_and_value->style_value;
  3731. remove_property(remaining_longhands, property_and_value->property);
  3732. if (property_and_value->property == width_property) {
  3733. VERIFY(!border_width);
  3734. border_width = value.release_nonnull();
  3735. } else if (property_and_value->property == color_property) {
  3736. VERIFY(!border_color);
  3737. border_color = value.release_nonnull();
  3738. } else if (property_and_value->property == style_property) {
  3739. VERIFY(!border_style);
  3740. border_style = value.release_nonnull();
  3741. } else {
  3742. VERIFY_NOT_REACHED();
  3743. }
  3744. }
  3745. if (!border_width)
  3746. border_width = property_initial_value(m_context.realm(), width_property);
  3747. if (!border_style)
  3748. border_style = property_initial_value(m_context.realm(), style_property);
  3749. if (!border_color)
  3750. border_color = property_initial_value(m_context.realm(), color_property);
  3751. transaction.commit();
  3752. return ShorthandStyleValue::create(property_id,
  3753. { width_property, style_property, color_property },
  3754. { border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull() });
  3755. }
  3756. RefPtr<CSSStyleValue> Parser::parse_border_radius_value(TokenStream<ComponentValue>& tokens)
  3757. {
  3758. if (tokens.remaining_token_count() == 2) {
  3759. auto transaction = tokens.begin_transaction();
  3760. auto horizontal = parse_length_percentage(tokens);
  3761. auto vertical = parse_length_percentage(tokens);
  3762. if (horizontal.has_value() && vertical.has_value()) {
  3763. transaction.commit();
  3764. return BorderRadiusStyleValue::create(horizontal.release_value(), vertical.release_value());
  3765. }
  3766. }
  3767. if (tokens.remaining_token_count() == 1) {
  3768. auto transaction = tokens.begin_transaction();
  3769. auto radius = parse_length_percentage(tokens);
  3770. if (radius.has_value()) {
  3771. transaction.commit();
  3772. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  3773. }
  3774. }
  3775. return nullptr;
  3776. }
  3777. RefPtr<CSSStyleValue> Parser::parse_border_radius_shorthand_value(TokenStream<ComponentValue>& tokens)
  3778. {
  3779. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  3780. auto top_right = [&](Vector<LengthPercentage>& radii) {
  3781. switch (radii.size()) {
  3782. case 4:
  3783. case 3:
  3784. case 2:
  3785. return radii[1];
  3786. case 1:
  3787. return radii[0];
  3788. default:
  3789. VERIFY_NOT_REACHED();
  3790. }
  3791. };
  3792. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  3793. switch (radii.size()) {
  3794. case 4:
  3795. case 3:
  3796. return radii[2];
  3797. case 2:
  3798. case 1:
  3799. return radii[0];
  3800. default:
  3801. VERIFY_NOT_REACHED();
  3802. }
  3803. };
  3804. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  3805. switch (radii.size()) {
  3806. case 4:
  3807. return radii[3];
  3808. case 3:
  3809. case 2:
  3810. return radii[1];
  3811. case 1:
  3812. return radii[0];
  3813. default:
  3814. VERIFY_NOT_REACHED();
  3815. }
  3816. };
  3817. Vector<LengthPercentage> horizontal_radii;
  3818. Vector<LengthPercentage> vertical_radii;
  3819. bool reading_vertical = false;
  3820. auto transaction = tokens.begin_transaction();
  3821. while (tokens.has_next_token()) {
  3822. if (tokens.next_token().is_delim('/')) {
  3823. if (reading_vertical || horizontal_radii.is_empty())
  3824. return nullptr;
  3825. reading_vertical = true;
  3826. tokens.discard_a_token(); // `/`
  3827. continue;
  3828. }
  3829. auto maybe_dimension = parse_length_percentage(tokens);
  3830. if (!maybe_dimension.has_value())
  3831. return nullptr;
  3832. if (reading_vertical) {
  3833. vertical_radii.append(maybe_dimension.release_value());
  3834. } else {
  3835. horizontal_radii.append(maybe_dimension.release_value());
  3836. }
  3837. }
  3838. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  3839. || horizontal_radii.is_empty()
  3840. || (reading_vertical && vertical_radii.is_empty()))
  3841. return nullptr;
  3842. auto top_left_radius = BorderRadiusStyleValue::create(top_left(horizontal_radii),
  3843. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii));
  3844. auto top_right_radius = BorderRadiusStyleValue::create(top_right(horizontal_radii),
  3845. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii));
  3846. auto bottom_right_radius = BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  3847. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii));
  3848. auto bottom_left_radius = BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  3849. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii));
  3850. transaction.commit();
  3851. return ShorthandStyleValue::create(PropertyID::BorderRadius,
  3852. { PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius },
  3853. { move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius) });
  3854. }
  3855. RefPtr<CSSStyleValue> Parser::parse_columns_value(TokenStream<ComponentValue>& tokens)
  3856. {
  3857. if (tokens.remaining_token_count() > 2)
  3858. return nullptr;
  3859. RefPtr<CSSStyleValue> column_count;
  3860. RefPtr<CSSStyleValue> column_width;
  3861. Vector<PropertyID> remaining_longhands { PropertyID::ColumnCount, PropertyID::ColumnWidth };
  3862. int found_autos = 0;
  3863. auto transaction = tokens.begin_transaction();
  3864. while (tokens.has_next_token()) {
  3865. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3866. if (!property_and_value.has_value())
  3867. return nullptr;
  3868. auto& value = property_and_value->style_value;
  3869. // since the values can be in either order, we want to skip over autos
  3870. if (value->has_auto()) {
  3871. found_autos++;
  3872. continue;
  3873. }
  3874. remove_property(remaining_longhands, property_and_value->property);
  3875. switch (property_and_value->property) {
  3876. case PropertyID::ColumnCount: {
  3877. VERIFY(!column_count);
  3878. column_count = value.release_nonnull();
  3879. continue;
  3880. }
  3881. case PropertyID::ColumnWidth: {
  3882. VERIFY(!column_width);
  3883. column_width = value.release_nonnull();
  3884. continue;
  3885. }
  3886. default:
  3887. VERIFY_NOT_REACHED();
  3888. }
  3889. }
  3890. if (found_autos > 2)
  3891. return nullptr;
  3892. if (found_autos == 2) {
  3893. column_count = CSSKeywordValue::create(Keyword::Auto);
  3894. column_width = CSSKeywordValue::create(Keyword::Auto);
  3895. }
  3896. if (found_autos == 1) {
  3897. if (!column_count)
  3898. column_count = CSSKeywordValue::create(Keyword::Auto);
  3899. if (!column_width)
  3900. column_width = CSSKeywordValue::create(Keyword::Auto);
  3901. }
  3902. if (!column_count)
  3903. column_count = property_initial_value(m_context.realm(), PropertyID::ColumnCount);
  3904. if (!column_width)
  3905. column_width = property_initial_value(m_context.realm(), PropertyID::ColumnWidth);
  3906. transaction.commit();
  3907. return ShorthandStyleValue::create(PropertyID::Columns,
  3908. { PropertyID::ColumnCount, PropertyID::ColumnWidth },
  3909. { column_count.release_nonnull(), column_width.release_nonnull() });
  3910. }
  3911. RefPtr<CSSStyleValue> Parser::parse_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  3912. {
  3913. // "none"
  3914. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  3915. return none;
  3916. return parse_comma_separated_value_list(tokens, [this, allow_inset_keyword](auto& tokens) {
  3917. return parse_single_shadow_value(tokens, allow_inset_keyword);
  3918. });
  3919. }
  3920. RefPtr<CSSStyleValue> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  3921. {
  3922. auto transaction = tokens.begin_transaction();
  3923. RefPtr<CSSStyleValue> color;
  3924. RefPtr<CSSStyleValue> offset_x;
  3925. RefPtr<CSSStyleValue> offset_y;
  3926. RefPtr<CSSStyleValue> blur_radius;
  3927. RefPtr<CSSStyleValue> spread_distance;
  3928. Optional<ShadowPlacement> placement;
  3929. auto possibly_dynamic_length = [&](ComponentValue const& token) -> RefPtr<CSSStyleValue> {
  3930. auto tokens = TokenStream<ComponentValue>::of_single_token(token);
  3931. auto maybe_length = parse_length(tokens);
  3932. if (!maybe_length.has_value())
  3933. return nullptr;
  3934. return maybe_length->as_style_value();
  3935. };
  3936. while (tokens.has_next_token()) {
  3937. if (auto maybe_color = parse_color_value(tokens); maybe_color) {
  3938. if (color)
  3939. return nullptr;
  3940. color = maybe_color.release_nonnull();
  3941. continue;
  3942. }
  3943. auto const& token = tokens.next_token();
  3944. if (auto maybe_offset_x = possibly_dynamic_length(token); maybe_offset_x) {
  3945. // horizontal offset
  3946. if (offset_x)
  3947. return nullptr;
  3948. offset_x = maybe_offset_x;
  3949. tokens.discard_a_token();
  3950. // vertical offset
  3951. if (!tokens.has_next_token())
  3952. return nullptr;
  3953. auto maybe_offset_y = possibly_dynamic_length(tokens.next_token());
  3954. if (!maybe_offset_y)
  3955. return nullptr;
  3956. offset_y = maybe_offset_y;
  3957. tokens.discard_a_token();
  3958. // blur radius (optional)
  3959. if (!tokens.has_next_token())
  3960. break;
  3961. auto maybe_blur_radius = possibly_dynamic_length(tokens.next_token());
  3962. if (!maybe_blur_radius)
  3963. continue;
  3964. blur_radius = maybe_blur_radius;
  3965. tokens.discard_a_token();
  3966. // spread distance (optional)
  3967. if (!tokens.has_next_token())
  3968. break;
  3969. auto maybe_spread_distance = possibly_dynamic_length(tokens.next_token());
  3970. if (!maybe_spread_distance)
  3971. continue;
  3972. spread_distance = maybe_spread_distance;
  3973. tokens.discard_a_token();
  3974. continue;
  3975. }
  3976. if (allow_inset_keyword == AllowInsetKeyword::Yes && token.is_ident("inset"sv)) {
  3977. if (placement.has_value())
  3978. return nullptr;
  3979. placement = ShadowPlacement::Inner;
  3980. tokens.discard_a_token();
  3981. continue;
  3982. }
  3983. if (token.is(Token::Type::Comma))
  3984. break;
  3985. return nullptr;
  3986. }
  3987. // If color is absent, default to `currentColor`
  3988. if (!color)
  3989. color = CSSKeywordValue::create(Keyword::Currentcolor);
  3990. // x/y offsets are required
  3991. if (!offset_x || !offset_y)
  3992. return nullptr;
  3993. // Other lengths default to 0
  3994. if (!blur_radius)
  3995. blur_radius = LengthStyleValue::create(Length::make_px(0));
  3996. if (!spread_distance)
  3997. spread_distance = LengthStyleValue::create(Length::make_px(0));
  3998. // Placement is outer by default
  3999. if (!placement.has_value())
  4000. placement = ShadowPlacement::Outer;
  4001. transaction.commit();
  4002. 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());
  4003. }
  4004. RefPtr<CSSStyleValue> Parser::parse_rotate_value(TokenStream<ComponentValue>& tokens)
  4005. {
  4006. // Value: none | <angle> | [ x | y | z | <number>{3} ] && <angle>
  4007. if (tokens.remaining_token_count() == 1) {
  4008. // "none"
  4009. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4010. return none;
  4011. // <angle>
  4012. if (auto angle = parse_angle_value(tokens))
  4013. return RotationStyleValue::create(angle.release_nonnull(), NumberStyleValue::create(0), NumberStyleValue::create(0), NumberStyleValue::create(1));
  4014. }
  4015. auto parse_one_of_xyz = [&]() -> Optional<ComponentValue> {
  4016. auto transaction = tokens.begin_transaction();
  4017. auto axis = tokens.consume_a_token();
  4018. if (axis.is_ident("x"sv) || axis.is_ident("y"sv) || axis.is_ident("z"sv)) {
  4019. transaction.commit();
  4020. return axis;
  4021. }
  4022. return {};
  4023. };
  4024. // [ x | y | z ] && <angle>
  4025. if (tokens.remaining_token_count() == 2) {
  4026. // Try parsing `x <angle>`
  4027. if (auto axis = parse_one_of_xyz(); axis.has_value()) {
  4028. if (auto angle = parse_angle_value(tokens); angle) {
  4029. if (axis->is_ident("x"sv))
  4030. return RotationStyleValue::create(angle.release_nonnull(), NumberStyleValue::create(1), NumberStyleValue::create(0), NumberStyleValue::create(0));
  4031. if (axis->is_ident("y"sv))
  4032. return RotationStyleValue::create(angle.release_nonnull(), NumberStyleValue::create(0), NumberStyleValue::create(1), NumberStyleValue::create(0));
  4033. if (axis->is_ident("z"sv))
  4034. return RotationStyleValue::create(angle.release_nonnull(), NumberStyleValue::create(0), NumberStyleValue::create(0), NumberStyleValue::create(1));
  4035. }
  4036. }
  4037. // Try parsing `<angle> x`
  4038. if (auto angle = parse_angle_value(tokens); angle) {
  4039. if (auto axis = parse_one_of_xyz(); axis.has_value()) {
  4040. if (axis->is_ident("x"sv))
  4041. return RotationStyleValue::create(angle.release_nonnull(), NumberStyleValue::create(1), NumberStyleValue::create(0), NumberStyleValue::create(0));
  4042. if (axis->is_ident("y"sv))
  4043. return RotationStyleValue::create(angle.release_nonnull(), NumberStyleValue::create(0), NumberStyleValue::create(1), NumberStyleValue::create(0));
  4044. if (axis->is_ident("z"sv))
  4045. return RotationStyleValue::create(angle.release_nonnull(), NumberStyleValue::create(0), NumberStyleValue::create(0), NumberStyleValue::create(1));
  4046. }
  4047. }
  4048. }
  4049. auto parse_three_numbers = [&]() -> Optional<StyleValueVector> {
  4050. auto transaction = tokens.begin_transaction();
  4051. StyleValueVector numbers;
  4052. for (size_t i = 0; i < 3; ++i) {
  4053. if (auto number = parse_number_value(tokens); number) {
  4054. numbers.append(number.release_nonnull());
  4055. } else {
  4056. return {};
  4057. }
  4058. }
  4059. transaction.commit();
  4060. return numbers;
  4061. };
  4062. // <number>{3} && <angle>
  4063. if (tokens.remaining_token_count() == 4) {
  4064. // Try parsing <number>{3} <angle>
  4065. if (auto maybe_numbers = parse_three_numbers(); maybe_numbers.has_value()) {
  4066. if (auto angle = parse_angle_value(tokens); angle) {
  4067. auto numbers = maybe_numbers.release_value();
  4068. return RotationStyleValue::create(angle.release_nonnull(), numbers[0], numbers[1], numbers[2]);
  4069. }
  4070. }
  4071. // Try parsing <angle> <number>{3}
  4072. if (auto angle = parse_angle_value(tokens); angle) {
  4073. if (auto maybe_numbers = parse_three_numbers(); maybe_numbers.has_value()) {
  4074. auto numbers = maybe_numbers.release_value();
  4075. return RotationStyleValue::create(angle.release_nonnull(), numbers[0], numbers[1], numbers[2]);
  4076. }
  4077. }
  4078. }
  4079. return nullptr;
  4080. }
  4081. RefPtr<CSSStyleValue> Parser::parse_content_value(TokenStream<ComponentValue>& tokens)
  4082. {
  4083. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  4084. auto is_single_value_keyword = [](Keyword keyword) -> bool {
  4085. switch (keyword) {
  4086. case Keyword::None:
  4087. case Keyword::Normal:
  4088. return true;
  4089. default:
  4090. return false;
  4091. }
  4092. };
  4093. if (tokens.remaining_token_count() == 1) {
  4094. auto transaction = tokens.begin_transaction();
  4095. if (auto keyword = parse_keyword_value(tokens)) {
  4096. if (is_single_value_keyword(keyword->to_keyword())) {
  4097. transaction.commit();
  4098. return keyword;
  4099. }
  4100. }
  4101. }
  4102. auto transaction = tokens.begin_transaction();
  4103. StyleValueVector content_values;
  4104. StyleValueVector alt_text_values;
  4105. bool in_alt_text = false;
  4106. while (tokens.has_next_token()) {
  4107. auto& next = tokens.next_token();
  4108. if (next.is_delim('/')) {
  4109. if (in_alt_text || content_values.is_empty())
  4110. return nullptr;
  4111. in_alt_text = true;
  4112. tokens.discard_a_token();
  4113. continue;
  4114. }
  4115. if (auto style_value = parse_css_value_for_property(PropertyID::Content, tokens)) {
  4116. if (is_single_value_keyword(style_value->to_keyword()))
  4117. return nullptr;
  4118. if (in_alt_text) {
  4119. alt_text_values.append(style_value.release_nonnull());
  4120. } else {
  4121. content_values.append(style_value.release_nonnull());
  4122. }
  4123. continue;
  4124. }
  4125. return nullptr;
  4126. }
  4127. if (content_values.is_empty())
  4128. return nullptr;
  4129. if (in_alt_text && alt_text_values.is_empty())
  4130. return nullptr;
  4131. RefPtr<StyleValueList> alt_text;
  4132. if (!alt_text_values.is_empty())
  4133. alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);
  4134. transaction.commit();
  4135. return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
  4136. }
  4137. // https://drafts.csswg.org/css-lists-3/#propdef-counter-increment
  4138. RefPtr<CSSStyleValue> Parser::parse_counter_increment_value(TokenStream<ComponentValue>& tokens)
  4139. {
  4140. // [ <counter-name> <integer>? ]+ | none
  4141. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4142. return none;
  4143. return parse_counter_definitions_value(tokens, AllowReversed::No, 1);
  4144. }
  4145. // https://drafts.csswg.org/css-lists-3/#propdef-counter-reset
  4146. RefPtr<CSSStyleValue> Parser::parse_counter_reset_value(TokenStream<ComponentValue>& tokens)
  4147. {
  4148. // [ <counter-name> <integer>? | <reversed-counter-name> <integer>? ]+ | none
  4149. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4150. return none;
  4151. return parse_counter_definitions_value(tokens, AllowReversed::Yes, 0);
  4152. }
  4153. // https://drafts.csswg.org/css-lists-3/#propdef-counter-set
  4154. RefPtr<CSSStyleValue> Parser::parse_counter_set_value(TokenStream<ComponentValue>& tokens)
  4155. {
  4156. // [ <counter-name> <integer>? ]+ | none
  4157. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4158. return none;
  4159. return parse_counter_definitions_value(tokens, AllowReversed::No, 0);
  4160. }
  4161. // https://www.w3.org/TR/css-display-3/#the-display-properties
  4162. RefPtr<CSSStyleValue> Parser::parse_display_value(TokenStream<ComponentValue>& tokens)
  4163. {
  4164. auto parse_single_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  4165. auto transaction = tokens.begin_transaction();
  4166. if (auto keyword_value = parse_keyword_value(tokens)) {
  4167. auto keyword = keyword_value->to_keyword();
  4168. if (keyword == Keyword::ListItem) {
  4169. transaction.commit();
  4170. return Display::from_short(Display::Short::ListItem);
  4171. }
  4172. if (auto display_outside = keyword_to_display_outside(keyword); display_outside.has_value()) {
  4173. transaction.commit();
  4174. switch (display_outside.value()) {
  4175. case DisplayOutside::Block:
  4176. return Display::from_short(Display::Short::Block);
  4177. case DisplayOutside::Inline:
  4178. return Display::from_short(Display::Short::Inline);
  4179. case DisplayOutside::RunIn:
  4180. return Display::from_short(Display::Short::RunIn);
  4181. }
  4182. }
  4183. if (auto display_inside = keyword_to_display_inside(keyword); display_inside.has_value()) {
  4184. transaction.commit();
  4185. switch (display_inside.value()) {
  4186. case DisplayInside::Flow:
  4187. return Display::from_short(Display::Short::Flow);
  4188. case DisplayInside::FlowRoot:
  4189. return Display::from_short(Display::Short::FlowRoot);
  4190. case DisplayInside::Table:
  4191. return Display::from_short(Display::Short::Table);
  4192. case DisplayInside::Flex:
  4193. return Display::from_short(Display::Short::Flex);
  4194. case DisplayInside::Grid:
  4195. return Display::from_short(Display::Short::Grid);
  4196. case DisplayInside::Ruby:
  4197. return Display::from_short(Display::Short::Ruby);
  4198. case DisplayInside::Math:
  4199. return Display::from_short(Display::Short::Math);
  4200. }
  4201. }
  4202. if (auto display_internal = keyword_to_display_internal(keyword); display_internal.has_value()) {
  4203. transaction.commit();
  4204. return Display { display_internal.value() };
  4205. }
  4206. if (auto display_box = keyword_to_display_box(keyword); display_box.has_value()) {
  4207. transaction.commit();
  4208. switch (display_box.value()) {
  4209. case DisplayBox::Contents:
  4210. return Display::from_short(Display::Short::Contents);
  4211. case DisplayBox::None:
  4212. return Display::from_short(Display::Short::None);
  4213. }
  4214. }
  4215. if (auto display_legacy = keyword_to_display_legacy(keyword); display_legacy.has_value()) {
  4216. transaction.commit();
  4217. switch (display_legacy.value()) {
  4218. case DisplayLegacy::InlineBlock:
  4219. return Display::from_short(Display::Short::InlineBlock);
  4220. case DisplayLegacy::InlineTable:
  4221. return Display::from_short(Display::Short::InlineTable);
  4222. case DisplayLegacy::InlineFlex:
  4223. return Display::from_short(Display::Short::InlineFlex);
  4224. case DisplayLegacy::InlineGrid:
  4225. return Display::from_short(Display::Short::InlineGrid);
  4226. }
  4227. }
  4228. }
  4229. return OptionalNone {};
  4230. };
  4231. auto parse_multi_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  4232. auto list_item = Display::ListItem::No;
  4233. Optional<DisplayInside> inside;
  4234. Optional<DisplayOutside> outside;
  4235. auto transaction = tokens.begin_transaction();
  4236. while (tokens.has_next_token()) {
  4237. if (auto value = parse_keyword_value(tokens)) {
  4238. auto keyword = value->to_keyword();
  4239. if (keyword == Keyword::ListItem) {
  4240. if (list_item == Display::ListItem::Yes)
  4241. return {};
  4242. list_item = Display::ListItem::Yes;
  4243. continue;
  4244. }
  4245. if (auto inside_value = keyword_to_display_inside(keyword); inside_value.has_value()) {
  4246. if (inside.has_value())
  4247. return {};
  4248. inside = inside_value.value();
  4249. continue;
  4250. }
  4251. if (auto outside_value = keyword_to_display_outside(keyword); outside_value.has_value()) {
  4252. if (outside.has_value())
  4253. return {};
  4254. outside = outside_value.value();
  4255. continue;
  4256. }
  4257. }
  4258. // Not a display value, abort.
  4259. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized display value: `{}`", tokens.next_token().to_string());
  4260. return {};
  4261. }
  4262. // The spec does not allow any other inside values to be combined with list-item
  4263. // <display-outside>? && [ flow | flow-root ]? && list-item
  4264. if (list_item == Display::ListItem::Yes && inside.has_value() && inside != DisplayInside::Flow && inside != DisplayInside::FlowRoot)
  4265. return {};
  4266. transaction.commit();
  4267. return Display { outside.value_or(DisplayOutside::Block), inside.value_or(DisplayInside::Flow), list_item };
  4268. };
  4269. Optional<Display> display;
  4270. if (tokens.remaining_token_count() == 1)
  4271. display = parse_single_component_display(tokens);
  4272. else
  4273. display = parse_multi_component_display(tokens);
  4274. if (display.has_value())
  4275. return DisplayStyleValue::create(display.value());
  4276. return nullptr;
  4277. }
  4278. RefPtr<CSSStyleValue> Parser::parse_filter_value_list_value(TokenStream<ComponentValue>& tokens)
  4279. {
  4280. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4281. return none;
  4282. auto transaction = tokens.begin_transaction();
  4283. // FIXME: <url>s are ignored for now
  4284. // <filter-value-list> = [ <filter-function> | <url> ]+
  4285. enum class FilterToken {
  4286. // Color filters:
  4287. Brightness,
  4288. Contrast,
  4289. Grayscale,
  4290. Invert,
  4291. Opacity,
  4292. Saturate,
  4293. Sepia,
  4294. // Special filters:
  4295. Blur,
  4296. DropShadow,
  4297. HueRotate
  4298. };
  4299. auto filter_token_to_operation = [&](auto filter) {
  4300. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  4301. return static_cast<FilterOperation::Color::Type>(filter);
  4302. };
  4303. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  4304. if (name.equals_ignoring_ascii_case("blur"sv))
  4305. return FilterToken::Blur;
  4306. if (name.equals_ignoring_ascii_case("brightness"sv))
  4307. return FilterToken::Brightness;
  4308. if (name.equals_ignoring_ascii_case("contrast"sv))
  4309. return FilterToken::Contrast;
  4310. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  4311. return FilterToken::DropShadow;
  4312. if (name.equals_ignoring_ascii_case("grayscale"sv))
  4313. return FilterToken::Grayscale;
  4314. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  4315. return FilterToken::HueRotate;
  4316. if (name.equals_ignoring_ascii_case("invert"sv))
  4317. return FilterToken::Invert;
  4318. if (name.equals_ignoring_ascii_case("opacity"sv))
  4319. return FilterToken::Opacity;
  4320. if (name.equals_ignoring_ascii_case("saturate"sv))
  4321. return FilterToken::Saturate;
  4322. if (name.equals_ignoring_ascii_case("sepia"sv))
  4323. return FilterToken::Sepia;
  4324. return {};
  4325. };
  4326. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  4327. TokenStream tokens { function_values };
  4328. tokens.discard_whitespace();
  4329. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  4330. tokens.discard_whitespace();
  4331. if (tokens.has_next_token())
  4332. return {};
  4333. return filter;
  4334. };
  4335. if (filter_token == FilterToken::Blur) {
  4336. // blur( <length>? )
  4337. if (!tokens.has_next_token())
  4338. return FilterOperation::Blur {};
  4339. auto blur_radius = parse_length(tokens);
  4340. tokens.discard_whitespace();
  4341. if (!blur_radius.has_value())
  4342. return {};
  4343. return if_no_more_tokens_return(FilterOperation::Blur { blur_radius.value() });
  4344. } else if (filter_token == FilterToken::DropShadow) {
  4345. if (!tokens.has_next_token())
  4346. return {};
  4347. // drop-shadow( [ <color>? && <length>{2,3} ] )
  4348. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  4349. Optional<LengthOrCalculated> maybe_radius = {};
  4350. auto maybe_color = parse_color_value(tokens);
  4351. tokens.discard_whitespace();
  4352. auto x_offset = parse_length(tokens);
  4353. tokens.discard_whitespace();
  4354. if (!x_offset.has_value() || !tokens.has_next_token())
  4355. return {};
  4356. auto y_offset = parse_length(tokens);
  4357. tokens.discard_whitespace();
  4358. if (!y_offset.has_value())
  4359. return {};
  4360. if (tokens.has_next_token()) {
  4361. maybe_radius = parse_length(tokens);
  4362. tokens.discard_whitespace();
  4363. if (!maybe_color && (!maybe_radius.has_value() || tokens.has_next_token())) {
  4364. maybe_color = parse_color_value(tokens);
  4365. if (!maybe_color)
  4366. return {};
  4367. } else if (!maybe_radius.has_value()) {
  4368. return {};
  4369. }
  4370. }
  4371. Optional<Color> color = {};
  4372. if (maybe_color)
  4373. color = maybe_color->to_color({});
  4374. return if_no_more_tokens_return(FilterOperation::DropShadow { x_offset.value(), y_offset.value(), maybe_radius, color });
  4375. } else if (filter_token == FilterToken::HueRotate) {
  4376. // hue-rotate( [ <angle> | <zero> ]? )
  4377. if (!tokens.has_next_token())
  4378. return FilterOperation::HueRotate {};
  4379. if (tokens.next_token().is(Token::Type::Number)) {
  4380. // hue-rotate(0)
  4381. auto number = tokens.consume_a_token().token().number();
  4382. if (number.is_integer() && number.integer_value() == 0)
  4383. return if_no_more_tokens_return(FilterOperation::HueRotate { FilterOperation::HueRotate::Zero {} });
  4384. return {};
  4385. }
  4386. if (auto angle = parse_angle(tokens); angle.has_value())
  4387. return if_no_more_tokens_return(FilterOperation::HueRotate { angle.value() });
  4388. return {};
  4389. } else {
  4390. // Simple filters:
  4391. // brightness( <number-percentage>? )
  4392. // contrast( <number-percentage>? )
  4393. // grayscale( <number-percentage>? )
  4394. // invert( <number-percentage>? )
  4395. // opacity( <number-percentage>? )
  4396. // sepia( <number-percentage>? )
  4397. // saturate( <number-percentage>? )
  4398. if (!tokens.has_next_token())
  4399. return FilterOperation::Color { filter_token_to_operation(filter_token) };
  4400. auto amount = parse_number_percentage(tokens);
  4401. return if_no_more_tokens_return(FilterOperation::Color { filter_token_to_operation(filter_token), amount });
  4402. }
  4403. };
  4404. Vector<FilterFunction> filter_value_list {};
  4405. while (tokens.has_next_token()) {
  4406. tokens.discard_whitespace();
  4407. if (!tokens.has_next_token())
  4408. break;
  4409. auto& token = tokens.consume_a_token();
  4410. if (!token.is_function())
  4411. return nullptr;
  4412. auto filter_token = parse_filter_function_name(token.function().name);
  4413. if (!filter_token.has_value())
  4414. return nullptr;
  4415. auto filter_function = parse_filter_function(*filter_token, token.function().value);
  4416. if (!filter_function.has_value())
  4417. return nullptr;
  4418. filter_value_list.append(*filter_function);
  4419. }
  4420. if (filter_value_list.is_empty())
  4421. return nullptr;
  4422. transaction.commit();
  4423. return FilterValueListStyleValue::create(move(filter_value_list));
  4424. }
  4425. RefPtr<CSSStyleValue> Parser::parse_flex_shorthand_value(TokenStream<ComponentValue>& tokens)
  4426. {
  4427. auto transaction = tokens.begin_transaction();
  4428. auto make_flex_shorthand = [&](NonnullRefPtr<CSSStyleValue> flex_grow, NonnullRefPtr<CSSStyleValue> flex_shrink, NonnullRefPtr<CSSStyleValue> flex_basis) {
  4429. transaction.commit();
  4430. return ShorthandStyleValue::create(PropertyID::Flex,
  4431. { PropertyID::FlexGrow, PropertyID::FlexShrink, PropertyID::FlexBasis },
  4432. { move(flex_grow), move(flex_shrink), move(flex_basis) });
  4433. };
  4434. if (tokens.remaining_token_count() == 1) {
  4435. // One-value syntax: <flex-grow> | <flex-basis> | none
  4436. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  4437. auto property_and_value = parse_css_value_for_properties(properties, tokens);
  4438. if (!property_and_value.has_value())
  4439. return nullptr;
  4440. auto& value = property_and_value->style_value;
  4441. switch (property_and_value->property) {
  4442. case PropertyID::FlexGrow: {
  4443. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4444. // https://github.com/w3c/csswg-drafts/issues/5742
  4445. auto flex_basis = PercentageStyleValue::create(Percentage(0));
  4446. auto one = NumberStyleValue::create(1);
  4447. return make_flex_shorthand(*value, one, flex_basis);
  4448. }
  4449. case PropertyID::FlexBasis: {
  4450. auto one = NumberStyleValue::create(1);
  4451. return make_flex_shorthand(one, one, *value);
  4452. }
  4453. case PropertyID::Flex: {
  4454. if (value->is_keyword() && value->to_keyword() == Keyword::None) {
  4455. auto zero = NumberStyleValue::create(0);
  4456. return make_flex_shorthand(zero, zero, CSSKeywordValue::create(Keyword::Auto));
  4457. }
  4458. break;
  4459. }
  4460. default:
  4461. VERIFY_NOT_REACHED();
  4462. }
  4463. return nullptr;
  4464. }
  4465. RefPtr<CSSStyleValue> flex_grow;
  4466. RefPtr<CSSStyleValue> flex_shrink;
  4467. RefPtr<CSSStyleValue> flex_basis;
  4468. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  4469. // if FlexGrow (along with optional FlexShrink) have already been specified.
  4470. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  4471. while (tokens.has_next_token()) {
  4472. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4473. if (!property_and_value.has_value())
  4474. return nullptr;
  4475. auto& value = property_and_value->style_value;
  4476. remove_property(remaining_longhands, property_and_value->property);
  4477. switch (property_and_value->property) {
  4478. case PropertyID::FlexGrow: {
  4479. VERIFY(!flex_grow);
  4480. flex_grow = value.release_nonnull();
  4481. // Flex-shrink may optionally follow directly after.
  4482. auto maybe_flex_shrink = parse_css_value_for_property(PropertyID::FlexShrink, tokens);
  4483. if (maybe_flex_shrink)
  4484. flex_shrink = maybe_flex_shrink.release_nonnull();
  4485. continue;
  4486. }
  4487. case PropertyID::FlexBasis: {
  4488. VERIFY(!flex_basis);
  4489. flex_basis = value.release_nonnull();
  4490. continue;
  4491. }
  4492. default:
  4493. VERIFY_NOT_REACHED();
  4494. }
  4495. }
  4496. if (!flex_grow)
  4497. flex_grow = property_initial_value(m_context.realm(), PropertyID::FlexGrow);
  4498. if (!flex_shrink)
  4499. flex_shrink = property_initial_value(m_context.realm(), PropertyID::FlexShrink);
  4500. if (!flex_basis) {
  4501. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4502. // https://github.com/w3c/csswg-drafts/issues/5742
  4503. flex_basis = PercentageStyleValue::create(Percentage(0));
  4504. }
  4505. return make_flex_shorthand(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  4506. }
  4507. RefPtr<CSSStyleValue> Parser::parse_flex_flow_value(TokenStream<ComponentValue>& tokens)
  4508. {
  4509. RefPtr<CSSStyleValue> flex_direction;
  4510. RefPtr<CSSStyleValue> flex_wrap;
  4511. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  4512. auto transaction = tokens.begin_transaction();
  4513. while (tokens.has_next_token()) {
  4514. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4515. if (!property_and_value.has_value())
  4516. return nullptr;
  4517. auto& value = property_and_value->style_value;
  4518. remove_property(remaining_longhands, property_and_value->property);
  4519. switch (property_and_value->property) {
  4520. case PropertyID::FlexDirection:
  4521. VERIFY(!flex_direction);
  4522. flex_direction = value.release_nonnull();
  4523. continue;
  4524. case PropertyID::FlexWrap:
  4525. VERIFY(!flex_wrap);
  4526. flex_wrap = value.release_nonnull();
  4527. continue;
  4528. default:
  4529. VERIFY_NOT_REACHED();
  4530. }
  4531. }
  4532. if (!flex_direction)
  4533. flex_direction = property_initial_value(m_context.realm(), PropertyID::FlexDirection);
  4534. if (!flex_wrap)
  4535. flex_wrap = property_initial_value(m_context.realm(), PropertyID::FlexWrap);
  4536. transaction.commit();
  4537. return ShorthandStyleValue::create(PropertyID::FlexFlow,
  4538. { PropertyID::FlexDirection, PropertyID::FlexWrap },
  4539. { flex_direction.release_nonnull(), flex_wrap.release_nonnull() });
  4540. }
  4541. bool Parser::is_generic_font_family(Keyword keyword)
  4542. {
  4543. switch (keyword) {
  4544. case Keyword::Cursive:
  4545. case Keyword::Fantasy:
  4546. case Keyword::Monospace:
  4547. case Keyword::Serif:
  4548. case Keyword::SansSerif:
  4549. case Keyword::UiMonospace:
  4550. case Keyword::UiRounded:
  4551. case Keyword::UiSerif:
  4552. case Keyword::UiSansSerif:
  4553. return true;
  4554. default:
  4555. return false;
  4556. }
  4557. }
  4558. RefPtr<CSSStyleValue> Parser::parse_font_value(TokenStream<ComponentValue>& tokens)
  4559. {
  4560. RefPtr<CSSStyleValue> font_width;
  4561. RefPtr<CSSStyleValue> font_style;
  4562. RefPtr<CSSStyleValue> font_weight;
  4563. RefPtr<CSSStyleValue> font_size;
  4564. RefPtr<CSSStyleValue> line_height;
  4565. RefPtr<CSSStyleValue> font_families;
  4566. RefPtr<CSSStyleValue> font_variant;
  4567. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  4568. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  4569. // So, we have to handle that separately.
  4570. int normal_count = 0;
  4571. // FIXME: `font-variant` allows a lot of different values which aren't allowed in the `font` shorthand.
  4572. // FIXME: `font-width` allows <percentage> values, which aren't allowed in the `font` shorthand.
  4573. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontWidth };
  4574. auto transaction = tokens.begin_transaction();
  4575. while (tokens.has_next_token()) {
  4576. auto& peek_token = tokens.next_token();
  4577. if (peek_token.is_ident("normal"sv)) {
  4578. normal_count++;
  4579. tokens.discard_a_token();
  4580. continue;
  4581. }
  4582. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4583. if (!property_and_value.has_value())
  4584. return nullptr;
  4585. auto& value = property_and_value->style_value;
  4586. remove_property(remaining_longhands, property_and_value->property);
  4587. switch (property_and_value->property) {
  4588. case PropertyID::FontSize: {
  4589. VERIFY(!font_size);
  4590. font_size = value.release_nonnull();
  4591. // Consume `/ line-height` if present
  4592. if (tokens.next_token().is_delim('/')) {
  4593. tokens.discard_a_token();
  4594. auto maybe_line_height = parse_css_value_for_property(PropertyID::LineHeight, tokens);
  4595. if (!maybe_line_height)
  4596. return nullptr;
  4597. line_height = maybe_line_height.release_nonnull();
  4598. }
  4599. // Consume font-families
  4600. auto maybe_font_families = parse_font_family_value(tokens);
  4601. // font-family comes last, so we must not have any tokens left over.
  4602. if (!maybe_font_families || tokens.has_next_token())
  4603. return nullptr;
  4604. font_families = maybe_font_families.release_nonnull();
  4605. continue;
  4606. }
  4607. case PropertyID::FontWidth: {
  4608. VERIFY(!font_width);
  4609. font_width = value.release_nonnull();
  4610. continue;
  4611. }
  4612. case PropertyID::FontStyle: {
  4613. VERIFY(!font_style);
  4614. font_style = value.release_nonnull();
  4615. continue;
  4616. }
  4617. case PropertyID::FontVariant: {
  4618. VERIFY(!font_variant);
  4619. font_variant = value.release_nonnull();
  4620. continue;
  4621. }
  4622. case PropertyID::FontWeight: {
  4623. VERIFY(!font_weight);
  4624. font_weight = value.release_nonnull();
  4625. continue;
  4626. }
  4627. default:
  4628. VERIFY_NOT_REACHED();
  4629. }
  4630. return nullptr;
  4631. }
  4632. // Since normal is the default value for all the properties that can have it, we don't have to actually
  4633. // set anything to normal here. It'll be set when we create the ShorthandStyleValue below.
  4634. // We just need to make sure we were not given more normals than will fit.
  4635. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1) + (font_variant ? 0 : 1) + (font_width ? 0 : 1);
  4636. if (unset_value_count < normal_count)
  4637. return nullptr;
  4638. if (!font_size || !font_families)
  4639. return nullptr;
  4640. if (!font_style)
  4641. font_style = property_initial_value(m_context.realm(), PropertyID::FontStyle);
  4642. if (!font_variant)
  4643. font_variant = property_initial_value(m_context.realm(), PropertyID::FontVariant);
  4644. if (!font_weight)
  4645. font_weight = property_initial_value(m_context.realm(), PropertyID::FontWeight);
  4646. if (!font_width)
  4647. font_width = property_initial_value(m_context.realm(), PropertyID::FontWidth);
  4648. if (!line_height)
  4649. line_height = property_initial_value(m_context.realm(), PropertyID::LineHeight);
  4650. transaction.commit();
  4651. return ShorthandStyleValue::create(PropertyID::Font,
  4652. { PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontWidth, PropertyID::FontSize, PropertyID::LineHeight, PropertyID::FontFamily },
  4653. { 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() });
  4654. }
  4655. RefPtr<CSSStyleValue> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  4656. {
  4657. auto next_is_comma_or_eof = [&]() -> bool {
  4658. return !tokens.has_next_token() || tokens.next_token().is(Token::Type::Comma);
  4659. };
  4660. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  4661. // eg, these are equivalent:
  4662. // font-family: my cool font\!, serif;
  4663. // font-family: "my cool font!", serif;
  4664. StyleValueVector font_families;
  4665. Vector<String> current_name_parts;
  4666. while (tokens.has_next_token()) {
  4667. auto const& peek = tokens.next_token();
  4668. if (peek.is(Token::Type::String)) {
  4669. // `font-family: my cool "font";` is invalid.
  4670. if (!current_name_parts.is_empty())
  4671. return nullptr;
  4672. tokens.discard_a_token(); // String
  4673. if (!next_is_comma_or_eof())
  4674. return nullptr;
  4675. font_families.append(StringStyleValue::create(peek.token().string()));
  4676. tokens.discard_a_token(); // Comma
  4677. continue;
  4678. }
  4679. if (peek.is(Token::Type::Ident)) {
  4680. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  4681. // CSS-wide keywords are not allowed
  4682. if (auto builtin = parse_builtin_value(tokens))
  4683. return nullptr;
  4684. auto maybe_keyword = keyword_from_string(peek.token().ident());
  4685. // Can't have a generic-font-name as a token in an unquoted font name.
  4686. if (maybe_keyword.has_value() && is_generic_font_family(maybe_keyword.value())) {
  4687. if (!current_name_parts.is_empty())
  4688. return nullptr;
  4689. tokens.discard_a_token(); // Ident
  4690. if (!next_is_comma_or_eof())
  4691. return nullptr;
  4692. font_families.append(CSSKeywordValue::create(maybe_keyword.value()));
  4693. tokens.discard_a_token(); // Comma
  4694. continue;
  4695. }
  4696. current_name_parts.append(tokens.consume_a_token().token().ident().to_string());
  4697. continue;
  4698. }
  4699. if (peek.is(Token::Type::Comma)) {
  4700. if (current_name_parts.is_empty())
  4701. return nullptr;
  4702. tokens.discard_a_token(); // Comma
  4703. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  4704. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  4705. current_name_parts.clear();
  4706. // Can't have a trailing comma
  4707. if (!tokens.has_next_token())
  4708. return nullptr;
  4709. continue;
  4710. }
  4711. return nullptr;
  4712. }
  4713. if (!current_name_parts.is_empty()) {
  4714. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  4715. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  4716. current_name_parts.clear();
  4717. }
  4718. if (font_families.is_empty())
  4719. return nullptr;
  4720. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  4721. }
  4722. RefPtr<CSSStyleValue> Parser::parse_font_language_override_value(TokenStream<ComponentValue>& tokens)
  4723. {
  4724. // https://drafts.csswg.org/css-fonts/#propdef-font-language-override
  4725. // This is `normal | <string>` but with the constraint that the string has to be 4 characters long:
  4726. // Shorter strings are right-padded with spaces, and longer strings are invalid.
  4727. if (auto normal = parse_all_as_single_keyword_value(tokens, Keyword::Normal))
  4728. return normal;
  4729. auto transaction = tokens.begin_transaction();
  4730. tokens.discard_whitespace();
  4731. if (auto string = parse_string_value(tokens)) {
  4732. auto string_value = string->string_value();
  4733. tokens.discard_whitespace();
  4734. if (tokens.has_next_token()) {
  4735. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse font-language-override: unexpected trailing tokens");
  4736. return nullptr;
  4737. }
  4738. auto length = string_value.code_points().length();
  4739. if (length > 4) {
  4740. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse font-language-override: <string> value \"{}\" is too long", string_value);
  4741. return nullptr;
  4742. }
  4743. transaction.commit();
  4744. if (length < 4)
  4745. return StringStyleValue::create(MUST(String::formatted("{<4}", string_value)));
  4746. return string;
  4747. }
  4748. return nullptr;
  4749. }
  4750. RefPtr<CSSStyleValue> Parser::parse_font_feature_settings_value(TokenStream<ComponentValue>& tokens)
  4751. {
  4752. // https://drafts.csswg.org/css-fonts/#propdef-font-feature-settings
  4753. // normal | <feature-tag-value>#
  4754. // normal
  4755. if (auto normal = parse_all_as_single_keyword_value(tokens, Keyword::Normal))
  4756. return normal;
  4757. // <feature-tag-value>#
  4758. auto transaction = tokens.begin_transaction();
  4759. auto tag_values = parse_a_comma_separated_list_of_component_values(tokens);
  4760. // "The computed value of font-feature-settings is a map, so any duplicates in the specified value must not be preserved.
  4761. // If the same feature tag appears more than once, the value associated with the last appearance supersedes any previous
  4762. // value for that axis."
  4763. // So, we deduplicate them here using a HashSet.
  4764. OrderedHashMap<FlyString, NonnullRefPtr<OpenTypeTaggedStyleValue>> feature_tags_map;
  4765. for (auto const& values : tag_values) {
  4766. // <feature-tag-value> = <opentype-tag> [ <integer [0,∞]> | on | off ]?
  4767. TokenStream tag_tokens { values };
  4768. tag_tokens.discard_whitespace();
  4769. auto opentype_tag = parse_opentype_tag_value(tag_tokens);
  4770. tag_tokens.discard_whitespace();
  4771. RefPtr<CSSStyleValue> value;
  4772. if (tag_tokens.has_next_token()) {
  4773. if (auto integer = parse_integer_value(tag_tokens)) {
  4774. if (integer->is_integer() && integer->as_integer().value() < 0)
  4775. return nullptr;
  4776. value = integer;
  4777. } else {
  4778. // A value of on is synonymous with 1 and off is synonymous with 0.
  4779. auto keyword = parse_keyword_value(tag_tokens);
  4780. if (!keyword)
  4781. return nullptr;
  4782. switch (keyword->to_keyword()) {
  4783. case Keyword::On:
  4784. value = IntegerStyleValue::create(1);
  4785. break;
  4786. case Keyword::Off:
  4787. value = IntegerStyleValue::create(0);
  4788. break;
  4789. default:
  4790. return nullptr;
  4791. }
  4792. }
  4793. tag_tokens.discard_whitespace();
  4794. } else {
  4795. // "If the value is omitted, a value of 1 is assumed."
  4796. value = IntegerStyleValue::create(1);
  4797. }
  4798. if (!opentype_tag || !value || tag_tokens.has_next_token())
  4799. return nullptr;
  4800. feature_tags_map.set(opentype_tag->string_value(), OpenTypeTaggedStyleValue::create(opentype_tag->string_value(), value.release_nonnull()));
  4801. }
  4802. // "The computed value contains the de-duplicated feature tags, sorted in ascending order by code unit."
  4803. StyleValueVector feature_tags;
  4804. feature_tags.ensure_capacity(feature_tags_map.size());
  4805. for (auto const& [key, feature_tag] : feature_tags_map)
  4806. feature_tags.append(feature_tag);
  4807. quick_sort(feature_tags, [](auto& a, auto& b) {
  4808. return a->as_open_type_tagged().tag() < b->as_open_type_tagged().tag();
  4809. });
  4810. transaction.commit();
  4811. return StyleValueList::create(move(feature_tags), StyleValueList::Separator::Comma);
  4812. }
  4813. RefPtr<CSSStyleValue> Parser::parse_font_variation_settings_value(TokenStream<ComponentValue>& tokens)
  4814. {
  4815. // https://drafts.csswg.org/css-fonts/#propdef-font-variation-settings
  4816. // normal | [ <opentype-tag> <number>]#
  4817. // normal
  4818. if (auto normal = parse_all_as_single_keyword_value(tokens, Keyword::Normal))
  4819. return normal;
  4820. // [ <opentype-tag> <number>]#
  4821. auto transaction = tokens.begin_transaction();
  4822. auto tag_values = parse_a_comma_separated_list_of_component_values(tokens);
  4823. // "If the same axis name appears more than once, the value associated with the last appearance supersedes any
  4824. // previous value for that axis. This deduplication is observable by accessing the computed value of this property."
  4825. // So, we deduplicate them here using a HashSet.
  4826. OrderedHashMap<FlyString, NonnullRefPtr<OpenTypeTaggedStyleValue>> axis_tags_map;
  4827. for (auto const& values : tag_values) {
  4828. TokenStream tag_tokens { values };
  4829. tag_tokens.discard_whitespace();
  4830. auto opentype_tag = parse_opentype_tag_value(tag_tokens);
  4831. tag_tokens.discard_whitespace();
  4832. auto number = parse_number_value(tag_tokens);
  4833. tag_tokens.discard_whitespace();
  4834. if (!opentype_tag || !number || tag_tokens.has_next_token())
  4835. return nullptr;
  4836. axis_tags_map.set(opentype_tag->string_value(), OpenTypeTaggedStyleValue::create(opentype_tag->string_value(), number.release_nonnull()));
  4837. }
  4838. // "The computed value contains the de-duplicated axis names, sorted in ascending order by code unit."
  4839. StyleValueVector axis_tags;
  4840. axis_tags.ensure_capacity(axis_tags_map.size());
  4841. for (auto const& [key, axis_tag] : axis_tags_map)
  4842. axis_tags.append(axis_tag);
  4843. quick_sort(axis_tags, [](auto& a, auto& b) {
  4844. return a->as_open_type_tagged().tag() < b->as_open_type_tagged().tag();
  4845. });
  4846. transaction.commit();
  4847. return StyleValueList::create(move(axis_tags), StyleValueList::Separator::Comma);
  4848. }
  4849. Vector<ParsedFontFace::Source> Parser::parse_as_font_face_src()
  4850. {
  4851. return parse_font_face_src(m_token_stream);
  4852. }
  4853. template<typename T>
  4854. Vector<ParsedFontFace::Source> Parser::parse_font_face_src(TokenStream<T>& component_values)
  4855. {
  4856. // FIXME: Get this information from the system somehow?
  4857. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  4858. auto font_format_is_supported = [](StringView name) {
  4859. // The spec requires us to treat opentype and truetype as synonymous.
  4860. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv, "woff2"sv))
  4861. return true;
  4862. return false;
  4863. };
  4864. Vector<ParsedFontFace::Source> supported_sources;
  4865. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  4866. for (auto const& source_token_list : list_of_source_token_lists) {
  4867. TokenStream source_tokens { source_token_list };
  4868. source_tokens.discard_whitespace();
  4869. // <url> [ format(<font-format>)]?
  4870. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  4871. if (auto maybe_url = parse_url_function(source_tokens); maybe_url.has_value()) {
  4872. auto url = maybe_url.release_value();
  4873. if (!url.is_valid()) {
  4874. continue;
  4875. }
  4876. Optional<FlyString> format;
  4877. source_tokens.discard_whitespace();
  4878. if (!source_tokens.has_next_token()) {
  4879. supported_sources.empend(move(url), format);
  4880. continue;
  4881. }
  4882. auto maybe_function = source_tokens.consume_a_token();
  4883. if (!maybe_function.is_function()) {
  4884. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  4885. return {};
  4886. }
  4887. auto const& function = maybe_function.function();
  4888. if (function.name.equals_ignoring_ascii_case("format"sv)) {
  4889. TokenStream format_tokens { function.value };
  4890. format_tokens.discard_whitespace();
  4891. auto const& format_name_token = format_tokens.consume_a_token();
  4892. StringView format_name;
  4893. if (format_name_token.is(Token::Type::Ident)) {
  4894. format_name = format_name_token.token().ident();
  4895. } else if (format_name_token.is(Token::Type::String)) {
  4896. format_name = format_name_token.token().string();
  4897. } else {
  4898. 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());
  4899. return {};
  4900. }
  4901. if (!font_format_is_supported(format_name)) {
  4902. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  4903. continue;
  4904. }
  4905. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  4906. } else {
  4907. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name);
  4908. return {};
  4909. }
  4910. source_tokens.discard_whitespace();
  4911. if (source_tokens.has_next_token()) {
  4912. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.next_token().to_debug_string());
  4913. return {};
  4914. }
  4915. supported_sources.empend(move(url), format);
  4916. continue;
  4917. }
  4918. auto const& first = source_tokens.consume_a_token();
  4919. if (first.is_function("local"sv)) {
  4920. if (first.function().value.is_empty()) {
  4921. continue;
  4922. }
  4923. supported_sources.empend(first.function().value.first().to_string(), Optional<FlyString> {});
  4924. continue;
  4925. }
  4926. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  4927. return {};
  4928. }
  4929. return supported_sources;
  4930. }
  4931. template Vector<ParsedFontFace::Source> Parser::parse_font_face_src(TokenStream<Token>& component_values);
  4932. template Vector<ParsedFontFace::Source> Parser::parse_font_face_src(TokenStream<ComponentValue>& component_values);
  4933. RefPtr<CSSStyleValue> Parser::parse_list_style_value(TokenStream<ComponentValue>& tokens)
  4934. {
  4935. RefPtr<CSSStyleValue> list_position;
  4936. RefPtr<CSSStyleValue> list_image;
  4937. RefPtr<CSSStyleValue> list_type;
  4938. int found_nones = 0;
  4939. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  4940. auto transaction = tokens.begin_transaction();
  4941. while (tokens.has_next_token()) {
  4942. if (auto peek = tokens.next_token(); peek.is_ident("none"sv)) {
  4943. tokens.discard_a_token();
  4944. found_nones++;
  4945. continue;
  4946. }
  4947. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4948. if (!property_and_value.has_value())
  4949. return nullptr;
  4950. auto& value = property_and_value->style_value;
  4951. remove_property(remaining_longhands, property_and_value->property);
  4952. switch (property_and_value->property) {
  4953. case PropertyID::ListStylePosition: {
  4954. VERIFY(!list_position);
  4955. list_position = value.release_nonnull();
  4956. continue;
  4957. }
  4958. case PropertyID::ListStyleImage: {
  4959. VERIFY(!list_image);
  4960. list_image = value.release_nonnull();
  4961. continue;
  4962. }
  4963. case PropertyID::ListStyleType: {
  4964. VERIFY(!list_type);
  4965. list_type = value.release_nonnull();
  4966. continue;
  4967. }
  4968. default:
  4969. VERIFY_NOT_REACHED();
  4970. }
  4971. }
  4972. if (found_nones > 2)
  4973. return nullptr;
  4974. if (found_nones == 2) {
  4975. if (list_image || list_type)
  4976. return nullptr;
  4977. auto none = CSSKeywordValue::create(Keyword::None);
  4978. list_image = none;
  4979. list_type = none;
  4980. } else if (found_nones == 1) {
  4981. if (list_image && list_type)
  4982. return nullptr;
  4983. auto none = CSSKeywordValue::create(Keyword::None);
  4984. if (!list_image)
  4985. list_image = none;
  4986. if (!list_type)
  4987. list_type = none;
  4988. }
  4989. if (!list_position)
  4990. list_position = property_initial_value(m_context.realm(), PropertyID::ListStylePosition);
  4991. if (!list_image)
  4992. list_image = property_initial_value(m_context.realm(), PropertyID::ListStyleImage);
  4993. if (!list_type)
  4994. list_type = property_initial_value(m_context.realm(), PropertyID::ListStyleType);
  4995. transaction.commit();
  4996. return ShorthandStyleValue::create(PropertyID::ListStyle,
  4997. { PropertyID::ListStylePosition, PropertyID::ListStyleImage, PropertyID::ListStyleType },
  4998. { list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull() });
  4999. }
  5000. RefPtr<CSSStyleValue> Parser::parse_math_depth_value(TokenStream<ComponentValue>& tokens)
  5001. {
  5002. // https://w3c.github.io/mathml-core/#propdef-math-depth
  5003. // auto-add | add(<integer>) | <integer>
  5004. auto transaction = tokens.begin_transaction();
  5005. auto token = tokens.consume_a_token();
  5006. if (tokens.has_next_token())
  5007. return nullptr;
  5008. // auto-add
  5009. if (token.is_ident("auto-add"sv)) {
  5010. transaction.commit();
  5011. return MathDepthStyleValue::create_auto_add();
  5012. }
  5013. // FIXME: Make it easier to parse "thing that might be <bar> or literally anything that resolves to it" and get rid of this
  5014. auto parse_something_that_resolves_to_integer = [this](ComponentValue& token) -> RefPtr<CSSStyleValue> {
  5015. if (token.is(Token::Type::Number) && token.token().number().is_integer())
  5016. return IntegerStyleValue::create(token.token().to_integer());
  5017. if (auto value = parse_calculated_value(token); value && value->resolves_to_number())
  5018. return value;
  5019. return nullptr;
  5020. };
  5021. // add(<integer>)
  5022. if (token.is_function("add"sv)) {
  5023. auto add_tokens = TokenStream { token.function().value };
  5024. add_tokens.discard_whitespace();
  5025. auto integer_token = add_tokens.consume_a_token();
  5026. add_tokens.discard_whitespace();
  5027. if (add_tokens.has_next_token())
  5028. return nullptr;
  5029. if (auto integer_value = parse_something_that_resolves_to_integer(integer_token)) {
  5030. transaction.commit();
  5031. return MathDepthStyleValue::create_add(integer_value.release_nonnull());
  5032. }
  5033. return nullptr;
  5034. }
  5035. // <integer>
  5036. if (auto integer_value = parse_something_that_resolves_to_integer(token)) {
  5037. transaction.commit();
  5038. return MathDepthStyleValue::create_integer(integer_value.release_nonnull());
  5039. }
  5040. return nullptr;
  5041. }
  5042. RefPtr<CSSStyleValue> Parser::parse_overflow_value(TokenStream<ComponentValue>& tokens)
  5043. {
  5044. auto transaction = tokens.begin_transaction();
  5045. auto maybe_x_value = parse_css_value_for_property(PropertyID::OverflowX, tokens);
  5046. if (!maybe_x_value)
  5047. return nullptr;
  5048. auto maybe_y_value = parse_css_value_for_property(PropertyID::OverflowY, tokens);
  5049. transaction.commit();
  5050. if (maybe_y_value) {
  5051. return ShorthandStyleValue::create(PropertyID::Overflow,
  5052. { PropertyID::OverflowX, PropertyID::OverflowY },
  5053. { maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull() });
  5054. }
  5055. return ShorthandStyleValue::create(PropertyID::Overflow,
  5056. { PropertyID::OverflowX, PropertyID::OverflowY },
  5057. { *maybe_x_value, *maybe_x_value });
  5058. }
  5059. RefPtr<CSSStyleValue> Parser::parse_place_content_value(TokenStream<ComponentValue>& tokens)
  5060. {
  5061. auto transaction = tokens.begin_transaction();
  5062. auto maybe_align_content_value = parse_css_value_for_property(PropertyID::AlignContent, tokens);
  5063. if (!maybe_align_content_value)
  5064. return nullptr;
  5065. if (!tokens.has_next_token()) {
  5066. if (!property_accepts_keyword(PropertyID::JustifyContent, maybe_align_content_value->to_keyword()))
  5067. return nullptr;
  5068. transaction.commit();
  5069. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  5070. { PropertyID::AlignContent, PropertyID::JustifyContent },
  5071. { *maybe_align_content_value, *maybe_align_content_value });
  5072. }
  5073. auto maybe_justify_content_value = parse_css_value_for_property(PropertyID::JustifyContent, tokens);
  5074. if (!maybe_justify_content_value)
  5075. return nullptr;
  5076. transaction.commit();
  5077. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  5078. { PropertyID::AlignContent, PropertyID::JustifyContent },
  5079. { maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull() });
  5080. }
  5081. RefPtr<CSSStyleValue> Parser::parse_place_items_value(TokenStream<ComponentValue>& tokens)
  5082. {
  5083. auto transaction = tokens.begin_transaction();
  5084. auto maybe_align_items_value = parse_css_value_for_property(PropertyID::AlignItems, tokens);
  5085. if (!maybe_align_items_value)
  5086. return nullptr;
  5087. if (!tokens.has_next_token()) {
  5088. if (!property_accepts_keyword(PropertyID::JustifyItems, maybe_align_items_value->to_keyword()))
  5089. return nullptr;
  5090. transaction.commit();
  5091. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  5092. { PropertyID::AlignItems, PropertyID::JustifyItems },
  5093. { *maybe_align_items_value, *maybe_align_items_value });
  5094. }
  5095. auto maybe_justify_items_value = parse_css_value_for_property(PropertyID::JustifyItems, tokens);
  5096. if (!maybe_justify_items_value)
  5097. return nullptr;
  5098. transaction.commit();
  5099. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  5100. { PropertyID::AlignItems, PropertyID::JustifyItems },
  5101. { *maybe_align_items_value, *maybe_justify_items_value });
  5102. }
  5103. RefPtr<CSSStyleValue> Parser::parse_place_self_value(TokenStream<ComponentValue>& tokens)
  5104. {
  5105. auto transaction = tokens.begin_transaction();
  5106. auto maybe_align_self_value = parse_css_value_for_property(PropertyID::AlignSelf, tokens);
  5107. if (!maybe_align_self_value)
  5108. return nullptr;
  5109. if (!tokens.has_next_token()) {
  5110. if (!property_accepts_keyword(PropertyID::JustifySelf, maybe_align_self_value->to_keyword()))
  5111. return nullptr;
  5112. transaction.commit();
  5113. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  5114. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  5115. { *maybe_align_self_value, *maybe_align_self_value });
  5116. }
  5117. auto maybe_justify_self_value = parse_css_value_for_property(PropertyID::JustifySelf, tokens);
  5118. if (!maybe_justify_self_value)
  5119. return nullptr;
  5120. transaction.commit();
  5121. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  5122. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  5123. { *maybe_align_self_value, *maybe_justify_self_value });
  5124. }
  5125. RefPtr<CSSStyleValue> Parser::parse_quotes_value(TokenStream<ComponentValue>& tokens)
  5126. {
  5127. // https://www.w3.org/TR/css-content-3/#quotes-property
  5128. // auto | none | [ <string> <string> ]+
  5129. auto transaction = tokens.begin_transaction();
  5130. if (tokens.remaining_token_count() == 1) {
  5131. auto keyword = parse_keyword_value(tokens);
  5132. if (keyword && property_accepts_keyword(PropertyID::Quotes, keyword->to_keyword())) {
  5133. transaction.commit();
  5134. return keyword;
  5135. }
  5136. return nullptr;
  5137. }
  5138. // Parse an even number of <string> values.
  5139. if (tokens.remaining_token_count() % 2 != 0)
  5140. return nullptr;
  5141. StyleValueVector string_values;
  5142. while (tokens.has_next_token()) {
  5143. auto maybe_string = parse_string_value(tokens);
  5144. if (!maybe_string)
  5145. return nullptr;
  5146. string_values.append(maybe_string.release_nonnull());
  5147. }
  5148. transaction.commit();
  5149. return StyleValueList::create(move(string_values), StyleValueList::Separator::Space);
  5150. }
  5151. RefPtr<CSSStyleValue> Parser::parse_text_decoration_value(TokenStream<ComponentValue>& tokens)
  5152. {
  5153. RefPtr<CSSStyleValue> decoration_line;
  5154. RefPtr<CSSStyleValue> decoration_thickness;
  5155. RefPtr<CSSStyleValue> decoration_style;
  5156. RefPtr<CSSStyleValue> decoration_color;
  5157. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  5158. auto transaction = tokens.begin_transaction();
  5159. while (tokens.has_next_token()) {
  5160. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  5161. if (!property_and_value.has_value())
  5162. return nullptr;
  5163. auto& value = property_and_value->style_value;
  5164. remove_property(remaining_longhands, property_and_value->property);
  5165. switch (property_and_value->property) {
  5166. case PropertyID::TextDecorationColor: {
  5167. VERIFY(!decoration_color);
  5168. decoration_color = value.release_nonnull();
  5169. continue;
  5170. }
  5171. case PropertyID::TextDecorationLine: {
  5172. VERIFY(!decoration_line);
  5173. tokens.reconsume_current_input_token();
  5174. auto parsed_decoration_line = parse_text_decoration_line_value(tokens);
  5175. if (!parsed_decoration_line)
  5176. return nullptr;
  5177. decoration_line = parsed_decoration_line.release_nonnull();
  5178. continue;
  5179. }
  5180. case PropertyID::TextDecorationThickness: {
  5181. VERIFY(!decoration_thickness);
  5182. decoration_thickness = value.release_nonnull();
  5183. continue;
  5184. }
  5185. case PropertyID::TextDecorationStyle: {
  5186. VERIFY(!decoration_style);
  5187. decoration_style = value.release_nonnull();
  5188. continue;
  5189. }
  5190. default:
  5191. VERIFY_NOT_REACHED();
  5192. }
  5193. }
  5194. if (!decoration_line)
  5195. decoration_line = property_initial_value(m_context.realm(), PropertyID::TextDecorationLine);
  5196. if (!decoration_thickness)
  5197. decoration_thickness = property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness);
  5198. if (!decoration_style)
  5199. decoration_style = property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle);
  5200. if (!decoration_color)
  5201. decoration_color = property_initial_value(m_context.realm(), PropertyID::TextDecorationColor);
  5202. transaction.commit();
  5203. return ShorthandStyleValue::create(PropertyID::TextDecoration,
  5204. { PropertyID::TextDecorationLine, PropertyID::TextDecorationThickness, PropertyID::TextDecorationStyle, PropertyID::TextDecorationColor },
  5205. { decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull() });
  5206. }
  5207. RefPtr<CSSStyleValue> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  5208. {
  5209. StyleValueVector style_values;
  5210. while (tokens.has_next_token()) {
  5211. auto maybe_value = parse_css_value_for_property(PropertyID::TextDecorationLine, tokens);
  5212. if (!maybe_value)
  5213. break;
  5214. auto value = maybe_value.release_nonnull();
  5215. if (auto maybe_line = keyword_to_text_decoration_line(value->to_keyword()); maybe_line.has_value()) {
  5216. if (maybe_line == TextDecorationLine::None) {
  5217. if (!style_values.is_empty())
  5218. break;
  5219. return value;
  5220. }
  5221. if (style_values.contains_slow(value))
  5222. break;
  5223. style_values.append(move(value));
  5224. continue;
  5225. }
  5226. break;
  5227. }
  5228. if (style_values.is_empty())
  5229. return nullptr;
  5230. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  5231. }
  5232. RefPtr<CSSStyleValue> Parser::parse_easing_value(TokenStream<ComponentValue>& tokens)
  5233. {
  5234. auto transaction = tokens.begin_transaction();
  5235. tokens.discard_whitespace();
  5236. auto const& part = tokens.consume_a_token();
  5237. if (part.is(Token::Type::Ident)) {
  5238. auto name = part.token().ident();
  5239. auto maybe_simple_easing = [&] -> RefPtr<EasingStyleValue> {
  5240. if (name == "linear"sv)
  5241. return EasingStyleValue::create(EasingStyleValue::Linear {});
  5242. if (name == "ease"sv)
  5243. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease());
  5244. if (name == "ease-in"sv)
  5245. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_in());
  5246. if (name == "ease-out"sv)
  5247. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_out());
  5248. if (name == "ease-in-out"sv)
  5249. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_in_out());
  5250. if (name == "step-start"sv)
  5251. return EasingStyleValue::create(EasingStyleValue::Steps::step_start());
  5252. if (name == "step-end"sv)
  5253. return EasingStyleValue::create(EasingStyleValue::Steps::step_end());
  5254. return {};
  5255. }();
  5256. if (!maybe_simple_easing)
  5257. return nullptr;
  5258. transaction.commit();
  5259. return maybe_simple_easing;
  5260. }
  5261. if (!part.is_function())
  5262. return nullptr;
  5263. TokenStream argument_tokens { part.function().value };
  5264. auto comma_separated_arguments = parse_a_comma_separated_list_of_component_values(argument_tokens);
  5265. // Remove whitespace
  5266. for (auto& argument : comma_separated_arguments)
  5267. argument.remove_all_matching([](auto& value) { return value.is(Token::Type::Whitespace); });
  5268. auto name = part.function().name;
  5269. if (name == "linear"sv) {
  5270. Vector<EasingStyleValue::Linear::Stop> stops;
  5271. for (auto const& argument : comma_separated_arguments) {
  5272. if (argument.is_empty() || argument.size() > 2)
  5273. return nullptr;
  5274. Optional<double> offset;
  5275. Optional<double> position;
  5276. for (auto const& part : argument) {
  5277. if (part.is(Token::Type::Number)) {
  5278. if (offset.has_value())
  5279. return nullptr;
  5280. offset = part.token().number_value();
  5281. } else if (part.is(Token::Type::Percentage)) {
  5282. if (position.has_value())
  5283. return nullptr;
  5284. position = part.token().percentage();
  5285. } else {
  5286. return nullptr;
  5287. };
  5288. }
  5289. if (!offset.has_value())
  5290. return nullptr;
  5291. stops.append({ offset.value(), move(position) });
  5292. }
  5293. if (stops.is_empty())
  5294. return nullptr;
  5295. transaction.commit();
  5296. return EasingStyleValue::create(EasingStyleValue::Linear { move(stops) });
  5297. }
  5298. if (name == "cubic-bezier") {
  5299. if (comma_separated_arguments.size() != 4)
  5300. return nullptr;
  5301. for (auto const& argument : comma_separated_arguments) {
  5302. if (argument.size() != 1)
  5303. return nullptr;
  5304. if (!argument[0].is(Token::Type::Number))
  5305. return nullptr;
  5306. }
  5307. EasingStyleValue::CubicBezier bezier {
  5308. comma_separated_arguments[0][0].token().number_value(),
  5309. comma_separated_arguments[1][0].token().number_value(),
  5310. comma_separated_arguments[2][0].token().number_value(),
  5311. comma_separated_arguments[3][0].token().number_value(),
  5312. };
  5313. if (bezier.x1 < 0.0 || bezier.x1 > 1.0 || bezier.x2 < 0.0 || bezier.x2 > 1.0)
  5314. return nullptr;
  5315. transaction.commit();
  5316. return EasingStyleValue::create(bezier);
  5317. }
  5318. if (name == "steps") {
  5319. if (comma_separated_arguments.is_empty() || comma_separated_arguments.size() > 2)
  5320. return nullptr;
  5321. for (auto const& argument : comma_separated_arguments) {
  5322. if (argument.size() != 1)
  5323. return nullptr;
  5324. }
  5325. EasingStyleValue::Steps steps;
  5326. auto intervals_argument = comma_separated_arguments[0][0];
  5327. if (!intervals_argument.is(Token::Type::Number))
  5328. return nullptr;
  5329. if (!intervals_argument.token().number().is_integer())
  5330. return nullptr;
  5331. auto intervals = intervals_argument.token().to_integer();
  5332. if (comma_separated_arguments.size() == 2) {
  5333. TokenStream identifier_stream { comma_separated_arguments[1] };
  5334. auto keyword_value = parse_keyword_value(identifier_stream);
  5335. if (!keyword_value)
  5336. return nullptr;
  5337. switch (keyword_value->to_keyword()) {
  5338. case Keyword::JumpStart:
  5339. steps.position = EasingStyleValue::Steps::Position::JumpStart;
  5340. break;
  5341. case Keyword::JumpEnd:
  5342. steps.position = EasingStyleValue::Steps::Position::JumpEnd;
  5343. break;
  5344. case Keyword::JumpBoth:
  5345. steps.position = EasingStyleValue::Steps::Position::JumpBoth;
  5346. break;
  5347. case Keyword::JumpNone:
  5348. steps.position = EasingStyleValue::Steps::Position::JumpNone;
  5349. break;
  5350. case Keyword::Start:
  5351. steps.position = EasingStyleValue::Steps::Position::Start;
  5352. break;
  5353. case Keyword::End:
  5354. steps.position = EasingStyleValue::Steps::Position::End;
  5355. break;
  5356. default:
  5357. return nullptr;
  5358. }
  5359. }
  5360. // Perform extra validation
  5361. // https://drafts.csswg.org/css-easing/#funcdef-step-easing-function-steps
  5362. // The first parameter specifies the number of intervals in the function. It must be a positive integer greater than 0
  5363. // unless the second parameter is jump-none in which case it must be a positive integer greater than 1.
  5364. if (steps.position == EasingStyleValue::Steps::Position::JumpNone) {
  5365. if (intervals < 1)
  5366. return nullptr;
  5367. } else if (intervals < 0) {
  5368. return nullptr;
  5369. }
  5370. steps.number_of_intervals = intervals;
  5371. transaction.commit();
  5372. return EasingStyleValue::create(steps);
  5373. }
  5374. return nullptr;
  5375. }
  5376. // https://www.w3.org/TR/css-transforms-1/#transform-property
  5377. RefPtr<CSSStyleValue> Parser::parse_transform_value(TokenStream<ComponentValue>& tokens)
  5378. {
  5379. // <transform> = none | <transform-list>
  5380. // <transform-list> = <transform-function>+
  5381. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  5382. return none;
  5383. StyleValueVector transformations;
  5384. auto transaction = tokens.begin_transaction();
  5385. while (tokens.has_next_token()) {
  5386. auto const& part = tokens.consume_a_token();
  5387. if (!part.is_function())
  5388. return nullptr;
  5389. auto maybe_function = transform_function_from_string(part.function().name);
  5390. if (!maybe_function.has_value())
  5391. return nullptr;
  5392. auto function = maybe_function.release_value();
  5393. auto function_metadata = transform_function_metadata(function);
  5394. auto function_tokens = TokenStream { part.function().value };
  5395. auto arguments = parse_a_comma_separated_list_of_component_values(function_tokens);
  5396. if (arguments.size() > function_metadata.parameters.size()) {
  5397. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name, function_metadata.parameters.size());
  5398. return nullptr;
  5399. }
  5400. if (arguments.size() < function_metadata.parameters.size() && function_metadata.parameters[arguments.size()].required) {
  5401. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", arguments.size());
  5402. return nullptr;
  5403. }
  5404. StyleValueVector values;
  5405. for (auto argument_index = 0u; argument_index < arguments.size(); ++argument_index) {
  5406. TokenStream argument_tokens { arguments[argument_index] };
  5407. argument_tokens.discard_whitespace();
  5408. auto const& value = argument_tokens.consume_a_token();
  5409. RefPtr<CSSMathValue> maybe_calc_value = parse_calculated_value(value);
  5410. switch (function_metadata.parameters[argument_index].type) {
  5411. case TransformFunctionParameterType::Angle: {
  5412. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  5413. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  5414. values.append(maybe_calc_value.release_nonnull());
  5415. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  5416. values.append(AngleStyleValue::create(Angle::make_degrees(0)));
  5417. } else {
  5418. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5419. argument_tokens.reconsume_current_input_token();
  5420. auto dimension_value = parse_dimension_value(argument_tokens);
  5421. if (!dimension_value || !dimension_value->is_angle())
  5422. return nullptr;
  5423. values.append(dimension_value.release_nonnull());
  5424. }
  5425. break;
  5426. }
  5427. case TransformFunctionParameterType::Length:
  5428. case TransformFunctionParameterType::LengthNone: {
  5429. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  5430. argument_tokens.discard_a_token(); // calc()
  5431. values.append(maybe_calc_value.release_nonnull());
  5432. } else {
  5433. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5434. argument_tokens.reconsume_current_input_token();
  5435. if (function_metadata.parameters[argument_index].type == TransformFunctionParameterType::LengthNone) {
  5436. auto keyword_transaction = argument_tokens.begin_transaction();
  5437. auto keyword_value = parse_keyword_value(argument_tokens);
  5438. if (keyword_value && keyword_value->to_keyword() == Keyword::None) {
  5439. values.append(keyword_value.release_nonnull());
  5440. keyword_transaction.commit();
  5441. break;
  5442. }
  5443. }
  5444. auto dimension_value = parse_dimension_value(argument_tokens);
  5445. if (!dimension_value || !dimension_value->is_length())
  5446. return nullptr;
  5447. values.append(dimension_value.release_nonnull());
  5448. }
  5449. break;
  5450. }
  5451. case TransformFunctionParameterType::LengthPercentage: {
  5452. if (maybe_calc_value && maybe_calc_value->resolves_to_length_percentage()) {
  5453. values.append(maybe_calc_value.release_nonnull());
  5454. } else {
  5455. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5456. argument_tokens.reconsume_current_input_token();
  5457. auto dimension_value = parse_dimension_value(argument_tokens);
  5458. if (!dimension_value)
  5459. return nullptr;
  5460. if (dimension_value->is_percentage() || dimension_value->is_length())
  5461. values.append(dimension_value.release_nonnull());
  5462. else
  5463. return nullptr;
  5464. }
  5465. break;
  5466. }
  5467. case TransformFunctionParameterType::Number: {
  5468. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5469. values.append(maybe_calc_value.release_nonnull());
  5470. } else {
  5471. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5472. argument_tokens.reconsume_current_input_token();
  5473. auto number = parse_number_value(argument_tokens);
  5474. if (!number)
  5475. return nullptr;
  5476. values.append(number.release_nonnull());
  5477. }
  5478. break;
  5479. }
  5480. case TransformFunctionParameterType::NumberPercentage: {
  5481. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5482. values.append(maybe_calc_value.release_nonnull());
  5483. } else {
  5484. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5485. argument_tokens.reconsume_current_input_token();
  5486. auto number_or_percentage = parse_number_percentage_value(argument_tokens);
  5487. if (!number_or_percentage)
  5488. return nullptr;
  5489. values.append(number_or_percentage.release_nonnull());
  5490. }
  5491. break;
  5492. }
  5493. }
  5494. argument_tokens.discard_whitespace();
  5495. if (argument_tokens.has_next_token())
  5496. return nullptr;
  5497. }
  5498. transformations.append(TransformationStyleValue::create(function, move(values)));
  5499. }
  5500. transaction.commit();
  5501. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  5502. }
  5503. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  5504. // FIXME: This only supports a 2D position
  5505. RefPtr<CSSStyleValue> Parser::parse_transform_origin_value(TokenStream<ComponentValue>& tokens)
  5506. {
  5507. enum class Axis {
  5508. None,
  5509. X,
  5510. Y,
  5511. };
  5512. struct AxisOffset {
  5513. Axis axis;
  5514. NonnullRefPtr<CSSStyleValue> offset;
  5515. };
  5516. auto to_axis_offset = [](RefPtr<CSSStyleValue> value) -> Optional<AxisOffset> {
  5517. if (!value)
  5518. return OptionalNone {};
  5519. if (value->is_percentage())
  5520. return AxisOffset { Axis::None, value->as_percentage() };
  5521. if (value->is_length())
  5522. return AxisOffset { Axis::None, value->as_length() };
  5523. if (value->is_keyword()) {
  5524. switch (value->to_keyword()) {
  5525. case Keyword::Top:
  5526. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
  5527. case Keyword::Left:
  5528. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
  5529. case Keyword::Center:
  5530. return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
  5531. case Keyword::Bottom:
  5532. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
  5533. case Keyword::Right:
  5534. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
  5535. default:
  5536. return OptionalNone {};
  5537. }
  5538. }
  5539. if (value->is_math()) {
  5540. return AxisOffset { Axis::None, value->as_math() };
  5541. }
  5542. return OptionalNone {};
  5543. };
  5544. auto transaction = tokens.begin_transaction();
  5545. auto make_list = [&transaction](NonnullRefPtr<CSSStyleValue> const& x_value, NonnullRefPtr<CSSStyleValue> const& y_value) -> NonnullRefPtr<StyleValueList> {
  5546. transaction.commit();
  5547. return StyleValueList::create(StyleValueVector { x_value, y_value }, StyleValueList::Separator::Space);
  5548. };
  5549. switch (tokens.remaining_token_count()) {
  5550. case 1: {
  5551. auto single_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5552. if (!single_value.has_value())
  5553. return nullptr;
  5554. // If only one value is specified, the second value is assumed to be center.
  5555. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  5556. switch (single_value->axis) {
  5557. case Axis::None:
  5558. case Axis::X:
  5559. return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
  5560. case Axis::Y:
  5561. return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
  5562. }
  5563. VERIFY_NOT_REACHED();
  5564. }
  5565. case 2: {
  5566. auto first_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5567. auto second_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5568. if (!first_value.has_value() || !second_value.has_value())
  5569. return nullptr;
  5570. RefPtr<CSSStyleValue> x_value;
  5571. RefPtr<CSSStyleValue> y_value;
  5572. if (first_value->axis == Axis::X) {
  5573. x_value = first_value->offset;
  5574. } else if (first_value->axis == Axis::Y) {
  5575. y_value = first_value->offset;
  5576. }
  5577. if (second_value->axis == Axis::X) {
  5578. if (x_value)
  5579. return nullptr;
  5580. x_value = second_value->offset;
  5581. // Put the other in Y since its axis can't have been X
  5582. y_value = first_value->offset;
  5583. } else if (second_value->axis == Axis::Y) {
  5584. if (y_value)
  5585. return nullptr;
  5586. y_value = second_value->offset;
  5587. // Put the other in X since its axis can't have been Y
  5588. x_value = first_value->offset;
  5589. } else {
  5590. if (x_value) {
  5591. VERIFY(!y_value);
  5592. y_value = second_value->offset;
  5593. } else {
  5594. VERIFY(!x_value);
  5595. x_value = second_value->offset;
  5596. }
  5597. }
  5598. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  5599. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  5600. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  5601. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  5602. x_value = first_value->offset;
  5603. y_value = second_value->offset;
  5604. }
  5605. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  5606. }
  5607. }
  5608. return nullptr;
  5609. }
  5610. RefPtr<CSSStyleValue> Parser::parse_transition_value(TokenStream<ComponentValue>& tokens)
  5611. {
  5612. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  5613. return none;
  5614. Vector<TransitionStyleValue::Transition> transitions;
  5615. auto transaction = tokens.begin_transaction();
  5616. while (tokens.has_next_token()) {
  5617. TransitionStyleValue::Transition transition;
  5618. auto time_value_count = 0;
  5619. while (tokens.has_next_token() && !tokens.next_token().is(Token::Type::Comma)) {
  5620. if (auto time = parse_time(tokens); time.has_value()) {
  5621. switch (time_value_count) {
  5622. case 0:
  5623. transition.duration = time.release_value();
  5624. break;
  5625. case 1:
  5626. transition.delay = time.release_value();
  5627. break;
  5628. default:
  5629. dbgln_if(CSS_PARSER_DEBUG, "Transition property has more than two time values");
  5630. return {};
  5631. }
  5632. time_value_count++;
  5633. continue;
  5634. }
  5635. if (auto easing = parse_easing_value(tokens)) {
  5636. if (transition.easing) {
  5637. dbgln_if(CSS_PARSER_DEBUG, "Transition property has multiple easing values");
  5638. return {};
  5639. }
  5640. transition.easing = easing->as_easing();
  5641. continue;
  5642. }
  5643. if (tokens.next_token().is(Token::Type::Ident)) {
  5644. if (transition.property_name) {
  5645. dbgln_if(CSS_PARSER_DEBUG, "Transition property has multiple property identifiers");
  5646. return {};
  5647. }
  5648. auto ident = tokens.consume_a_token().token().ident();
  5649. if (auto property = property_id_from_string(ident); property.has_value())
  5650. transition.property_name = CustomIdentStyleValue::create(ident);
  5651. continue;
  5652. }
  5653. dbgln_if(CSS_PARSER_DEBUG, "Transition property has unexpected token \"{}\"", tokens.next_token().to_string());
  5654. return {};
  5655. }
  5656. if (!transition.property_name)
  5657. transition.property_name = CustomIdentStyleValue::create("all"_fly_string);
  5658. if (!transition.easing)
  5659. transition.easing = EasingStyleValue::create(EasingStyleValue::CubicBezier::ease());
  5660. transitions.append(move(transition));
  5661. if (!tokens.next_token().is(Token::Type::Comma))
  5662. break;
  5663. tokens.discard_a_token();
  5664. }
  5665. transaction.commit();
  5666. return TransitionStyleValue::create(move(transitions));
  5667. }
  5668. RefPtr<CSSStyleValue> Parser::parse_as_css_value(PropertyID property_id)
  5669. {
  5670. auto component_values = parse_a_list_of_component_values(m_token_stream);
  5671. auto tokens = TokenStream(component_values);
  5672. auto parsed_value = parse_css_value(property_id, tokens);
  5673. if (parsed_value.is_error())
  5674. return nullptr;
  5675. return parsed_value.release_value();
  5676. }
  5677. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  5678. {
  5679. if (component_value.is_function()) {
  5680. if (auto maybe_calculated = parse_calculated_value(component_value)) {
  5681. if (maybe_calculated->resolves_to_length_percentage())
  5682. return GridSize(LengthPercentage(maybe_calculated.release_nonnull()));
  5683. // FIXME: Support calculated <flex>
  5684. }
  5685. return {};
  5686. }
  5687. if (component_value.is_ident("auto"sv))
  5688. return GridSize::make_auto();
  5689. if (component_value.is_ident("max-content"sv))
  5690. return GridSize(GridSize::Type::MaxContent);
  5691. if (component_value.is_ident("min-content"sv))
  5692. return GridSize(GridSize::Type::MinContent);
  5693. auto dimension = parse_dimension(component_value);
  5694. if (!dimension.has_value())
  5695. return {};
  5696. if (dimension->is_length())
  5697. return GridSize(dimension->length());
  5698. else if (dimension->is_percentage())
  5699. return GridSize(dimension->percentage());
  5700. else if (dimension->is_flex())
  5701. return GridSize(dimension->flex());
  5702. return {};
  5703. }
  5704. Optional<CSS::GridFitContent> Parser::parse_fit_content(Vector<ComponentValue> const& component_values)
  5705. {
  5706. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-fit-content
  5707. // 'fit-content( <length-percentage> )'
  5708. // Represents the formula max(minimum, min(limit, max-content)), where minimum represents an auto minimum (which is often, but not always,
  5709. // equal to a min-content minimum), and limit is the track sizing function passed as an argument to fit-content().
  5710. // This is essentially calculated as the smaller of minmax(auto, max-content) and minmax(auto, limit).
  5711. auto function_tokens = TokenStream(component_values);
  5712. function_tokens.discard_whitespace();
  5713. auto maybe_length_percentage = parse_length_percentage(function_tokens);
  5714. if (maybe_length_percentage.has_value())
  5715. return CSS::GridFitContent(CSS::GridSize(CSS::GridSize::Type::FitContent, maybe_length_percentage.value()));
  5716. return {};
  5717. }
  5718. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  5719. {
  5720. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5721. // 'minmax(min, max)'
  5722. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  5723. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  5724. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5725. auto function_tokens = TokenStream(component_values);
  5726. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5727. if (comma_separated_list.size() != 2)
  5728. return {};
  5729. TokenStream part_one_tokens { comma_separated_list[0] };
  5730. part_one_tokens.discard_whitespace();
  5731. if (!part_one_tokens.has_next_token())
  5732. return {};
  5733. auto current_token = part_one_tokens.consume_a_token();
  5734. auto min_grid_size = parse_grid_size(current_token);
  5735. TokenStream part_two_tokens { comma_separated_list[1] };
  5736. part_two_tokens.discard_whitespace();
  5737. if (!part_two_tokens.has_next_token())
  5738. return {};
  5739. current_token = part_two_tokens.consume_a_token();
  5740. auto max_grid_size = parse_grid_size(current_token);
  5741. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  5742. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  5743. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  5744. if (min_grid_size.value().is_flexible_length())
  5745. return {};
  5746. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  5747. }
  5748. return {};
  5749. }
  5750. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  5751. {
  5752. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  5753. // 7.2.3.1. Syntax of repeat()
  5754. // The generic form of the repeat() syntax is, approximately,
  5755. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  5756. auto is_auto_fill = false;
  5757. auto is_auto_fit = false;
  5758. auto function_tokens = TokenStream(component_values);
  5759. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  5760. if (comma_separated_list.size() != 2)
  5761. return {};
  5762. // The first argument specifies the number of repetitions.
  5763. TokenStream part_one_tokens { comma_separated_list[0] };
  5764. part_one_tokens.discard_whitespace();
  5765. if (!part_one_tokens.has_next_token())
  5766. return {};
  5767. auto& current_token = part_one_tokens.consume_a_token();
  5768. auto repeat_count = 0;
  5769. if (current_token.is(Token::Type::Number) && current_token.token().number().is_integer() && current_token.token().number_value() > 0)
  5770. repeat_count = current_token.token().number_value();
  5771. else if (current_token.is_ident("auto-fill"sv))
  5772. is_auto_fill = true;
  5773. else if (current_token.is_ident("auto-fit"sv))
  5774. is_auto_fit = true;
  5775. // The second argument is a track list, which is repeated that number of times.
  5776. TokenStream part_two_tokens { comma_separated_list[1] };
  5777. part_two_tokens.discard_whitespace();
  5778. if (!part_two_tokens.has_next_token())
  5779. return {};
  5780. Vector<Variant<ExplicitGridTrack, GridLineNames>> repeat_params;
  5781. auto last_object_was_line_names = false;
  5782. while (part_two_tokens.has_next_token()) {
  5783. auto token = part_two_tokens.consume_a_token();
  5784. Vector<String> line_names;
  5785. if (token.is_block()) {
  5786. if (last_object_was_line_names)
  5787. return {};
  5788. last_object_was_line_names = true;
  5789. if (!token.block().is_square())
  5790. return {};
  5791. TokenStream block_tokens { token.block().value };
  5792. while (block_tokens.has_next_token()) {
  5793. auto current_block_token = block_tokens.consume_a_token();
  5794. line_names.append(current_block_token.token().ident().to_string());
  5795. block_tokens.discard_whitespace();
  5796. }
  5797. repeat_params.append(GridLineNames { move(line_names) });
  5798. part_two_tokens.discard_whitespace();
  5799. } else {
  5800. last_object_was_line_names = false;
  5801. auto track_sizing_function = parse_track_sizing_function(token);
  5802. if (!track_sizing_function.has_value())
  5803. return {};
  5804. // However, there are some restrictions:
  5805. // The repeat() notation can’t be nested.
  5806. if (track_sizing_function.value().is_repeat())
  5807. return {};
  5808. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  5809. // Note that 'auto' is also an intrinsic size (and thus not permitted) but we can't use
  5810. // track_sizing_function.is_auto(..) to check for it, as it requires AvailableSize, which is why there is
  5811. // a separate check for it below.
  5812. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  5813. // https://www.w3.org/TR/css-grid-2/#intrinsic-sizing-function
  5814. if (track_sizing_function.value().is_default()
  5815. && (track_sizing_function.value().grid_size().is_flexible_length() || token.is_ident("auto"sv))
  5816. && (is_auto_fill || is_auto_fit))
  5817. return {};
  5818. repeat_params.append(track_sizing_function.value());
  5819. part_two_tokens.discard_whitespace();
  5820. }
  5821. }
  5822. // Thus the precise syntax of the repeat() notation has several forms:
  5823. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  5824. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  5825. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  5826. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  5827. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  5828. // fixed number of repetitions.
  5829. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  5830. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  5831. // list, but the same track list can also contain <fixed-repeat>s.
  5832. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  5833. // subgrid keyword and cannot specify track sizes, only line names.
  5834. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  5835. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  5836. // 1fr [b a] 1fr [b].
  5837. if (is_auto_fill)
  5838. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFill);
  5839. else if (is_auto_fit)
  5840. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFit);
  5841. else
  5842. return GridRepeat(GridTrackSizeList(move(repeat_params)), repeat_count);
  5843. }
  5844. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  5845. {
  5846. if (token.is_function()) {
  5847. auto const& function_token = token.function();
  5848. if (function_token.name.equals_ignoring_ascii_case("repeat"sv)) {
  5849. auto maybe_repeat = parse_repeat(function_token.value);
  5850. if (maybe_repeat.has_value())
  5851. return CSS::ExplicitGridTrack(maybe_repeat.value());
  5852. else
  5853. return {};
  5854. } else if (function_token.name.equals_ignoring_ascii_case("minmax"sv)) {
  5855. auto maybe_min_max_value = parse_min_max(function_token.value);
  5856. if (maybe_min_max_value.has_value())
  5857. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  5858. else
  5859. return {};
  5860. } else if (function_token.name.equals_ignoring_ascii_case("fit-content"sv)) {
  5861. auto maybe_fit_content_value = parse_fit_content(function_token.value);
  5862. if (maybe_fit_content_value.has_value())
  5863. return CSS::ExplicitGridTrack(maybe_fit_content_value.value());
  5864. return {};
  5865. } else if (auto maybe_calculated = parse_calculated_value(token)) {
  5866. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_calculated.release_nonnull())));
  5867. }
  5868. return {};
  5869. } else if (token.is_ident("auto"sv)) {
  5870. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  5871. } else if (token.is_block()) {
  5872. return {};
  5873. } else {
  5874. auto grid_size = parse_grid_size(token);
  5875. if (!grid_size.has_value())
  5876. return {};
  5877. return CSS::ExplicitGridTrack(grid_size.value());
  5878. }
  5879. }
  5880. RefPtr<CSSStyleValue> Parser::parse_grid_track_size_list(TokenStream<ComponentValue>& tokens, bool allow_separate_line_name_blocks)
  5881. {
  5882. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  5883. return GridTrackSizeListStyleValue::make_none();
  5884. auto transaction = tokens.begin_transaction();
  5885. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  5886. auto last_object_was_line_names = false;
  5887. while (tokens.has_next_token()) {
  5888. auto token = tokens.consume_a_token();
  5889. if (token.is_block()) {
  5890. if (last_object_was_line_names && !allow_separate_line_name_blocks) {
  5891. transaction.commit();
  5892. return GridTrackSizeListStyleValue::make_auto();
  5893. }
  5894. last_object_was_line_names = true;
  5895. Vector<String> line_names;
  5896. if (!token.block().is_square()) {
  5897. transaction.commit();
  5898. return GridTrackSizeListStyleValue::make_auto();
  5899. }
  5900. TokenStream block_tokens { token.block().value };
  5901. block_tokens.discard_whitespace();
  5902. while (block_tokens.has_next_token()) {
  5903. auto current_block_token = block_tokens.consume_a_token();
  5904. line_names.append(current_block_token.token().ident().to_string());
  5905. block_tokens.discard_whitespace();
  5906. }
  5907. track_list.append(GridLineNames { move(line_names) });
  5908. } else {
  5909. last_object_was_line_names = false;
  5910. auto track_sizing_function = parse_track_sizing_function(token);
  5911. if (!track_sizing_function.has_value()) {
  5912. transaction.commit();
  5913. return GridTrackSizeListStyleValue::make_auto();
  5914. }
  5915. // FIXME: Handle multiple repeat values (should combine them here, or remove
  5916. // any other ones if the first one is auto-fill, etc.)
  5917. track_list.append(track_sizing_function.value());
  5918. }
  5919. }
  5920. transaction.commit();
  5921. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  5922. }
  5923. // https://www.w3.org/TR/css-grid-1/#grid-auto-flow-property
  5924. RefPtr<GridAutoFlowStyleValue> Parser::parse_grid_auto_flow_value(TokenStream<ComponentValue>& tokens)
  5925. {
  5926. // [ row | column ] || dense
  5927. if (!tokens.has_next_token())
  5928. return nullptr;
  5929. auto transaction = tokens.begin_transaction();
  5930. auto parse_axis = [&]() -> Optional<GridAutoFlowStyleValue::Axis> {
  5931. auto transaction = tokens.begin_transaction();
  5932. auto token = tokens.consume_a_token();
  5933. if (!token.is(Token::Type::Ident))
  5934. return {};
  5935. auto const& ident = token.token().ident();
  5936. if (ident.equals_ignoring_ascii_case("row"sv)) {
  5937. transaction.commit();
  5938. return GridAutoFlowStyleValue::Axis::Row;
  5939. } else if (ident.equals_ignoring_ascii_case("column"sv)) {
  5940. transaction.commit();
  5941. return GridAutoFlowStyleValue::Axis::Column;
  5942. }
  5943. return {};
  5944. };
  5945. auto parse_dense = [&]() -> Optional<GridAutoFlowStyleValue::Dense> {
  5946. auto transaction = tokens.begin_transaction();
  5947. auto token = tokens.consume_a_token();
  5948. if (!token.is(Token::Type::Ident))
  5949. return {};
  5950. auto const& ident = token.token().ident();
  5951. if (ident.equals_ignoring_ascii_case("dense"sv)) {
  5952. transaction.commit();
  5953. return GridAutoFlowStyleValue::Dense::Yes;
  5954. }
  5955. return {};
  5956. };
  5957. Optional<GridAutoFlowStyleValue::Axis> axis;
  5958. Optional<GridAutoFlowStyleValue::Dense> dense;
  5959. if (axis = parse_axis(); axis.has_value()) {
  5960. dense = parse_dense();
  5961. } else if (dense = parse_dense(); dense.has_value()) {
  5962. axis = parse_axis();
  5963. }
  5964. if (tokens.has_next_token())
  5965. return nullptr;
  5966. transaction.commit();
  5967. return GridAutoFlowStyleValue::create(axis.value_or(GridAutoFlowStyleValue::Axis::Row), dense.value_or(GridAutoFlowStyleValue::Dense::No));
  5968. }
  5969. // https://drafts.csswg.org/css-overflow/#propdef-scrollbar-gutter
  5970. RefPtr<CSSStyleValue> Parser::parse_scrollbar_gutter_value(TokenStream<ComponentValue>& tokens)
  5971. {
  5972. // auto | stable && both-edges?
  5973. if (!tokens.has_next_token())
  5974. return nullptr;
  5975. auto transaction = tokens.begin_transaction();
  5976. auto parse_stable = [&]() -> Optional<bool> {
  5977. auto transaction = tokens.begin_transaction();
  5978. auto token = tokens.consume_a_token();
  5979. if (!token.is(Token::Type::Ident))
  5980. return {};
  5981. auto const& ident = token.token().ident();
  5982. if (ident.equals_ignoring_ascii_case("auto"sv)) {
  5983. transaction.commit();
  5984. return false;
  5985. } else if (ident.equals_ignoring_ascii_case("stable"sv)) {
  5986. transaction.commit();
  5987. return true;
  5988. }
  5989. return {};
  5990. };
  5991. auto parse_both_edges = [&]() -> Optional<bool> {
  5992. auto transaction = tokens.begin_transaction();
  5993. auto token = tokens.consume_a_token();
  5994. if (!token.is(Token::Type::Ident))
  5995. return {};
  5996. auto const& ident = token.token().ident();
  5997. if (ident.equals_ignoring_ascii_case("both-edges"sv)) {
  5998. transaction.commit();
  5999. return true;
  6000. }
  6001. return {};
  6002. };
  6003. Optional<bool> stable;
  6004. Optional<bool> both_edges;
  6005. if (stable = parse_stable(); stable.has_value()) {
  6006. if (stable.value())
  6007. both_edges = parse_both_edges();
  6008. } else if (both_edges = parse_both_edges(); both_edges.has_value()) {
  6009. stable = parse_stable();
  6010. if (!stable.has_value() || !stable.value())
  6011. return nullptr;
  6012. }
  6013. if (tokens.has_next_token())
  6014. return nullptr;
  6015. transaction.commit();
  6016. ScrollbarGutter gutter_value;
  6017. if (both_edges.has_value())
  6018. gutter_value = ScrollbarGutter::BothEdges;
  6019. else if (stable.has_value() && stable.value())
  6020. gutter_value = ScrollbarGutter::Stable;
  6021. else
  6022. gutter_value = ScrollbarGutter::Auto;
  6023. return ScrollbarGutterStyleValue::create(gutter_value);
  6024. }
  6025. RefPtr<CSSStyleValue> Parser::parse_grid_auto_track_sizes(TokenStream<ComponentValue>& tokens)
  6026. {
  6027. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  6028. // <track-size>+
  6029. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  6030. auto transaction = tokens.begin_transaction();
  6031. while (tokens.has_next_token()) {
  6032. auto token = tokens.consume_a_token();
  6033. auto track_sizing_function = parse_track_sizing_function(token);
  6034. if (!track_sizing_function.has_value()) {
  6035. transaction.commit();
  6036. return GridTrackSizeListStyleValue::make_auto();
  6037. }
  6038. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6039. // any other ones if the first one is auto-fill, etc.)
  6040. track_list.append(track_sizing_function.value());
  6041. }
  6042. transaction.commit();
  6043. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  6044. }
  6045. RefPtr<GridTrackPlacementStyleValue> Parser::parse_grid_track_placement(TokenStream<ComponentValue>& tokens)
  6046. {
  6047. // FIXME: This shouldn't be needed. Right now, the below code returns a CSSStyleValue even if no tokens are consumed!
  6048. if (!tokens.has_next_token())
  6049. return nullptr;
  6050. // https://www.w3.org/TR/css-grid-2/#line-placement
  6051. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  6052. // <grid-line> =
  6053. // auto |
  6054. // <custom-ident> |
  6055. // [ <integer> && <custom-ident>? ] |
  6056. // [ span && [ <integer> || <custom-ident> ] ]
  6057. auto is_valid_integer = [](auto& token) -> bool {
  6058. // An <integer> value of zero makes the declaration invalid.
  6059. if (token.is(Token::Type::Number) && token.token().number().is_integer() && token.token().number_value() != 0)
  6060. return true;
  6061. return false;
  6062. };
  6063. auto parse_custom_ident = [this](auto& tokens) {
  6064. // The <custom-ident> additionally excludes the keywords span and auto.
  6065. return parse_custom_ident_value(tokens, { "span"sv, "auto"sv });
  6066. };
  6067. auto transaction = tokens.begin_transaction();
  6068. // FIXME: Handle the single-token case inside the loop instead, so that we can more easily call this from
  6069. // `parse_grid_area_shorthand_value()` using a single TokenStream.
  6070. if (tokens.remaining_token_count() == 1) {
  6071. if (auto custom_ident = parse_custom_ident(tokens)) {
  6072. transaction.commit();
  6073. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line({}, custom_ident->custom_ident().to_string()));
  6074. }
  6075. auto& token = tokens.consume_a_token();
  6076. if (auto maybe_calculated = parse_calculated_value(token); maybe_calculated && maybe_calculated->resolves_to_number()) {
  6077. transaction.commit();
  6078. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(maybe_calculated->resolve_integer().value()), {}));
  6079. }
  6080. if (token.is_ident("auto"sv)) {
  6081. transaction.commit();
  6082. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto());
  6083. }
  6084. if (token.is_ident("span"sv)) {
  6085. transaction.commit();
  6086. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(1));
  6087. }
  6088. if (is_valid_integer(token)) {
  6089. transaction.commit();
  6090. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(token.token().number_value()), {}));
  6091. }
  6092. return nullptr;
  6093. }
  6094. auto span_value = false;
  6095. auto span_or_position_value = 0;
  6096. String identifier_value;
  6097. while (tokens.has_next_token()) {
  6098. auto& token = tokens.next_token();
  6099. if (token.is_ident("auto"sv))
  6100. return nullptr;
  6101. if (token.is_ident("span"sv)) {
  6102. if (span_value)
  6103. return nullptr;
  6104. tokens.discard_a_token(); // span
  6105. span_value = true;
  6106. continue;
  6107. }
  6108. if (is_valid_integer(token)) {
  6109. if (span_or_position_value != 0)
  6110. return nullptr;
  6111. span_or_position_value = static_cast<int>(tokens.consume_a_token().token().to_integer());
  6112. continue;
  6113. }
  6114. if (auto custom_ident = parse_custom_ident(tokens)) {
  6115. if (!identifier_value.is_empty())
  6116. return nullptr;
  6117. identifier_value = custom_ident->custom_ident().to_string();
  6118. continue;
  6119. }
  6120. break;
  6121. }
  6122. // Negative integers or zero are invalid.
  6123. if (span_value && span_or_position_value < 1)
  6124. return nullptr;
  6125. // If the <integer> is omitted, it defaults to 1.
  6126. if (span_or_position_value == 0)
  6127. span_or_position_value = 1;
  6128. transaction.commit();
  6129. if (!identifier_value.is_empty())
  6130. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(span_or_position_value, identifier_value));
  6131. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(span_or_position_value));
  6132. }
  6133. RefPtr<CSSStyleValue> Parser::parse_grid_track_placement_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6134. {
  6135. auto start_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnStart : PropertyID::GridRowStart;
  6136. auto end_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnEnd : PropertyID::GridRowEnd;
  6137. auto transaction = tokens.begin_transaction();
  6138. auto current_token = tokens.consume_a_token();
  6139. Vector<ComponentValue> track_start_placement_tokens;
  6140. while (true) {
  6141. if (current_token.is_delim('/'))
  6142. break;
  6143. track_start_placement_tokens.append(current_token);
  6144. if (!tokens.has_next_token())
  6145. break;
  6146. current_token = tokens.consume_a_token();
  6147. }
  6148. Vector<ComponentValue> track_end_placement_tokens;
  6149. if (tokens.has_next_token()) {
  6150. current_token = tokens.consume_a_token();
  6151. while (true) {
  6152. track_end_placement_tokens.append(current_token);
  6153. if (!tokens.has_next_token())
  6154. break;
  6155. current_token = tokens.consume_a_token();
  6156. }
  6157. }
  6158. TokenStream track_start_placement_token_stream { track_start_placement_tokens };
  6159. auto parsed_start_value = parse_grid_track_placement(track_start_placement_token_stream);
  6160. if (parsed_start_value && track_end_placement_tokens.is_empty()) {
  6161. transaction.commit();
  6162. if (parsed_start_value->grid_track_placement().has_identifier()) {
  6163. auto custom_ident = parsed_start_value.release_nonnull();
  6164. return ShorthandStyleValue::create(property_id, { start_property, end_property }, { custom_ident, custom_ident });
  6165. }
  6166. return ShorthandStyleValue::create(property_id,
  6167. { start_property, end_property },
  6168. { parsed_start_value.release_nonnull(), GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto()) });
  6169. }
  6170. TokenStream track_end_placement_token_stream { track_end_placement_tokens };
  6171. auto parsed_end_value = parse_grid_track_placement(track_end_placement_token_stream);
  6172. if (parsed_start_value && parsed_end_value) {
  6173. transaction.commit();
  6174. return ShorthandStyleValue::create(property_id,
  6175. { start_property, end_property },
  6176. { parsed_start_value.release_nonnull(), parsed_end_value.release_nonnull() });
  6177. }
  6178. return nullptr;
  6179. }
  6180. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  6181. // 7.4. Explicit Grid Shorthand: the grid-template property
  6182. RefPtr<CSSStyleValue> Parser::parse_grid_track_size_list_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6183. {
  6184. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  6185. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  6186. // none
  6187. // - Sets all three properties to their initial values (none).
  6188. // <'grid-template-rows'> / <'grid-template-columns'>
  6189. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  6190. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  6191. // - Sets grid-template-areas to the strings listed.
  6192. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  6193. // and splicing in the named lines defined before/after each size.
  6194. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  6195. auto transaction = tokens.begin_transaction();
  6196. // FIXME: Read the parts in place if possible, instead of constructing separate vectors and streams.
  6197. Vector<ComponentValue> template_rows_tokens;
  6198. Vector<ComponentValue> template_columns_tokens;
  6199. Vector<ComponentValue> template_area_tokens;
  6200. bool found_forward_slash = false;
  6201. while (tokens.has_next_token()) {
  6202. auto& token = tokens.consume_a_token();
  6203. if (token.is_delim('/')) {
  6204. if (found_forward_slash)
  6205. return nullptr;
  6206. found_forward_slash = true;
  6207. continue;
  6208. }
  6209. if (found_forward_slash) {
  6210. template_columns_tokens.append(token);
  6211. continue;
  6212. }
  6213. if (token.is(Token::Type::String))
  6214. template_area_tokens.append(token);
  6215. else
  6216. template_rows_tokens.append(token);
  6217. }
  6218. TokenStream template_area_token_stream { template_area_tokens };
  6219. TokenStream template_rows_token_stream { template_rows_tokens };
  6220. TokenStream template_columns_token_stream { template_columns_tokens };
  6221. auto parsed_template_areas_values = parse_grid_template_areas_value(template_area_token_stream);
  6222. auto parsed_template_rows_values = parse_grid_track_size_list(template_rows_token_stream, true);
  6223. auto parsed_template_columns_values = parse_grid_track_size_list(template_columns_token_stream);
  6224. if (template_area_token_stream.has_next_token()
  6225. || template_rows_token_stream.has_next_token()
  6226. || template_columns_token_stream.has_next_token())
  6227. return nullptr;
  6228. transaction.commit();
  6229. return ShorthandStyleValue::create(property_id,
  6230. { PropertyID::GridTemplateAreas, PropertyID::GridTemplateRows, PropertyID::GridTemplateColumns },
  6231. { parsed_template_areas_values.release_nonnull(), parsed_template_rows_values.release_nonnull(), parsed_template_columns_values.release_nonnull() });
  6232. }
  6233. RefPtr<CSSStyleValue> Parser::parse_grid_area_shorthand_value(TokenStream<ComponentValue>& tokens)
  6234. {
  6235. auto transaction = tokens.begin_transaction();
  6236. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  6237. while (tokens.has_next_token()) {
  6238. auto& current_token = tokens.consume_a_token();
  6239. if (check_for_delimiter && current_token.is_delim('/'))
  6240. break;
  6241. placement_tokens.append(current_token);
  6242. }
  6243. };
  6244. Vector<ComponentValue> row_start_placement_tokens;
  6245. parse_placement_tokens(row_start_placement_tokens);
  6246. Vector<ComponentValue> column_start_placement_tokens;
  6247. if (tokens.has_next_token())
  6248. parse_placement_tokens(column_start_placement_tokens);
  6249. Vector<ComponentValue> row_end_placement_tokens;
  6250. if (tokens.has_next_token())
  6251. parse_placement_tokens(row_end_placement_tokens);
  6252. Vector<ComponentValue> column_end_placement_tokens;
  6253. if (tokens.has_next_token())
  6254. parse_placement_tokens(column_end_placement_tokens, false);
  6255. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  6256. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  6257. // grid-column-end.
  6258. TokenStream row_start_placement_token_stream { row_start_placement_tokens };
  6259. auto row_start_style_value = parse_grid_track_placement(row_start_placement_token_stream);
  6260. if (row_start_placement_token_stream.has_next_token())
  6261. return nullptr;
  6262. TokenStream column_start_placement_token_stream { column_start_placement_tokens };
  6263. auto column_start_style_value = parse_grid_track_placement(column_start_placement_token_stream);
  6264. if (column_start_placement_token_stream.has_next_token())
  6265. return nullptr;
  6266. TokenStream row_end_placement_token_stream { row_end_placement_tokens };
  6267. auto row_end_style_value = parse_grid_track_placement(row_end_placement_token_stream);
  6268. if (row_end_placement_token_stream.has_next_token())
  6269. return nullptr;
  6270. TokenStream column_end_placement_token_stream { column_end_placement_tokens };
  6271. auto column_end_style_value = parse_grid_track_placement(column_end_placement_token_stream);
  6272. if (column_end_placement_token_stream.has_next_token())
  6273. return nullptr;
  6274. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  6275. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  6276. // fourth value.
  6277. auto row_start = GridTrackPlacement::make_auto();
  6278. auto column_start = GridTrackPlacement::make_auto();
  6279. auto row_end = GridTrackPlacement::make_auto();
  6280. auto column_end = GridTrackPlacement::make_auto();
  6281. if (row_start_style_value)
  6282. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6283. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  6284. // that value. Otherwise, it is set to auto.
  6285. if (column_start_style_value)
  6286. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6287. else
  6288. column_start = row_start;
  6289. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  6290. // <custom-ident>; otherwise, it is set to auto.
  6291. if (row_end_style_value)
  6292. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6293. else
  6294. row_end = column_start;
  6295. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  6296. // that <custom-ident>; otherwise, it is set to auto.
  6297. if (column_end_style_value)
  6298. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6299. else
  6300. column_end = row_end;
  6301. transaction.commit();
  6302. return ShorthandStyleValue::create(PropertyID::GridArea,
  6303. { PropertyID::GridRowStart, PropertyID::GridColumnStart, PropertyID::GridRowEnd, PropertyID::GridColumnEnd },
  6304. { GridTrackPlacementStyleValue::create(row_start), GridTrackPlacementStyleValue::create(column_start), GridTrackPlacementStyleValue::create(row_end), GridTrackPlacementStyleValue::create(column_end) });
  6305. }
  6306. RefPtr<CSSStyleValue> Parser::parse_grid_shorthand_value(TokenStream<ComponentValue>& tokens)
  6307. {
  6308. // <'grid-template'> |
  6309. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  6310. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  6311. return parse_grid_track_size_list_shorthand_value(PropertyID::Grid, tokens);
  6312. }
  6313. // https://www.w3.org/TR/css-grid-1/#grid-template-areas-property
  6314. RefPtr<CSSStyleValue> Parser::parse_grid_template_areas_value(TokenStream<ComponentValue>& tokens)
  6315. {
  6316. // none | <string>+
  6317. Vector<Vector<String>> grid_area_rows;
  6318. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  6319. return GridTemplateAreaStyleValue::create(move(grid_area_rows));
  6320. auto transaction = tokens.begin_transaction();
  6321. while (tokens.has_next_token() && tokens.next_token().is(Token::Type::String)) {
  6322. Vector<String> grid_area_columns;
  6323. auto const parts = MUST(tokens.consume_a_token().token().string().to_string().split(' '));
  6324. for (auto& part : parts) {
  6325. grid_area_columns.append(part);
  6326. }
  6327. grid_area_rows.append(move(grid_area_columns));
  6328. }
  6329. transaction.commit();
  6330. return GridTemplateAreaStyleValue::create(grid_area_rows);
  6331. }
  6332. static bool block_contains_var_or_attr(SimpleBlock const& block);
  6333. static bool function_contains_var_or_attr(Function const& function)
  6334. {
  6335. if (function.name.equals_ignoring_ascii_case("var"sv) || function.name.equals_ignoring_ascii_case("attr"sv))
  6336. return true;
  6337. for (auto const& token : function.value) {
  6338. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6339. return true;
  6340. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6341. return true;
  6342. }
  6343. return false;
  6344. }
  6345. bool block_contains_var_or_attr(SimpleBlock const& block)
  6346. {
  6347. for (auto const& token : block.value) {
  6348. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6349. return true;
  6350. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6351. return true;
  6352. }
  6353. return false;
  6354. }
  6355. Parser::ParseErrorOr<NonnullRefPtr<CSSStyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& unprocessed_tokens, Optional<String> original_source_text)
  6356. {
  6357. m_context.set_current_property_id(property_id);
  6358. Vector<ComponentValue> component_values;
  6359. bool contains_var_or_attr = false;
  6360. bool const property_accepts_custom_ident = property_accepts_type(property_id, ValueType::CustomIdent);
  6361. while (unprocessed_tokens.has_next_token()) {
  6362. auto const& token = unprocessed_tokens.consume_a_token();
  6363. if (token.is(Token::Type::Semicolon)) {
  6364. unprocessed_tokens.reconsume_current_input_token();
  6365. break;
  6366. }
  6367. if (property_id != PropertyID::Custom) {
  6368. if (token.is(Token::Type::Whitespace))
  6369. continue;
  6370. if (!property_accepts_custom_ident && token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  6371. return ParseError::IncludesIgnoredVendorPrefix;
  6372. }
  6373. if (!contains_var_or_attr) {
  6374. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6375. contains_var_or_attr = true;
  6376. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  6377. contains_var_or_attr = true;
  6378. }
  6379. component_values.append(token);
  6380. }
  6381. if (property_id == PropertyID::Custom || contains_var_or_attr)
  6382. return UnresolvedStyleValue::create(move(component_values), contains_var_or_attr, original_source_text);
  6383. if (component_values.is_empty())
  6384. return ParseError::SyntaxError;
  6385. auto tokens = TokenStream { component_values };
  6386. if (component_values.size() == 1) {
  6387. if (auto parsed_value = parse_builtin_value(tokens))
  6388. return parsed_value.release_nonnull();
  6389. }
  6390. // Special-case property handling
  6391. switch (property_id) {
  6392. case PropertyID::AspectRatio:
  6393. if (auto parsed_value = parse_aspect_ratio_value(tokens); parsed_value && !tokens.has_next_token())
  6394. return parsed_value.release_nonnull();
  6395. return ParseError::SyntaxError;
  6396. case PropertyID::BackdropFilter:
  6397. case PropertyID::Filter:
  6398. if (auto parsed_value = parse_filter_value_list_value(tokens); parsed_value && !tokens.has_next_token())
  6399. return parsed_value.release_nonnull();
  6400. return ParseError::SyntaxError;
  6401. case PropertyID::Background:
  6402. if (auto parsed_value = parse_background_value(tokens); parsed_value && !tokens.has_next_token())
  6403. return parsed_value.release_nonnull();
  6404. return ParseError::SyntaxError;
  6405. case PropertyID::BackgroundAttachment:
  6406. case PropertyID::BackgroundClip:
  6407. case PropertyID::BackgroundImage:
  6408. case PropertyID::BackgroundOrigin:
  6409. if (auto parsed_value = parse_simple_comma_separated_value_list(property_id, tokens))
  6410. return parsed_value.release_nonnull();
  6411. return ParseError::SyntaxError;
  6412. case PropertyID::BackgroundPosition:
  6413. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_position_value(tokens, PositionParsingMode::BackgroundPosition); }))
  6414. return parsed_value.release_nonnull();
  6415. return ParseError::SyntaxError;
  6416. case PropertyID::BackgroundPositionX:
  6417. case PropertyID::BackgroundPositionY:
  6418. 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); }))
  6419. return parsed_value.release_nonnull();
  6420. return ParseError::SyntaxError;
  6421. case PropertyID::BackgroundRepeat:
  6422. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  6423. return parsed_value.release_nonnull();
  6424. return ParseError::SyntaxError;
  6425. case PropertyID::BackgroundSize:
  6426. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  6427. return parsed_value.release_nonnull();
  6428. return ParseError::SyntaxError;
  6429. case PropertyID::Border:
  6430. case PropertyID::BorderBottom:
  6431. case PropertyID::BorderLeft:
  6432. case PropertyID::BorderRight:
  6433. case PropertyID::BorderTop:
  6434. if (auto parsed_value = parse_border_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6435. return parsed_value.release_nonnull();
  6436. return ParseError::SyntaxError;
  6437. case PropertyID::BorderTopLeftRadius:
  6438. case PropertyID::BorderTopRightRadius:
  6439. case PropertyID::BorderBottomRightRadius:
  6440. case PropertyID::BorderBottomLeftRadius:
  6441. if (auto parsed_value = parse_border_radius_value(tokens); parsed_value && !tokens.has_next_token())
  6442. return parsed_value.release_nonnull();
  6443. return ParseError::SyntaxError;
  6444. case PropertyID::BorderRadius:
  6445. if (auto parsed_value = parse_border_radius_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6446. return parsed_value.release_nonnull();
  6447. return ParseError::SyntaxError;
  6448. case PropertyID::BoxShadow:
  6449. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::Yes); parsed_value && !tokens.has_next_token())
  6450. return parsed_value.release_nonnull();
  6451. return ParseError::SyntaxError;
  6452. case PropertyID::Columns:
  6453. if (auto parsed_value = parse_columns_value(tokens); parsed_value && !tokens.has_next_token())
  6454. return parsed_value.release_nonnull();
  6455. return ParseError::SyntaxError;
  6456. case PropertyID::Content:
  6457. if (auto parsed_value = parse_content_value(tokens); parsed_value && !tokens.has_next_token())
  6458. return parsed_value.release_nonnull();
  6459. return ParseError::SyntaxError;
  6460. case PropertyID::CounterIncrement:
  6461. if (auto parsed_value = parse_counter_increment_value(tokens); parsed_value && !tokens.has_next_token())
  6462. return parsed_value.release_nonnull();
  6463. return ParseError::SyntaxError;
  6464. case PropertyID::CounterReset:
  6465. if (auto parsed_value = parse_counter_reset_value(tokens); parsed_value && !tokens.has_next_token())
  6466. return parsed_value.release_nonnull();
  6467. return ParseError::SyntaxError;
  6468. case PropertyID::CounterSet:
  6469. if (auto parsed_value = parse_counter_set_value(tokens); parsed_value && !tokens.has_next_token())
  6470. return parsed_value.release_nonnull();
  6471. return ParseError::SyntaxError;
  6472. case PropertyID::Display:
  6473. if (auto parsed_value = parse_display_value(tokens); parsed_value && !tokens.has_next_token())
  6474. return parsed_value.release_nonnull();
  6475. return ParseError::SyntaxError;
  6476. case PropertyID::Flex:
  6477. if (auto parsed_value = parse_flex_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6478. return parsed_value.release_nonnull();
  6479. return ParseError::SyntaxError;
  6480. case PropertyID::FlexFlow:
  6481. if (auto parsed_value = parse_flex_flow_value(tokens); parsed_value && !tokens.has_next_token())
  6482. return parsed_value.release_nonnull();
  6483. return ParseError::SyntaxError;
  6484. case PropertyID::Font:
  6485. if (auto parsed_value = parse_font_value(tokens); parsed_value && !tokens.has_next_token())
  6486. return parsed_value.release_nonnull();
  6487. return ParseError::SyntaxError;
  6488. case PropertyID::FontFamily:
  6489. if (auto parsed_value = parse_font_family_value(tokens); parsed_value && !tokens.has_next_token())
  6490. return parsed_value.release_nonnull();
  6491. return ParseError::SyntaxError;
  6492. case PropertyID::FontFeatureSettings:
  6493. if (auto parsed_value = parse_font_feature_settings_value(tokens); parsed_value && !tokens.has_next_token())
  6494. return parsed_value.release_nonnull();
  6495. return ParseError::SyntaxError;
  6496. case PropertyID::FontLanguageOverride:
  6497. if (auto parsed_value = parse_font_language_override_value(tokens); parsed_value && !tokens.has_next_token())
  6498. return parsed_value.release_nonnull();
  6499. return ParseError::SyntaxError;
  6500. case PropertyID::FontVariationSettings:
  6501. if (auto parsed_value = parse_font_variation_settings_value(tokens); parsed_value && !tokens.has_next_token())
  6502. return parsed_value.release_nonnull();
  6503. return ParseError::SyntaxError;
  6504. case PropertyID::GridArea:
  6505. if (auto parsed_value = parse_grid_area_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6506. return parsed_value.release_nonnull();
  6507. return ParseError::SyntaxError;
  6508. case PropertyID::GridAutoFlow:
  6509. if (auto parsed_value = parse_grid_auto_flow_value(tokens); parsed_value && !tokens.has_next_token())
  6510. return parsed_value.release_nonnull();
  6511. return ParseError::SyntaxError;
  6512. case PropertyID::GridColumn:
  6513. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6514. return parsed_value.release_nonnull();
  6515. return ParseError::SyntaxError;
  6516. case PropertyID::GridColumnEnd:
  6517. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6518. return parsed_value.release_nonnull();
  6519. return ParseError::SyntaxError;
  6520. case PropertyID::GridColumnStart:
  6521. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6522. return parsed_value.release_nonnull();
  6523. return ParseError::SyntaxError;
  6524. case PropertyID::GridRow:
  6525. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6526. return parsed_value.release_nonnull();
  6527. return ParseError::SyntaxError;
  6528. case PropertyID::GridRowEnd:
  6529. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6530. return parsed_value.release_nonnull();
  6531. return ParseError::SyntaxError;
  6532. case PropertyID::GridRowStart:
  6533. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6534. return parsed_value.release_nonnull();
  6535. return ParseError::SyntaxError;
  6536. case PropertyID::Grid:
  6537. if (auto parsed_value = parse_grid_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6538. return parsed_value.release_nonnull();
  6539. return ParseError::SyntaxError;
  6540. case PropertyID::GridTemplate:
  6541. if (auto parsed_value = parse_grid_track_size_list_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6542. return parsed_value.release_nonnull();
  6543. return ParseError::SyntaxError;
  6544. case PropertyID::GridTemplateAreas:
  6545. if (auto parsed_value = parse_grid_template_areas_value(tokens); parsed_value && !tokens.has_next_token())
  6546. return parsed_value.release_nonnull();
  6547. return ParseError::SyntaxError;
  6548. case PropertyID::GridTemplateColumns:
  6549. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  6550. return parsed_value.release_nonnull();
  6551. return ParseError::SyntaxError;
  6552. case PropertyID::GridTemplateRows:
  6553. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  6554. return parsed_value.release_nonnull();
  6555. return ParseError::SyntaxError;
  6556. case PropertyID::GridAutoColumns:
  6557. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  6558. return parsed_value.release_nonnull();
  6559. return ParseError::SyntaxError;
  6560. case PropertyID::GridAutoRows:
  6561. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  6562. return parsed_value.release_nonnull();
  6563. return ParseError::SyntaxError;
  6564. case PropertyID::ListStyle:
  6565. if (auto parsed_value = parse_list_style_value(tokens); parsed_value && !tokens.has_next_token())
  6566. return parsed_value.release_nonnull();
  6567. return ParseError::SyntaxError;
  6568. case PropertyID::MathDepth:
  6569. if (auto parsed_value = parse_math_depth_value(tokens); parsed_value && !tokens.has_next_token())
  6570. return parsed_value.release_nonnull();
  6571. return ParseError::SyntaxError;
  6572. case PropertyID::Overflow:
  6573. if (auto parsed_value = parse_overflow_value(tokens); parsed_value && !tokens.has_next_token())
  6574. return parsed_value.release_nonnull();
  6575. return ParseError::SyntaxError;
  6576. case PropertyID::PlaceContent:
  6577. if (auto parsed_value = parse_place_content_value(tokens); parsed_value && !tokens.has_next_token())
  6578. return parsed_value.release_nonnull();
  6579. return ParseError::SyntaxError;
  6580. case PropertyID::PlaceItems:
  6581. if (auto parsed_value = parse_place_items_value(tokens); parsed_value && !tokens.has_next_token())
  6582. return parsed_value.release_nonnull();
  6583. return ParseError::SyntaxError;
  6584. case PropertyID::PlaceSelf:
  6585. if (auto parsed_value = parse_place_self_value(tokens); parsed_value && !tokens.has_next_token())
  6586. return parsed_value.release_nonnull();
  6587. return ParseError::SyntaxError;
  6588. case PropertyID::Quotes:
  6589. if (auto parsed_value = parse_quotes_value(tokens); parsed_value && !tokens.has_next_token())
  6590. return parsed_value.release_nonnull();
  6591. return ParseError::SyntaxError;
  6592. case PropertyID::Rotate:
  6593. if (auto parsed_value = parse_rotate_value(tokens); parsed_value && !tokens.has_next_token())
  6594. return parsed_value.release_nonnull();
  6595. return ParseError::SyntaxError;
  6596. case PropertyID::ScrollbarGutter:
  6597. if (auto parsed_value = parse_scrollbar_gutter_value(tokens); parsed_value && !tokens.has_next_token())
  6598. return parsed_value.release_nonnull();
  6599. return ParseError::SyntaxError;
  6600. case PropertyID::TextDecoration:
  6601. if (auto parsed_value = parse_text_decoration_value(tokens); parsed_value && !tokens.has_next_token())
  6602. return parsed_value.release_nonnull();
  6603. return ParseError::SyntaxError;
  6604. case PropertyID::TextDecorationLine:
  6605. if (auto parsed_value = parse_text_decoration_line_value(tokens); parsed_value && !tokens.has_next_token())
  6606. return parsed_value.release_nonnull();
  6607. return ParseError::SyntaxError;
  6608. case PropertyID::TextShadow:
  6609. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::No); parsed_value && !tokens.has_next_token())
  6610. return parsed_value.release_nonnull();
  6611. return ParseError::SyntaxError;
  6612. case PropertyID::Transform:
  6613. if (auto parsed_value = parse_transform_value(tokens); parsed_value && !tokens.has_next_token())
  6614. return parsed_value.release_nonnull();
  6615. return ParseError::SyntaxError;
  6616. case PropertyID::TransformOrigin:
  6617. if (auto parsed_value = parse_transform_origin_value(tokens); parsed_value && !tokens.has_next_token())
  6618. return parsed_value.release_nonnull();
  6619. return ParseError::SyntaxError;
  6620. case PropertyID::Transition:
  6621. if (auto parsed_value = parse_transition_value(tokens); parsed_value && !tokens.has_next_token())
  6622. return parsed_value.release_nonnull();
  6623. return ParseError::SyntaxError;
  6624. default:
  6625. break;
  6626. }
  6627. // If there's only 1 ComponentValue, we can only produce a single CSSStyleValue.
  6628. if (component_values.size() == 1) {
  6629. auto stream = TokenStream { component_values };
  6630. if (auto parsed_value = parse_css_value_for_property(property_id, stream))
  6631. return parsed_value.release_nonnull();
  6632. } else {
  6633. StyleValueVector parsed_values;
  6634. auto stream = TokenStream { component_values };
  6635. while (auto parsed_value = parse_css_value_for_property(property_id, stream)) {
  6636. parsed_values.append(parsed_value.release_nonnull());
  6637. if (!stream.has_next_token())
  6638. break;
  6639. }
  6640. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 CSSStyleValue, return it directly.
  6641. if (parsed_values.size() == 1)
  6642. return *parsed_values.take_first();
  6643. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  6644. return StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space);
  6645. }
  6646. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  6647. auto unassigned_properties = longhands_for_shorthand(property_id);
  6648. if (unassigned_properties.is_empty())
  6649. return ParseError::SyntaxError;
  6650. auto stream = TokenStream { component_values };
  6651. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<CSSStyleValue const>>> assigned_values;
  6652. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  6653. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  6654. if (property_and_value.has_value()) {
  6655. auto property = property_and_value->property;
  6656. auto value = property_and_value->style_value;
  6657. auto& values = assigned_values.ensure(to_underlying(property));
  6658. if (values.size() + 1 == property_maximum_value_count(property)) {
  6659. // We're done with this property, move on to the next one.
  6660. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  6661. }
  6662. values.append(value.release_nonnull());
  6663. continue;
  6664. }
  6665. // No property matched, so we're done.
  6666. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.next_token().to_debug_string());
  6667. for (auto id : unassigned_properties)
  6668. dbgln(" {}", string_from_property_id(id));
  6669. break;
  6670. }
  6671. for (auto& property : unassigned_properties)
  6672. assigned_values.ensure(to_underlying(property)).append(property_initial_value(m_context.realm(), property));
  6673. stream.discard_whitespace();
  6674. if (stream.has_next_token())
  6675. return ParseError::SyntaxError;
  6676. Vector<PropertyID> longhand_properties;
  6677. longhand_properties.ensure_capacity(assigned_values.size());
  6678. for (auto& it : assigned_values)
  6679. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  6680. StyleValueVector longhand_values;
  6681. longhand_values.ensure_capacity(assigned_values.size());
  6682. for (auto& it : assigned_values) {
  6683. if (it.value.size() == 1)
  6684. longhand_values.unchecked_append(it.value.take_first());
  6685. else
  6686. longhand_values.unchecked_append(StyleValueList::create(move(it.value), StyleValueList::Separator::Space));
  6687. }
  6688. return { ShorthandStyleValue::create(property_id, move(longhand_properties), move(longhand_values)) };
  6689. }
  6690. RefPtr<CSSStyleValue> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6691. {
  6692. return parse_css_value_for_properties({ &property_id, 1 }, tokens)
  6693. .map([](auto& it) { return it.style_value; })
  6694. .value_or(nullptr);
  6695. }
  6696. Optional<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  6697. {
  6698. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  6699. for (auto const& property : property_ids) {
  6700. if (property_accepts_type(property, value_type))
  6701. return property;
  6702. }
  6703. return {};
  6704. };
  6705. auto any_property_accepts_type_percentage = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  6706. for (auto const& property : property_ids) {
  6707. if (property_accepts_type(property, value_type) && property_accepts_type(property, ValueType::Percentage))
  6708. return property;
  6709. }
  6710. return {};
  6711. };
  6712. auto any_property_accepts_keyword = [](ReadonlySpan<PropertyID> property_ids, Keyword keyword) -> Optional<PropertyID> {
  6713. for (auto const& property : property_ids) {
  6714. if (property_accepts_keyword(property, keyword))
  6715. return property;
  6716. }
  6717. return {};
  6718. };
  6719. auto& peek_token = tokens.next_token();
  6720. if (auto property = any_property_accepts_type(property_ids, ValueType::EasingFunction); property.has_value()) {
  6721. if (auto maybe_easing_function = parse_easing_value(tokens))
  6722. return PropertyAndValue { *property, maybe_easing_function };
  6723. }
  6724. if (peek_token.is(Token::Type::Ident)) {
  6725. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  6726. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  6727. auto keyword = keyword_from_string(peek_token.token().ident());
  6728. if (keyword.has_value()) {
  6729. if (auto property = any_property_accepts_keyword(property_ids, keyword.value()); property.has_value()) {
  6730. tokens.discard_a_token();
  6731. return PropertyAndValue { *property, CSSKeywordValue::create(keyword.value()) };
  6732. }
  6733. }
  6734. // Custom idents
  6735. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  6736. if (auto custom_ident = parse_custom_ident_value(tokens, {}))
  6737. return PropertyAndValue { *property, custom_ident };
  6738. }
  6739. }
  6740. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  6741. if (auto maybe_color = parse_color_value(tokens))
  6742. return PropertyAndValue { *property, maybe_color };
  6743. }
  6744. if (auto property = any_property_accepts_type(property_ids, ValueType::Counter); property.has_value()) {
  6745. if (auto maybe_counter = parse_counter_value(tokens))
  6746. return PropertyAndValue { *property, maybe_counter };
  6747. }
  6748. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  6749. if (auto maybe_image = parse_image_value(tokens))
  6750. return PropertyAndValue { *property, maybe_image };
  6751. }
  6752. if (auto property = any_property_accepts_type(property_ids, ValueType::Position); property.has_value()) {
  6753. if (auto maybe_position = parse_position_value(tokens))
  6754. return PropertyAndValue { *property, maybe_position };
  6755. }
  6756. if (auto property = any_property_accepts_type(property_ids, ValueType::BackgroundPosition); property.has_value()) {
  6757. if (auto maybe_position = parse_position_value(tokens, PositionParsingMode::BackgroundPosition))
  6758. return PropertyAndValue { *property, maybe_position };
  6759. }
  6760. if (auto property = any_property_accepts_type(property_ids, ValueType::BasicShape); property.has_value()) {
  6761. if (auto maybe_basic_shape = parse_basic_shape_value(tokens))
  6762. return PropertyAndValue { *property, maybe_basic_shape };
  6763. }
  6764. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  6765. if (auto maybe_ratio = parse_ratio_value(tokens))
  6766. return PropertyAndValue { *property, maybe_ratio };
  6767. }
  6768. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  6769. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  6770. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  6771. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  6772. if (peek_token.token().number().is_integer() && property_accepting_integer.has_value()) {
  6773. auto integer = IntegerStyleValue::create(peek_token.token().number().integer_value());
  6774. if (property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  6775. tokens.discard_a_token(); // integer
  6776. return PropertyAndValue { *property_accepting_integer, integer };
  6777. }
  6778. }
  6779. if (property_accepting_number.has_value()) {
  6780. auto number = NumberStyleValue::create(peek_token.token().number().value());
  6781. if (property_accepts_number(*property_accepting_number, number->as_number().number())) {
  6782. tokens.discard_a_token(); // number
  6783. return PropertyAndValue { *property_accepting_number, number };
  6784. }
  6785. }
  6786. }
  6787. if (auto property = any_property_accepts_type(property_ids, ValueType::OpenTypeTag); property.has_value()) {
  6788. if (auto maybe_rect = parse_opentype_tag_value(tokens))
  6789. return PropertyAndValue { *property, maybe_rect };
  6790. }
  6791. if (peek_token.is(Token::Type::Percentage)) {
  6792. auto percentage = Percentage(peek_token.token().percentage());
  6793. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  6794. tokens.discard_a_token();
  6795. return PropertyAndValue { *property, PercentageStyleValue::create(percentage) };
  6796. }
  6797. }
  6798. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  6799. if (auto maybe_rect = parse_rect_value(tokens))
  6800. return PropertyAndValue { *property, maybe_rect };
  6801. }
  6802. if (peek_token.is(Token::Type::String)) {
  6803. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  6804. return PropertyAndValue { *property, StringStyleValue::create(tokens.consume_a_token().token().string()) };
  6805. }
  6806. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  6807. if (auto url = parse_url_value(tokens))
  6808. return PropertyAndValue { *property, url };
  6809. }
  6810. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  6811. || any_property_accepts_type(property_ids, ValueType::Flex).has_value()
  6812. || any_property_accepts_type(property_ids, ValueType::Frequency).has_value()
  6813. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  6814. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  6815. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  6816. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  6817. if (property_accepts_dimension) {
  6818. if (peek_token.is(Token::Type::Number) && m_context.is_parsing_svg_presentation_attribute()) {
  6819. auto transaction = tokens.begin_transaction();
  6820. auto token = tokens.consume_a_token();
  6821. // https://svgwg.org/svg2-draft/types.html#presentation-attribute-css-value
  6822. // We need to allow <number> in any place that expects a <length> or <angle>.
  6823. // FIXME: How should these numbers be interpreted? https://github.com/w3c/svgwg/issues/792
  6824. // For now: Convert them to px lengths, or deg angles.
  6825. auto angle = Angle::make_degrees(token.token().number_value());
  6826. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  6827. transaction.commit();
  6828. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  6829. }
  6830. auto length = Length::make_px(CSSPixels::nearest_value_for(token.token().number_value()));
  6831. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  6832. transaction.commit();
  6833. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  6834. }
  6835. }
  6836. auto transaction = tokens.begin_transaction();
  6837. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  6838. tokens.discard_a_token();
  6839. auto dimension = maybe_dimension.release_value();
  6840. if (dimension.is_angle()) {
  6841. auto angle = dimension.angle();
  6842. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  6843. transaction.commit();
  6844. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  6845. }
  6846. }
  6847. if (dimension.is_flex()) {
  6848. auto flex = dimension.flex();
  6849. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value() && property_accepts_flex(*property, flex)) {
  6850. transaction.commit();
  6851. return PropertyAndValue { *property, FlexStyleValue::create(flex) };
  6852. }
  6853. }
  6854. if (dimension.is_frequency()) {
  6855. auto frequency = dimension.frequency();
  6856. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  6857. transaction.commit();
  6858. return PropertyAndValue { *property, FrequencyStyleValue::create(frequency) };
  6859. }
  6860. }
  6861. if (dimension.is_length()) {
  6862. auto length = dimension.length();
  6863. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  6864. transaction.commit();
  6865. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  6866. }
  6867. }
  6868. if (dimension.is_resolution()) {
  6869. auto resolution = dimension.resolution();
  6870. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  6871. transaction.commit();
  6872. return PropertyAndValue { *property, ResolutionStyleValue::create(resolution) };
  6873. }
  6874. }
  6875. if (dimension.is_time()) {
  6876. auto time = dimension.time();
  6877. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  6878. transaction.commit();
  6879. return PropertyAndValue { *property, TimeStyleValue::create(time) };
  6880. }
  6881. }
  6882. }
  6883. }
  6884. // In order to not end up parsing `calc()` and other math expressions multiple times,
  6885. // we parse it once, and then see if its resolved type matches what the property accepts.
  6886. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  6887. if (auto maybe_calculated = parse_calculated_value(peek_token); maybe_calculated) {
  6888. tokens.discard_a_token();
  6889. auto& calculated = *maybe_calculated;
  6890. // This is a bit sensitive to ordering: `<foo>` and `<percentage>` have to be checked before `<foo-percentage>`.
  6891. // FIXME: When parsing SVG presentation attributes, <number> is permitted wherever <length>, <length-percentage>, or <angle> are.
  6892. // The specifics are unclear, so I'm ignoring this for calculated values for now.
  6893. // See https://github.com/w3c/svgwg/issues/792
  6894. if (calculated.resolves_to_percentage()) {
  6895. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  6896. return PropertyAndValue { *property, calculated };
  6897. } else if (calculated.resolves_to_angle()) {
  6898. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  6899. return PropertyAndValue { *property, calculated };
  6900. } else if (calculated.resolves_to_angle_percentage()) {
  6901. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Angle); property.has_value())
  6902. return PropertyAndValue { *property, calculated };
  6903. } else if (calculated.resolves_to_flex()) {
  6904. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value())
  6905. return PropertyAndValue { *property, calculated };
  6906. } else if (calculated.resolves_to_frequency()) {
  6907. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  6908. return PropertyAndValue { *property, calculated };
  6909. } else if (calculated.resolves_to_frequency_percentage()) {
  6910. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Frequency); property.has_value())
  6911. return PropertyAndValue { *property, calculated };
  6912. } else if (calculated.resolves_to_number()) {
  6913. if (property_accepts_numeric) {
  6914. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  6915. return PropertyAndValue { property_or_resolved, calculated };
  6916. }
  6917. } else if (calculated.resolves_to_number_percentage()) {
  6918. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Number); property.has_value())
  6919. return PropertyAndValue { *property, calculated };
  6920. } else if (calculated.resolves_to_length()) {
  6921. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  6922. return PropertyAndValue { *property, calculated };
  6923. } else if (calculated.resolves_to_length_percentage()) {
  6924. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Length); property.has_value())
  6925. return PropertyAndValue { *property, calculated };
  6926. } else if (calculated.resolves_to_time()) {
  6927. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  6928. return PropertyAndValue { *property, calculated };
  6929. } else if (calculated.resolves_to_time_percentage()) {
  6930. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Time); property.has_value())
  6931. return PropertyAndValue { *property, calculated };
  6932. }
  6933. }
  6934. }
  6935. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  6936. if (auto value = parse_paint_value(tokens))
  6937. return PropertyAndValue { *property, value.release_nonnull() };
  6938. }
  6939. return OptionalNone {};
  6940. }
  6941. class UnparsedCalculationNode final : public CalculationNode {
  6942. public:
  6943. static NonnullOwnPtr<UnparsedCalculationNode> create(ComponentValue component_value)
  6944. {
  6945. return adopt_own(*new (nothrow) UnparsedCalculationNode(move(component_value)));
  6946. }
  6947. virtual ~UnparsedCalculationNode() = default;
  6948. ComponentValue& component_value() { return m_component_value; }
  6949. virtual String to_string() const override { VERIFY_NOT_REACHED(); }
  6950. virtual Optional<CSSMathValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  6951. virtual Optional<CSSNumericType> determine_type(Web::CSS::PropertyID) const override { VERIFY_NOT_REACHED(); }
  6952. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  6953. virtual CSSMathValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CSSMathValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  6954. virtual void for_each_child_node(AK::Function<void(NonnullOwnPtr<CalculationNode>&)> const&) override { }
  6955. virtual void dump(StringBuilder& builder, int indent) const override
  6956. {
  6957. builder.appendff("{: >{}}UNPARSED({})\n", "", indent, m_component_value.to_debug_string());
  6958. }
  6959. virtual bool equals(CalculationNode const&) const override { return false; }
  6960. private:
  6961. UnparsedCalculationNode(ComponentValue component_value)
  6962. : CalculationNode(Type::Unparsed)
  6963. , m_component_value(move(component_value))
  6964. {
  6965. }
  6966. ComponentValue m_component_value;
  6967. };
  6968. // https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
  6969. LengthOrCalculated Parser::Parser::parse_as_sizes_attribute(DOM::Element const& element, HTML::HTMLImageElement const* img)
  6970. {
  6971. // When asked to parse a sizes attribute from an element element, with an img element or null img:
  6972. // AD-HOC: If element has no sizes attribute, this algorithm always logs a parse error and then returns 100vw.
  6973. // The attribute is optional, so avoid spamming the debug log with false positives by just returning early.
  6974. if (!element.has_attribute(HTML::AttributeNames::sizes))
  6975. return Length(100, Length::Type::Vw);
  6976. // 1. Let unparsed sizes list be the result of parsing a comma-separated list of component values
  6977. // from the value of element's sizes attribute (or the empty string, if the attribute is absent).
  6978. // NOTE: The sizes attribute has already been tokenized into m_token_stream by this point.
  6979. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  6980. // 2. Let size be null.
  6981. Optional<LengthOrCalculated> size;
  6982. auto size_is_auto = [&size]() {
  6983. return !size->is_calculated() && size->value().is_auto();
  6984. };
  6985. auto remove_all_consecutive_whitespace_tokens_from_the_end_of = [](auto& tokens) {
  6986. while (!tokens.is_empty() && tokens.last().is_token() && tokens.last().token().is(Token::Type::Whitespace))
  6987. tokens.take_last();
  6988. };
  6989. // 3. For each unparsed size in unparsed sizes list:
  6990. for (auto i = 0u; i < unparsed_sizes_list.size(); i++) {
  6991. auto& unparsed_size = unparsed_sizes_list[i];
  6992. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  6993. // If unparsed size is now empty, that is a parse error; continue.
  6994. remove_all_consecutive_whitespace_tokens_from_the_end_of(unparsed_size);
  6995. if (unparsed_size.is_empty()) {
  6996. log_parse_error();
  6997. dbgln_if(CSS_PARSER_DEBUG, "-> Failed in step 3.1; all whitespace");
  6998. continue;
  6999. }
  7000. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  7001. // then set size to its value and remove the component value from unparsed size.
  7002. // Any CSS function other than the math functions is invalid.
  7003. // Otherwise, there is a parse error; continue.
  7004. auto last_value_stream = TokenStream<ComponentValue>::of_single_token(unparsed_size.last());
  7005. if (auto source_size_value = parse_source_size_value(last_value_stream); source_size_value.has_value()) {
  7006. size = source_size_value.value();
  7007. unparsed_size.take_last();
  7008. } else {
  7009. log_parse_error();
  7010. dbgln_if(CSS_PARSER_DEBUG, "-> Failed in step 3.2; couldn't parse {} as a <source-size-value>", unparsed_size.last().to_debug_string());
  7011. continue;
  7012. }
  7013. // 3. If size is auto, and img is not null, and img is being rendered, and img allows auto-sizes,
  7014. // then set size to the concrete object size width of img, in CSS pixels.
  7015. // FIXME: "img is being rendered" - we just see if it has a bitmap for now
  7016. if (size_is_auto() && img && img->immutable_bitmap() && img->allows_auto_sizes()) {
  7017. // FIXME: The spec doesn't seem to tell us how to determine the concrete size of an <img>, so use the default sizing algorithm.
  7018. // Should this use some of the methods from FormattingContext?
  7019. auto concrete_size = run_default_sizing_algorithm(
  7020. img->width(), img->height(),
  7021. img->natural_width(), img->natural_height(), img->intrinsic_aspect_ratio(),
  7022. // NOTE: https://html.spec.whatwg.org/multipage/rendering.html#img-contain-size
  7023. CSSPixelSize { 300, 150 });
  7024. size = Length::make_px(concrete_size.width());
  7025. }
  7026. // 4. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7027. // If unparsed size is now empty:
  7028. remove_all_consecutive_whitespace_tokens_from_the_end_of(unparsed_size);
  7029. if (unparsed_size.is_empty()) {
  7030. // 1. If this was not the last item in unparsed sizes list, that is a parse error.
  7031. if (i != unparsed_sizes_list.size() - 1) {
  7032. log_parse_error();
  7033. dbgln_if(CSS_PARSER_DEBUG, "-> Failed in step 3.4.1; is unparsed size #{}, count {}", i, unparsed_sizes_list.size());
  7034. }
  7035. // 2. If size is not auto, then return size. Otherwise, continue.
  7036. if (!size_is_auto())
  7037. return size.release_value();
  7038. continue;
  7039. }
  7040. // 5. Parse the remaining component values in unparsed size as a <media-condition>.
  7041. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  7042. TokenStream<ComponentValue> token_stream { unparsed_size };
  7043. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  7044. auto const* context_window = m_context.window();
  7045. if (!media_condition || (context_window && media_condition->evaluate(*context_window) == MatchResult::False)) {
  7046. continue;
  7047. }
  7048. // 5. If size is not auto, then return size. Otherwise, continue.
  7049. if (!size_is_auto())
  7050. return size.value();
  7051. }
  7052. // 4. Return 100vw.
  7053. return Length(100, Length::Type::Vw);
  7054. }
  7055. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  7056. OwnPtr<CalculationNode> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  7057. {
  7058. // 1. Discard any <whitespace-token>s from values.
  7059. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  7060. struct Operator {
  7061. char delim;
  7062. };
  7063. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  7064. Vector<Value> values;
  7065. for (auto& value : original_values) {
  7066. if (value.is(Token::Type::Whitespace))
  7067. continue;
  7068. if (value.is(Token::Type::Delim)) {
  7069. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  7070. // NOTE: Sequential operators are invalid syntax.
  7071. if (!values.is_empty() && values.last().has<Operator>())
  7072. return nullptr;
  7073. values.append(Operator { static_cast<char>(value.token().delim()) });
  7074. continue;
  7075. }
  7076. }
  7077. if (value.is(Token::Type::Ident)) {
  7078. auto maybe_constant = CalculationNode::constant_type_from_string(value.token().ident());
  7079. if (maybe_constant.has_value()) {
  7080. values.append({ ConstantCalculationNode::create(maybe_constant.value()) });
  7081. continue;
  7082. }
  7083. }
  7084. if (value.is(Token::Type::Number)) {
  7085. values.append({ NumericCalculationNode::create(value.token().number()) });
  7086. continue;
  7087. }
  7088. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  7089. if (dimension->is_angle())
  7090. values.append({ NumericCalculationNode::create(dimension->angle()) });
  7091. else if (dimension->is_frequency())
  7092. values.append({ NumericCalculationNode::create(dimension->frequency()) });
  7093. else if (dimension->is_length())
  7094. values.append({ NumericCalculationNode::create(dimension->length()) });
  7095. else if (dimension->is_percentage())
  7096. values.append({ NumericCalculationNode::create(dimension->percentage()) });
  7097. else if (dimension->is_resolution())
  7098. values.append({ NumericCalculationNode::create(dimension->resolution()) });
  7099. else if (dimension->is_time())
  7100. values.append({ NumericCalculationNode::create(dimension->time()) });
  7101. else if (dimension->is_flex()) {
  7102. // https://www.w3.org/TR/css3-grid-layout/#fr-unit
  7103. // NOTE: <flex> values are not <length>s (nor are they compatible with <length>s, like some <percentage> values),
  7104. // so they cannot be represented in or combined with other unit types in calc() expressions.
  7105. return nullptr;
  7106. } else {
  7107. VERIFY_NOT_REACHED();
  7108. }
  7109. continue;
  7110. }
  7111. values.append({ UnparsedCalculationNode::create(value) });
  7112. }
  7113. // If we have no values, the syntax is invalid.
  7114. if (values.is_empty())
  7115. return nullptr;
  7116. // NOTE: If the first or last value is an operator, the syntax is invalid.
  7117. if (values.first().has<Operator>() || values.last().has<Operator>())
  7118. return nullptr;
  7119. // 3. Collect children into Product and Invert nodes.
  7120. // For every consecutive run of value items in values separated by "*" or "/" operators:
  7121. while (true) {
  7122. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  7123. return item.template has<Operator>()
  7124. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  7125. });
  7126. if (!first_product_operator.has_value())
  7127. break;
  7128. auto start_of_run = first_product_operator.value() - 1;
  7129. auto end_of_run = first_product_operator.value() + 1;
  7130. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  7131. auto& item = values[i];
  7132. if (!item.has<Operator>()) {
  7133. end_of_run = i - 1;
  7134. break;
  7135. }
  7136. auto delim = item.get<Operator>().delim;
  7137. if (!first_is_one_of(delim, '*', '/')) {
  7138. end_of_run = i - 1;
  7139. break;
  7140. }
  7141. }
  7142. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  7143. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  7144. run_values.append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>()));
  7145. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  7146. auto& operator_ = values[i].get<Operator>().delim;
  7147. auto& rhs = values[i + 1];
  7148. if (operator_ == '/') {
  7149. run_values.append(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7150. continue;
  7151. }
  7152. VERIFY(operator_ == '*');
  7153. run_values.append(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  7154. }
  7155. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  7156. auto product_node = ProductCalculationNode::create(move(run_values));
  7157. values.remove(start_of_run, end_of_run - start_of_run + 1);
  7158. values.insert(start_of_run, { move(product_node) });
  7159. }
  7160. // 4. Collect children into Sum and Negate nodes.
  7161. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  7162. {
  7163. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  7164. for (auto i = 0u; i < values.size(); ++i) {
  7165. auto& maybe_minus_operator = values[i];
  7166. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  7167. continue;
  7168. auto rhs_index = ++i;
  7169. auto& rhs = values[rhs_index];
  7170. NonnullOwnPtr<CalculationNode> negate_node = NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  7171. values.remove(rhs_index);
  7172. values.insert(rhs_index, move(negate_node));
  7173. }
  7174. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  7175. if (values.size() == 1) {
  7176. values.first().visit(
  7177. [&](ComponentValue& component_value) {
  7178. if (component_value.is_block() && component_value.block().is_paren())
  7179. single_value = UnparsedCalculationNode::create(component_value);
  7180. },
  7181. [&](NonnullOwnPtr<CalculationNode>& node) {
  7182. if (node->type() == CalculationNode::Type::Product)
  7183. single_value = move(node);
  7184. },
  7185. [](auto&) {});
  7186. }
  7187. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  7188. if (!single_value.has_value()) {
  7189. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  7190. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  7191. value_items.ensure_capacity(values.size());
  7192. for (auto& value : values) {
  7193. if (value.has<Operator>())
  7194. continue;
  7195. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  7196. }
  7197. single_value = SumCalculationNode::create(move(value_items));
  7198. }
  7199. }
  7200. // 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.
  7201. // For every leaf node leaf in values:
  7202. bool parsing_failed_for_child_node = false;
  7203. single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) {
  7204. if (node->type() != CalculationNode::Type::Unparsed)
  7205. return;
  7206. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  7207. auto& component_value = unparsed_node.component_value();
  7208. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  7209. if (component_value.is_block() && component_value.block().is_paren()) {
  7210. auto leaf_calculation = parse_a_calculation(component_value.block().value);
  7211. if (!leaf_calculation) {
  7212. parsing_failed_for_child_node = true;
  7213. return;
  7214. }
  7215. node = leaf_calculation.release_nonnull();
  7216. return;
  7217. }
  7218. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  7219. // NOTE: All function tokens at this point should be math functions.
  7220. else if (component_value.is_function()) {
  7221. auto& function = component_value.function();
  7222. auto leaf_calculation = parse_a_calc_function_node(function);
  7223. if (!leaf_calculation) {
  7224. parsing_failed_for_child_node = true;
  7225. return;
  7226. }
  7227. node = leaf_calculation.release_nonnull();
  7228. return;
  7229. }
  7230. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  7231. // So, the calc() is invalid.
  7232. 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());
  7233. parsing_failed_for_child_node = true;
  7234. return;
  7235. });
  7236. if (parsing_failed_for_child_node)
  7237. return nullptr;
  7238. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  7239. return single_value.release_value();
  7240. }
  7241. bool Parser::has_ignored_vendor_prefix(StringView string)
  7242. {
  7243. if (!string.starts_with('-'))
  7244. return false;
  7245. if (string.starts_with("--"sv))
  7246. return false;
  7247. if (string.starts_with("-libweb-"sv))
  7248. return false;
  7249. return true;
  7250. }
  7251. 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)
  7252. {
  7253. // Unresolved always contains a var() or attr(), unless it is a custom property's value, in which case we shouldn't be trying
  7254. // to produce a different CSSStyleValue from it.
  7255. VERIFY(unresolved.contains_var_or_attr());
  7256. // If the value is invalid, we fall back to `unset`: https://www.w3.org/TR/css-variables-1/#invalid-at-computed-value-time
  7257. auto parser = Parser::create(context, ""sv);
  7258. return parser.resolve_unresolved_style_value(element, pseudo_element, property_id, unresolved);
  7259. }
  7260. class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> {
  7261. public:
  7262. static NonnullRefPtr<PropertyDependencyNode> create(FlyString name)
  7263. {
  7264. return adopt_ref(*new PropertyDependencyNode(move(name)));
  7265. }
  7266. void add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  7267. {
  7268. for (auto const& child : m_children) {
  7269. if (child->m_name == new_child->m_name)
  7270. return;
  7271. }
  7272. // We detect self-reference already.
  7273. VERIFY(new_child->m_name != m_name);
  7274. m_children.append(move(new_child));
  7275. }
  7276. bool has_cycles()
  7277. {
  7278. if (m_marked)
  7279. return true;
  7280. TemporaryChange change { m_marked, true };
  7281. for (auto& child : m_children) {
  7282. if (child->has_cycles())
  7283. return true;
  7284. }
  7285. return false;
  7286. }
  7287. private:
  7288. explicit PropertyDependencyNode(FlyString name)
  7289. : m_name(move(name))
  7290. {
  7291. }
  7292. FlyString m_name;
  7293. Vector<NonnullRefPtr<PropertyDependencyNode>> m_children;
  7294. bool m_marked { false };
  7295. };
  7296. NonnullRefPtr<CSSStyleValue> Parser::resolve_unresolved_style_value(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  7297. {
  7298. TokenStream unresolved_values_without_variables_expanded { unresolved.values() };
  7299. Vector<ComponentValue> values_with_variables_expanded;
  7300. HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  7301. if (!expand_variables(element, pseudo_element, string_from_property_id(property_id), dependencies, unresolved_values_without_variables_expanded, values_with_variables_expanded))
  7302. return CSSKeywordValue::create(Keyword::Unset);
  7303. TokenStream unresolved_values_with_variables_expanded { values_with_variables_expanded };
  7304. Vector<ComponentValue> expanded_values;
  7305. if (!expand_unresolved_values(element, string_from_property_id(property_id), unresolved_values_with_variables_expanded, expanded_values))
  7306. return CSSKeywordValue::create(Keyword::Unset);
  7307. auto expanded_value_tokens = TokenStream { expanded_values };
  7308. if (auto parsed_value = parse_css_value(property_id, expanded_value_tokens); !parsed_value.is_error())
  7309. return parsed_value.release_value();
  7310. return CSSKeywordValue::create(Keyword::Unset);
  7311. }
  7312. static RefPtr<CSSStyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, FlyString const& custom_property_name)
  7313. {
  7314. if (pseudo_element.has_value()) {
  7315. if (auto it = element.custom_properties(pseudo_element).find(custom_property_name); it != element.custom_properties(pseudo_element).end())
  7316. return it->value.value;
  7317. }
  7318. for (auto const* current_element = &element; current_element; current_element = current_element->parent_or_shadow_host_element()) {
  7319. if (auto it = current_element->custom_properties({}).find(custom_property_name); it != current_element->custom_properties({}).end())
  7320. return it->value.value;
  7321. }
  7322. return nullptr;
  7323. }
  7324. 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)
  7325. {
  7326. // Arbitrary large value chosen to avoid the billion-laughs attack.
  7327. // https://www.w3.org/TR/css-variables-1/#long-variables
  7328. size_t const MAX_VALUE_COUNT = 16384;
  7329. if (source.remaining_token_count() + dest.size() > MAX_VALUE_COUNT) {
  7330. dbgln("Stopped expanding CSS variables: maximum length reached.");
  7331. return false;
  7332. }
  7333. auto get_dependency_node = [&](FlyString const& name) -> NonnullRefPtr<PropertyDependencyNode> {
  7334. if (auto existing = dependencies.get(name); existing.has_value())
  7335. return *existing.value();
  7336. auto new_node = PropertyDependencyNode::create(name);
  7337. dependencies.set(name, new_node);
  7338. return new_node;
  7339. };
  7340. while (source.has_next_token()) {
  7341. auto const& value = source.consume_a_token();
  7342. if (value.is_block()) {
  7343. auto const& source_block = value.block();
  7344. Vector<ComponentValue> block_values;
  7345. TokenStream source_block_contents { source_block.value };
  7346. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_block_contents, block_values))
  7347. return false;
  7348. dest.empend(SimpleBlock { source_block.token, move(block_values) });
  7349. continue;
  7350. }
  7351. if (!value.is_function()) {
  7352. dest.empend(value);
  7353. continue;
  7354. }
  7355. if (!value.function().name.equals_ignoring_ascii_case("var"sv)) {
  7356. auto const& source_function = value.function();
  7357. Vector<ComponentValue> function_values;
  7358. TokenStream source_function_contents { source_function.value };
  7359. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_function_contents, function_values))
  7360. return false;
  7361. dest.empend(Function { source_function.name, move(function_values) });
  7362. continue;
  7363. }
  7364. TokenStream var_contents { value.function().value };
  7365. var_contents.discard_whitespace();
  7366. if (!var_contents.has_next_token())
  7367. return false;
  7368. auto const& custom_property_name_token = var_contents.consume_a_token();
  7369. if (!custom_property_name_token.is(Token::Type::Ident))
  7370. return false;
  7371. auto custom_property_name = custom_property_name_token.token().ident();
  7372. if (!custom_property_name.bytes_as_string_view().starts_with("--"sv))
  7373. return false;
  7374. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  7375. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  7376. // but rebuilding it every time.
  7377. if (custom_property_name == property_name)
  7378. return false;
  7379. auto parent = get_dependency_node(property_name);
  7380. auto child = get_dependency_node(custom_property_name);
  7381. parent->add_child(child);
  7382. if (parent->has_cycles())
  7383. return false;
  7384. if (auto custom_property_value = get_custom_property(element, pseudo_element, custom_property_name)) {
  7385. VERIFY(custom_property_value->is_unresolved());
  7386. TokenStream custom_property_tokens { custom_property_value->as_unresolved().values() };
  7387. if (!expand_variables(element, pseudo_element, custom_property_name, dependencies, custom_property_tokens, dest))
  7388. return false;
  7389. continue;
  7390. }
  7391. // Use the provided fallback value, if any.
  7392. var_contents.discard_whitespace();
  7393. if (var_contents.has_next_token()) {
  7394. auto const& comma_token = var_contents.consume_a_token();
  7395. if (!comma_token.is(Token::Type::Comma))
  7396. return false;
  7397. var_contents.discard_whitespace();
  7398. if (!expand_variables(element, pseudo_element, property_name, dependencies, var_contents, dest))
  7399. return false;
  7400. }
  7401. }
  7402. return true;
  7403. }
  7404. bool Parser::expand_unresolved_values(DOM::Element& element, FlyString const& property_name, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  7405. {
  7406. auto property = property_id_from_string(property_name);
  7407. while (source.has_next_token()) {
  7408. auto const& value = source.consume_a_token();
  7409. if (value.is_function()) {
  7410. if (value.function().name.equals_ignoring_ascii_case("attr"sv)) {
  7411. if (!substitute_attr_function(element, property_name, value.function(), dest))
  7412. return false;
  7413. continue;
  7414. }
  7415. if (property.has_value()) {
  7416. if (auto maybe_calc_value = parse_calculated_value(value); maybe_calc_value && maybe_calc_value->is_math()) {
  7417. // FIXME: Run the actual simplification algorithm
  7418. auto& calc_value = maybe_calc_value->as_math();
  7419. if (property_accepts_type(*property, ValueType::Angle) && calc_value.resolves_to_angle()) {
  7420. auto resolved_value = calc_value.resolve_angle();
  7421. dest.empend(Token::create_dimension(resolved_value->to_degrees(), "deg"_fly_string));
  7422. continue;
  7423. }
  7424. if (property_accepts_type(*property, ValueType::Frequency) && calc_value.resolves_to_frequency()) {
  7425. auto resolved_value = calc_value.resolve_frequency();
  7426. dest.empend(Token::create_dimension(resolved_value->to_hertz(), "hz"_fly_string));
  7427. continue;
  7428. }
  7429. if (property_accepts_type(*property, ValueType::Length) && calc_value.resolves_to_length()) {
  7430. // FIXME: In order to resolve lengths, we need to know the font metrics in case a font-relative unit
  7431. // is used. So... we can't do that until style is computed?
  7432. // This might be easier once we have calc-simplification implemented.
  7433. }
  7434. if (property_accepts_type(*property, ValueType::Percentage) && calc_value.resolves_to_percentage()) {
  7435. auto resolved_value = calc_value.resolve_percentage();
  7436. dest.empend(Token::create_percentage(resolved_value.value().value()));
  7437. continue;
  7438. }
  7439. if (property_accepts_type(*property, ValueType::Time) && calc_value.resolves_to_time()) {
  7440. auto resolved_value = calc_value.resolve_time();
  7441. dest.empend(Token::create_dimension(resolved_value->to_seconds(), "s"_fly_string));
  7442. continue;
  7443. }
  7444. if (property_accepts_type(*property, ValueType::Number) && calc_value.resolves_to_number()) {
  7445. auto resolved_value = calc_value.resolve_number();
  7446. dest.empend(Token::create_number(resolved_value.value(), Number::Type::Number));
  7447. continue;
  7448. }
  7449. if (property_accepts_type(*property, ValueType::Integer) && calc_value.resolves_to_number()) {
  7450. auto resolved_value = calc_value.resolve_integer();
  7451. dest.empend(Token::create_number(resolved_value.value(), Number::Type::Integer));
  7452. continue;
  7453. }
  7454. }
  7455. }
  7456. auto const& source_function = value.function();
  7457. Vector<ComponentValue> function_values;
  7458. TokenStream source_function_contents { source_function.value };
  7459. if (!expand_unresolved_values(element, property_name, source_function_contents, function_values))
  7460. return false;
  7461. dest.empend(Function { source_function.name, move(function_values) });
  7462. continue;
  7463. }
  7464. if (value.is_block()) {
  7465. auto const& source_block = value.block();
  7466. TokenStream source_block_values { source_block.value };
  7467. Vector<ComponentValue> block_values;
  7468. if (!expand_unresolved_values(element, property_name, source_block_values, block_values))
  7469. return false;
  7470. dest.empend(SimpleBlock { source_block.token, move(block_values) });
  7471. continue;
  7472. }
  7473. dest.empend(value.token());
  7474. }
  7475. return true;
  7476. }
  7477. // https://drafts.csswg.org/css-values-5/#attr-substitution
  7478. bool Parser::substitute_attr_function(DOM::Element& element, FlyString const& property_name, Function const& attr_function, Vector<ComponentValue>& dest)
  7479. {
  7480. // First, parse the arguments to attr():
  7481. // attr() = attr( <q-name> <attr-type>? , <declaration-value>?)
  7482. // <attr-type> = string | url | ident | color | number | percentage | length | angle | time | frequency | flex | <dimension-unit>
  7483. TokenStream attr_contents { attr_function.value };
  7484. attr_contents.discard_whitespace();
  7485. if (!attr_contents.has_next_token())
  7486. return false;
  7487. // - Attribute name
  7488. // FIXME: Support optional attribute namespace
  7489. if (!attr_contents.next_token().is(Token::Type::Ident))
  7490. return false;
  7491. auto attribute_name = attr_contents.consume_a_token().token().ident();
  7492. attr_contents.discard_whitespace();
  7493. // - Attribute type (optional)
  7494. auto attribute_type = "string"_fly_string;
  7495. if (attr_contents.next_token().is(Token::Type::Ident)) {
  7496. attribute_type = attr_contents.consume_a_token().token().ident();
  7497. attr_contents.discard_whitespace();
  7498. }
  7499. // - Comma, then fallback values (optional)
  7500. bool has_fallback_values = false;
  7501. if (attr_contents.has_next_token()) {
  7502. if (!attr_contents.next_token().is(Token::Type::Comma))
  7503. return false;
  7504. (void)attr_contents.consume_a_token(); // Comma
  7505. has_fallback_values = true;
  7506. }
  7507. // Then, run the substitution algorithm:
  7508. // 1. If the attr() function has a substitution value, replace the attr() function by the substitution value.
  7509. // https://drafts.csswg.org/css-values-5/#attr-types
  7510. if (element.has_attribute(attribute_name)) {
  7511. auto attribute_value = element.get_attribute_value(attribute_name);
  7512. if (attribute_type.equals_ignoring_ascii_case("angle"_fly_string)) {
  7513. // Parse a component value from the attribute’s value.
  7514. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7515. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7516. // Otherwise, there is no substitution value.
  7517. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7518. if (Angle::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7519. dest.append(component_value.release_value());
  7520. return true;
  7521. }
  7522. }
  7523. } else if (attribute_type.equals_ignoring_ascii_case("color"_fly_string)) {
  7524. // Parse a component value from the attribute’s value.
  7525. // If the result is a <hex-color> or a named color ident, the substitution value is that result as a <color>.
  7526. // Otherwise there is no substitution value.
  7527. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7528. if (component_value.has_value()) {
  7529. if ((component_value->is(Token::Type::Hash)
  7530. && Color::from_string(MUST(String::formatted("#{}", component_value->token().hash_value()))).has_value())
  7531. || (component_value->is(Token::Type::Ident)
  7532. && Color::from_string(component_value->token().ident()).has_value())) {
  7533. dest.append(component_value.release_value());
  7534. return true;
  7535. }
  7536. }
  7537. } else if (attribute_type.equals_ignoring_ascii_case("flex"_fly_string)) {
  7538. // Parse a component value from the attribute’s value.
  7539. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7540. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7541. // Otherwise, there is no substitution value.
  7542. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7543. if (Flex::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7544. dest.append(component_value.release_value());
  7545. return true;
  7546. }
  7547. }
  7548. } else if (attribute_type.equals_ignoring_ascii_case("frequency"_fly_string)) {
  7549. // Parse a component value from the attribute’s value.
  7550. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7551. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7552. // Otherwise, there is no substitution value.
  7553. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7554. if (Frequency::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7555. dest.append(component_value.release_value());
  7556. return true;
  7557. }
  7558. }
  7559. } else if (attribute_type.equals_ignoring_ascii_case("ident"_fly_string)) {
  7560. // The substitution value is a CSS <custom-ident>, whose value is the literal value of the attribute,
  7561. // with leading and trailing ASCII whitespace stripped. (No CSS parsing of the value is performed.)
  7562. // If the attribute value, after trimming, is the empty string, there is instead no substitution value.
  7563. // If the <custom-ident>’s value is a CSS-wide keyword or `default`, there is instead no substitution value.
  7564. auto substitution_value = MUST(attribute_value.trim(Infra::ASCII_WHITESPACE));
  7565. if (!substitution_value.is_empty()
  7566. && !substitution_value.equals_ignoring_ascii_case("default"sv)
  7567. && !is_css_wide_keyword(substitution_value)) {
  7568. dest.empend(Token::create_ident(substitution_value));
  7569. return true;
  7570. }
  7571. } else if (attribute_type.equals_ignoring_ascii_case("length"_fly_string)) {
  7572. // Parse a component value from the attribute’s value.
  7573. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7574. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7575. // Otherwise, there is no substitution value.
  7576. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7577. if (Length::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7578. dest.append(component_value.release_value());
  7579. return true;
  7580. }
  7581. }
  7582. } else if (attribute_type.equals_ignoring_ascii_case("number"_fly_string)) {
  7583. // Parse a component value from the attribute’s value.
  7584. // If the result is a <number-token>, the result is the substitution value.
  7585. // Otherwise, there is no substitution value.
  7586. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7587. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  7588. dest.append(component_value.release_value());
  7589. return true;
  7590. }
  7591. } else if (attribute_type.equals_ignoring_ascii_case("percentage"_fly_string)) {
  7592. // Parse a component value from the attribute’s value.
  7593. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7594. // If the result is a <percentage-token>, the result is the substitution value.
  7595. // Otherwise, there is no substitution value.
  7596. if (component_value.has_value() && component_value->is(Token::Type::Percentage)) {
  7597. dest.append(component_value.release_value());
  7598. return true;
  7599. }
  7600. } else if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  7601. // The substitution value is a CSS string, whose value is the literal value of the attribute.
  7602. // (No CSS parsing or "cleanup" of the value is performed.)
  7603. // No value triggers fallback.
  7604. dest.empend(Token::create_string(attribute_value));
  7605. return true;
  7606. } else if (attribute_type.equals_ignoring_ascii_case("time"_fly_string)) {
  7607. // Parse a component value from the attribute’s value.
  7608. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7609. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7610. // Otherwise, there is no substitution value.
  7611. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7612. if (Time::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7613. dest.append(component_value.release_value());
  7614. return true;
  7615. }
  7616. }
  7617. } else if (attribute_type.equals_ignoring_ascii_case("url"_fly_string)) {
  7618. // The substitution value is a CSS <url> value, whose url is the literal value of the attribute.
  7619. // (No CSS parsing or "cleanup" of the value is performed.)
  7620. // No value triggers fallback.
  7621. dest.empend(Token::create_url(attribute_value));
  7622. return true;
  7623. } else {
  7624. // Dimension units
  7625. // Parse a component value from the attribute’s value.
  7626. // If the result is a <number-token>, the substitution value is a dimension with the result’s value, and the given unit.
  7627. // Otherwise, there is no substitution value.
  7628. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7629. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  7630. if (attribute_value == "%"sv) {
  7631. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7632. return true;
  7633. } else if (auto angle_unit = Angle::unit_from_name(attribute_type); angle_unit.has_value()) {
  7634. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7635. return true;
  7636. } else if (auto flex_unit = Flex::unit_from_name(attribute_type); flex_unit.has_value()) {
  7637. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7638. return true;
  7639. } else if (auto frequency_unit = Frequency::unit_from_name(attribute_type); frequency_unit.has_value()) {
  7640. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7641. return true;
  7642. } else if (auto length_unit = Length::unit_from_name(attribute_type); length_unit.has_value()) {
  7643. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7644. return true;
  7645. } else if (auto time_unit = Time::unit_from_name(attribute_type); time_unit.has_value()) {
  7646. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7647. return true;
  7648. } else {
  7649. // Not a dimension unit.
  7650. return false;
  7651. }
  7652. }
  7653. }
  7654. }
  7655. // 2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value.
  7656. // If there are any var() or attr() references in the fallback, substitute them as well.
  7657. if (has_fallback_values)
  7658. return expand_unresolved_values(element, property_name, attr_contents, dest);
  7659. if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  7660. // If the <attr-type> argument is string, defaults to the empty string if omitted
  7661. dest.empend(Token::create_string({}));
  7662. return true;
  7663. }
  7664. // 3. Otherwise, the property containing the attr() function is invalid at computed-value time.
  7665. return false;
  7666. }
  7667. // https://drafts.csswg.org/css-fonts/#typedef-opentype-tag
  7668. RefPtr<StringStyleValue> Parser::parse_opentype_tag_value(TokenStream<ComponentValue>& tokens)
  7669. {
  7670. // <opentype-tag> = <string>
  7671. // The <opentype-tag> is a case-sensitive OpenType feature tag.
  7672. // As specified in the OpenType specification [OPENTYPE], feature tags contain four ASCII characters.
  7673. // Tag strings longer or shorter than four characters, or containing characters outside the U+20–7E codepoint range are invalid.
  7674. auto transaction = tokens.begin_transaction();
  7675. auto string_value = parse_string_value(tokens);
  7676. if (string_value == nullptr)
  7677. return nullptr;
  7678. auto string = string_value->string_value().bytes_as_string_view();
  7679. if (string.length() != 4)
  7680. return nullptr;
  7681. for (char c : string) {
  7682. if (c < 0x20 || c > 0x7E)
  7683. return nullptr;
  7684. }
  7685. transaction.commit();
  7686. return string_value;
  7687. }
  7688. }