Parser.cpp 366 KB

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