Parser.cpp 296 KB

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