Parser.cpp 301 KB

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