Parser.cpp 369 KB

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