Parser.cpp 351 KB

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