Parser.cpp 340 KB

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