Parser.cpp 282 KB

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