Parser.cpp 328 KB

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