Parser.cpp 404 KB

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