Parser.cpp 283 KB

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