Parser.cpp 302 KB

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