Parser.cpp 302 KB

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