Parser.cpp 289 KB

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