Parser.cpp 364 KB

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