Parser.cpp 404 KB

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