Parser.cpp 297 KB

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