Parser.cpp 359 KB

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