Parser.cpp 353 KB

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