Parser.cpp 268 KB

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