Parser.cpp 338 KB

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