Parser.cpp 391 KB

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