Parser.cpp 301 KB

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