Parser.cpp 403 KB

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