Parser.cpp 375 KB

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