Parser.cpp 269 KB

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