Parser.cpp 301 KB

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