Parser.cpp 348 KB

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