Parser.cpp 382 KB

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