Parser.cpp 302 KB

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