Parser.cpp 375 KB

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