Parser.cpp 301 KB

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