Parser.cpp 341 KB

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