Parser.cpp 292 KB

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