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