Parser.cpp 300 KB

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