Parser.cpp 359 KB

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