Parser.cpp 353 KB

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