Parser.cpp 306 KB

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