Parser.cpp 376 KB

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