Parser.cpp 387 KB

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