Parser.cpp 385 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280
  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/CSSOKLCH.h>
  51. #include <LibWeb/CSS/StyleValues/CSSOKLab.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. // https://www.w3.org/TR/css-color-4/#funcdef-oklab
  2759. RefPtr<CSSStyleValue> Parser::parse_oklab_color_value(TokenStream<ComponentValue>& outer_tokens)
  2760. {
  2761. // oklab() = oklab( [ <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("oklab"sv))
  2769. return {};
  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 {};
  2779. inner_tokens.discard_whitespace();
  2780. a = parse_number_percentage_value(inner_tokens);
  2781. if (!a)
  2782. return {};
  2783. inner_tokens.discard_whitespace();
  2784. b = parse_number_percentage_value(inner_tokens);
  2785. if (!b)
  2786. return {};
  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 {};
  2792. }
  2793. if (!alpha)
  2794. alpha = NumberStyleValue::create(1);
  2795. transaction.commit();
  2796. return CSSOKLab::create(l.release_nonnull(), a.release_nonnull(), b.release_nonnull(), alpha.release_nonnull());
  2797. }
  2798. // https://www.w3.org/TR/css-color-4/#funcdef-oklch
  2799. RefPtr<CSSStyleValue> Parser::parse_oklch_color_value(TokenStream<ComponentValue>& outer_tokens)
  2800. {
  2801. // oklch() = oklch( [ <percentage> | <number> | none]
  2802. // [ <percentage> | <number> | none]
  2803. // [ <hue> | none]
  2804. // [ / [<alpha-value> | none] ]? )
  2805. auto transaction = outer_tokens.begin_transaction();
  2806. outer_tokens.discard_whitespace();
  2807. auto& function_token = outer_tokens.consume_a_token();
  2808. if (!function_token.is_function("oklch"sv))
  2809. return {};
  2810. RefPtr<CSSStyleValue> l;
  2811. RefPtr<CSSStyleValue> c;
  2812. RefPtr<CSSStyleValue> h;
  2813. RefPtr<CSSStyleValue> alpha;
  2814. auto inner_tokens = TokenStream { function_token.function().value };
  2815. inner_tokens.discard_whitespace();
  2816. l = parse_number_percentage_value(inner_tokens);
  2817. if (!l)
  2818. return {};
  2819. inner_tokens.discard_whitespace();
  2820. c = parse_number_percentage_value(inner_tokens);
  2821. if (!c)
  2822. return {};
  2823. inner_tokens.discard_whitespace();
  2824. h = parse_hue_value(inner_tokens);
  2825. if (!h)
  2826. return {};
  2827. inner_tokens.discard_whitespace();
  2828. if (inner_tokens.has_next_token()) {
  2829. alpha = parse_solidus_and_alpha_value(inner_tokens);
  2830. if (!alpha || inner_tokens.has_next_token())
  2831. return {};
  2832. }
  2833. if (!alpha)
  2834. alpha = NumberStyleValue::create(1);
  2835. transaction.commit();
  2836. return CSSOKLCH::create(l.release_nonnull(), c.release_nonnull(), h.release_nonnull(), alpha.release_nonnull());
  2837. }
  2838. // https://www.w3.org/TR/css-color-4/#color-syntax
  2839. RefPtr<CSSStyleValue> Parser::parse_color_value(TokenStream<ComponentValue>& tokens)
  2840. {
  2841. // Keywords: <system-color> | <deprecated-color> | currentColor
  2842. {
  2843. auto transaction = tokens.begin_transaction();
  2844. if (auto keyword = parse_keyword_value(tokens); keyword && keyword->has_color()) {
  2845. transaction.commit();
  2846. return keyword;
  2847. }
  2848. }
  2849. // Functions
  2850. if (auto rgb = parse_rgb_color_value(tokens))
  2851. return rgb;
  2852. if (auto hsl = parse_hsl_color_value(tokens))
  2853. return hsl;
  2854. if (auto hwb = parse_hwb_color_value(tokens))
  2855. return hwb;
  2856. if (auto oklab = parse_oklab_color_value(tokens))
  2857. return oklab;
  2858. if (auto oklch = parse_oklch_color_value(tokens))
  2859. return oklch;
  2860. auto transaction = tokens.begin_transaction();
  2861. tokens.discard_whitespace();
  2862. auto component_value = tokens.consume_a_token();
  2863. if (component_value.is(Token::Type::Ident)) {
  2864. auto ident = component_value.token().ident();
  2865. auto color = Color::from_string(ident);
  2866. if (color.has_value()) {
  2867. transaction.commit();
  2868. return CSSColorValue::create_from_color(color.release_value());
  2869. }
  2870. // Otherwise, fall through to the hashless-hex-color case
  2871. }
  2872. if (component_value.is(Token::Type::Hash)) {
  2873. auto color = Color::from_string(MUST(String::formatted("#{}", component_value.token().hash_value())));
  2874. if (color.has_value()) {
  2875. transaction.commit();
  2876. return CSSColorValue::create_from_color(color.release_value());
  2877. }
  2878. return {};
  2879. }
  2880. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  2881. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  2882. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  2883. // aborting on the first step that returns a value:
  2884. // 1. Let cv be the component value.
  2885. auto const& cv = component_value;
  2886. String serialization;
  2887. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  2888. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  2889. // 1. If cv’s type flag is not "integer", return an error.
  2890. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  2891. if (!cv.token().number().is_integer())
  2892. return {};
  2893. // 2. If cv’s value is less than zero, return an error.
  2894. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  2895. if (value < 0)
  2896. return {};
  2897. // 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.
  2898. StringBuilder serialization_builder;
  2899. serialization_builder.appendff("{}", value);
  2900. // 4. If cv is a <dimension-token>, append the unit to serialization.
  2901. if (cv.is(Token::Type::Dimension))
  2902. serialization_builder.append(cv.token().dimension_unit());
  2903. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  2904. serialization = MUST(serialization_builder.to_string());
  2905. if (serialization_builder.length() < 6) {
  2906. StringBuilder builder;
  2907. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  2908. builder.append('0');
  2909. builder.append(serialization_builder.string_view());
  2910. serialization = MUST(builder.to_string());
  2911. }
  2912. }
  2913. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  2914. else {
  2915. if (!cv.is(Token::Type::Ident))
  2916. return {};
  2917. serialization = cv.token().ident().to_string();
  2918. }
  2919. // 4. If serialization does not consist of three or six characters, return an error.
  2920. if (serialization.bytes().size() != 3 && serialization.bytes().size() != 6)
  2921. return {};
  2922. // 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.
  2923. for (auto c : serialization.bytes_as_string_view()) {
  2924. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  2925. return {};
  2926. }
  2927. // 6. Return the concatenation of "#" (U+0023) and serialization.
  2928. auto color = Color::from_string(MUST(String::formatted("#{}", serialization)));
  2929. if (color.has_value()) {
  2930. transaction.commit();
  2931. return CSSColorValue::create_from_color(color.release_value());
  2932. }
  2933. }
  2934. return {};
  2935. }
  2936. // https://drafts.csswg.org/css-lists-3/#counter-functions
  2937. RefPtr<CSSStyleValue> Parser::parse_counter_value(TokenStream<ComponentValue>& tokens)
  2938. {
  2939. auto parse_counter_name = [this](TokenStream<ComponentValue>& tokens) -> Optional<FlyString> {
  2940. // https://drafts.csswg.org/css-lists-3/#typedef-counter-name
  2941. // Counters are referred to in CSS syntax using the <counter-name> type, which represents
  2942. // their name as a <custom-ident>. A <counter-name> name cannot match the keyword none;
  2943. // such an identifier is invalid as a <counter-name>.
  2944. auto transaction = tokens.begin_transaction();
  2945. tokens.discard_whitespace();
  2946. auto counter_name = parse_custom_ident_value(tokens, { "none"sv });
  2947. if (!counter_name)
  2948. return {};
  2949. tokens.discard_whitespace();
  2950. if (tokens.has_next_token())
  2951. return {};
  2952. transaction.commit();
  2953. return counter_name->custom_ident();
  2954. };
  2955. auto parse_counter_style = [this](TokenStream<ComponentValue>& tokens) -> RefPtr<CSSStyleValue> {
  2956. // https://drafts.csswg.org/css-counter-styles-3/#typedef-counter-style
  2957. // <counter-style> = <counter-style-name> | <symbols()>
  2958. // For now we just support <counter-style-name>, found here:
  2959. // https://drafts.csswg.org/css-counter-styles-3/#typedef-counter-style-name
  2960. // <counter-style-name> is a <custom-ident> that is not an ASCII case-insensitive match for none.
  2961. auto transaction = tokens.begin_transaction();
  2962. tokens.discard_whitespace();
  2963. auto counter_style_name = parse_custom_ident_value(tokens, { "none"sv });
  2964. if (!counter_style_name)
  2965. return {};
  2966. tokens.discard_whitespace();
  2967. if (tokens.has_next_token())
  2968. return {};
  2969. transaction.commit();
  2970. return counter_style_name.release_nonnull();
  2971. };
  2972. auto transaction = tokens.begin_transaction();
  2973. auto token = tokens.consume_a_token();
  2974. if (token.is_function("counter"sv)) {
  2975. // counter() = counter( <counter-name>, <counter-style>? )
  2976. auto& function = token.function();
  2977. TokenStream function_tokens { function.value };
  2978. auto function_values = parse_a_comma_separated_list_of_component_values(function_tokens);
  2979. if (function_values.is_empty() || function_values.size() > 2)
  2980. return nullptr;
  2981. TokenStream name_tokens { function_values[0] };
  2982. auto counter_name = parse_counter_name(name_tokens);
  2983. if (!counter_name.has_value())
  2984. return nullptr;
  2985. RefPtr<CSSStyleValue> counter_style;
  2986. if (function_values.size() > 1) {
  2987. TokenStream counter_style_tokens { function_values[1] };
  2988. counter_style = parse_counter_style(counter_style_tokens);
  2989. if (!counter_style)
  2990. return nullptr;
  2991. } else {
  2992. // In both cases, if the <counter-style> argument is omitted it defaults to `decimal`.
  2993. counter_style = CustomIdentStyleValue::create("decimal"_fly_string);
  2994. }
  2995. transaction.commit();
  2996. return CounterStyleValue::create_counter(counter_name.release_value(), counter_style.release_nonnull());
  2997. }
  2998. if (token.is_function("counters"sv)) {
  2999. // counters() = counters( <counter-name>, <string>, <counter-style>? )
  3000. auto& function = token.function();
  3001. TokenStream function_tokens { function.value };
  3002. auto function_values = parse_a_comma_separated_list_of_component_values(function_tokens);
  3003. if (function_values.size() < 2 || function_values.size() > 3)
  3004. return nullptr;
  3005. TokenStream name_tokens { function_values[0] };
  3006. auto counter_name = parse_counter_name(name_tokens);
  3007. if (!counter_name.has_value())
  3008. return nullptr;
  3009. TokenStream string_tokens { function_values[1] };
  3010. string_tokens.discard_whitespace();
  3011. auto join_string = parse_string_value(string_tokens);
  3012. string_tokens.discard_whitespace();
  3013. if (!join_string || string_tokens.has_next_token())
  3014. return nullptr;
  3015. RefPtr<CSSStyleValue> counter_style;
  3016. if (function_values.size() > 2) {
  3017. TokenStream counter_style_tokens { function_values[2] };
  3018. counter_style = parse_counter_style(counter_style_tokens);
  3019. if (!counter_style)
  3020. return nullptr;
  3021. } else {
  3022. // In both cases, if the <counter-style> argument is omitted it defaults to `decimal`.
  3023. counter_style = CustomIdentStyleValue::create("decimal"_fly_string);
  3024. }
  3025. transaction.commit();
  3026. return CounterStyleValue::create_counters(counter_name.release_value(), join_string->string_value(), counter_style.release_nonnull());
  3027. }
  3028. return nullptr;
  3029. }
  3030. RefPtr<CSSStyleValue> Parser::parse_counter_definitions_value(TokenStream<ComponentValue>& tokens, AllowReversed allow_reversed, i32 default_value_if_not_reversed)
  3031. {
  3032. // If AllowReversed is Yes, parses:
  3033. // [ <counter-name> <integer>? | <reversed-counter-name> <integer>? ]+
  3034. // Otherwise parses:
  3035. // [ <counter-name> <integer>? ]+
  3036. // FIXME: This disabled parsing of `reversed()` counters. Remove this line once they're supported.
  3037. allow_reversed = AllowReversed::No;
  3038. auto transaction = tokens.begin_transaction();
  3039. tokens.discard_whitespace();
  3040. Vector<CounterDefinition> counter_definitions;
  3041. while (tokens.has_next_token()) {
  3042. auto per_item_transaction = tokens.begin_transaction();
  3043. CounterDefinition definition {};
  3044. // <counter-name> | <reversed-counter-name>
  3045. auto& token = tokens.consume_a_token();
  3046. if (token.is(Token::Type::Ident)) {
  3047. definition.name = token.token().ident();
  3048. definition.is_reversed = false;
  3049. } else if (allow_reversed == AllowReversed::Yes && token.is_function("reversed"sv)) {
  3050. TokenStream function_tokens { token.function().value };
  3051. function_tokens.discard_whitespace();
  3052. auto& name_token = function_tokens.consume_a_token();
  3053. if (!name_token.is(Token::Type::Ident))
  3054. break;
  3055. function_tokens.discard_whitespace();
  3056. if (function_tokens.has_next_token())
  3057. break;
  3058. definition.name = name_token.token().ident();
  3059. definition.is_reversed = true;
  3060. } else {
  3061. break;
  3062. }
  3063. tokens.discard_whitespace();
  3064. // <integer>?
  3065. definition.value = parse_integer_value(tokens);
  3066. if (!definition.value && !definition.is_reversed)
  3067. definition.value = IntegerStyleValue::create(default_value_if_not_reversed);
  3068. counter_definitions.append(move(definition));
  3069. tokens.discard_whitespace();
  3070. per_item_transaction.commit();
  3071. }
  3072. if (counter_definitions.is_empty())
  3073. return {};
  3074. transaction.commit();
  3075. return CounterDefinitionsStyleValue::create(move(counter_definitions));
  3076. }
  3077. RefPtr<CSSStyleValue> Parser::parse_ratio_value(TokenStream<ComponentValue>& tokens)
  3078. {
  3079. if (auto ratio = parse_ratio(tokens); ratio.has_value())
  3080. return RatioStyleValue::create(ratio.release_value());
  3081. return nullptr;
  3082. }
  3083. RefPtr<StringStyleValue> Parser::parse_string_value(TokenStream<ComponentValue>& tokens)
  3084. {
  3085. auto peek = tokens.next_token();
  3086. if (peek.is(Token::Type::String)) {
  3087. tokens.discard_a_token();
  3088. return StringStyleValue::create(peek.token().string());
  3089. }
  3090. return nullptr;
  3091. }
  3092. RefPtr<CSSStyleValue> Parser::parse_image_value(TokenStream<ComponentValue>& tokens)
  3093. {
  3094. if (auto url = parse_url_function(tokens); url.has_value())
  3095. return ImageStyleValue::create(url.value());
  3096. if (auto linear_gradient = parse_linear_gradient_function(tokens))
  3097. return linear_gradient;
  3098. if (auto conic_gradient = parse_conic_gradient_function(tokens))
  3099. return conic_gradient;
  3100. if (auto radial_gradient = parse_radial_gradient_function(tokens))
  3101. return radial_gradient;
  3102. return nullptr;
  3103. }
  3104. // https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint
  3105. RefPtr<CSSStyleValue> Parser::parse_paint_value(TokenStream<ComponentValue>& tokens)
  3106. {
  3107. // `<paint> = none | <color> | <url> [none | <color>]? | context-fill | context-stroke`
  3108. auto parse_color_or_none = [&]() -> Optional<RefPtr<CSSStyleValue>> {
  3109. if (auto color = parse_color_value(tokens))
  3110. return color;
  3111. // NOTE: <color> also accepts identifiers, so we do this identifier check last.
  3112. if (tokens.next_token().is(Token::Type::Ident)) {
  3113. auto maybe_keyword = keyword_from_string(tokens.next_token().token().ident());
  3114. if (maybe_keyword.has_value()) {
  3115. // FIXME: Accept `context-fill` and `context-stroke`
  3116. switch (*maybe_keyword) {
  3117. case Keyword::None:
  3118. tokens.discard_a_token();
  3119. return CSSKeywordValue::create(*maybe_keyword);
  3120. default:
  3121. return nullptr;
  3122. }
  3123. }
  3124. }
  3125. return OptionalNone {};
  3126. };
  3127. // FIMXE: Allow context-fill/context-stroke here
  3128. if (auto color_or_none = parse_color_or_none(); color_or_none.has_value())
  3129. return *color_or_none;
  3130. if (auto url = parse_url_value(tokens)) {
  3131. tokens.discard_whitespace();
  3132. if (auto color_or_none = parse_color_or_none(); color_or_none == nullptr) {
  3133. // Fail to parse if the fallback is invalid, but otherwise ignore it.
  3134. // FIXME: Use fallback color
  3135. return nullptr;
  3136. }
  3137. return url;
  3138. }
  3139. return nullptr;
  3140. }
  3141. // https://www.w3.org/TR/css-values-4/#position
  3142. RefPtr<PositionStyleValue> Parser::parse_position_value(TokenStream<ComponentValue>& tokens, PositionParsingMode position_parsing_mode)
  3143. {
  3144. auto parse_position_edge = [](ComponentValue const& token) -> Optional<PositionEdge> {
  3145. if (!token.is(Token::Type::Ident))
  3146. return {};
  3147. auto keyword = keyword_from_string(token.token().ident());
  3148. if (!keyword.has_value())
  3149. return {};
  3150. return keyword_to_position_edge(*keyword);
  3151. };
  3152. auto parse_length_percentage = [&](ComponentValue const& token) -> Optional<LengthPercentage> {
  3153. if (token.is(Token::Type::EndOfFile))
  3154. return {};
  3155. if (auto dimension = parse_dimension(token); dimension.has_value()) {
  3156. if (dimension->is_length_percentage())
  3157. return dimension->length_percentage();
  3158. return {};
  3159. }
  3160. if (auto calc = parse_calculated_value(token); calc && calc->resolves_to_length_percentage())
  3161. return LengthPercentage { calc.release_nonnull() };
  3162. return {};
  3163. };
  3164. auto is_horizontal = [](PositionEdge edge, bool accept_center) -> bool {
  3165. switch (edge) {
  3166. case PositionEdge::Left:
  3167. case PositionEdge::Right:
  3168. return true;
  3169. case PositionEdge::Center:
  3170. return accept_center;
  3171. default:
  3172. return false;
  3173. }
  3174. };
  3175. auto is_vertical = [](PositionEdge edge, bool accept_center) -> bool {
  3176. switch (edge) {
  3177. case PositionEdge::Top:
  3178. case PositionEdge::Bottom:
  3179. return true;
  3180. case PositionEdge::Center:
  3181. return accept_center;
  3182. default:
  3183. return false;
  3184. }
  3185. };
  3186. auto make_edge_style_value = [](PositionEdge position_edge, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  3187. if (position_edge == PositionEdge::Center)
  3188. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  3189. return EdgeStyleValue::create(position_edge, Length::make_px(0));
  3190. };
  3191. // <position> = [
  3192. // [ left | center | right | top | bottom | <length-percentage> ]
  3193. // |
  3194. // [ left | center | right ] && [ top | center | bottom ]
  3195. // |
  3196. // [ left | center | right | <length-percentage> ]
  3197. // [ top | center | bottom | <length-percentage> ]
  3198. // |
  3199. // [ [ left | right ] <length-percentage> ] &&
  3200. // [ [ top | bottom ] <length-percentage> ]
  3201. // ]
  3202. // [ left | center | right | top | bottom | <length-percentage> ]
  3203. auto alternative_1 = [&]() -> RefPtr<PositionStyleValue> {
  3204. auto transaction = tokens.begin_transaction();
  3205. tokens.discard_whitespace();
  3206. auto const& token = tokens.consume_a_token();
  3207. // [ left | center | right | top | bottom ]
  3208. if (auto maybe_edge = parse_position_edge(token); maybe_edge.has_value()) {
  3209. auto edge = maybe_edge.release_value();
  3210. transaction.commit();
  3211. // [ left | right ]
  3212. if (is_horizontal(edge, false))
  3213. return PositionStyleValue::create(make_edge_style_value(edge, true), make_edge_style_value(PositionEdge::Center, false));
  3214. // [ top | bottom ]
  3215. if (is_vertical(edge, false))
  3216. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(edge, false));
  3217. // [ center ]
  3218. VERIFY(edge == PositionEdge::Center);
  3219. return PositionStyleValue::create(make_edge_style_value(PositionEdge::Center, true), make_edge_style_value(PositionEdge::Center, false));
  3220. }
  3221. // [ <length-percentage> ]
  3222. if (auto maybe_percentage = parse_length_percentage(token); maybe_percentage.has_value()) {
  3223. transaction.commit();
  3224. return PositionStyleValue::create(EdgeStyleValue::create(PositionEdge::Left, *maybe_percentage), make_edge_style_value(PositionEdge::Center, false));
  3225. }
  3226. return nullptr;
  3227. };
  3228. // [ left | center | right ] && [ top | center | bottom ]
  3229. auto alternative_2 = [&]() -> RefPtr<PositionStyleValue> {
  3230. auto transaction = tokens.begin_transaction();
  3231. tokens.discard_whitespace();
  3232. // Parse out two position edges
  3233. auto maybe_first_edge = parse_position_edge(tokens.consume_a_token());
  3234. if (!maybe_first_edge.has_value())
  3235. return nullptr;
  3236. auto first_edge = maybe_first_edge.release_value();
  3237. tokens.discard_whitespace();
  3238. auto maybe_second_edge = parse_position_edge(tokens.consume_a_token());
  3239. if (!maybe_second_edge.has_value())
  3240. return nullptr;
  3241. auto second_edge = maybe_second_edge.release_value();
  3242. // If 'left' or 'right' is given, that position is X and the other is Y.
  3243. // Conversely -
  3244. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  3245. if (is_vertical(first_edge, false) || is_horizontal(second_edge, false))
  3246. swap(first_edge, second_edge);
  3247. // [ left | center | right ] [ top | bottom | center ]
  3248. if (is_horizontal(first_edge, true) && is_vertical(second_edge, true)) {
  3249. transaction.commit();
  3250. return PositionStyleValue::create(make_edge_style_value(first_edge, true), make_edge_style_value(second_edge, false));
  3251. }
  3252. return nullptr;
  3253. };
  3254. // [ left | center | right | <length-percentage> ]
  3255. // [ top | center | bottom | <length-percentage> ]
  3256. auto alternative_3 = [&]() -> RefPtr<PositionStyleValue> {
  3257. auto transaction = tokens.begin_transaction();
  3258. auto parse_position_or_length = [&](bool as_horizontal) -> RefPtr<EdgeStyleValue> {
  3259. tokens.discard_whitespace();
  3260. auto const& token = tokens.consume_a_token();
  3261. if (auto maybe_position = parse_position_edge(token); maybe_position.has_value()) {
  3262. auto position = maybe_position.release_value();
  3263. bool valid = as_horizontal ? is_horizontal(position, true) : is_vertical(position, true);
  3264. if (!valid)
  3265. return nullptr;
  3266. return make_edge_style_value(position, as_horizontal);
  3267. }
  3268. auto maybe_length = parse_length_percentage(token);
  3269. if (!maybe_length.has_value())
  3270. return nullptr;
  3271. return EdgeStyleValue::create(as_horizontal ? PositionEdge::Left : PositionEdge::Top, maybe_length.release_value());
  3272. };
  3273. // [ left | center | right | <length-percentage> ]
  3274. auto horizontal_edge = parse_position_or_length(true);
  3275. if (!horizontal_edge)
  3276. return nullptr;
  3277. // [ top | center | bottom | <length-percentage> ]
  3278. auto vertical_edge = parse_position_or_length(false);
  3279. if (!vertical_edge)
  3280. return nullptr;
  3281. transaction.commit();
  3282. return PositionStyleValue::create(horizontal_edge.release_nonnull(), vertical_edge.release_nonnull());
  3283. };
  3284. // [ [ left | right ] <length-percentage> ] &&
  3285. // [ [ top | bottom ] <length-percentage> ]
  3286. auto alternative_4 = [&]() -> RefPtr<PositionStyleValue> {
  3287. struct PositionAndLength {
  3288. PositionEdge position;
  3289. LengthPercentage length;
  3290. };
  3291. auto parse_position_and_length = [&]() -> Optional<PositionAndLength> {
  3292. tokens.discard_whitespace();
  3293. auto maybe_position = parse_position_edge(tokens.consume_a_token());
  3294. if (!maybe_position.has_value())
  3295. return {};
  3296. tokens.discard_whitespace();
  3297. auto maybe_length = parse_length_percentage(tokens.consume_a_token());
  3298. if (!maybe_length.has_value())
  3299. return {};
  3300. return PositionAndLength {
  3301. .position = maybe_position.release_value(),
  3302. .length = maybe_length.release_value(),
  3303. };
  3304. };
  3305. auto transaction = tokens.begin_transaction();
  3306. auto maybe_group1 = parse_position_and_length();
  3307. if (!maybe_group1.has_value())
  3308. return nullptr;
  3309. auto maybe_group2 = parse_position_and_length();
  3310. if (!maybe_group2.has_value())
  3311. return nullptr;
  3312. auto group1 = maybe_group1.release_value();
  3313. auto group2 = maybe_group2.release_value();
  3314. // [ [ left | right ] <length-percentage> ] [ [ top | bottom ] <length-percentage> ]
  3315. if (is_horizontal(group1.position, false) && is_vertical(group2.position, false)) {
  3316. transaction.commit();
  3317. return PositionStyleValue::create(EdgeStyleValue::create(group1.position, group1.length), EdgeStyleValue::create(group2.position, group2.length));
  3318. }
  3319. // [ [ top | bottom ] <length-percentage> ] [ [ left | right ] <length-percentage> ]
  3320. if (is_vertical(group1.position, false) && is_horizontal(group2.position, false)) {
  3321. transaction.commit();
  3322. return PositionStyleValue::create(EdgeStyleValue::create(group2.position, group2.length), EdgeStyleValue::create(group1.position, group1.length));
  3323. }
  3324. return nullptr;
  3325. };
  3326. // The extra 3-value syntax that's allowed for background-position:
  3327. // [ center | [ left | right ] <length-percentage>? ] &&
  3328. // [ center | [ top | bottom ] <length-percentage>? ]
  3329. auto alternative_5_for_background_position = [&]() -> RefPtr<PositionStyleValue> {
  3330. auto transaction = tokens.begin_transaction();
  3331. struct PositionAndMaybeLength {
  3332. PositionEdge position;
  3333. Optional<LengthPercentage> length;
  3334. };
  3335. // [ <position> <length-percentage>? ]
  3336. auto parse_position_and_maybe_length = [&]() -> Optional<PositionAndMaybeLength> {
  3337. tokens.discard_whitespace();
  3338. auto maybe_position = parse_position_edge(tokens.consume_a_token());
  3339. if (!maybe_position.has_value())
  3340. return {};
  3341. tokens.discard_whitespace();
  3342. auto maybe_length = parse_length_percentage(tokens.next_token());
  3343. if (maybe_length.has_value()) {
  3344. // 'center' cannot be followed by a <length-percentage>
  3345. if (maybe_position.value() == PositionEdge::Center && maybe_length.has_value())
  3346. return {};
  3347. tokens.discard_a_token();
  3348. }
  3349. return PositionAndMaybeLength {
  3350. .position = maybe_position.release_value(),
  3351. .length = move(maybe_length),
  3352. };
  3353. };
  3354. auto maybe_group1 = parse_position_and_maybe_length();
  3355. if (!maybe_group1.has_value())
  3356. return nullptr;
  3357. auto maybe_group2 = parse_position_and_maybe_length();
  3358. if (!maybe_group2.has_value())
  3359. return nullptr;
  3360. auto group1 = maybe_group1.release_value();
  3361. auto group2 = maybe_group2.release_value();
  3362. // 2-value or 4-value if both <length-percentage>s are present or missing.
  3363. if (group1.length.has_value() == group2.length.has_value())
  3364. return nullptr;
  3365. // If 'left' or 'right' is given, that position is X and the other is Y.
  3366. // Conversely -
  3367. // If 'top' or 'bottom' is given, that position is Y and the other is X.
  3368. if (is_vertical(group1.position, false) || is_horizontal(group2.position, false))
  3369. swap(group1, group2);
  3370. // [ center | [ left | right ] ]
  3371. if (!is_horizontal(group1.position, true))
  3372. return nullptr;
  3373. // [ center | [ top | bottom ] ]
  3374. if (!is_vertical(group2.position, true))
  3375. return nullptr;
  3376. auto to_style_value = [&](PositionAndMaybeLength const& group, bool is_horizontal) -> NonnullRefPtr<EdgeStyleValue> {
  3377. if (group.position == PositionEdge::Center)
  3378. return EdgeStyleValue::create(is_horizontal ? PositionEdge::Left : PositionEdge::Top, Percentage { 50 });
  3379. return EdgeStyleValue::create(group.position, group.length.value_or(Length::make_px(0)));
  3380. };
  3381. transaction.commit();
  3382. return PositionStyleValue::create(to_style_value(group1, true), to_style_value(group2, false));
  3383. };
  3384. // Note: The alternatives must be attempted in this order since shorter alternatives can match a prefix of longer ones.
  3385. if (auto position = alternative_4())
  3386. return position;
  3387. if (position_parsing_mode == PositionParsingMode::BackgroundPosition) {
  3388. if (auto position = alternative_5_for_background_position())
  3389. return position;
  3390. }
  3391. if (auto position = alternative_3())
  3392. return position;
  3393. if (auto position = alternative_2())
  3394. return position;
  3395. if (auto position = alternative_1())
  3396. return position;
  3397. return nullptr;
  3398. }
  3399. template<typename ParseFunction>
  3400. RefPtr<CSSStyleValue> Parser::parse_comma_separated_value_list(TokenStream<ComponentValue>& tokens, ParseFunction parse_one_value)
  3401. {
  3402. auto first = parse_one_value(tokens);
  3403. if (!first || !tokens.has_next_token())
  3404. return first;
  3405. StyleValueVector values;
  3406. values.append(first.release_nonnull());
  3407. while (tokens.has_next_token()) {
  3408. if (!tokens.consume_a_token().is(Token::Type::Comma))
  3409. return nullptr;
  3410. if (auto maybe_value = parse_one_value(tokens)) {
  3411. values.append(maybe_value.release_nonnull());
  3412. continue;
  3413. }
  3414. return nullptr;
  3415. }
  3416. return StyleValueList::create(move(values), StyleValueList::Separator::Comma);
  3417. }
  3418. RefPtr<CSSStyleValue> Parser::parse_simple_comma_separated_value_list(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  3419. {
  3420. return parse_comma_separated_value_list(tokens, [this, property_id](auto& tokens) -> RefPtr<CSSStyleValue> {
  3421. if (auto value = parse_css_value_for_property(property_id, tokens))
  3422. return value;
  3423. tokens.reconsume_current_input_token();
  3424. return nullptr;
  3425. });
  3426. }
  3427. RefPtr<CSSStyleValue> Parser::parse_all_as_single_keyword_value(TokenStream<ComponentValue>& tokens, Keyword keyword)
  3428. {
  3429. auto transaction = tokens.begin_transaction();
  3430. tokens.discard_whitespace();
  3431. auto keyword_value = parse_keyword_value(tokens);
  3432. tokens.discard_whitespace();
  3433. if (tokens.has_next_token() || !keyword_value || keyword_value->to_keyword() != keyword)
  3434. return {};
  3435. transaction.commit();
  3436. return keyword_value;
  3437. }
  3438. static void remove_property(Vector<PropertyID>& properties, PropertyID property_to_remove)
  3439. {
  3440. properties.remove_first_matching([&](auto it) { return it == property_to_remove; });
  3441. }
  3442. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio
  3443. RefPtr<CSSStyleValue> Parser::parse_aspect_ratio_value(TokenStream<ComponentValue>& tokens)
  3444. {
  3445. // `auto || <ratio>`
  3446. RefPtr<CSSStyleValue> auto_value;
  3447. RefPtr<CSSStyleValue> ratio_value;
  3448. auto transaction = tokens.begin_transaction();
  3449. while (tokens.has_next_token()) {
  3450. auto maybe_value = parse_css_value_for_property(PropertyID::AspectRatio, tokens);
  3451. if (!maybe_value)
  3452. return nullptr;
  3453. if (maybe_value->is_ratio()) {
  3454. if (ratio_value)
  3455. return nullptr;
  3456. ratio_value = maybe_value.release_nonnull();
  3457. continue;
  3458. }
  3459. if (maybe_value->is_keyword() && maybe_value->as_keyword().keyword() == Keyword::Auto) {
  3460. if (auto_value)
  3461. return nullptr;
  3462. auto_value = maybe_value.release_nonnull();
  3463. continue;
  3464. }
  3465. return nullptr;
  3466. }
  3467. if (auto_value && ratio_value) {
  3468. transaction.commit();
  3469. return StyleValueList::create(
  3470. StyleValueVector { auto_value.release_nonnull(), ratio_value.release_nonnull() },
  3471. StyleValueList::Separator::Space);
  3472. }
  3473. if (ratio_value) {
  3474. transaction.commit();
  3475. return ratio_value.release_nonnull();
  3476. }
  3477. if (auto_value) {
  3478. transaction.commit();
  3479. return auto_value.release_nonnull();
  3480. }
  3481. return nullptr;
  3482. }
  3483. RefPtr<CSSStyleValue> Parser::parse_background_value(TokenStream<ComponentValue>& tokens)
  3484. {
  3485. auto transaction = tokens.begin_transaction();
  3486. 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) {
  3487. return ShorthandStyleValue::create(PropertyID::Background,
  3488. { PropertyID::BackgroundColor, PropertyID::BackgroundImage, PropertyID::BackgroundPosition, PropertyID::BackgroundSize, PropertyID::BackgroundRepeat, PropertyID::BackgroundAttachment, PropertyID::BackgroundOrigin, PropertyID::BackgroundClip },
  3489. { move(background_color), move(background_image), move(background_position), move(background_size), move(background_repeat), move(background_attachment), move(background_origin), move(background_clip) });
  3490. };
  3491. StyleValueVector background_images;
  3492. StyleValueVector background_positions;
  3493. StyleValueVector background_sizes;
  3494. StyleValueVector background_repeats;
  3495. StyleValueVector background_attachments;
  3496. StyleValueVector background_clips;
  3497. StyleValueVector background_origins;
  3498. RefPtr<CSSStyleValue> background_color;
  3499. auto initial_background_image = property_initial_value(m_context.realm(), PropertyID::BackgroundImage);
  3500. auto initial_background_position = property_initial_value(m_context.realm(), PropertyID::BackgroundPosition);
  3501. auto initial_background_size = property_initial_value(m_context.realm(), PropertyID::BackgroundSize);
  3502. auto initial_background_repeat = property_initial_value(m_context.realm(), PropertyID::BackgroundRepeat);
  3503. auto initial_background_attachment = property_initial_value(m_context.realm(), PropertyID::BackgroundAttachment);
  3504. auto initial_background_clip = property_initial_value(m_context.realm(), PropertyID::BackgroundClip);
  3505. auto initial_background_origin = property_initial_value(m_context.realm(), PropertyID::BackgroundOrigin);
  3506. auto initial_background_color = property_initial_value(m_context.realm(), PropertyID::BackgroundColor);
  3507. // Per-layer values
  3508. RefPtr<CSSStyleValue> background_image;
  3509. RefPtr<CSSStyleValue> background_position;
  3510. RefPtr<CSSStyleValue> background_size;
  3511. RefPtr<CSSStyleValue> background_repeat;
  3512. RefPtr<CSSStyleValue> background_attachment;
  3513. RefPtr<CSSStyleValue> background_clip;
  3514. RefPtr<CSSStyleValue> background_origin;
  3515. bool has_multiple_layers = false;
  3516. // BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
  3517. Vector<PropertyID> remaining_layer_properties {
  3518. PropertyID::BackgroundAttachment,
  3519. PropertyID::BackgroundClip,
  3520. PropertyID::BackgroundColor,
  3521. PropertyID::BackgroundImage,
  3522. PropertyID::BackgroundOrigin,
  3523. PropertyID::BackgroundPosition,
  3524. PropertyID::BackgroundRepeat,
  3525. };
  3526. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  3527. if (allow_background_color) {
  3528. if (background_color)
  3529. return true;
  3530. } else {
  3531. if (background_color)
  3532. return false;
  3533. }
  3534. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  3535. };
  3536. auto complete_background_layer = [&]() {
  3537. background_images.append(background_image ? background_image.release_nonnull() : initial_background_image);
  3538. background_positions.append(background_position ? background_position.release_nonnull() : initial_background_position);
  3539. background_sizes.append(background_size ? background_size.release_nonnull() : initial_background_size);
  3540. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : initial_background_repeat);
  3541. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : initial_background_attachment);
  3542. if (!background_origin && !background_clip) {
  3543. background_origin = initial_background_origin;
  3544. background_clip = initial_background_clip;
  3545. } else if (!background_clip) {
  3546. background_clip = background_origin;
  3547. }
  3548. background_origins.append(background_origin.release_nonnull());
  3549. background_clips.append(background_clip.release_nonnull());
  3550. background_image = nullptr;
  3551. background_position = nullptr;
  3552. background_size = nullptr;
  3553. background_repeat = nullptr;
  3554. background_attachment = nullptr;
  3555. background_clip = nullptr;
  3556. background_origin = nullptr;
  3557. remaining_layer_properties.clear_with_capacity();
  3558. remaining_layer_properties.unchecked_append(PropertyID::BackgroundAttachment);
  3559. remaining_layer_properties.unchecked_append(PropertyID::BackgroundClip);
  3560. remaining_layer_properties.unchecked_append(PropertyID::BackgroundColor);
  3561. remaining_layer_properties.unchecked_append(PropertyID::BackgroundImage);
  3562. remaining_layer_properties.unchecked_append(PropertyID::BackgroundOrigin);
  3563. remaining_layer_properties.unchecked_append(PropertyID::BackgroundPosition);
  3564. remaining_layer_properties.unchecked_append(PropertyID::BackgroundRepeat);
  3565. };
  3566. while (tokens.has_next_token()) {
  3567. if (tokens.next_token().is(Token::Type::Comma)) {
  3568. has_multiple_layers = true;
  3569. if (!background_layer_is_valid(false))
  3570. return nullptr;
  3571. complete_background_layer();
  3572. tokens.discard_a_token();
  3573. continue;
  3574. }
  3575. auto value_and_property = parse_css_value_for_properties(remaining_layer_properties, tokens);
  3576. if (!value_and_property.has_value())
  3577. return nullptr;
  3578. auto& value = value_and_property->style_value;
  3579. remove_property(remaining_layer_properties, value_and_property->property);
  3580. switch (value_and_property->property) {
  3581. case PropertyID::BackgroundAttachment:
  3582. VERIFY(!background_attachment);
  3583. background_attachment = value.release_nonnull();
  3584. continue;
  3585. case PropertyID::BackgroundColor:
  3586. VERIFY(!background_color);
  3587. background_color = value.release_nonnull();
  3588. continue;
  3589. case PropertyID::BackgroundImage:
  3590. VERIFY(!background_image);
  3591. background_image = value.release_nonnull();
  3592. continue;
  3593. case PropertyID::BackgroundClip:
  3594. case PropertyID::BackgroundOrigin: {
  3595. // background-origin and background-clip accept the same values. From the spec:
  3596. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  3597. // If two values are present, then the first sets background-origin and the second background-clip."
  3598. // - https://www.w3.org/TR/css-backgrounds-3/#background
  3599. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  3600. // If we only get one, we copy the value before creating the ShorthandStyleValue.
  3601. if (!background_origin) {
  3602. background_origin = value.release_nonnull();
  3603. } else if (!background_clip) {
  3604. background_clip = value.release_nonnull();
  3605. } else {
  3606. VERIFY_NOT_REACHED();
  3607. }
  3608. continue;
  3609. }
  3610. case PropertyID::BackgroundPosition: {
  3611. VERIFY(!background_position);
  3612. background_position = value.release_nonnull();
  3613. // Attempt to parse `/ <background-size>`
  3614. auto background_size_transaction = tokens.begin_transaction();
  3615. auto& maybe_slash = tokens.consume_a_token();
  3616. if (maybe_slash.is_delim('/')) {
  3617. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  3618. background_size_transaction.commit();
  3619. background_size = maybe_background_size.release_nonnull();
  3620. continue;
  3621. }
  3622. return nullptr;
  3623. }
  3624. continue;
  3625. }
  3626. case PropertyID::BackgroundRepeat: {
  3627. VERIFY(!background_repeat);
  3628. tokens.reconsume_current_input_token();
  3629. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  3630. background_repeat = maybe_repeat.release_nonnull();
  3631. continue;
  3632. }
  3633. return nullptr;
  3634. }
  3635. default:
  3636. VERIFY_NOT_REACHED();
  3637. }
  3638. return nullptr;
  3639. }
  3640. if (!background_layer_is_valid(true))
  3641. return nullptr;
  3642. // We only need to create StyleValueLists if there are multiple layers.
  3643. // Otherwise, we can pass the single StyleValues directly.
  3644. if (has_multiple_layers) {
  3645. complete_background_layer();
  3646. if (!background_color)
  3647. background_color = initial_background_color;
  3648. transaction.commit();
  3649. return make_background_shorthand(
  3650. background_color.release_nonnull(),
  3651. StyleValueList::create(move(background_images), StyleValueList::Separator::Comma),
  3652. StyleValueList::create(move(background_positions), StyleValueList::Separator::Comma),
  3653. StyleValueList::create(move(background_sizes), StyleValueList::Separator::Comma),
  3654. StyleValueList::create(move(background_repeats), StyleValueList::Separator::Comma),
  3655. StyleValueList::create(move(background_attachments), StyleValueList::Separator::Comma),
  3656. StyleValueList::create(move(background_origins), StyleValueList::Separator::Comma),
  3657. StyleValueList::create(move(background_clips), StyleValueList::Separator::Comma));
  3658. }
  3659. if (!background_color)
  3660. background_color = initial_background_color;
  3661. if (!background_image)
  3662. background_image = initial_background_image;
  3663. if (!background_position)
  3664. background_position = initial_background_position;
  3665. if (!background_size)
  3666. background_size = initial_background_size;
  3667. if (!background_repeat)
  3668. background_repeat = initial_background_repeat;
  3669. if (!background_attachment)
  3670. background_attachment = initial_background_attachment;
  3671. if (!background_origin && !background_clip) {
  3672. background_origin = initial_background_origin;
  3673. background_clip = initial_background_clip;
  3674. } else if (!background_clip) {
  3675. background_clip = background_origin;
  3676. }
  3677. transaction.commit();
  3678. return make_background_shorthand(
  3679. background_color.release_nonnull(),
  3680. background_image.release_nonnull(),
  3681. background_position.release_nonnull(),
  3682. background_size.release_nonnull(),
  3683. background_repeat.release_nonnull(),
  3684. background_attachment.release_nonnull(),
  3685. background_origin.release_nonnull(),
  3686. background_clip.release_nonnull());
  3687. }
  3688. static Optional<LengthPercentage> style_value_to_length_percentage(auto value)
  3689. {
  3690. if (value->is_percentage())
  3691. return LengthPercentage { value->as_percentage().percentage() };
  3692. if (value->is_length())
  3693. return LengthPercentage { value->as_length().length() };
  3694. if (value->is_math())
  3695. return LengthPercentage { value->as_math() };
  3696. return {};
  3697. }
  3698. RefPtr<CSSStyleValue> Parser::parse_single_background_position_x_or_y_value(TokenStream<ComponentValue>& tokens, PropertyID property)
  3699. {
  3700. PositionEdge relative_edge {};
  3701. if (property == PropertyID::BackgroundPositionX) {
  3702. // [ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
  3703. relative_edge = PositionEdge::Left;
  3704. } else if (property == PropertyID::BackgroundPositionY) {
  3705. // [ center | [ [ top | bottom | y-start | y-end ]? <length-percentage>? ]! ]#
  3706. relative_edge = PositionEdge::Top;
  3707. } else {
  3708. VERIFY_NOT_REACHED();
  3709. }
  3710. auto transaction = tokens.begin_transaction();
  3711. if (!tokens.has_next_token())
  3712. return nullptr;
  3713. auto value = parse_css_value_for_property(property, tokens);
  3714. if (!value)
  3715. return nullptr;
  3716. if (value->is_keyword()) {
  3717. auto keyword = value->to_keyword();
  3718. if (keyword == Keyword::Center) {
  3719. transaction.commit();
  3720. return EdgeStyleValue::create(relative_edge, Percentage { 50 });
  3721. }
  3722. if (auto edge = keyword_to_position_edge(keyword); edge.has_value()) {
  3723. relative_edge = *edge;
  3724. } else {
  3725. return nullptr;
  3726. }
  3727. if (tokens.has_next_token()) {
  3728. value = parse_css_value_for_property(property, tokens);
  3729. if (!value) {
  3730. transaction.commit();
  3731. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  3732. }
  3733. }
  3734. }
  3735. auto offset = style_value_to_length_percentage(value);
  3736. if (offset.has_value()) {
  3737. transaction.commit();
  3738. return EdgeStyleValue::create(relative_edge, *offset);
  3739. }
  3740. // If no offset is provided create this element but with an offset of default value of zero
  3741. transaction.commit();
  3742. return EdgeStyleValue::create(relative_edge, Length::make_px(0));
  3743. }
  3744. RefPtr<CSSStyleValue> Parser::parse_single_background_repeat_value(TokenStream<ComponentValue>& tokens)
  3745. {
  3746. auto transaction = tokens.begin_transaction();
  3747. auto is_directional_repeat = [](CSSStyleValue const& value) -> bool {
  3748. auto keyword = value.to_keyword();
  3749. return keyword == Keyword::RepeatX || keyword == Keyword::RepeatY;
  3750. };
  3751. auto as_repeat = [](Keyword keyword) -> Optional<Repeat> {
  3752. switch (keyword) {
  3753. case Keyword::NoRepeat:
  3754. return Repeat::NoRepeat;
  3755. case Keyword::Repeat:
  3756. return Repeat::Repeat;
  3757. case Keyword::Round:
  3758. return Repeat::Round;
  3759. case Keyword::Space:
  3760. return Repeat::Space;
  3761. default:
  3762. return {};
  3763. }
  3764. };
  3765. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  3766. if (!maybe_x_value)
  3767. return nullptr;
  3768. auto x_value = maybe_x_value.release_nonnull();
  3769. if (is_directional_repeat(*x_value)) {
  3770. auto keyword = x_value->to_keyword();
  3771. transaction.commit();
  3772. return BackgroundRepeatStyleValue::create(
  3773. keyword == Keyword::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  3774. keyword == Keyword::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  3775. }
  3776. auto x_repeat = as_repeat(x_value->to_keyword());
  3777. if (!x_repeat.has_value())
  3778. return nullptr;
  3779. // See if we have a second value for Y
  3780. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundRepeat, tokens);
  3781. if (!maybe_y_value) {
  3782. // We don't have a second value, so use x for both
  3783. transaction.commit();
  3784. return BackgroundRepeatStyleValue::create(x_repeat.value(), x_repeat.value());
  3785. }
  3786. auto y_value = maybe_y_value.release_nonnull();
  3787. if (is_directional_repeat(*y_value))
  3788. return nullptr;
  3789. auto y_repeat = as_repeat(y_value->to_keyword());
  3790. if (!y_repeat.has_value())
  3791. return nullptr;
  3792. transaction.commit();
  3793. return BackgroundRepeatStyleValue::create(x_repeat.value(), y_repeat.value());
  3794. }
  3795. RefPtr<CSSStyleValue> Parser::parse_single_background_size_value(TokenStream<ComponentValue>& tokens)
  3796. {
  3797. auto transaction = tokens.begin_transaction();
  3798. auto get_length_percentage = [](CSSStyleValue& style_value) -> Optional<LengthPercentage> {
  3799. if (style_value.has_auto())
  3800. return LengthPercentage { Length::make_auto() };
  3801. if (style_value.is_percentage())
  3802. return LengthPercentage { style_value.as_percentage().percentage() };
  3803. if (style_value.is_length())
  3804. return LengthPercentage { style_value.as_length().length() };
  3805. if (style_value.is_math())
  3806. return LengthPercentage { style_value.as_math() };
  3807. return {};
  3808. };
  3809. auto maybe_x_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  3810. if (!maybe_x_value)
  3811. return nullptr;
  3812. auto x_value = maybe_x_value.release_nonnull();
  3813. if (x_value->to_keyword() == Keyword::Cover || x_value->to_keyword() == Keyword::Contain) {
  3814. transaction.commit();
  3815. return x_value;
  3816. }
  3817. auto maybe_y_value = parse_css_value_for_property(PropertyID::BackgroundSize, tokens);
  3818. if (!maybe_y_value) {
  3819. auto y_value = LengthPercentage { Length::make_auto() };
  3820. auto x_size = get_length_percentage(*x_value);
  3821. if (!x_size.has_value())
  3822. return nullptr;
  3823. transaction.commit();
  3824. return BackgroundSizeStyleValue::create(x_size.value(), y_value);
  3825. }
  3826. auto y_value = maybe_y_value.release_nonnull();
  3827. auto x_size = get_length_percentage(*x_value);
  3828. auto y_size = get_length_percentage(*y_value);
  3829. if (!x_size.has_value() || !y_size.has_value())
  3830. return nullptr;
  3831. transaction.commit();
  3832. return BackgroundSizeStyleValue::create(x_size.release_value(), y_size.release_value());
  3833. }
  3834. RefPtr<CSSStyleValue> Parser::parse_border_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  3835. {
  3836. RefPtr<CSSStyleValue> border_width;
  3837. RefPtr<CSSStyleValue> border_color;
  3838. RefPtr<CSSStyleValue> border_style;
  3839. auto color_property = PropertyID::Invalid;
  3840. auto style_property = PropertyID::Invalid;
  3841. auto width_property = PropertyID::Invalid;
  3842. switch (property_id) {
  3843. case PropertyID::Border:
  3844. color_property = PropertyID::BorderColor;
  3845. style_property = PropertyID::BorderStyle;
  3846. width_property = PropertyID::BorderWidth;
  3847. break;
  3848. case PropertyID::BorderBottom:
  3849. color_property = PropertyID::BorderBottomColor;
  3850. style_property = PropertyID::BorderBottomStyle;
  3851. width_property = PropertyID::BorderBottomWidth;
  3852. break;
  3853. case PropertyID::BorderLeft:
  3854. color_property = PropertyID::BorderLeftColor;
  3855. style_property = PropertyID::BorderLeftStyle;
  3856. width_property = PropertyID::BorderLeftWidth;
  3857. break;
  3858. case PropertyID::BorderRight:
  3859. color_property = PropertyID::BorderRightColor;
  3860. style_property = PropertyID::BorderRightStyle;
  3861. width_property = PropertyID::BorderRightWidth;
  3862. break;
  3863. case PropertyID::BorderTop:
  3864. color_property = PropertyID::BorderTopColor;
  3865. style_property = PropertyID::BorderTopStyle;
  3866. width_property = PropertyID::BorderTopWidth;
  3867. break;
  3868. default:
  3869. VERIFY_NOT_REACHED();
  3870. }
  3871. auto remaining_longhands = Vector { width_property, color_property, style_property };
  3872. auto transaction = tokens.begin_transaction();
  3873. while (tokens.has_next_token()) {
  3874. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  3875. if (!property_and_value.has_value())
  3876. return nullptr;
  3877. auto& value = property_and_value->style_value;
  3878. remove_property(remaining_longhands, property_and_value->property);
  3879. if (property_and_value->property == width_property) {
  3880. VERIFY(!border_width);
  3881. border_width = value.release_nonnull();
  3882. } else if (property_and_value->property == color_property) {
  3883. VERIFY(!border_color);
  3884. border_color = value.release_nonnull();
  3885. } else if (property_and_value->property == style_property) {
  3886. VERIFY(!border_style);
  3887. border_style = value.release_nonnull();
  3888. } else {
  3889. VERIFY_NOT_REACHED();
  3890. }
  3891. }
  3892. if (!border_width)
  3893. border_width = property_initial_value(m_context.realm(), width_property);
  3894. if (!border_style)
  3895. border_style = property_initial_value(m_context.realm(), style_property);
  3896. if (!border_color)
  3897. border_color = property_initial_value(m_context.realm(), color_property);
  3898. transaction.commit();
  3899. return ShorthandStyleValue::create(property_id,
  3900. { width_property, style_property, color_property },
  3901. { border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull() });
  3902. }
  3903. RefPtr<CSSStyleValue> Parser::parse_border_radius_value(TokenStream<ComponentValue>& tokens)
  3904. {
  3905. if (tokens.remaining_token_count() == 2) {
  3906. auto transaction = tokens.begin_transaction();
  3907. auto horizontal = parse_length_percentage(tokens);
  3908. auto vertical = parse_length_percentage(tokens);
  3909. if (horizontal.has_value() && vertical.has_value()) {
  3910. transaction.commit();
  3911. return BorderRadiusStyleValue::create(horizontal.release_value(), vertical.release_value());
  3912. }
  3913. }
  3914. if (tokens.remaining_token_count() == 1) {
  3915. auto transaction = tokens.begin_transaction();
  3916. auto radius = parse_length_percentage(tokens);
  3917. if (radius.has_value()) {
  3918. transaction.commit();
  3919. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  3920. }
  3921. }
  3922. return nullptr;
  3923. }
  3924. RefPtr<CSSStyleValue> Parser::parse_border_radius_shorthand_value(TokenStream<ComponentValue>& tokens)
  3925. {
  3926. auto top_left = [&](Vector<LengthPercentage>& radii) { return radii[0]; };
  3927. auto top_right = [&](Vector<LengthPercentage>& radii) {
  3928. switch (radii.size()) {
  3929. case 4:
  3930. case 3:
  3931. case 2:
  3932. return radii[1];
  3933. case 1:
  3934. return radii[0];
  3935. default:
  3936. VERIFY_NOT_REACHED();
  3937. }
  3938. };
  3939. auto bottom_right = [&](Vector<LengthPercentage>& radii) {
  3940. switch (radii.size()) {
  3941. case 4:
  3942. case 3:
  3943. return radii[2];
  3944. case 2:
  3945. case 1:
  3946. return radii[0];
  3947. default:
  3948. VERIFY_NOT_REACHED();
  3949. }
  3950. };
  3951. auto bottom_left = [&](Vector<LengthPercentage>& radii) {
  3952. switch (radii.size()) {
  3953. case 4:
  3954. return radii[3];
  3955. case 3:
  3956. case 2:
  3957. return radii[1];
  3958. case 1:
  3959. return radii[0];
  3960. default:
  3961. VERIFY_NOT_REACHED();
  3962. }
  3963. };
  3964. Vector<LengthPercentage> horizontal_radii;
  3965. Vector<LengthPercentage> vertical_radii;
  3966. bool reading_vertical = false;
  3967. auto transaction = tokens.begin_transaction();
  3968. while (tokens.has_next_token()) {
  3969. if (tokens.next_token().is_delim('/')) {
  3970. if (reading_vertical || horizontal_radii.is_empty())
  3971. return nullptr;
  3972. reading_vertical = true;
  3973. tokens.discard_a_token(); // `/`
  3974. continue;
  3975. }
  3976. auto maybe_dimension = parse_length_percentage(tokens);
  3977. if (!maybe_dimension.has_value())
  3978. return nullptr;
  3979. if (reading_vertical) {
  3980. vertical_radii.append(maybe_dimension.release_value());
  3981. } else {
  3982. horizontal_radii.append(maybe_dimension.release_value());
  3983. }
  3984. }
  3985. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  3986. || horizontal_radii.is_empty()
  3987. || (reading_vertical && vertical_radii.is_empty()))
  3988. return nullptr;
  3989. auto top_left_radius = BorderRadiusStyleValue::create(top_left(horizontal_radii),
  3990. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii));
  3991. auto top_right_radius = BorderRadiusStyleValue::create(top_right(horizontal_radii),
  3992. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii));
  3993. auto bottom_right_radius = BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  3994. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii));
  3995. auto bottom_left_radius = BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  3996. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii));
  3997. transaction.commit();
  3998. return ShorthandStyleValue::create(PropertyID::BorderRadius,
  3999. { PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius },
  4000. { move(top_left_radius), move(top_right_radius), move(bottom_right_radius), move(bottom_left_radius) });
  4001. }
  4002. RefPtr<CSSStyleValue> Parser::parse_columns_value(TokenStream<ComponentValue>& tokens)
  4003. {
  4004. if (tokens.remaining_token_count() > 2)
  4005. return nullptr;
  4006. RefPtr<CSSStyleValue> column_count;
  4007. RefPtr<CSSStyleValue> column_width;
  4008. Vector<PropertyID> remaining_longhands { PropertyID::ColumnCount, PropertyID::ColumnWidth };
  4009. int found_autos = 0;
  4010. auto transaction = tokens.begin_transaction();
  4011. while (tokens.has_next_token()) {
  4012. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4013. if (!property_and_value.has_value())
  4014. return nullptr;
  4015. auto& value = property_and_value->style_value;
  4016. // since the values can be in either order, we want to skip over autos
  4017. if (value->has_auto()) {
  4018. found_autos++;
  4019. continue;
  4020. }
  4021. remove_property(remaining_longhands, property_and_value->property);
  4022. switch (property_and_value->property) {
  4023. case PropertyID::ColumnCount: {
  4024. VERIFY(!column_count);
  4025. column_count = value.release_nonnull();
  4026. continue;
  4027. }
  4028. case PropertyID::ColumnWidth: {
  4029. VERIFY(!column_width);
  4030. column_width = value.release_nonnull();
  4031. continue;
  4032. }
  4033. default:
  4034. VERIFY_NOT_REACHED();
  4035. }
  4036. }
  4037. if (found_autos > 2)
  4038. return nullptr;
  4039. if (found_autos == 2) {
  4040. column_count = CSSKeywordValue::create(Keyword::Auto);
  4041. column_width = CSSKeywordValue::create(Keyword::Auto);
  4042. }
  4043. if (found_autos == 1) {
  4044. if (!column_count)
  4045. column_count = CSSKeywordValue::create(Keyword::Auto);
  4046. if (!column_width)
  4047. column_width = CSSKeywordValue::create(Keyword::Auto);
  4048. }
  4049. if (!column_count)
  4050. column_count = property_initial_value(m_context.realm(), PropertyID::ColumnCount);
  4051. if (!column_width)
  4052. column_width = property_initial_value(m_context.realm(), PropertyID::ColumnWidth);
  4053. transaction.commit();
  4054. return ShorthandStyleValue::create(PropertyID::Columns,
  4055. { PropertyID::ColumnCount, PropertyID::ColumnWidth },
  4056. { column_count.release_nonnull(), column_width.release_nonnull() });
  4057. }
  4058. RefPtr<CSSStyleValue> Parser::parse_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  4059. {
  4060. // "none"
  4061. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4062. return none;
  4063. return parse_comma_separated_value_list(tokens, [this, allow_inset_keyword](auto& tokens) {
  4064. return parse_single_shadow_value(tokens, allow_inset_keyword);
  4065. });
  4066. }
  4067. RefPtr<CSSStyleValue> Parser::parse_single_shadow_value(TokenStream<ComponentValue>& tokens, AllowInsetKeyword allow_inset_keyword)
  4068. {
  4069. auto transaction = tokens.begin_transaction();
  4070. RefPtr<CSSStyleValue> color;
  4071. RefPtr<CSSStyleValue> offset_x;
  4072. RefPtr<CSSStyleValue> offset_y;
  4073. RefPtr<CSSStyleValue> blur_radius;
  4074. RefPtr<CSSStyleValue> spread_distance;
  4075. Optional<ShadowPlacement> placement;
  4076. auto possibly_dynamic_length = [&](ComponentValue const& token) -> RefPtr<CSSStyleValue> {
  4077. auto tokens = TokenStream<ComponentValue>::of_single_token(token);
  4078. auto maybe_length = parse_length(tokens);
  4079. if (!maybe_length.has_value())
  4080. return nullptr;
  4081. return maybe_length->as_style_value();
  4082. };
  4083. while (tokens.has_next_token()) {
  4084. if (auto maybe_color = parse_color_value(tokens); maybe_color) {
  4085. if (color)
  4086. return nullptr;
  4087. color = maybe_color.release_nonnull();
  4088. continue;
  4089. }
  4090. auto const& token = tokens.next_token();
  4091. if (auto maybe_offset_x = possibly_dynamic_length(token); maybe_offset_x) {
  4092. // horizontal offset
  4093. if (offset_x)
  4094. return nullptr;
  4095. offset_x = maybe_offset_x;
  4096. tokens.discard_a_token();
  4097. // vertical offset
  4098. if (!tokens.has_next_token())
  4099. return nullptr;
  4100. auto maybe_offset_y = possibly_dynamic_length(tokens.next_token());
  4101. if (!maybe_offset_y)
  4102. return nullptr;
  4103. offset_y = maybe_offset_y;
  4104. tokens.discard_a_token();
  4105. // blur radius (optional)
  4106. if (!tokens.has_next_token())
  4107. break;
  4108. auto maybe_blur_radius = possibly_dynamic_length(tokens.next_token());
  4109. if (!maybe_blur_radius)
  4110. continue;
  4111. blur_radius = maybe_blur_radius;
  4112. tokens.discard_a_token();
  4113. // spread distance (optional)
  4114. if (!tokens.has_next_token())
  4115. break;
  4116. auto maybe_spread_distance = possibly_dynamic_length(tokens.next_token());
  4117. if (!maybe_spread_distance)
  4118. continue;
  4119. spread_distance = maybe_spread_distance;
  4120. tokens.discard_a_token();
  4121. continue;
  4122. }
  4123. if (allow_inset_keyword == AllowInsetKeyword::Yes && token.is_ident("inset"sv)) {
  4124. if (placement.has_value())
  4125. return nullptr;
  4126. placement = ShadowPlacement::Inner;
  4127. tokens.discard_a_token();
  4128. continue;
  4129. }
  4130. if (token.is(Token::Type::Comma))
  4131. break;
  4132. return nullptr;
  4133. }
  4134. // If color is absent, default to `currentColor`
  4135. if (!color)
  4136. color = CSSKeywordValue::create(Keyword::Currentcolor);
  4137. // x/y offsets are required
  4138. if (!offset_x || !offset_y)
  4139. return nullptr;
  4140. // Other lengths default to 0
  4141. if (!blur_radius)
  4142. blur_radius = LengthStyleValue::create(Length::make_px(0));
  4143. if (!spread_distance)
  4144. spread_distance = LengthStyleValue::create(Length::make_px(0));
  4145. // Placement is outer by default
  4146. if (!placement.has_value())
  4147. placement = ShadowPlacement::Outer;
  4148. transaction.commit();
  4149. 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());
  4150. }
  4151. RefPtr<CSSStyleValue> Parser::parse_content_value(TokenStream<ComponentValue>& tokens)
  4152. {
  4153. // FIXME: `content` accepts several kinds of function() type, which we don't handle in property_accepts_value() yet.
  4154. auto is_single_value_keyword = [](Keyword keyword) -> bool {
  4155. switch (keyword) {
  4156. case Keyword::None:
  4157. case Keyword::Normal:
  4158. return true;
  4159. default:
  4160. return false;
  4161. }
  4162. };
  4163. if (tokens.remaining_token_count() == 1) {
  4164. auto transaction = tokens.begin_transaction();
  4165. if (auto keyword = parse_keyword_value(tokens)) {
  4166. if (is_single_value_keyword(keyword->to_keyword())) {
  4167. transaction.commit();
  4168. return keyword;
  4169. }
  4170. }
  4171. }
  4172. auto transaction = tokens.begin_transaction();
  4173. StyleValueVector content_values;
  4174. StyleValueVector alt_text_values;
  4175. bool in_alt_text = false;
  4176. while (tokens.has_next_token()) {
  4177. auto& next = tokens.next_token();
  4178. if (next.is_delim('/')) {
  4179. if (in_alt_text || content_values.is_empty())
  4180. return nullptr;
  4181. in_alt_text = true;
  4182. tokens.discard_a_token();
  4183. continue;
  4184. }
  4185. if (auto style_value = parse_css_value_for_property(PropertyID::Content, tokens)) {
  4186. if (is_single_value_keyword(style_value->to_keyword()))
  4187. return nullptr;
  4188. if (in_alt_text) {
  4189. alt_text_values.append(style_value.release_nonnull());
  4190. } else {
  4191. content_values.append(style_value.release_nonnull());
  4192. }
  4193. continue;
  4194. }
  4195. return nullptr;
  4196. }
  4197. if (content_values.is_empty())
  4198. return nullptr;
  4199. if (in_alt_text && alt_text_values.is_empty())
  4200. return nullptr;
  4201. RefPtr<StyleValueList> alt_text;
  4202. if (!alt_text_values.is_empty())
  4203. alt_text = StyleValueList::create(move(alt_text_values), StyleValueList::Separator::Space);
  4204. transaction.commit();
  4205. return ContentStyleValue::create(StyleValueList::create(move(content_values), StyleValueList::Separator::Space), move(alt_text));
  4206. }
  4207. // https://drafts.csswg.org/css-lists-3/#propdef-counter-increment
  4208. RefPtr<CSSStyleValue> Parser::parse_counter_increment_value(TokenStream<ComponentValue>& tokens)
  4209. {
  4210. // [ <counter-name> <integer>? ]+ | none
  4211. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4212. return none;
  4213. return parse_counter_definitions_value(tokens, AllowReversed::No, 1);
  4214. }
  4215. // https://drafts.csswg.org/css-lists-3/#propdef-counter-reset
  4216. RefPtr<CSSStyleValue> Parser::parse_counter_reset_value(TokenStream<ComponentValue>& tokens)
  4217. {
  4218. // [ <counter-name> <integer>? | <reversed-counter-name> <integer>? ]+ | none
  4219. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4220. return none;
  4221. return parse_counter_definitions_value(tokens, AllowReversed::Yes, 0);
  4222. }
  4223. // https://drafts.csswg.org/css-lists-3/#propdef-counter-set
  4224. RefPtr<CSSStyleValue> Parser::parse_counter_set_value(TokenStream<ComponentValue>& tokens)
  4225. {
  4226. // [ <counter-name> <integer>? ]+ | none
  4227. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4228. return none;
  4229. return parse_counter_definitions_value(tokens, AllowReversed::No, 0);
  4230. }
  4231. // https://www.w3.org/TR/css-display-3/#the-display-properties
  4232. RefPtr<CSSStyleValue> Parser::parse_display_value(TokenStream<ComponentValue>& tokens)
  4233. {
  4234. auto parse_single_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  4235. auto transaction = tokens.begin_transaction();
  4236. if (auto keyword_value = parse_keyword_value(tokens)) {
  4237. auto keyword = keyword_value->to_keyword();
  4238. if (keyword == Keyword::ListItem) {
  4239. transaction.commit();
  4240. return Display::from_short(Display::Short::ListItem);
  4241. }
  4242. if (auto display_outside = keyword_to_display_outside(keyword); display_outside.has_value()) {
  4243. transaction.commit();
  4244. switch (display_outside.value()) {
  4245. case DisplayOutside::Block:
  4246. return Display::from_short(Display::Short::Block);
  4247. case DisplayOutside::Inline:
  4248. return Display::from_short(Display::Short::Inline);
  4249. case DisplayOutside::RunIn:
  4250. return Display::from_short(Display::Short::RunIn);
  4251. }
  4252. }
  4253. if (auto display_inside = keyword_to_display_inside(keyword); display_inside.has_value()) {
  4254. transaction.commit();
  4255. switch (display_inside.value()) {
  4256. case DisplayInside::Flow:
  4257. return Display::from_short(Display::Short::Flow);
  4258. case DisplayInside::FlowRoot:
  4259. return Display::from_short(Display::Short::FlowRoot);
  4260. case DisplayInside::Table:
  4261. return Display::from_short(Display::Short::Table);
  4262. case DisplayInside::Flex:
  4263. return Display::from_short(Display::Short::Flex);
  4264. case DisplayInside::Grid:
  4265. return Display::from_short(Display::Short::Grid);
  4266. case DisplayInside::Ruby:
  4267. return Display::from_short(Display::Short::Ruby);
  4268. case DisplayInside::Math:
  4269. return Display::from_short(Display::Short::Math);
  4270. }
  4271. }
  4272. if (auto display_internal = keyword_to_display_internal(keyword); display_internal.has_value()) {
  4273. transaction.commit();
  4274. return Display { display_internal.value() };
  4275. }
  4276. if (auto display_box = keyword_to_display_box(keyword); display_box.has_value()) {
  4277. transaction.commit();
  4278. switch (display_box.value()) {
  4279. case DisplayBox::Contents:
  4280. return Display::from_short(Display::Short::Contents);
  4281. case DisplayBox::None:
  4282. return Display::from_short(Display::Short::None);
  4283. }
  4284. }
  4285. if (auto display_legacy = keyword_to_display_legacy(keyword); display_legacy.has_value()) {
  4286. transaction.commit();
  4287. switch (display_legacy.value()) {
  4288. case DisplayLegacy::InlineBlock:
  4289. return Display::from_short(Display::Short::InlineBlock);
  4290. case DisplayLegacy::InlineTable:
  4291. return Display::from_short(Display::Short::InlineTable);
  4292. case DisplayLegacy::InlineFlex:
  4293. return Display::from_short(Display::Short::InlineFlex);
  4294. case DisplayLegacy::InlineGrid:
  4295. return Display::from_short(Display::Short::InlineGrid);
  4296. }
  4297. }
  4298. }
  4299. return OptionalNone {};
  4300. };
  4301. auto parse_multi_component_display = [this](TokenStream<ComponentValue>& tokens) -> Optional<Display> {
  4302. auto list_item = Display::ListItem::No;
  4303. Optional<DisplayInside> inside;
  4304. Optional<DisplayOutside> outside;
  4305. auto transaction = tokens.begin_transaction();
  4306. while (tokens.has_next_token()) {
  4307. if (auto value = parse_keyword_value(tokens)) {
  4308. auto keyword = value->to_keyword();
  4309. if (keyword == Keyword::ListItem) {
  4310. if (list_item == Display::ListItem::Yes)
  4311. return {};
  4312. list_item = Display::ListItem::Yes;
  4313. continue;
  4314. }
  4315. if (auto inside_value = keyword_to_display_inside(keyword); inside_value.has_value()) {
  4316. if (inside.has_value())
  4317. return {};
  4318. inside = inside_value.value();
  4319. continue;
  4320. }
  4321. if (auto outside_value = keyword_to_display_outside(keyword); outside_value.has_value()) {
  4322. if (outside.has_value())
  4323. return {};
  4324. outside = outside_value.value();
  4325. continue;
  4326. }
  4327. }
  4328. // Not a display value, abort.
  4329. dbgln_if(CSS_PARSER_DEBUG, "Unrecognized display value: `{}`", tokens.next_token().to_string());
  4330. return {};
  4331. }
  4332. // The spec does not allow any other inside values to be combined with list-item
  4333. // <display-outside>? && [ flow | flow-root ]? && list-item
  4334. if (list_item == Display::ListItem::Yes && inside.has_value() && inside != DisplayInside::Flow && inside != DisplayInside::FlowRoot)
  4335. return {};
  4336. transaction.commit();
  4337. return Display { outside.value_or(DisplayOutside::Block), inside.value_or(DisplayInside::Flow), list_item };
  4338. };
  4339. Optional<Display> display;
  4340. if (tokens.remaining_token_count() == 1)
  4341. display = parse_single_component_display(tokens);
  4342. else
  4343. display = parse_multi_component_display(tokens);
  4344. if (display.has_value())
  4345. return DisplayStyleValue::create(display.value());
  4346. return nullptr;
  4347. }
  4348. RefPtr<CSSStyleValue> Parser::parse_filter_value_list_value(TokenStream<ComponentValue>& tokens)
  4349. {
  4350. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  4351. return none;
  4352. auto transaction = tokens.begin_transaction();
  4353. // FIXME: <url>s are ignored for now
  4354. // <filter-value-list> = [ <filter-function> | <url> ]+
  4355. enum class FilterToken {
  4356. // Color filters:
  4357. Brightness,
  4358. Contrast,
  4359. Grayscale,
  4360. Invert,
  4361. Opacity,
  4362. Saturate,
  4363. Sepia,
  4364. // Special filters:
  4365. Blur,
  4366. DropShadow,
  4367. HueRotate
  4368. };
  4369. auto filter_token_to_operation = [&](auto filter) {
  4370. VERIFY(to_underlying(filter) < to_underlying(FilterToken::Blur));
  4371. return static_cast<Filter::Color::Operation>(filter);
  4372. };
  4373. auto parse_number_percentage = [&](auto& token) -> Optional<NumberPercentage> {
  4374. if (token.is(Token::Type::Percentage))
  4375. return NumberPercentage(Percentage(token.token().percentage()));
  4376. if (token.is(Token::Type::Number))
  4377. return NumberPercentage(Number(Number::Type::Number, token.token().number_value()));
  4378. return {};
  4379. };
  4380. auto parse_filter_function_name = [&](auto name) -> Optional<FilterToken> {
  4381. if (name.equals_ignoring_ascii_case("blur"sv))
  4382. return FilterToken::Blur;
  4383. if (name.equals_ignoring_ascii_case("brightness"sv))
  4384. return FilterToken::Brightness;
  4385. if (name.equals_ignoring_ascii_case("contrast"sv))
  4386. return FilterToken::Contrast;
  4387. if (name.equals_ignoring_ascii_case("drop-shadow"sv))
  4388. return FilterToken::DropShadow;
  4389. if (name.equals_ignoring_ascii_case("grayscale"sv))
  4390. return FilterToken::Grayscale;
  4391. if (name.equals_ignoring_ascii_case("hue-rotate"sv))
  4392. return FilterToken::HueRotate;
  4393. if (name.equals_ignoring_ascii_case("invert"sv))
  4394. return FilterToken::Invert;
  4395. if (name.equals_ignoring_ascii_case("opacity"sv))
  4396. return FilterToken::Opacity;
  4397. if (name.equals_ignoring_ascii_case("saturate"sv))
  4398. return FilterToken::Saturate;
  4399. if (name.equals_ignoring_ascii_case("sepia"sv))
  4400. return FilterToken::Sepia;
  4401. return {};
  4402. };
  4403. auto parse_filter_function = [&](auto filter_token, auto function_values) -> Optional<FilterFunction> {
  4404. TokenStream tokens { function_values };
  4405. tokens.discard_whitespace();
  4406. auto if_no_more_tokens_return = [&](auto filter) -> Optional<FilterFunction> {
  4407. tokens.discard_whitespace();
  4408. if (tokens.has_next_token())
  4409. return {};
  4410. return filter;
  4411. };
  4412. if (filter_token == FilterToken::Blur) {
  4413. // blur( <length>? )
  4414. if (!tokens.has_next_token())
  4415. return Filter::Blur {};
  4416. auto blur_radius = parse_length(tokens);
  4417. tokens.discard_whitespace();
  4418. if (!blur_radius.has_value())
  4419. return {};
  4420. // FIXME: Support calculated radius
  4421. return if_no_more_tokens_return(Filter::Blur { blur_radius->value() });
  4422. } else if (filter_token == FilterToken::DropShadow) {
  4423. if (!tokens.has_next_token())
  4424. return {};
  4425. // drop-shadow( [ <color>? && <length>{2,3} ] )
  4426. // Note: The following code is a little awkward to allow the color to be before or after the lengths.
  4427. Optional<LengthOrCalculated> maybe_radius = {};
  4428. auto maybe_color = parse_color_value(tokens);
  4429. auto x_offset = parse_length(tokens);
  4430. tokens.discard_whitespace();
  4431. if (!x_offset.has_value() || !tokens.has_next_token()) {
  4432. return {};
  4433. }
  4434. auto y_offset = parse_length(tokens);
  4435. if (!y_offset.has_value()) {
  4436. return {};
  4437. }
  4438. if (tokens.has_next_token()) {
  4439. maybe_radius = parse_length(tokens);
  4440. if (!maybe_color && (!maybe_radius.has_value() || tokens.has_next_token())) {
  4441. maybe_color = parse_color_value(tokens);
  4442. tokens.discard_whitespace();
  4443. if (!maybe_color)
  4444. return {};
  4445. } else if (!maybe_radius.has_value()) {
  4446. return {};
  4447. }
  4448. }
  4449. // FIXME: Support calculated offsets and radius
  4450. return if_no_more_tokens_return(Filter::DropShadow { x_offset->value(), y_offset->value(), maybe_radius.map([](auto& it) { return it.value(); }), maybe_color->to_color({}) });
  4451. } else if (filter_token == FilterToken::HueRotate) {
  4452. // hue-rotate( [ <angle> | <zero> ]? )
  4453. if (!tokens.has_next_token())
  4454. return Filter::HueRotate {};
  4455. auto& token = tokens.consume_a_token();
  4456. if (token.is(Token::Type::Number)) {
  4457. // hue-rotate(0)
  4458. auto number = token.token().number();
  4459. if (number.is_integer() && number.integer_value() == 0)
  4460. return if_no_more_tokens_return(Filter::HueRotate { Filter::HueRotate::Zero {} });
  4461. return {};
  4462. }
  4463. if (!token.is(Token::Type::Dimension))
  4464. return {};
  4465. auto angle_value = token.token().dimension_value();
  4466. auto angle_unit_name = token.token().dimension_unit();
  4467. auto angle_unit = Angle::unit_from_name(angle_unit_name);
  4468. if (!angle_unit.has_value())
  4469. return {};
  4470. Angle angle { angle_value, angle_unit.release_value() };
  4471. return if_no_more_tokens_return(Filter::HueRotate { angle });
  4472. } else {
  4473. // Simple filters:
  4474. // brightness( <number-percentage>? )
  4475. // contrast( <number-percentage>? )
  4476. // grayscale( <number-percentage>? )
  4477. // invert( <number-percentage>? )
  4478. // opacity( <number-percentage>? )
  4479. // sepia( <number-percentage>? )
  4480. // saturate( <number-percentage>? )
  4481. if (!tokens.has_next_token())
  4482. return Filter::Color { filter_token_to_operation(filter_token) };
  4483. auto amount = parse_number_percentage(tokens.consume_a_token());
  4484. if (!amount.has_value())
  4485. return {};
  4486. return if_no_more_tokens_return(Filter::Color { filter_token_to_operation(filter_token), *amount });
  4487. }
  4488. };
  4489. Vector<FilterFunction> filter_value_list {};
  4490. while (tokens.has_next_token()) {
  4491. tokens.discard_whitespace();
  4492. if (!tokens.has_next_token())
  4493. break;
  4494. auto& token = tokens.consume_a_token();
  4495. if (!token.is_function())
  4496. return nullptr;
  4497. auto filter_token = parse_filter_function_name(token.function().name);
  4498. if (!filter_token.has_value())
  4499. return nullptr;
  4500. auto filter_function = parse_filter_function(*filter_token, token.function().value);
  4501. if (!filter_function.has_value())
  4502. return nullptr;
  4503. filter_value_list.append(*filter_function);
  4504. }
  4505. if (filter_value_list.is_empty())
  4506. return nullptr;
  4507. transaction.commit();
  4508. return FilterValueListStyleValue::create(move(filter_value_list));
  4509. }
  4510. RefPtr<CSSStyleValue> Parser::parse_flex_shorthand_value(TokenStream<ComponentValue>& tokens)
  4511. {
  4512. auto transaction = tokens.begin_transaction();
  4513. auto make_flex_shorthand = [&](NonnullRefPtr<CSSStyleValue> flex_grow, NonnullRefPtr<CSSStyleValue> flex_shrink, NonnullRefPtr<CSSStyleValue> flex_basis) {
  4514. transaction.commit();
  4515. return ShorthandStyleValue::create(PropertyID::Flex,
  4516. { PropertyID::FlexGrow, PropertyID::FlexShrink, PropertyID::FlexBasis },
  4517. { move(flex_grow), move(flex_shrink), move(flex_basis) });
  4518. };
  4519. if (tokens.remaining_token_count() == 1) {
  4520. // One-value syntax: <flex-grow> | <flex-basis> | none
  4521. auto properties = Array { PropertyID::FlexGrow, PropertyID::FlexBasis, PropertyID::Flex };
  4522. auto property_and_value = parse_css_value_for_properties(properties, tokens);
  4523. if (!property_and_value.has_value())
  4524. return nullptr;
  4525. auto& value = property_and_value->style_value;
  4526. switch (property_and_value->property) {
  4527. case PropertyID::FlexGrow: {
  4528. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4529. // https://github.com/w3c/csswg-drafts/issues/5742
  4530. auto flex_basis = PercentageStyleValue::create(Percentage(0));
  4531. auto one = NumberStyleValue::create(1);
  4532. return make_flex_shorthand(*value, one, flex_basis);
  4533. }
  4534. case PropertyID::FlexBasis: {
  4535. auto one = NumberStyleValue::create(1);
  4536. return make_flex_shorthand(one, one, *value);
  4537. }
  4538. case PropertyID::Flex: {
  4539. if (value->is_keyword() && value->to_keyword() == Keyword::None) {
  4540. auto zero = NumberStyleValue::create(0);
  4541. return make_flex_shorthand(zero, zero, CSSKeywordValue::create(Keyword::Auto));
  4542. }
  4543. break;
  4544. }
  4545. default:
  4546. VERIFY_NOT_REACHED();
  4547. }
  4548. return nullptr;
  4549. }
  4550. RefPtr<CSSStyleValue> flex_grow;
  4551. RefPtr<CSSStyleValue> flex_shrink;
  4552. RefPtr<CSSStyleValue> flex_basis;
  4553. // NOTE: FlexGrow has to be before FlexBasis. `0` is a valid FlexBasis, but only
  4554. // if FlexGrow (along with optional FlexShrink) have already been specified.
  4555. auto remaining_longhands = Vector { PropertyID::FlexGrow, PropertyID::FlexBasis };
  4556. while (tokens.has_next_token()) {
  4557. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4558. if (!property_and_value.has_value())
  4559. return nullptr;
  4560. auto& value = property_and_value->style_value;
  4561. remove_property(remaining_longhands, property_and_value->property);
  4562. switch (property_and_value->property) {
  4563. case PropertyID::FlexGrow: {
  4564. VERIFY(!flex_grow);
  4565. flex_grow = value.release_nonnull();
  4566. // Flex-shrink may optionally follow directly after.
  4567. auto maybe_flex_shrink = parse_css_value_for_property(PropertyID::FlexShrink, tokens);
  4568. if (maybe_flex_shrink)
  4569. flex_shrink = maybe_flex_shrink.release_nonnull();
  4570. continue;
  4571. }
  4572. case PropertyID::FlexBasis: {
  4573. VERIFY(!flex_basis);
  4574. flex_basis = value.release_nonnull();
  4575. continue;
  4576. }
  4577. default:
  4578. VERIFY_NOT_REACHED();
  4579. }
  4580. }
  4581. if (!flex_grow)
  4582. flex_grow = property_initial_value(m_context.realm(), PropertyID::FlexGrow);
  4583. if (!flex_shrink)
  4584. flex_shrink = property_initial_value(m_context.realm(), PropertyID::FlexShrink);
  4585. if (!flex_basis) {
  4586. // NOTE: The spec says that flex-basis should be 0 here, but other engines currently use 0%.
  4587. // https://github.com/w3c/csswg-drafts/issues/5742
  4588. flex_basis = PercentageStyleValue::create(Percentage(0));
  4589. }
  4590. return make_flex_shorthand(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  4591. }
  4592. RefPtr<CSSStyleValue> Parser::parse_flex_flow_value(TokenStream<ComponentValue>& tokens)
  4593. {
  4594. RefPtr<CSSStyleValue> flex_direction;
  4595. RefPtr<CSSStyleValue> flex_wrap;
  4596. auto remaining_longhands = Vector { PropertyID::FlexDirection, PropertyID::FlexWrap };
  4597. auto transaction = tokens.begin_transaction();
  4598. while (tokens.has_next_token()) {
  4599. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4600. if (!property_and_value.has_value())
  4601. return nullptr;
  4602. auto& value = property_and_value->style_value;
  4603. remove_property(remaining_longhands, property_and_value->property);
  4604. switch (property_and_value->property) {
  4605. case PropertyID::FlexDirection:
  4606. VERIFY(!flex_direction);
  4607. flex_direction = value.release_nonnull();
  4608. continue;
  4609. case PropertyID::FlexWrap:
  4610. VERIFY(!flex_wrap);
  4611. flex_wrap = value.release_nonnull();
  4612. continue;
  4613. default:
  4614. VERIFY_NOT_REACHED();
  4615. }
  4616. }
  4617. if (!flex_direction)
  4618. flex_direction = property_initial_value(m_context.realm(), PropertyID::FlexDirection);
  4619. if (!flex_wrap)
  4620. flex_wrap = property_initial_value(m_context.realm(), PropertyID::FlexWrap);
  4621. transaction.commit();
  4622. return ShorthandStyleValue::create(PropertyID::FlexFlow,
  4623. { PropertyID::FlexDirection, PropertyID::FlexWrap },
  4624. { flex_direction.release_nonnull(), flex_wrap.release_nonnull() });
  4625. }
  4626. static bool is_generic_font_family(Keyword keyword)
  4627. {
  4628. switch (keyword) {
  4629. case Keyword::Cursive:
  4630. case Keyword::Fantasy:
  4631. case Keyword::Monospace:
  4632. case Keyword::Serif:
  4633. case Keyword::SansSerif:
  4634. case Keyword::UiMonospace:
  4635. case Keyword::UiRounded:
  4636. case Keyword::UiSerif:
  4637. case Keyword::UiSansSerif:
  4638. return true;
  4639. default:
  4640. return false;
  4641. }
  4642. }
  4643. RefPtr<CSSStyleValue> Parser::parse_font_value(TokenStream<ComponentValue>& tokens)
  4644. {
  4645. RefPtr<CSSStyleValue> font_width;
  4646. RefPtr<CSSStyleValue> font_style;
  4647. RefPtr<CSSStyleValue> font_weight;
  4648. RefPtr<CSSStyleValue> font_size;
  4649. RefPtr<CSSStyleValue> line_height;
  4650. RefPtr<CSSStyleValue> font_families;
  4651. RefPtr<CSSStyleValue> font_variant;
  4652. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  4653. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  4654. // So, we have to handle that separately.
  4655. int normal_count = 0;
  4656. // FIXME: `font-variant` allows a lot of different values which aren't allowed in the `font` shorthand.
  4657. // FIXME: `font-width` allows <percentage> values, which aren't allowed in the `font` shorthand.
  4658. auto remaining_longhands = Vector { PropertyID::FontSize, PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontWidth };
  4659. auto transaction = tokens.begin_transaction();
  4660. while (tokens.has_next_token()) {
  4661. auto& peek_token = tokens.next_token();
  4662. if (peek_token.is_ident("normal"sv)) {
  4663. normal_count++;
  4664. tokens.discard_a_token();
  4665. continue;
  4666. }
  4667. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  4668. if (!property_and_value.has_value())
  4669. return nullptr;
  4670. auto& value = property_and_value->style_value;
  4671. remove_property(remaining_longhands, property_and_value->property);
  4672. switch (property_and_value->property) {
  4673. case PropertyID::FontSize: {
  4674. VERIFY(!font_size);
  4675. font_size = value.release_nonnull();
  4676. // Consume `/ line-height` if present
  4677. if (tokens.next_token().is_delim('/')) {
  4678. tokens.discard_a_token();
  4679. auto maybe_line_height = parse_css_value_for_property(PropertyID::LineHeight, tokens);
  4680. if (!maybe_line_height)
  4681. return nullptr;
  4682. line_height = maybe_line_height.release_nonnull();
  4683. }
  4684. // Consume font-families
  4685. auto maybe_font_families = parse_font_family_value(tokens);
  4686. // font-family comes last, so we must not have any tokens left over.
  4687. if (!maybe_font_families || tokens.has_next_token())
  4688. return nullptr;
  4689. font_families = maybe_font_families.release_nonnull();
  4690. continue;
  4691. }
  4692. case PropertyID::FontWidth: {
  4693. VERIFY(!font_width);
  4694. font_width = value.release_nonnull();
  4695. continue;
  4696. }
  4697. case PropertyID::FontStyle: {
  4698. VERIFY(!font_style);
  4699. font_style = value.release_nonnull();
  4700. continue;
  4701. }
  4702. case PropertyID::FontVariant: {
  4703. VERIFY(!font_variant);
  4704. font_variant = value.release_nonnull();
  4705. continue;
  4706. }
  4707. case PropertyID::FontWeight: {
  4708. VERIFY(!font_weight);
  4709. font_weight = value.release_nonnull();
  4710. continue;
  4711. }
  4712. default:
  4713. VERIFY_NOT_REACHED();
  4714. }
  4715. return nullptr;
  4716. }
  4717. // Since normal is the default value for all the properties that can have it, we don't have to actually
  4718. // set anything to normal here. It'll be set when we create the ShorthandStyleValue below.
  4719. // We just need to make sure we were not given more normals than will fit.
  4720. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1) + (font_variant ? 0 : 1) + (font_width ? 0 : 1);
  4721. if (unset_value_count < normal_count)
  4722. return nullptr;
  4723. if (!font_size || !font_families)
  4724. return nullptr;
  4725. if (!font_style)
  4726. font_style = property_initial_value(m_context.realm(), PropertyID::FontStyle);
  4727. if (!font_variant)
  4728. font_variant = property_initial_value(m_context.realm(), PropertyID::FontVariant);
  4729. if (!font_weight)
  4730. font_weight = property_initial_value(m_context.realm(), PropertyID::FontWeight);
  4731. if (!font_width)
  4732. font_width = property_initial_value(m_context.realm(), PropertyID::FontWidth);
  4733. if (!line_height)
  4734. line_height = property_initial_value(m_context.realm(), PropertyID::LineHeight);
  4735. transaction.commit();
  4736. return ShorthandStyleValue::create(PropertyID::Font,
  4737. { PropertyID::FontStyle, PropertyID::FontVariant, PropertyID::FontWeight, PropertyID::FontWidth, PropertyID::FontSize, PropertyID::LineHeight, PropertyID::FontFamily },
  4738. { 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() });
  4739. }
  4740. RefPtr<CSSStyleValue> Parser::parse_font_family_value(TokenStream<ComponentValue>& tokens)
  4741. {
  4742. auto next_is_comma_or_eof = [&]() -> bool {
  4743. return !tokens.has_next_token() || tokens.next_token().is(Token::Type::Comma);
  4744. };
  4745. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  4746. // eg, these are equivalent:
  4747. // font-family: my cool font\!, serif;
  4748. // font-family: "my cool font!", serif;
  4749. StyleValueVector font_families;
  4750. Vector<String> current_name_parts;
  4751. while (tokens.has_next_token()) {
  4752. auto const& peek = tokens.next_token();
  4753. if (peek.is(Token::Type::String)) {
  4754. // `font-family: my cool "font";` is invalid.
  4755. if (!current_name_parts.is_empty())
  4756. return nullptr;
  4757. tokens.discard_a_token(); // String
  4758. if (!next_is_comma_or_eof())
  4759. return nullptr;
  4760. font_families.append(StringStyleValue::create(peek.token().string()));
  4761. tokens.discard_a_token(); // Comma
  4762. continue;
  4763. }
  4764. if (peek.is(Token::Type::Ident)) {
  4765. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  4766. // CSS-wide keywords are not allowed
  4767. if (auto builtin = parse_builtin_value(tokens))
  4768. return nullptr;
  4769. auto maybe_keyword = keyword_from_string(peek.token().ident());
  4770. // Can't have a generic-font-name as a token in an unquoted font name.
  4771. if (maybe_keyword.has_value() && is_generic_font_family(maybe_keyword.value())) {
  4772. if (!current_name_parts.is_empty())
  4773. return nullptr;
  4774. tokens.discard_a_token(); // Ident
  4775. if (!next_is_comma_or_eof())
  4776. return nullptr;
  4777. font_families.append(CSSKeywordValue::create(maybe_keyword.value()));
  4778. tokens.discard_a_token(); // Comma
  4779. continue;
  4780. }
  4781. current_name_parts.append(tokens.consume_a_token().token().ident().to_string());
  4782. continue;
  4783. }
  4784. if (peek.is(Token::Type::Comma)) {
  4785. if (current_name_parts.is_empty())
  4786. return nullptr;
  4787. tokens.discard_a_token(); // Comma
  4788. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  4789. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  4790. current_name_parts.clear();
  4791. // Can't have a trailing comma
  4792. if (!tokens.has_next_token())
  4793. return nullptr;
  4794. continue;
  4795. }
  4796. return nullptr;
  4797. }
  4798. if (!current_name_parts.is_empty()) {
  4799. // This is really a series of custom-idents, not just one. But for the sake of simplicity we'll make it one.
  4800. font_families.append(CustomIdentStyleValue::create(MUST(String::join(' ', current_name_parts))));
  4801. current_name_parts.clear();
  4802. }
  4803. if (font_families.is_empty())
  4804. return nullptr;
  4805. return StyleValueList::create(move(font_families), StyleValueList::Separator::Comma);
  4806. }
  4807. RefPtr<CSSStyleValue> Parser::parse_font_language_override_value(TokenStream<ComponentValue>& tokens)
  4808. {
  4809. // https://drafts.csswg.org/css-fonts/#propdef-font-language-override
  4810. // This is `normal | <string>` but with the constraint that the string has to be 4 characters long:
  4811. // Shorter strings are right-padded with spaces, and longer strings are invalid.
  4812. if (auto normal = parse_all_as_single_keyword_value(tokens, Keyword::Normal))
  4813. return normal;
  4814. auto transaction = tokens.begin_transaction();
  4815. tokens.discard_whitespace();
  4816. if (auto string = parse_string_value(tokens)) {
  4817. auto string_value = string->string_value();
  4818. tokens.discard_whitespace();
  4819. if (tokens.has_next_token()) {
  4820. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse font-language-override: unexpected trailing tokens");
  4821. return nullptr;
  4822. }
  4823. auto length = string_value.code_points().length();
  4824. if (length > 4) {
  4825. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse font-language-override: <string> value \"{}\" is too long", string_value);
  4826. return nullptr;
  4827. }
  4828. transaction.commit();
  4829. if (length < 4)
  4830. return StringStyleValue::create(MUST(String::formatted("{<4}", string_value)));
  4831. return string;
  4832. }
  4833. return nullptr;
  4834. }
  4835. RefPtr<CSSStyleValue> Parser::parse_font_feature_settings_value(TokenStream<ComponentValue>& tokens)
  4836. {
  4837. // https://drafts.csswg.org/css-fonts/#propdef-font-feature-settings
  4838. // normal | <feature-tag-value>#
  4839. // normal
  4840. if (auto normal = parse_all_as_single_keyword_value(tokens, Keyword::Normal))
  4841. return normal;
  4842. // <feature-tag-value>#
  4843. auto transaction = tokens.begin_transaction();
  4844. auto tag_values = parse_a_comma_separated_list_of_component_values(tokens);
  4845. // "The computed value of font-feature-settings is a map, so any duplicates in the specified value must not be preserved.
  4846. // If the same feature tag appears more than once, the value associated with the last appearance supersedes any previous
  4847. // value for that axis."
  4848. // So, we deduplicate them here using a HashSet.
  4849. OrderedHashMap<FlyString, NonnullRefPtr<OpenTypeTaggedStyleValue>> feature_tags_map;
  4850. for (auto const& values : tag_values) {
  4851. // <feature-tag-value> = <opentype-tag> [ <integer [0,∞]> | on | off ]?
  4852. TokenStream tag_tokens { values };
  4853. tag_tokens.discard_whitespace();
  4854. auto opentype_tag = parse_opentype_tag_value(tag_tokens);
  4855. tag_tokens.discard_whitespace();
  4856. RefPtr<CSSStyleValue> value;
  4857. if (tag_tokens.has_next_token()) {
  4858. if (auto integer = parse_integer_value(tag_tokens)) {
  4859. if (integer->is_integer() && integer->as_integer().value() < 0)
  4860. return nullptr;
  4861. value = integer;
  4862. } else {
  4863. // A value of on is synonymous with 1 and off is synonymous with 0.
  4864. auto keyword = parse_keyword_value(tag_tokens);
  4865. if (!keyword)
  4866. return nullptr;
  4867. switch (keyword->to_keyword()) {
  4868. case Keyword::On:
  4869. value = IntegerStyleValue::create(1);
  4870. break;
  4871. case Keyword::Off:
  4872. value = IntegerStyleValue::create(0);
  4873. break;
  4874. default:
  4875. return nullptr;
  4876. }
  4877. }
  4878. tag_tokens.discard_whitespace();
  4879. } else {
  4880. // "If the value is omitted, a value of 1 is assumed."
  4881. value = IntegerStyleValue::create(1);
  4882. }
  4883. if (!opentype_tag || !value || tag_tokens.has_next_token())
  4884. return nullptr;
  4885. feature_tags_map.set(opentype_tag->string_value(), OpenTypeTaggedStyleValue::create(opentype_tag->string_value(), value.release_nonnull()));
  4886. }
  4887. // "The computed value contains the de-duplicated feature tags, sorted in ascending order by code unit."
  4888. StyleValueVector feature_tags;
  4889. feature_tags.ensure_capacity(feature_tags_map.size());
  4890. for (auto const& [key, feature_tag] : feature_tags_map)
  4891. feature_tags.append(feature_tag);
  4892. quick_sort(feature_tags, [](auto& a, auto& b) {
  4893. return a->as_open_type_tagged().tag() < b->as_open_type_tagged().tag();
  4894. });
  4895. transaction.commit();
  4896. return StyleValueList::create(move(feature_tags), StyleValueList::Separator::Comma);
  4897. }
  4898. RefPtr<CSSStyleValue> Parser::parse_font_variation_settings_value(TokenStream<ComponentValue>& tokens)
  4899. {
  4900. // https://drafts.csswg.org/css-fonts/#propdef-font-variation-settings
  4901. // normal | [ <opentype-tag> <number>]#
  4902. // normal
  4903. if (auto normal = parse_all_as_single_keyword_value(tokens, Keyword::Normal))
  4904. return normal;
  4905. // [ <opentype-tag> <number>]#
  4906. auto transaction = tokens.begin_transaction();
  4907. auto tag_values = parse_a_comma_separated_list_of_component_values(tokens);
  4908. // "If the same axis name appears more than once, the value associated with the last appearance supersedes any
  4909. // previous value for that axis. This deduplication is observable by accessing the computed value of this property."
  4910. // So, we deduplicate them here using a HashSet.
  4911. OrderedHashMap<FlyString, NonnullRefPtr<OpenTypeTaggedStyleValue>> axis_tags_map;
  4912. for (auto const& values : tag_values) {
  4913. TokenStream tag_tokens { values };
  4914. tag_tokens.discard_whitespace();
  4915. auto opentype_tag = parse_opentype_tag_value(tag_tokens);
  4916. tag_tokens.discard_whitespace();
  4917. auto number = parse_number_value(tag_tokens);
  4918. tag_tokens.discard_whitespace();
  4919. if (!opentype_tag || !number || tag_tokens.has_next_token())
  4920. return nullptr;
  4921. axis_tags_map.set(opentype_tag->string_value(), OpenTypeTaggedStyleValue::create(opentype_tag->string_value(), number.release_nonnull()));
  4922. }
  4923. // "The computed value contains the de-duplicated axis names, sorted in ascending order by code unit."
  4924. StyleValueVector axis_tags;
  4925. axis_tags.ensure_capacity(axis_tags_map.size());
  4926. for (auto const& [key, axis_tag] : axis_tags_map)
  4927. axis_tags.append(axis_tag);
  4928. quick_sort(axis_tags, [](auto& a, auto& b) {
  4929. return a->as_open_type_tagged().tag() < b->as_open_type_tagged().tag();
  4930. });
  4931. transaction.commit();
  4932. return StyleValueList::create(move(axis_tags), StyleValueList::Separator::Comma);
  4933. }
  4934. JS::GCPtr<CSSFontFaceRule> Parser::convert_to_font_face_rule(AtRule const& rule)
  4935. {
  4936. // https://drafts.csswg.org/css-fonts/#font-face-rule
  4937. Optional<FlyString> font_family;
  4938. Optional<FlyString> font_named_instance;
  4939. Vector<ParsedFontFace::Source> src;
  4940. Vector<Gfx::UnicodeRange> unicode_range;
  4941. Optional<int> weight;
  4942. Optional<int> slope;
  4943. Optional<int> width;
  4944. Optional<Percentage> ascent_override;
  4945. Optional<Percentage> descent_override;
  4946. Optional<Percentage> line_gap_override;
  4947. FontDisplay font_display = FontDisplay::Auto;
  4948. Optional<FlyString> language_override;
  4949. Optional<OrderedHashMap<FlyString, i64>> font_feature_settings;
  4950. Optional<OrderedHashMap<FlyString, double>> font_variation_settings;
  4951. // "normal" is returned as nullptr
  4952. auto parse_as_percentage_or_normal = [&](Vector<ComponentValue> const& values) -> ErrorOr<Optional<Percentage>> {
  4953. // normal | <percentage [0,∞]>
  4954. TokenStream tokens { values };
  4955. if (auto percentage_value = parse_percentage_value(tokens)) {
  4956. tokens.discard_whitespace();
  4957. if (tokens.has_next_token())
  4958. return Error::from_string_literal("Unexpected trailing tokens");
  4959. if (percentage_value->is_percentage() && percentage_value->as_percentage().percentage().value() >= 0)
  4960. return percentage_value->as_percentage().percentage();
  4961. // TODO: Once we implement calc-simplification in the parser, we should no longer see math values here,
  4962. // unless they're impossible to resolve and thus invalid.
  4963. if (percentage_value->is_math()) {
  4964. if (auto result = percentage_value->as_math().resolve_percentage(); result.has_value())
  4965. return result.value();
  4966. }
  4967. return Error::from_string_literal("Invalid percentage");
  4968. }
  4969. tokens.discard_whitespace();
  4970. if (!tokens.consume_a_token().is_ident("normal"sv))
  4971. return Error::from_string_literal("Expected `normal | <percentage [0,∞]>`");
  4972. tokens.discard_whitespace();
  4973. if (tokens.has_next_token())
  4974. return Error::from_string_literal("Unexpected trailing tokens");
  4975. return OptionalNone {};
  4976. };
  4977. rule.for_each_as_declaration_list([&](auto& declaration) {
  4978. if (declaration.name.equals_ignoring_ascii_case("ascent-override"sv)) {
  4979. auto value = parse_as_percentage_or_normal(declaration.value);
  4980. if (value.is_error()) {
  4981. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face ascent-override: {}", value.error());
  4982. } else {
  4983. ascent_override = value.release_value();
  4984. }
  4985. return;
  4986. }
  4987. if (declaration.name.equals_ignoring_ascii_case("descent-override"sv)) {
  4988. auto value = parse_as_percentage_or_normal(declaration.value);
  4989. if (value.is_error()) {
  4990. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face descent-override: {}", value.error());
  4991. } else {
  4992. descent_override = value.release_value();
  4993. }
  4994. return;
  4995. }
  4996. if (declaration.name.equals_ignoring_ascii_case("font-display"sv)) {
  4997. TokenStream token_stream { declaration.value };
  4998. if (auto keyword_value = parse_keyword_value(token_stream)) {
  4999. token_stream.discard_whitespace();
  5000. if (token_stream.has_next_token()) {
  5001. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unexpected trailing tokens in font-display");
  5002. } else {
  5003. auto value = keyword_to_font_display(keyword_value->to_keyword());
  5004. if (value.has_value()) {
  5005. font_display = *value;
  5006. } else {
  5007. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: `{}` is not a valid value for font-display", keyword_value->to_string());
  5008. }
  5009. }
  5010. }
  5011. return;
  5012. }
  5013. if (declaration.name.equals_ignoring_ascii_case("font-family"sv)) {
  5014. // FIXME: This is very similar to, but different from, the logic in parse_font_family_value().
  5015. // Ideally they could share code.
  5016. Vector<FlyString> font_family_parts;
  5017. bool had_syntax_error = false;
  5018. for (size_t i = 0; i < declaration.value.size(); ++i) {
  5019. auto const& part = declaration.value[i];
  5020. if (part.is(Token::Type::Whitespace))
  5021. continue;
  5022. if (part.is(Token::Type::String)) {
  5023. if (!font_family_parts.is_empty()) {
  5024. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5025. had_syntax_error = true;
  5026. break;
  5027. }
  5028. font_family_parts.append(part.token().string());
  5029. continue;
  5030. }
  5031. if (part.is(Token::Type::Ident)) {
  5032. if (is_css_wide_keyword(part.token().ident())) {
  5033. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5034. had_syntax_error = true;
  5035. break;
  5036. }
  5037. auto keyword = keyword_from_string(part.token().ident());
  5038. if (keyword.has_value() && is_generic_font_family(keyword.value())) {
  5039. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5040. had_syntax_error = true;
  5041. break;
  5042. }
  5043. font_family_parts.append(part.token().ident());
  5044. continue;
  5045. }
  5046. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face font-family format invalid; discarding.");
  5047. had_syntax_error = true;
  5048. break;
  5049. }
  5050. if (had_syntax_error || font_family_parts.is_empty())
  5051. return;
  5052. font_family = String::join(' ', font_family_parts).release_value_but_fixme_should_propagate_errors();
  5053. return;
  5054. }
  5055. if (declaration.name.equals_ignoring_ascii_case("font-feature-settings"sv)) {
  5056. TokenStream token_stream { declaration.value };
  5057. if (auto value = parse_css_value(CSS::PropertyID::FontFeatureSettings, token_stream); !value.is_error()) {
  5058. if (value.value()->to_keyword() == Keyword::Normal) {
  5059. font_feature_settings.clear();
  5060. } else if (value.value()->is_value_list()) {
  5061. auto const& feature_tags = value.value()->as_value_list().values();
  5062. OrderedHashMap<FlyString, i64> settings;
  5063. settings.ensure_capacity(feature_tags.size());
  5064. for (auto const& feature_tag : feature_tags) {
  5065. if (!feature_tag->is_open_type_tagged()) {
  5066. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Value in font-feature-settings descriptor is not an OpenTypeTaggedStyleValue; skipping");
  5067. continue;
  5068. }
  5069. auto const& setting_value = feature_tag->as_open_type_tagged().value();
  5070. if (setting_value->is_integer()) {
  5071. settings.set(feature_tag->as_open_type_tagged().tag(), setting_value->as_integer().integer());
  5072. } else if (setting_value->is_math() && setting_value->as_math().resolves_to_number()) {
  5073. if (auto integer = setting_value->as_math().resolve_integer(); integer.has_value()) {
  5074. settings.set(feature_tag->as_open_type_tagged().tag(), *integer);
  5075. } else {
  5076. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Calculated value in font-feature-settings descriptor cannot be resolved at parse time; skipping");
  5077. }
  5078. } else {
  5079. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Value in font-feature-settings descriptor is not an OpenTypeTaggedStyleValue holding a <integer>; skipping");
  5080. }
  5081. }
  5082. font_feature_settings = move(settings);
  5083. } else {
  5084. 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());
  5085. }
  5086. }
  5087. return;
  5088. }
  5089. if (declaration.name.equals_ignoring_ascii_case("font-language-override"sv)) {
  5090. TokenStream token_stream { declaration.value };
  5091. if (auto maybe_value = parse_css_value(CSS::PropertyID::FontLanguageOverride, token_stream); !maybe_value.is_error()) {
  5092. auto& value = maybe_value.value();
  5093. if (value->is_string()) {
  5094. language_override = value->as_string().string_value();
  5095. } else {
  5096. language_override.clear();
  5097. }
  5098. }
  5099. return;
  5100. }
  5101. if (declaration.name.equals_ignoring_ascii_case("font-named-instance"sv)) {
  5102. // auto | <string>
  5103. TokenStream token_stream { declaration.value };
  5104. token_stream.discard_whitespace();
  5105. auto& token = token_stream.consume_a_token();
  5106. token_stream.discard_whitespace();
  5107. if (token_stream.has_next_token()) {
  5108. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unexpected trailing tokens in font-named-instance");
  5109. return;
  5110. }
  5111. if (token.is_ident("auto"sv)) {
  5112. font_named_instance.clear();
  5113. } else if (token.is(Token::Type::String)) {
  5114. font_named_instance = token.token().string();
  5115. } else {
  5116. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse font-named-instance from {}", token.to_debug_string());
  5117. }
  5118. return;
  5119. }
  5120. if (declaration.name.equals_ignoring_ascii_case("font-style"sv)) {
  5121. TokenStream token_stream { declaration.value };
  5122. if (auto value = parse_css_value(CSS::PropertyID::FontStyle, token_stream); !value.is_error()) {
  5123. slope = value.value()->to_font_slope();
  5124. }
  5125. return;
  5126. }
  5127. if (declaration.name.equals_ignoring_ascii_case("font-variation-settings"sv)) {
  5128. TokenStream token_stream { declaration.value };
  5129. if (auto value = parse_css_value(CSS::PropertyID::FontVariationSettings, token_stream); !value.is_error()) {
  5130. if (value.value()->to_keyword() == Keyword::Normal) {
  5131. font_variation_settings.clear();
  5132. } else if (value.value()->is_value_list()) {
  5133. auto const& variation_tags = value.value()->as_value_list().values();
  5134. OrderedHashMap<FlyString, double> settings;
  5135. settings.ensure_capacity(variation_tags.size());
  5136. for (auto const& variation_tag : variation_tags) {
  5137. if (!variation_tag->is_open_type_tagged()) {
  5138. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Value in font-variation-settings descriptor is not an OpenTypeTaggedStyleValue; skipping");
  5139. continue;
  5140. }
  5141. auto const& setting_value = variation_tag->as_open_type_tagged().value();
  5142. if (setting_value->is_number()) {
  5143. settings.set(variation_tag->as_open_type_tagged().tag(), setting_value->as_number().number());
  5144. } else if (setting_value->is_math() && setting_value->as_math().resolves_to_number()) {
  5145. if (auto number = setting_value->as_math().resolve_number(); number.has_value()) {
  5146. settings.set(variation_tag->as_open_type_tagged().tag(), *number);
  5147. } else {
  5148. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Calculated value in font-variation-settings descriptor cannot be resolved at parse time; skipping");
  5149. }
  5150. } else {
  5151. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Value in font-variation-settings descriptor is not an OpenTypeTaggedStyleValue holding a <number>; skipping");
  5152. }
  5153. }
  5154. font_variation_settings = move(settings);
  5155. } else {
  5156. 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());
  5157. }
  5158. }
  5159. return;
  5160. }
  5161. if (declaration.name.equals_ignoring_ascii_case("font-weight"sv)) {
  5162. TokenStream token_stream { declaration.value };
  5163. if (auto value = parse_css_value(CSS::PropertyID::FontWeight, token_stream); !value.is_error()) {
  5164. weight = value.value()->to_font_weight();
  5165. }
  5166. return;
  5167. }
  5168. if (declaration.name.equals_ignoring_ascii_case("font-width"sv)
  5169. || declaration.name.equals_ignoring_ascii_case("font-stretch"sv)) {
  5170. TokenStream token_stream { declaration.value };
  5171. if (auto value = parse_css_value(CSS::PropertyID::FontWidth, token_stream); !value.is_error()) {
  5172. width = value.value()->to_font_width();
  5173. }
  5174. return;
  5175. }
  5176. if (declaration.name.equals_ignoring_ascii_case("line-gap-override"sv)) {
  5177. auto value = parse_as_percentage_or_normal(declaration.value);
  5178. if (value.is_error()) {
  5179. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face line-gap-override: {}", value.error());
  5180. } else {
  5181. line_gap_override = value.release_value();
  5182. }
  5183. return;
  5184. }
  5185. if (declaration.name.equals_ignoring_ascii_case("src"sv)) {
  5186. TokenStream token_stream { declaration.value };
  5187. Vector<ParsedFontFace::Source> supported_sources = parse_font_face_src(token_stream);
  5188. if (!supported_sources.is_empty())
  5189. src = move(supported_sources);
  5190. return;
  5191. }
  5192. if (declaration.name.equals_ignoring_ascii_case("unicode-range"sv)) {
  5193. TokenStream token_stream { declaration.value };
  5194. auto unicode_ranges = parse_unicode_ranges(token_stream);
  5195. if (unicode_ranges.is_empty())
  5196. return;
  5197. unicode_range = move(unicode_ranges);
  5198. return;
  5199. }
  5200. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Unrecognized descriptor '{}' in @font-face; discarding.", declaration.name);
  5201. });
  5202. if (!font_family.has_value()) {
  5203. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: Failed to parse @font-face: no font-family!");
  5204. return {};
  5205. }
  5206. if (unicode_range.is_empty()) {
  5207. unicode_range.empend(0x0u, 0x10FFFFu);
  5208. }
  5209. 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) });
  5210. }
  5211. Vector<ParsedFontFace::Source> Parser::parse_as_font_face_src()
  5212. {
  5213. return parse_font_face_src(m_token_stream);
  5214. }
  5215. template<typename T>
  5216. Vector<ParsedFontFace::Source> Parser::parse_font_face_src(TokenStream<T>& component_values)
  5217. {
  5218. // FIXME: Get this information from the system somehow?
  5219. // Format-name table: https://www.w3.org/TR/css-fonts-4/#font-format-definitions
  5220. auto font_format_is_supported = [](StringView name) {
  5221. // The spec requires us to treat opentype and truetype as synonymous.
  5222. if (name.is_one_of_ignoring_ascii_case("opentype"sv, "truetype"sv, "woff"sv, "woff2"sv))
  5223. return true;
  5224. return false;
  5225. };
  5226. Vector<ParsedFontFace::Source> supported_sources;
  5227. auto list_of_source_token_lists = parse_a_comma_separated_list_of_component_values(component_values);
  5228. for (auto const& source_token_list : list_of_source_token_lists) {
  5229. TokenStream source_tokens { source_token_list };
  5230. source_tokens.discard_whitespace();
  5231. // <url> [ format(<font-format>)]?
  5232. // FIXME: Implement optional tech() function from CSS-Fonts-4.
  5233. if (auto maybe_url = parse_url_function(source_tokens); maybe_url.has_value()) {
  5234. auto url = maybe_url.release_value();
  5235. if (!url.is_valid()) {
  5236. continue;
  5237. }
  5238. Optional<FlyString> format;
  5239. source_tokens.discard_whitespace();
  5240. if (!source_tokens.has_next_token()) {
  5241. supported_sources.empend(move(url), format);
  5242. continue;
  5243. }
  5244. auto maybe_function = source_tokens.consume_a_token();
  5245. if (!maybe_function.is_function()) {
  5246. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (token after `url()` that isn't a function: {}); discarding.", maybe_function.to_debug_string());
  5247. return {};
  5248. }
  5249. auto const& function = maybe_function.function();
  5250. if (function.name.equals_ignoring_ascii_case("format"sv)) {
  5251. TokenStream format_tokens { function.value };
  5252. format_tokens.discard_whitespace();
  5253. auto const& format_name_token = format_tokens.consume_a_token();
  5254. StringView format_name;
  5255. if (format_name_token.is(Token::Type::Ident)) {
  5256. format_name = format_name_token.token().ident();
  5257. } else if (format_name_token.is(Token::Type::String)) {
  5258. format_name = format_name_token.token().string();
  5259. } else {
  5260. 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());
  5261. return {};
  5262. }
  5263. if (!font_format_is_supported(format_name)) {
  5264. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src format({}) not supported; skipping.", format_name);
  5265. continue;
  5266. }
  5267. format = FlyString::from_utf8(format_name).release_value_but_fixme_should_propagate_errors();
  5268. } else {
  5269. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (unrecognized function token `{}`); discarding.", function.name);
  5270. return {};
  5271. }
  5272. source_tokens.discard_whitespace();
  5273. if (source_tokens.has_next_token()) {
  5274. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (extra token `{}`); discarding.", source_tokens.next_token().to_debug_string());
  5275. return {};
  5276. }
  5277. supported_sources.empend(move(url), format);
  5278. continue;
  5279. }
  5280. auto const& first = source_tokens.consume_a_token();
  5281. if (first.is_function("local"sv)) {
  5282. if (first.function().value.is_empty()) {
  5283. continue;
  5284. }
  5285. supported_sources.empend(first.function().value.first().to_string(), Optional<FlyString> {});
  5286. continue;
  5287. }
  5288. dbgln_if(CSS_PARSER_DEBUG, "CSSParser: @font-face src invalid (failed to parse url from: {}); discarding.", first.to_debug_string());
  5289. return {};
  5290. }
  5291. return supported_sources;
  5292. }
  5293. RefPtr<CSSStyleValue> Parser::parse_list_style_value(TokenStream<ComponentValue>& tokens)
  5294. {
  5295. RefPtr<CSSStyleValue> list_position;
  5296. RefPtr<CSSStyleValue> list_image;
  5297. RefPtr<CSSStyleValue> list_type;
  5298. int found_nones = 0;
  5299. Vector<PropertyID> remaining_longhands { PropertyID::ListStyleImage, PropertyID::ListStylePosition, PropertyID::ListStyleType };
  5300. auto transaction = tokens.begin_transaction();
  5301. while (tokens.has_next_token()) {
  5302. if (auto peek = tokens.next_token(); peek.is_ident("none"sv)) {
  5303. tokens.discard_a_token();
  5304. found_nones++;
  5305. continue;
  5306. }
  5307. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  5308. if (!property_and_value.has_value())
  5309. return nullptr;
  5310. auto& value = property_and_value->style_value;
  5311. remove_property(remaining_longhands, property_and_value->property);
  5312. switch (property_and_value->property) {
  5313. case PropertyID::ListStylePosition: {
  5314. VERIFY(!list_position);
  5315. list_position = value.release_nonnull();
  5316. continue;
  5317. }
  5318. case PropertyID::ListStyleImage: {
  5319. VERIFY(!list_image);
  5320. list_image = value.release_nonnull();
  5321. continue;
  5322. }
  5323. case PropertyID::ListStyleType: {
  5324. VERIFY(!list_type);
  5325. list_type = value.release_nonnull();
  5326. continue;
  5327. }
  5328. default:
  5329. VERIFY_NOT_REACHED();
  5330. }
  5331. }
  5332. if (found_nones > 2)
  5333. return nullptr;
  5334. if (found_nones == 2) {
  5335. if (list_image || list_type)
  5336. return nullptr;
  5337. auto none = CSSKeywordValue::create(Keyword::None);
  5338. list_image = none;
  5339. list_type = none;
  5340. } else if (found_nones == 1) {
  5341. if (list_image && list_type)
  5342. return nullptr;
  5343. auto none = CSSKeywordValue::create(Keyword::None);
  5344. if (!list_image)
  5345. list_image = none;
  5346. if (!list_type)
  5347. list_type = none;
  5348. }
  5349. if (!list_position)
  5350. list_position = property_initial_value(m_context.realm(), PropertyID::ListStylePosition);
  5351. if (!list_image)
  5352. list_image = property_initial_value(m_context.realm(), PropertyID::ListStyleImage);
  5353. if (!list_type)
  5354. list_type = property_initial_value(m_context.realm(), PropertyID::ListStyleType);
  5355. transaction.commit();
  5356. return ShorthandStyleValue::create(PropertyID::ListStyle,
  5357. { PropertyID::ListStylePosition, PropertyID::ListStyleImage, PropertyID::ListStyleType },
  5358. { list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull() });
  5359. }
  5360. RefPtr<CSSStyleValue> Parser::parse_math_depth_value(TokenStream<ComponentValue>& tokens)
  5361. {
  5362. // https://w3c.github.io/mathml-core/#propdef-math-depth
  5363. // auto-add | add(<integer>) | <integer>
  5364. auto transaction = tokens.begin_transaction();
  5365. auto token = tokens.consume_a_token();
  5366. if (tokens.has_next_token())
  5367. return nullptr;
  5368. // auto-add
  5369. if (token.is_ident("auto-add"sv)) {
  5370. transaction.commit();
  5371. return MathDepthStyleValue::create_auto_add();
  5372. }
  5373. // FIXME: Make it easier to parse "thing that might be <bar> or literally anything that resolves to it" and get rid of this
  5374. auto parse_something_that_resolves_to_integer = [this](ComponentValue& token) -> RefPtr<CSSStyleValue> {
  5375. if (token.is(Token::Type::Number) && token.token().number().is_integer())
  5376. return IntegerStyleValue::create(token.token().to_integer());
  5377. if (auto value = parse_calculated_value(token); value && value->resolves_to_number())
  5378. return value;
  5379. return nullptr;
  5380. };
  5381. // add(<integer>)
  5382. if (token.is_function("add"sv)) {
  5383. auto add_tokens = TokenStream { token.function().value };
  5384. add_tokens.discard_whitespace();
  5385. auto integer_token = add_tokens.consume_a_token();
  5386. add_tokens.discard_whitespace();
  5387. if (add_tokens.has_next_token())
  5388. return nullptr;
  5389. if (auto integer_value = parse_something_that_resolves_to_integer(integer_token)) {
  5390. transaction.commit();
  5391. return MathDepthStyleValue::create_add(integer_value.release_nonnull());
  5392. }
  5393. return nullptr;
  5394. }
  5395. // <integer>
  5396. if (auto integer_value = parse_something_that_resolves_to_integer(token)) {
  5397. transaction.commit();
  5398. return MathDepthStyleValue::create_integer(integer_value.release_nonnull());
  5399. }
  5400. return nullptr;
  5401. }
  5402. RefPtr<CSSStyleValue> Parser::parse_overflow_value(TokenStream<ComponentValue>& tokens)
  5403. {
  5404. auto transaction = tokens.begin_transaction();
  5405. auto maybe_x_value = parse_css_value_for_property(PropertyID::OverflowX, tokens);
  5406. if (!maybe_x_value)
  5407. return nullptr;
  5408. auto maybe_y_value = parse_css_value_for_property(PropertyID::OverflowY, tokens);
  5409. transaction.commit();
  5410. if (maybe_y_value) {
  5411. return ShorthandStyleValue::create(PropertyID::Overflow,
  5412. { PropertyID::OverflowX, PropertyID::OverflowY },
  5413. { maybe_x_value.release_nonnull(), maybe_y_value.release_nonnull() });
  5414. }
  5415. return ShorthandStyleValue::create(PropertyID::Overflow,
  5416. { PropertyID::OverflowX, PropertyID::OverflowY },
  5417. { *maybe_x_value, *maybe_x_value });
  5418. }
  5419. RefPtr<CSSStyleValue> Parser::parse_place_content_value(TokenStream<ComponentValue>& tokens)
  5420. {
  5421. auto transaction = tokens.begin_transaction();
  5422. auto maybe_align_content_value = parse_css_value_for_property(PropertyID::AlignContent, tokens);
  5423. if (!maybe_align_content_value)
  5424. return nullptr;
  5425. if (!tokens.has_next_token()) {
  5426. if (!property_accepts_keyword(PropertyID::JustifyContent, maybe_align_content_value->to_keyword()))
  5427. return nullptr;
  5428. transaction.commit();
  5429. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  5430. { PropertyID::AlignContent, PropertyID::JustifyContent },
  5431. { *maybe_align_content_value, *maybe_align_content_value });
  5432. }
  5433. auto maybe_justify_content_value = parse_css_value_for_property(PropertyID::JustifyContent, tokens);
  5434. if (!maybe_justify_content_value)
  5435. return nullptr;
  5436. transaction.commit();
  5437. return ShorthandStyleValue::create(PropertyID::PlaceContent,
  5438. { PropertyID::AlignContent, PropertyID::JustifyContent },
  5439. { maybe_align_content_value.release_nonnull(), maybe_justify_content_value.release_nonnull() });
  5440. }
  5441. RefPtr<CSSStyleValue> Parser::parse_place_items_value(TokenStream<ComponentValue>& tokens)
  5442. {
  5443. auto transaction = tokens.begin_transaction();
  5444. auto maybe_align_items_value = parse_css_value_for_property(PropertyID::AlignItems, tokens);
  5445. if (!maybe_align_items_value)
  5446. return nullptr;
  5447. if (!tokens.has_next_token()) {
  5448. if (!property_accepts_keyword(PropertyID::JustifyItems, maybe_align_items_value->to_keyword()))
  5449. return nullptr;
  5450. transaction.commit();
  5451. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  5452. { PropertyID::AlignItems, PropertyID::JustifyItems },
  5453. { *maybe_align_items_value, *maybe_align_items_value });
  5454. }
  5455. auto maybe_justify_items_value = parse_css_value_for_property(PropertyID::JustifyItems, tokens);
  5456. if (!maybe_justify_items_value)
  5457. return nullptr;
  5458. transaction.commit();
  5459. return ShorthandStyleValue::create(PropertyID::PlaceItems,
  5460. { PropertyID::AlignItems, PropertyID::JustifyItems },
  5461. { *maybe_align_items_value, *maybe_justify_items_value });
  5462. }
  5463. RefPtr<CSSStyleValue> Parser::parse_place_self_value(TokenStream<ComponentValue>& tokens)
  5464. {
  5465. auto transaction = tokens.begin_transaction();
  5466. auto maybe_align_self_value = parse_css_value_for_property(PropertyID::AlignSelf, tokens);
  5467. if (!maybe_align_self_value)
  5468. return nullptr;
  5469. if (!tokens.has_next_token()) {
  5470. if (!property_accepts_keyword(PropertyID::JustifySelf, maybe_align_self_value->to_keyword()))
  5471. return nullptr;
  5472. transaction.commit();
  5473. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  5474. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  5475. { *maybe_align_self_value, *maybe_align_self_value });
  5476. }
  5477. auto maybe_justify_self_value = parse_css_value_for_property(PropertyID::JustifySelf, tokens);
  5478. if (!maybe_justify_self_value)
  5479. return nullptr;
  5480. transaction.commit();
  5481. return ShorthandStyleValue::create(PropertyID::PlaceSelf,
  5482. { PropertyID::AlignSelf, PropertyID::JustifySelf },
  5483. { *maybe_align_self_value, *maybe_justify_self_value });
  5484. }
  5485. RefPtr<CSSStyleValue> Parser::parse_quotes_value(TokenStream<ComponentValue>& tokens)
  5486. {
  5487. // https://www.w3.org/TR/css-content-3/#quotes-property
  5488. // auto | none | [ <string> <string> ]+
  5489. auto transaction = tokens.begin_transaction();
  5490. if (tokens.remaining_token_count() == 1) {
  5491. auto keyword = parse_keyword_value(tokens);
  5492. if (keyword && property_accepts_keyword(PropertyID::Quotes, keyword->to_keyword())) {
  5493. transaction.commit();
  5494. return keyword;
  5495. }
  5496. return nullptr;
  5497. }
  5498. // Parse an even number of <string> values.
  5499. if (tokens.remaining_token_count() % 2 != 0)
  5500. return nullptr;
  5501. StyleValueVector string_values;
  5502. while (tokens.has_next_token()) {
  5503. auto maybe_string = parse_string_value(tokens);
  5504. if (!maybe_string)
  5505. return nullptr;
  5506. string_values.append(maybe_string.release_nonnull());
  5507. }
  5508. transaction.commit();
  5509. return StyleValueList::create(move(string_values), StyleValueList::Separator::Space);
  5510. }
  5511. RefPtr<CSSStyleValue> Parser::parse_text_decoration_value(TokenStream<ComponentValue>& tokens)
  5512. {
  5513. RefPtr<CSSStyleValue> decoration_line;
  5514. RefPtr<CSSStyleValue> decoration_thickness;
  5515. RefPtr<CSSStyleValue> decoration_style;
  5516. RefPtr<CSSStyleValue> decoration_color;
  5517. auto remaining_longhands = Vector { PropertyID::TextDecorationColor, PropertyID::TextDecorationLine, PropertyID::TextDecorationStyle, PropertyID::TextDecorationThickness };
  5518. auto transaction = tokens.begin_transaction();
  5519. while (tokens.has_next_token()) {
  5520. auto property_and_value = parse_css_value_for_properties(remaining_longhands, tokens);
  5521. if (!property_and_value.has_value())
  5522. return nullptr;
  5523. auto& value = property_and_value->style_value;
  5524. remove_property(remaining_longhands, property_and_value->property);
  5525. switch (property_and_value->property) {
  5526. case PropertyID::TextDecorationColor: {
  5527. VERIFY(!decoration_color);
  5528. decoration_color = value.release_nonnull();
  5529. continue;
  5530. }
  5531. case PropertyID::TextDecorationLine: {
  5532. VERIFY(!decoration_line);
  5533. tokens.reconsume_current_input_token();
  5534. auto parsed_decoration_line = parse_text_decoration_line_value(tokens);
  5535. if (!parsed_decoration_line)
  5536. return nullptr;
  5537. decoration_line = parsed_decoration_line.release_nonnull();
  5538. continue;
  5539. }
  5540. case PropertyID::TextDecorationThickness: {
  5541. VERIFY(!decoration_thickness);
  5542. decoration_thickness = value.release_nonnull();
  5543. continue;
  5544. }
  5545. case PropertyID::TextDecorationStyle: {
  5546. VERIFY(!decoration_style);
  5547. decoration_style = value.release_nonnull();
  5548. continue;
  5549. }
  5550. default:
  5551. VERIFY_NOT_REACHED();
  5552. }
  5553. }
  5554. if (!decoration_line)
  5555. decoration_line = property_initial_value(m_context.realm(), PropertyID::TextDecorationLine);
  5556. if (!decoration_thickness)
  5557. decoration_thickness = property_initial_value(m_context.realm(), PropertyID::TextDecorationThickness);
  5558. if (!decoration_style)
  5559. decoration_style = property_initial_value(m_context.realm(), PropertyID::TextDecorationStyle);
  5560. if (!decoration_color)
  5561. decoration_color = property_initial_value(m_context.realm(), PropertyID::TextDecorationColor);
  5562. transaction.commit();
  5563. return ShorthandStyleValue::create(PropertyID::TextDecoration,
  5564. { PropertyID::TextDecorationLine, PropertyID::TextDecorationThickness, PropertyID::TextDecorationStyle, PropertyID::TextDecorationColor },
  5565. { decoration_line.release_nonnull(), decoration_thickness.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull() });
  5566. }
  5567. RefPtr<CSSStyleValue> Parser::parse_text_decoration_line_value(TokenStream<ComponentValue>& tokens)
  5568. {
  5569. StyleValueVector style_values;
  5570. while (tokens.has_next_token()) {
  5571. auto maybe_value = parse_css_value_for_property(PropertyID::TextDecorationLine, tokens);
  5572. if (!maybe_value)
  5573. break;
  5574. auto value = maybe_value.release_nonnull();
  5575. if (auto maybe_line = keyword_to_text_decoration_line(value->to_keyword()); maybe_line.has_value()) {
  5576. if (maybe_line == TextDecorationLine::None) {
  5577. if (!style_values.is_empty())
  5578. break;
  5579. return value;
  5580. }
  5581. if (style_values.contains_slow(value))
  5582. break;
  5583. style_values.append(move(value));
  5584. continue;
  5585. }
  5586. break;
  5587. }
  5588. if (style_values.is_empty())
  5589. return nullptr;
  5590. return StyleValueList::create(move(style_values), StyleValueList::Separator::Space);
  5591. }
  5592. RefPtr<CSSStyleValue> Parser::parse_easing_value(TokenStream<ComponentValue>& tokens)
  5593. {
  5594. auto transaction = tokens.begin_transaction();
  5595. tokens.discard_whitespace();
  5596. auto const& part = tokens.consume_a_token();
  5597. if (part.is(Token::Type::Ident)) {
  5598. auto name = part.token().ident();
  5599. auto maybe_simple_easing = [&] -> RefPtr<EasingStyleValue> {
  5600. if (name == "linear"sv)
  5601. return EasingStyleValue::create(EasingStyleValue::Linear {});
  5602. if (name == "ease"sv)
  5603. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease());
  5604. if (name == "ease-in"sv)
  5605. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_in());
  5606. if (name == "ease-out"sv)
  5607. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_out());
  5608. if (name == "ease-in-out"sv)
  5609. return EasingStyleValue::create(EasingStyleValue::CubicBezier::ease_in_out());
  5610. if (name == "step-start"sv)
  5611. return EasingStyleValue::create(EasingStyleValue::Steps::step_start());
  5612. if (name == "step-end"sv)
  5613. return EasingStyleValue::create(EasingStyleValue::Steps::step_end());
  5614. return {};
  5615. }();
  5616. if (!maybe_simple_easing)
  5617. return nullptr;
  5618. transaction.commit();
  5619. return maybe_simple_easing;
  5620. }
  5621. if (!part.is_function())
  5622. return nullptr;
  5623. TokenStream argument_tokens { part.function().value };
  5624. auto comma_separated_arguments = parse_a_comma_separated_list_of_component_values(argument_tokens);
  5625. // Remove whitespace
  5626. for (auto& argument : comma_separated_arguments)
  5627. argument.remove_all_matching([](auto& value) { return value.is(Token::Type::Whitespace); });
  5628. auto name = part.function().name;
  5629. if (name == "linear"sv) {
  5630. Vector<EasingStyleValue::Linear::Stop> stops;
  5631. for (auto const& argument : comma_separated_arguments) {
  5632. if (argument.is_empty() || argument.size() > 2)
  5633. return nullptr;
  5634. Optional<double> offset;
  5635. Optional<double> position;
  5636. for (auto const& part : argument) {
  5637. if (part.is(Token::Type::Number)) {
  5638. if (offset.has_value())
  5639. return nullptr;
  5640. offset = part.token().number_value();
  5641. } else if (part.is(Token::Type::Percentage)) {
  5642. if (position.has_value())
  5643. return nullptr;
  5644. position = part.token().percentage();
  5645. } else {
  5646. return nullptr;
  5647. };
  5648. }
  5649. if (!offset.has_value())
  5650. return nullptr;
  5651. stops.append({ offset.value(), move(position) });
  5652. }
  5653. if (stops.is_empty())
  5654. return nullptr;
  5655. transaction.commit();
  5656. return EasingStyleValue::create(EasingStyleValue::Linear { move(stops) });
  5657. }
  5658. if (name == "cubic-bezier") {
  5659. if (comma_separated_arguments.size() != 4)
  5660. return nullptr;
  5661. for (auto const& argument : comma_separated_arguments) {
  5662. if (argument.size() != 1)
  5663. return nullptr;
  5664. if (!argument[0].is(Token::Type::Number))
  5665. return nullptr;
  5666. }
  5667. EasingStyleValue::CubicBezier bezier {
  5668. comma_separated_arguments[0][0].token().number_value(),
  5669. comma_separated_arguments[1][0].token().number_value(),
  5670. comma_separated_arguments[2][0].token().number_value(),
  5671. comma_separated_arguments[3][0].token().number_value(),
  5672. };
  5673. if (bezier.x1 < 0.0 || bezier.x1 > 1.0 || bezier.x2 < 0.0 || bezier.x2 > 1.0)
  5674. return nullptr;
  5675. transaction.commit();
  5676. return EasingStyleValue::create(bezier);
  5677. }
  5678. if (name == "steps") {
  5679. if (comma_separated_arguments.is_empty() || comma_separated_arguments.size() > 2)
  5680. return nullptr;
  5681. for (auto const& argument : comma_separated_arguments) {
  5682. if (argument.size() != 1)
  5683. return nullptr;
  5684. }
  5685. EasingStyleValue::Steps steps;
  5686. auto intervals_argument = comma_separated_arguments[0][0];
  5687. if (!intervals_argument.is(Token::Type::Number))
  5688. return nullptr;
  5689. if (!intervals_argument.token().number().is_integer())
  5690. return nullptr;
  5691. auto intervals = intervals_argument.token().to_integer();
  5692. if (comma_separated_arguments.size() == 2) {
  5693. TokenStream identifier_stream { comma_separated_arguments[1] };
  5694. auto keyword_value = parse_keyword_value(identifier_stream);
  5695. if (!keyword_value)
  5696. return nullptr;
  5697. switch (keyword_value->to_keyword()) {
  5698. case Keyword::JumpStart:
  5699. steps.position = EasingStyleValue::Steps::Position::JumpStart;
  5700. break;
  5701. case Keyword::JumpEnd:
  5702. steps.position = EasingStyleValue::Steps::Position::JumpEnd;
  5703. break;
  5704. case Keyword::JumpBoth:
  5705. steps.position = EasingStyleValue::Steps::Position::JumpBoth;
  5706. break;
  5707. case Keyword::JumpNone:
  5708. steps.position = EasingStyleValue::Steps::Position::JumpNone;
  5709. break;
  5710. case Keyword::Start:
  5711. steps.position = EasingStyleValue::Steps::Position::Start;
  5712. break;
  5713. case Keyword::End:
  5714. steps.position = EasingStyleValue::Steps::Position::End;
  5715. break;
  5716. default:
  5717. return nullptr;
  5718. }
  5719. }
  5720. // Perform extra validation
  5721. // https://drafts.csswg.org/css-easing/#funcdef-step-easing-function-steps
  5722. // The first parameter specifies the number of intervals in the function. It must be a positive integer greater than 0
  5723. // unless the second parameter is jump-none in which case it must be a positive integer greater than 1.
  5724. if (steps.position == EasingStyleValue::Steps::Position::JumpNone) {
  5725. if (intervals < 1)
  5726. return nullptr;
  5727. } else if (intervals < 0) {
  5728. return nullptr;
  5729. }
  5730. steps.number_of_intervals = intervals;
  5731. transaction.commit();
  5732. return EasingStyleValue::create(steps);
  5733. }
  5734. return nullptr;
  5735. }
  5736. // https://www.w3.org/TR/css-transforms-1/#transform-property
  5737. RefPtr<CSSStyleValue> Parser::parse_transform_value(TokenStream<ComponentValue>& tokens)
  5738. {
  5739. // <transform> = none | <transform-list>
  5740. // <transform-list> = <transform-function>+
  5741. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  5742. return none;
  5743. StyleValueVector transformations;
  5744. auto transaction = tokens.begin_transaction();
  5745. while (tokens.has_next_token()) {
  5746. auto const& part = tokens.consume_a_token();
  5747. if (!part.is_function())
  5748. return nullptr;
  5749. auto maybe_function = transform_function_from_string(part.function().name);
  5750. if (!maybe_function.has_value())
  5751. return nullptr;
  5752. auto function = maybe_function.release_value();
  5753. auto function_metadata = transform_function_metadata(function);
  5754. auto function_tokens = TokenStream { part.function().value };
  5755. auto arguments = parse_a_comma_separated_list_of_component_values(function_tokens);
  5756. if (arguments.size() > function_metadata.parameters.size()) {
  5757. dbgln_if(CSS_PARSER_DEBUG, "Too many arguments to {}. max: {}", part.function().name, function_metadata.parameters.size());
  5758. return nullptr;
  5759. }
  5760. if (arguments.size() < function_metadata.parameters.size() && function_metadata.parameters[arguments.size()].required) {
  5761. dbgln_if(CSS_PARSER_DEBUG, "Required parameter at position {} is missing", arguments.size());
  5762. return nullptr;
  5763. }
  5764. StyleValueVector values;
  5765. for (auto argument_index = 0u; argument_index < arguments.size(); ++argument_index) {
  5766. TokenStream argument_tokens { arguments[argument_index] };
  5767. argument_tokens.discard_whitespace();
  5768. auto const& value = argument_tokens.consume_a_token();
  5769. RefPtr<CSSMathValue> maybe_calc_value = parse_calculated_value(value);
  5770. switch (function_metadata.parameters[argument_index].type) {
  5771. case TransformFunctionParameterType::Angle: {
  5772. // These are `<angle> | <zero>` in the spec, so we have to check for both kinds.
  5773. if (maybe_calc_value && maybe_calc_value->resolves_to_angle()) {
  5774. values.append(maybe_calc_value.release_nonnull());
  5775. } else if (value.is(Token::Type::Number) && value.token().number_value() == 0) {
  5776. values.append(AngleStyleValue::create(Angle::make_degrees(0)));
  5777. } else {
  5778. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5779. argument_tokens.reconsume_current_input_token();
  5780. auto dimension_value = parse_dimension_value(argument_tokens);
  5781. if (!dimension_value || !dimension_value->is_angle())
  5782. return nullptr;
  5783. values.append(dimension_value.release_nonnull());
  5784. }
  5785. break;
  5786. }
  5787. case TransformFunctionParameterType::Length:
  5788. case TransformFunctionParameterType::LengthNone: {
  5789. if (maybe_calc_value && maybe_calc_value->resolves_to_length()) {
  5790. argument_tokens.discard_a_token(); // calc()
  5791. values.append(maybe_calc_value.release_nonnull());
  5792. } else {
  5793. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5794. argument_tokens.reconsume_current_input_token();
  5795. if (function_metadata.parameters[argument_index].type == TransformFunctionParameterType::LengthNone) {
  5796. auto keyword_transaction = argument_tokens.begin_transaction();
  5797. auto keyword_value = parse_keyword_value(argument_tokens);
  5798. if (keyword_value && keyword_value->to_keyword() == Keyword::None) {
  5799. values.append(keyword_value.release_nonnull());
  5800. keyword_transaction.commit();
  5801. break;
  5802. }
  5803. }
  5804. auto dimension_value = parse_dimension_value(argument_tokens);
  5805. if (!dimension_value || !dimension_value->is_length())
  5806. return nullptr;
  5807. values.append(dimension_value.release_nonnull());
  5808. }
  5809. break;
  5810. }
  5811. case TransformFunctionParameterType::LengthPercentage: {
  5812. if (maybe_calc_value && maybe_calc_value->resolves_to_length_percentage()) {
  5813. values.append(maybe_calc_value.release_nonnull());
  5814. } else {
  5815. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5816. argument_tokens.reconsume_current_input_token();
  5817. auto dimension_value = parse_dimension_value(argument_tokens);
  5818. if (!dimension_value)
  5819. return nullptr;
  5820. if (dimension_value->is_percentage() || dimension_value->is_length())
  5821. values.append(dimension_value.release_nonnull());
  5822. else
  5823. return nullptr;
  5824. }
  5825. break;
  5826. }
  5827. case TransformFunctionParameterType::Number: {
  5828. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5829. values.append(maybe_calc_value.release_nonnull());
  5830. } else {
  5831. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5832. argument_tokens.reconsume_current_input_token();
  5833. auto number = parse_number_value(argument_tokens);
  5834. if (!number)
  5835. return nullptr;
  5836. values.append(number.release_nonnull());
  5837. }
  5838. break;
  5839. }
  5840. case TransformFunctionParameterType::NumberPercentage: {
  5841. if (maybe_calc_value && maybe_calc_value->resolves_to_number()) {
  5842. values.append(maybe_calc_value.release_nonnull());
  5843. } else {
  5844. // FIXME: Remove this reconsume once all parsing functions are TokenStream-based.
  5845. argument_tokens.reconsume_current_input_token();
  5846. auto number_or_percentage = parse_number_percentage_value(argument_tokens);
  5847. if (!number_or_percentage)
  5848. return nullptr;
  5849. values.append(number_or_percentage.release_nonnull());
  5850. }
  5851. break;
  5852. }
  5853. }
  5854. argument_tokens.discard_whitespace();
  5855. if (argument_tokens.has_next_token())
  5856. return nullptr;
  5857. }
  5858. transformations.append(TransformationStyleValue::create(function, move(values)));
  5859. }
  5860. transaction.commit();
  5861. return StyleValueList::create(move(transformations), StyleValueList::Separator::Space);
  5862. }
  5863. // https://www.w3.org/TR/css-transforms-1/#propdef-transform-origin
  5864. // FIXME: This only supports a 2D position
  5865. RefPtr<CSSStyleValue> Parser::parse_transform_origin_value(TokenStream<ComponentValue>& tokens)
  5866. {
  5867. enum class Axis {
  5868. None,
  5869. X,
  5870. Y,
  5871. };
  5872. struct AxisOffset {
  5873. Axis axis;
  5874. NonnullRefPtr<CSSStyleValue> offset;
  5875. };
  5876. auto to_axis_offset = [](RefPtr<CSSStyleValue> value) -> Optional<AxisOffset> {
  5877. if (!value)
  5878. return OptionalNone {};
  5879. if (value->is_percentage())
  5880. return AxisOffset { Axis::None, value->as_percentage() };
  5881. if (value->is_length())
  5882. return AxisOffset { Axis::None, value->as_length() };
  5883. if (value->is_keyword()) {
  5884. switch (value->to_keyword()) {
  5885. case Keyword::Top:
  5886. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(0)) };
  5887. case Keyword::Left:
  5888. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(0)) };
  5889. case Keyword::Center:
  5890. return AxisOffset { Axis::None, PercentageStyleValue::create(Percentage(50)) };
  5891. case Keyword::Bottom:
  5892. return AxisOffset { Axis::Y, PercentageStyleValue::create(Percentage(100)) };
  5893. case Keyword::Right:
  5894. return AxisOffset { Axis::X, PercentageStyleValue::create(Percentage(100)) };
  5895. default:
  5896. return OptionalNone {};
  5897. }
  5898. }
  5899. return OptionalNone {};
  5900. };
  5901. auto transaction = tokens.begin_transaction();
  5902. auto make_list = [&transaction](NonnullRefPtr<CSSStyleValue> const& x_value, NonnullRefPtr<CSSStyleValue> const& y_value) -> NonnullRefPtr<StyleValueList> {
  5903. transaction.commit();
  5904. return StyleValueList::create(StyleValueVector { x_value, y_value }, StyleValueList::Separator::Space);
  5905. };
  5906. switch (tokens.remaining_token_count()) {
  5907. case 1: {
  5908. auto single_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5909. if (!single_value.has_value())
  5910. return nullptr;
  5911. // If only one value is specified, the second value is assumed to be center.
  5912. // FIXME: If one or two values are specified, the third value is assumed to be 0px.
  5913. switch (single_value->axis) {
  5914. case Axis::None:
  5915. case Axis::X:
  5916. return make_list(single_value->offset, PercentageStyleValue::create(Percentage(50)));
  5917. case Axis::Y:
  5918. return make_list(PercentageStyleValue::create(Percentage(50)), single_value->offset);
  5919. }
  5920. VERIFY_NOT_REACHED();
  5921. }
  5922. case 2: {
  5923. auto first_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5924. auto second_value = to_axis_offset(parse_css_value_for_property(PropertyID::TransformOrigin, tokens));
  5925. if (!first_value.has_value() || !second_value.has_value())
  5926. return nullptr;
  5927. RefPtr<CSSStyleValue> x_value;
  5928. RefPtr<CSSStyleValue> y_value;
  5929. if (first_value->axis == Axis::X) {
  5930. x_value = first_value->offset;
  5931. } else if (first_value->axis == Axis::Y) {
  5932. y_value = first_value->offset;
  5933. }
  5934. if (second_value->axis == Axis::X) {
  5935. if (x_value)
  5936. return nullptr;
  5937. x_value = second_value->offset;
  5938. // Put the other in Y since its axis can't have been X
  5939. y_value = first_value->offset;
  5940. } else if (second_value->axis == Axis::Y) {
  5941. if (y_value)
  5942. return nullptr;
  5943. y_value = second_value->offset;
  5944. // Put the other in X since its axis can't have been Y
  5945. x_value = first_value->offset;
  5946. } else {
  5947. if (x_value) {
  5948. VERIFY(!y_value);
  5949. y_value = second_value->offset;
  5950. } else {
  5951. VERIFY(!x_value);
  5952. x_value = second_value->offset;
  5953. }
  5954. }
  5955. // If two or more values are defined and either no value is a keyword, or the only used keyword is center,
  5956. // then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset).
  5957. // FIXME: A third value always represents the Z position (or offset) and must be of type <length>.
  5958. if (first_value->axis == Axis::None && second_value->axis == Axis::None) {
  5959. x_value = first_value->offset;
  5960. y_value = second_value->offset;
  5961. }
  5962. return make_list(x_value.release_nonnull(), y_value.release_nonnull());
  5963. }
  5964. }
  5965. return nullptr;
  5966. }
  5967. RefPtr<CSSStyleValue> Parser::parse_transition_value(TokenStream<ComponentValue>& tokens)
  5968. {
  5969. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  5970. return none;
  5971. Vector<TransitionStyleValue::Transition> transitions;
  5972. auto transaction = tokens.begin_transaction();
  5973. while (tokens.has_next_token()) {
  5974. TransitionStyleValue::Transition transition;
  5975. auto time_value_count = 0;
  5976. while (tokens.has_next_token() && !tokens.next_token().is(Token::Type::Comma)) {
  5977. if (auto time = parse_time(tokens); time.has_value()) {
  5978. switch (time_value_count) {
  5979. case 0:
  5980. transition.duration = time.release_value();
  5981. break;
  5982. case 1:
  5983. transition.delay = time.release_value();
  5984. break;
  5985. default:
  5986. dbgln_if(CSS_PARSER_DEBUG, "Transition property has more than two time values");
  5987. return {};
  5988. }
  5989. time_value_count++;
  5990. continue;
  5991. }
  5992. if (auto easing = parse_easing_value(tokens)) {
  5993. if (transition.easing) {
  5994. dbgln_if(CSS_PARSER_DEBUG, "Transition property has multiple easing values");
  5995. return {};
  5996. }
  5997. transition.easing = easing->as_easing();
  5998. continue;
  5999. }
  6000. if (tokens.next_token().is(Token::Type::Ident)) {
  6001. if (transition.property_name) {
  6002. dbgln_if(CSS_PARSER_DEBUG, "Transition property has multiple property identifiers");
  6003. return {};
  6004. }
  6005. auto ident = tokens.consume_a_token().token().ident();
  6006. if (auto property = property_id_from_string(ident); property.has_value())
  6007. transition.property_name = CustomIdentStyleValue::create(ident);
  6008. continue;
  6009. }
  6010. dbgln_if(CSS_PARSER_DEBUG, "Transition property has unexpected token \"{}\"", tokens.next_token().to_string());
  6011. return {};
  6012. }
  6013. if (!transition.property_name)
  6014. transition.property_name = CustomIdentStyleValue::create("all"_fly_string);
  6015. if (!transition.easing)
  6016. transition.easing = EasingStyleValue::create(EasingStyleValue::CubicBezier::ease());
  6017. transitions.append(move(transition));
  6018. if (!tokens.next_token().is(Token::Type::Comma))
  6019. break;
  6020. tokens.discard_a_token();
  6021. }
  6022. transaction.commit();
  6023. return TransitionStyleValue::create(move(transitions));
  6024. }
  6025. RefPtr<CSSStyleValue> Parser::parse_as_css_value(PropertyID property_id)
  6026. {
  6027. auto component_values = parse_a_list_of_component_values(m_token_stream);
  6028. auto tokens = TokenStream(component_values);
  6029. auto parsed_value = parse_css_value(property_id, tokens);
  6030. if (parsed_value.is_error())
  6031. return nullptr;
  6032. return parsed_value.release_value();
  6033. }
  6034. Optional<CSS::GridSize> Parser::parse_grid_size(ComponentValue const& component_value)
  6035. {
  6036. if (component_value.is_function()) {
  6037. if (auto maybe_calculated = parse_calculated_value(component_value)) {
  6038. if (maybe_calculated->resolves_to_length_percentage())
  6039. return GridSize(LengthPercentage(maybe_calculated.release_nonnull()));
  6040. // FIXME: Support calculated <flex>
  6041. }
  6042. return {};
  6043. }
  6044. if (component_value.is_ident("auto"sv))
  6045. return GridSize::make_auto();
  6046. if (component_value.is_ident("max-content"sv))
  6047. return GridSize(GridSize::Type::MaxContent);
  6048. if (component_value.is_ident("min-content"sv))
  6049. return GridSize(GridSize::Type::MinContent);
  6050. auto dimension = parse_dimension(component_value);
  6051. if (!dimension.has_value())
  6052. return {};
  6053. if (dimension->is_length())
  6054. return GridSize(dimension->length());
  6055. else if (dimension->is_percentage())
  6056. return GridSize(dimension->percentage());
  6057. else if (dimension->is_flex())
  6058. return GridSize(dimension->flex());
  6059. return {};
  6060. }
  6061. Optional<CSS::GridFitContent> Parser::parse_fit_content(Vector<ComponentValue> const& component_values)
  6062. {
  6063. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-fit-content
  6064. // 'fit-content( <length-percentage> )'
  6065. // Represents the formula max(minimum, min(limit, max-content)), where minimum represents an auto minimum (which is often, but not always,
  6066. // equal to a min-content minimum), and limit is the track sizing function passed as an argument to fit-content().
  6067. // This is essentially calculated as the smaller of minmax(auto, max-content) and minmax(auto, limit).
  6068. auto function_tokens = TokenStream(component_values);
  6069. function_tokens.discard_whitespace();
  6070. auto maybe_length_percentage = parse_length_percentage(function_tokens);
  6071. if (maybe_length_percentage.has_value())
  6072. return CSS::GridFitContent(CSS::GridSize(CSS::GridSize::Type::FitContent, maybe_length_percentage.value()));
  6073. return {};
  6074. }
  6075. Optional<CSS::GridMinMax> Parser::parse_min_max(Vector<ComponentValue> const& component_values)
  6076. {
  6077. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  6078. // 'minmax(min, max)'
  6079. // Defines a size range greater than or equal to min and less than or equal to max. If the max is
  6080. // less than the min, then the max will be floored by the min (essentially yielding minmax(min,
  6081. // min)). As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  6082. auto function_tokens = TokenStream(component_values);
  6083. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  6084. if (comma_separated_list.size() != 2)
  6085. return {};
  6086. TokenStream part_one_tokens { comma_separated_list[0] };
  6087. part_one_tokens.discard_whitespace();
  6088. if (!part_one_tokens.has_next_token())
  6089. return {};
  6090. auto current_token = part_one_tokens.consume_a_token();
  6091. auto min_grid_size = parse_grid_size(current_token);
  6092. TokenStream part_two_tokens { comma_separated_list[1] };
  6093. part_two_tokens.discard_whitespace();
  6094. if (!part_two_tokens.has_next_token())
  6095. return {};
  6096. current_token = part_two_tokens.consume_a_token();
  6097. auto max_grid_size = parse_grid_size(current_token);
  6098. if (min_grid_size.has_value() && max_grid_size.has_value()) {
  6099. // https://www.w3.org/TR/css-grid-2/#valdef-grid-template-columns-minmax
  6100. // As a maximum, a <flex> value sets the track’s flex factor; it is invalid as a minimum.
  6101. if (min_grid_size.value().is_flexible_length())
  6102. return {};
  6103. return CSS::GridMinMax(min_grid_size.value(), max_grid_size.value());
  6104. }
  6105. return {};
  6106. }
  6107. Optional<CSS::GridRepeat> Parser::parse_repeat(Vector<ComponentValue> const& component_values)
  6108. {
  6109. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  6110. // 7.2.3.1. Syntax of repeat()
  6111. // The generic form of the repeat() syntax is, approximately,
  6112. // repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> )
  6113. auto is_auto_fill = false;
  6114. auto is_auto_fit = false;
  6115. auto function_tokens = TokenStream(component_values);
  6116. auto comma_separated_list = parse_a_comma_separated_list_of_component_values(function_tokens);
  6117. if (comma_separated_list.size() != 2)
  6118. return {};
  6119. // The first argument specifies the number of repetitions.
  6120. TokenStream part_one_tokens { comma_separated_list[0] };
  6121. part_one_tokens.discard_whitespace();
  6122. if (!part_one_tokens.has_next_token())
  6123. return {};
  6124. auto& current_token = part_one_tokens.consume_a_token();
  6125. auto repeat_count = 0;
  6126. if (current_token.is(Token::Type::Number) && current_token.token().number().is_integer() && current_token.token().number_value() > 0)
  6127. repeat_count = current_token.token().number_value();
  6128. else if (current_token.is_ident("auto-fill"sv))
  6129. is_auto_fill = true;
  6130. else if (current_token.is_ident("auto-fit"sv))
  6131. is_auto_fit = true;
  6132. // The second argument is a track list, which is repeated that number of times.
  6133. TokenStream part_two_tokens { comma_separated_list[1] };
  6134. part_two_tokens.discard_whitespace();
  6135. if (!part_two_tokens.has_next_token())
  6136. return {};
  6137. Vector<Variant<ExplicitGridTrack, GridLineNames>> repeat_params;
  6138. auto last_object_was_line_names = false;
  6139. while (part_two_tokens.has_next_token()) {
  6140. auto token = part_two_tokens.consume_a_token();
  6141. Vector<String> line_names;
  6142. if (token.is_block()) {
  6143. if (last_object_was_line_names)
  6144. return {};
  6145. last_object_was_line_names = true;
  6146. if (!token.block().is_square())
  6147. return {};
  6148. TokenStream block_tokens { token.block().value };
  6149. while (block_tokens.has_next_token()) {
  6150. auto current_block_token = block_tokens.consume_a_token();
  6151. line_names.append(current_block_token.token().ident().to_string());
  6152. block_tokens.discard_whitespace();
  6153. }
  6154. repeat_params.append(GridLineNames { move(line_names) });
  6155. part_two_tokens.discard_whitespace();
  6156. } else {
  6157. last_object_was_line_names = false;
  6158. auto track_sizing_function = parse_track_sizing_function(token);
  6159. if (!track_sizing_function.has_value())
  6160. return {};
  6161. // However, there are some restrictions:
  6162. // The repeat() notation can’t be nested.
  6163. if (track_sizing_function.value().is_repeat())
  6164. return {};
  6165. // Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.
  6166. // Note that 'auto' is also an intrinsic size (and thus not permitted) but we can't use
  6167. // track_sizing_function.is_auto(..) to check for it, as it requires AvailableSize, which is why there is
  6168. // a separate check for it below.
  6169. // https://www.w3.org/TR/css-grid-2/#repeat-syntax
  6170. // https://www.w3.org/TR/css-grid-2/#intrinsic-sizing-function
  6171. if (track_sizing_function.value().is_default()
  6172. && (track_sizing_function.value().grid_size().is_flexible_length() || token.is_ident("auto"sv))
  6173. && (is_auto_fill || is_auto_fit))
  6174. return {};
  6175. repeat_params.append(track_sizing_function.value());
  6176. part_two_tokens.discard_whitespace();
  6177. }
  6178. }
  6179. // Thus the precise syntax of the repeat() notation has several forms:
  6180. // <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? )
  6181. // <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  6182. // <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
  6183. // <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
  6184. // The <track-repeat> variant can represent the repetition of any <track-size>, but is limited to a
  6185. // fixed number of repetitions.
  6186. // The <auto-repeat> variant can repeat automatically to fill a space, but requires definite track
  6187. // sizes so that the number of repetitions can be calculated. It can only appear once in the track
  6188. // list, but the same track list can also contain <fixed-repeat>s.
  6189. // The <name-repeat> variant is for adding line names to subgrids. It can only be used with the
  6190. // subgrid keyword and cannot specify track sizes, only line names.
  6191. // If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to
  6192. // each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a]
  6193. // 1fr [b a] 1fr [b].
  6194. if (is_auto_fill)
  6195. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFill);
  6196. else if (is_auto_fit)
  6197. return GridRepeat(GridTrackSizeList(move(repeat_params)), GridRepeat::Type::AutoFit);
  6198. else
  6199. return GridRepeat(GridTrackSizeList(move(repeat_params)), repeat_count);
  6200. }
  6201. Optional<CSS::ExplicitGridTrack> Parser::parse_track_sizing_function(ComponentValue const& token)
  6202. {
  6203. if (token.is_function()) {
  6204. auto const& function_token = token.function();
  6205. if (function_token.name.equals_ignoring_ascii_case("repeat"sv)) {
  6206. auto maybe_repeat = parse_repeat(function_token.value);
  6207. if (maybe_repeat.has_value())
  6208. return CSS::ExplicitGridTrack(maybe_repeat.value());
  6209. else
  6210. return {};
  6211. } else if (function_token.name.equals_ignoring_ascii_case("minmax"sv)) {
  6212. auto maybe_min_max_value = parse_min_max(function_token.value);
  6213. if (maybe_min_max_value.has_value())
  6214. return CSS::ExplicitGridTrack(maybe_min_max_value.value());
  6215. else
  6216. return {};
  6217. } else if (function_token.name.equals_ignoring_ascii_case("fit-content"sv)) {
  6218. auto maybe_fit_content_value = parse_fit_content(function_token.value);
  6219. if (maybe_fit_content_value.has_value())
  6220. return CSS::ExplicitGridTrack(maybe_fit_content_value.value());
  6221. return {};
  6222. } else if (auto maybe_calculated = parse_calculated_value(token)) {
  6223. return CSS::ExplicitGridTrack(GridSize(LengthPercentage(maybe_calculated.release_nonnull())));
  6224. }
  6225. return {};
  6226. } else if (token.is_ident("auto"sv)) {
  6227. return CSS::ExplicitGridTrack(GridSize(Length::make_auto()));
  6228. } else if (token.is_block()) {
  6229. return {};
  6230. } else {
  6231. auto grid_size = parse_grid_size(token);
  6232. if (!grid_size.has_value())
  6233. return {};
  6234. return CSS::ExplicitGridTrack(grid_size.value());
  6235. }
  6236. }
  6237. RefPtr<CSSStyleValue> Parser::parse_grid_track_size_list(TokenStream<ComponentValue>& tokens, bool allow_separate_line_name_blocks)
  6238. {
  6239. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  6240. return GridTrackSizeListStyleValue::make_none();
  6241. auto transaction = tokens.begin_transaction();
  6242. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  6243. auto last_object_was_line_names = false;
  6244. while (tokens.has_next_token()) {
  6245. auto token = tokens.consume_a_token();
  6246. if (token.is_block()) {
  6247. if (last_object_was_line_names && !allow_separate_line_name_blocks) {
  6248. transaction.commit();
  6249. return GridTrackSizeListStyleValue::make_auto();
  6250. }
  6251. last_object_was_line_names = true;
  6252. Vector<String> line_names;
  6253. if (!token.block().is_square()) {
  6254. transaction.commit();
  6255. return GridTrackSizeListStyleValue::make_auto();
  6256. }
  6257. TokenStream block_tokens { token.block().value };
  6258. block_tokens.discard_whitespace();
  6259. while (block_tokens.has_next_token()) {
  6260. auto current_block_token = block_tokens.consume_a_token();
  6261. line_names.append(current_block_token.token().ident().to_string());
  6262. block_tokens.discard_whitespace();
  6263. }
  6264. track_list.append(GridLineNames { move(line_names) });
  6265. } else {
  6266. last_object_was_line_names = false;
  6267. auto track_sizing_function = parse_track_sizing_function(token);
  6268. if (!track_sizing_function.has_value()) {
  6269. transaction.commit();
  6270. return GridTrackSizeListStyleValue::make_auto();
  6271. }
  6272. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6273. // any other ones if the first one is auto-fill, etc.)
  6274. track_list.append(track_sizing_function.value());
  6275. }
  6276. }
  6277. transaction.commit();
  6278. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  6279. }
  6280. // https://www.w3.org/TR/css-grid-1/#grid-auto-flow-property
  6281. RefPtr<GridAutoFlowStyleValue> Parser::parse_grid_auto_flow_value(TokenStream<ComponentValue>& tokens)
  6282. {
  6283. // [ row | column ] || dense
  6284. if (!tokens.has_next_token())
  6285. return nullptr;
  6286. auto transaction = tokens.begin_transaction();
  6287. auto parse_axis = [&]() -> Optional<GridAutoFlowStyleValue::Axis> {
  6288. auto transaction = tokens.begin_transaction();
  6289. auto token = tokens.consume_a_token();
  6290. if (!token.is(Token::Type::Ident))
  6291. return {};
  6292. auto const& ident = token.token().ident();
  6293. if (ident.equals_ignoring_ascii_case("row"sv)) {
  6294. transaction.commit();
  6295. return GridAutoFlowStyleValue::Axis::Row;
  6296. } else if (ident.equals_ignoring_ascii_case("column"sv)) {
  6297. transaction.commit();
  6298. return GridAutoFlowStyleValue::Axis::Column;
  6299. }
  6300. return {};
  6301. };
  6302. auto parse_dense = [&]() -> Optional<GridAutoFlowStyleValue::Dense> {
  6303. auto transaction = tokens.begin_transaction();
  6304. auto token = tokens.consume_a_token();
  6305. if (!token.is(Token::Type::Ident))
  6306. return {};
  6307. auto const& ident = token.token().ident();
  6308. if (ident.equals_ignoring_ascii_case("dense"sv)) {
  6309. transaction.commit();
  6310. return GridAutoFlowStyleValue::Dense::Yes;
  6311. }
  6312. return {};
  6313. };
  6314. Optional<GridAutoFlowStyleValue::Axis> axis;
  6315. Optional<GridAutoFlowStyleValue::Dense> dense;
  6316. if (axis = parse_axis(); axis.has_value()) {
  6317. dense = parse_dense();
  6318. } else if (dense = parse_dense(); dense.has_value()) {
  6319. axis = parse_axis();
  6320. }
  6321. if (tokens.has_next_token())
  6322. return nullptr;
  6323. transaction.commit();
  6324. return GridAutoFlowStyleValue::create(axis.value_or(GridAutoFlowStyleValue::Axis::Row), dense.value_or(GridAutoFlowStyleValue::Dense::No));
  6325. }
  6326. // https://drafts.csswg.org/css-overflow/#propdef-scrollbar-gutter
  6327. RefPtr<CSSStyleValue> Parser::parse_scrollbar_gutter_value(TokenStream<ComponentValue>& tokens)
  6328. {
  6329. // auto | stable && both-edges?
  6330. if (!tokens.has_next_token())
  6331. return nullptr;
  6332. auto transaction = tokens.begin_transaction();
  6333. auto parse_stable = [&]() -> Optional<bool> {
  6334. auto transaction = tokens.begin_transaction();
  6335. auto token = tokens.consume_a_token();
  6336. if (!token.is(Token::Type::Ident))
  6337. return {};
  6338. auto const& ident = token.token().ident();
  6339. if (ident.equals_ignoring_ascii_case("auto"sv)) {
  6340. transaction.commit();
  6341. return false;
  6342. } else if (ident.equals_ignoring_ascii_case("stable"sv)) {
  6343. transaction.commit();
  6344. return true;
  6345. }
  6346. return {};
  6347. };
  6348. auto parse_both_edges = [&]() -> Optional<bool> {
  6349. auto transaction = tokens.begin_transaction();
  6350. auto token = tokens.consume_a_token();
  6351. if (!token.is(Token::Type::Ident))
  6352. return {};
  6353. auto const& ident = token.token().ident();
  6354. if (ident.equals_ignoring_ascii_case("both-edges"sv)) {
  6355. transaction.commit();
  6356. return true;
  6357. }
  6358. return {};
  6359. };
  6360. Optional<bool> stable;
  6361. Optional<bool> both_edges;
  6362. if (stable = parse_stable(); stable.has_value()) {
  6363. if (stable.value())
  6364. both_edges = parse_both_edges();
  6365. } else if (both_edges = parse_both_edges(); both_edges.has_value()) {
  6366. stable = parse_stable();
  6367. if (!stable.has_value() || !stable.value())
  6368. return nullptr;
  6369. }
  6370. if (tokens.has_next_token())
  6371. return nullptr;
  6372. transaction.commit();
  6373. ScrollbarGutter gutter_value;
  6374. if (both_edges.has_value())
  6375. gutter_value = ScrollbarGutter::BothEdges;
  6376. else if (stable.has_value() && stable.value())
  6377. gutter_value = ScrollbarGutter::Stable;
  6378. else
  6379. gutter_value = ScrollbarGutter::Auto;
  6380. return ScrollbarGutterStyleValue::create(gutter_value);
  6381. }
  6382. RefPtr<CSSStyleValue> Parser::parse_grid_auto_track_sizes(TokenStream<ComponentValue>& tokens)
  6383. {
  6384. // https://www.w3.org/TR/css-grid-2/#auto-tracks
  6385. // <track-size>+
  6386. Vector<Variant<ExplicitGridTrack, GridLineNames>> track_list;
  6387. auto transaction = tokens.begin_transaction();
  6388. while (tokens.has_next_token()) {
  6389. auto token = tokens.consume_a_token();
  6390. auto track_sizing_function = parse_track_sizing_function(token);
  6391. if (!track_sizing_function.has_value()) {
  6392. transaction.commit();
  6393. return GridTrackSizeListStyleValue::make_auto();
  6394. }
  6395. // FIXME: Handle multiple repeat values (should combine them here, or remove
  6396. // any other ones if the first one is auto-fill, etc.)
  6397. track_list.append(track_sizing_function.value());
  6398. }
  6399. transaction.commit();
  6400. return GridTrackSizeListStyleValue::create(GridTrackSizeList(move(track_list)));
  6401. }
  6402. RefPtr<GridTrackPlacementStyleValue> Parser::parse_grid_track_placement(TokenStream<ComponentValue>& tokens)
  6403. {
  6404. // FIXME: This shouldn't be needed. Right now, the below code returns a CSSStyleValue even if no tokens are consumed!
  6405. if (!tokens.has_next_token())
  6406. return nullptr;
  6407. // https://www.w3.org/TR/css-grid-2/#line-placement
  6408. // Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
  6409. // <grid-line> =
  6410. // auto |
  6411. // <custom-ident> |
  6412. // [ <integer> && <custom-ident>? ] |
  6413. // [ span && [ <integer> || <custom-ident> ] ]
  6414. auto is_valid_integer = [](auto& token) -> bool {
  6415. // An <integer> value of zero makes the declaration invalid.
  6416. if (token.is(Token::Type::Number) && token.token().number().is_integer() && token.token().number_value() != 0)
  6417. return true;
  6418. return false;
  6419. };
  6420. auto parse_custom_ident = [this](auto& tokens) {
  6421. // The <custom-ident> additionally excludes the keywords span and auto.
  6422. return parse_custom_ident_value(tokens, { "span"sv, "auto"sv });
  6423. };
  6424. auto transaction = tokens.begin_transaction();
  6425. // FIXME: Handle the single-token case inside the loop instead, so that we can more easily call this from
  6426. // `parse_grid_area_shorthand_value()` using a single TokenStream.
  6427. if (tokens.remaining_token_count() == 1) {
  6428. if (auto custom_ident = parse_custom_ident(tokens)) {
  6429. transaction.commit();
  6430. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line({}, custom_ident->custom_ident().to_string()));
  6431. }
  6432. auto& token = tokens.consume_a_token();
  6433. if (auto maybe_calculated = parse_calculated_value(token); maybe_calculated && maybe_calculated->resolves_to_number()) {
  6434. transaction.commit();
  6435. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(maybe_calculated->resolve_integer().value()), {}));
  6436. }
  6437. if (token.is_ident("auto"sv)) {
  6438. transaction.commit();
  6439. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto());
  6440. }
  6441. if (token.is_ident("span"sv)) {
  6442. transaction.commit();
  6443. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(1));
  6444. }
  6445. if (is_valid_integer(token)) {
  6446. transaction.commit();
  6447. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(static_cast<int>(token.token().number_value()), {}));
  6448. }
  6449. return nullptr;
  6450. }
  6451. auto span_value = false;
  6452. auto span_or_position_value = 0;
  6453. String identifier_value;
  6454. while (tokens.has_next_token()) {
  6455. auto& token = tokens.next_token();
  6456. if (token.is_ident("auto"sv))
  6457. return nullptr;
  6458. if (token.is_ident("span"sv)) {
  6459. if (span_value)
  6460. return nullptr;
  6461. tokens.discard_a_token(); // span
  6462. span_value = true;
  6463. continue;
  6464. }
  6465. if (is_valid_integer(token)) {
  6466. if (span_or_position_value != 0)
  6467. return nullptr;
  6468. span_or_position_value = static_cast<int>(tokens.consume_a_token().token().to_integer());
  6469. continue;
  6470. }
  6471. if (auto custom_ident = parse_custom_ident(tokens)) {
  6472. if (!identifier_value.is_empty())
  6473. return nullptr;
  6474. identifier_value = custom_ident->custom_ident().to_string();
  6475. continue;
  6476. }
  6477. break;
  6478. }
  6479. // Negative integers or zero are invalid.
  6480. if (span_value && span_or_position_value < 1)
  6481. return nullptr;
  6482. // If the <integer> is omitted, it defaults to 1.
  6483. if (span_or_position_value == 0)
  6484. span_or_position_value = 1;
  6485. transaction.commit();
  6486. if (!identifier_value.is_empty())
  6487. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_line(span_or_position_value, identifier_value));
  6488. return GridTrackPlacementStyleValue::create(GridTrackPlacement::make_span(span_or_position_value));
  6489. }
  6490. RefPtr<CSSStyleValue> Parser::parse_grid_track_placement_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6491. {
  6492. auto start_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnStart : PropertyID::GridRowStart;
  6493. auto end_property = (property_id == PropertyID::GridColumn) ? PropertyID::GridColumnEnd : PropertyID::GridRowEnd;
  6494. auto transaction = tokens.begin_transaction();
  6495. auto current_token = tokens.consume_a_token();
  6496. Vector<ComponentValue> track_start_placement_tokens;
  6497. while (true) {
  6498. if (current_token.is_delim('/'))
  6499. break;
  6500. track_start_placement_tokens.append(current_token);
  6501. if (!tokens.has_next_token())
  6502. break;
  6503. current_token = tokens.consume_a_token();
  6504. }
  6505. Vector<ComponentValue> track_end_placement_tokens;
  6506. if (tokens.has_next_token()) {
  6507. current_token = tokens.consume_a_token();
  6508. while (true) {
  6509. track_end_placement_tokens.append(current_token);
  6510. if (!tokens.has_next_token())
  6511. break;
  6512. current_token = tokens.consume_a_token();
  6513. }
  6514. }
  6515. TokenStream track_start_placement_token_stream { track_start_placement_tokens };
  6516. auto parsed_start_value = parse_grid_track_placement(track_start_placement_token_stream);
  6517. if (parsed_start_value && track_end_placement_tokens.is_empty()) {
  6518. transaction.commit();
  6519. if (parsed_start_value->grid_track_placement().has_identifier()) {
  6520. auto custom_ident = parsed_start_value.release_nonnull();
  6521. return ShorthandStyleValue::create(property_id, { start_property, end_property }, { custom_ident, custom_ident });
  6522. }
  6523. return ShorthandStyleValue::create(property_id,
  6524. { start_property, end_property },
  6525. { parsed_start_value.release_nonnull(), GridTrackPlacementStyleValue::create(GridTrackPlacement::make_auto()) });
  6526. }
  6527. TokenStream track_end_placement_token_stream { track_end_placement_tokens };
  6528. auto parsed_end_value = parse_grid_track_placement(track_end_placement_token_stream);
  6529. if (parsed_start_value && parsed_end_value) {
  6530. transaction.commit();
  6531. return ShorthandStyleValue::create(property_id,
  6532. { start_property, end_property },
  6533. { parsed_start_value.release_nonnull(), parsed_end_value.release_nonnull() });
  6534. }
  6535. return nullptr;
  6536. }
  6537. // https://www.w3.org/TR/css-grid-2/#explicit-grid-shorthand
  6538. // 7.4. Explicit Grid Shorthand: the grid-template property
  6539. RefPtr<CSSStyleValue> Parser::parse_grid_track_size_list_shorthand_value(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  6540. {
  6541. // The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows,
  6542. // and grid-template-areas in a single declaration. It has several distinct syntax forms:
  6543. // none
  6544. // - Sets all three properties to their initial values (none).
  6545. // <'grid-template-rows'> / <'grid-template-columns'>
  6546. // - Sets grid-template-rows and grid-template-columns to the specified values, respectively, and sets grid-template-areas to none.
  6547. // [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
  6548. // - Sets grid-template-areas to the strings listed.
  6549. // - Sets grid-template-rows to the <track-size>s following each string (filling in auto for any missing sizes),
  6550. // and splicing in the named lines defined before/after each size.
  6551. // - Sets grid-template-columns to the track listing specified after the slash (or none, if not specified).
  6552. auto transaction = tokens.begin_transaction();
  6553. // FIXME: Read the parts in place if possible, instead of constructing separate vectors and streams.
  6554. Vector<ComponentValue> template_rows_tokens;
  6555. Vector<ComponentValue> template_columns_tokens;
  6556. Vector<ComponentValue> template_area_tokens;
  6557. bool found_forward_slash = false;
  6558. while (tokens.has_next_token()) {
  6559. auto& token = tokens.consume_a_token();
  6560. if (token.is_delim('/')) {
  6561. if (found_forward_slash)
  6562. return nullptr;
  6563. found_forward_slash = true;
  6564. continue;
  6565. }
  6566. if (found_forward_slash) {
  6567. template_columns_tokens.append(token);
  6568. continue;
  6569. }
  6570. if (token.is(Token::Type::String))
  6571. template_area_tokens.append(token);
  6572. else
  6573. template_rows_tokens.append(token);
  6574. }
  6575. TokenStream template_area_token_stream { template_area_tokens };
  6576. TokenStream template_rows_token_stream { template_rows_tokens };
  6577. TokenStream template_columns_token_stream { template_columns_tokens };
  6578. auto parsed_template_areas_values = parse_grid_template_areas_value(template_area_token_stream);
  6579. auto parsed_template_rows_values = parse_grid_track_size_list(template_rows_token_stream, true);
  6580. auto parsed_template_columns_values = parse_grid_track_size_list(template_columns_token_stream);
  6581. if (template_area_token_stream.has_next_token()
  6582. || template_rows_token_stream.has_next_token()
  6583. || template_columns_token_stream.has_next_token())
  6584. return nullptr;
  6585. transaction.commit();
  6586. return ShorthandStyleValue::create(property_id,
  6587. { PropertyID::GridTemplateAreas, PropertyID::GridTemplateRows, PropertyID::GridTemplateColumns },
  6588. { parsed_template_areas_values.release_nonnull(), parsed_template_rows_values.release_nonnull(), parsed_template_columns_values.release_nonnull() });
  6589. }
  6590. RefPtr<CSSStyleValue> Parser::parse_grid_area_shorthand_value(TokenStream<ComponentValue>& tokens)
  6591. {
  6592. auto transaction = tokens.begin_transaction();
  6593. auto parse_placement_tokens = [&](Vector<ComponentValue>& placement_tokens, bool check_for_delimiter = true) -> void {
  6594. while (tokens.has_next_token()) {
  6595. auto& current_token = tokens.consume_a_token();
  6596. if (check_for_delimiter && current_token.is_delim('/'))
  6597. break;
  6598. placement_tokens.append(current_token);
  6599. }
  6600. };
  6601. Vector<ComponentValue> row_start_placement_tokens;
  6602. parse_placement_tokens(row_start_placement_tokens);
  6603. Vector<ComponentValue> column_start_placement_tokens;
  6604. if (tokens.has_next_token())
  6605. parse_placement_tokens(column_start_placement_tokens);
  6606. Vector<ComponentValue> row_end_placement_tokens;
  6607. if (tokens.has_next_token())
  6608. parse_placement_tokens(row_end_placement_tokens);
  6609. Vector<ComponentValue> column_end_placement_tokens;
  6610. if (tokens.has_next_token())
  6611. parse_placement_tokens(column_end_placement_tokens, false);
  6612. // https://www.w3.org/TR/css-grid-2/#placement-shorthands
  6613. // The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and
  6614. // grid-column-end.
  6615. TokenStream row_start_placement_token_stream { row_start_placement_tokens };
  6616. auto row_start_style_value = parse_grid_track_placement(row_start_placement_token_stream);
  6617. if (row_start_placement_token_stream.has_next_token())
  6618. return nullptr;
  6619. TokenStream column_start_placement_token_stream { column_start_placement_tokens };
  6620. auto column_start_style_value = parse_grid_track_placement(column_start_placement_token_stream);
  6621. if (column_start_placement_token_stream.has_next_token())
  6622. return nullptr;
  6623. TokenStream row_end_placement_token_stream { row_end_placement_tokens };
  6624. auto row_end_style_value = parse_grid_track_placement(row_end_placement_token_stream);
  6625. if (row_end_placement_token_stream.has_next_token())
  6626. return nullptr;
  6627. TokenStream column_end_placement_token_stream { column_end_placement_tokens };
  6628. auto column_end_style_value = parse_grid_track_placement(column_end_placement_token_stream);
  6629. if (column_end_placement_token_stream.has_next_token())
  6630. return nullptr;
  6631. // If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start
  6632. // is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the
  6633. // fourth value.
  6634. auto row_start = GridTrackPlacement::make_auto();
  6635. auto column_start = GridTrackPlacement::make_auto();
  6636. auto row_end = GridTrackPlacement::make_auto();
  6637. auto column_end = GridTrackPlacement::make_auto();
  6638. if (row_start_style_value)
  6639. row_start = row_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6640. // When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to
  6641. // that value. Otherwise, it is set to auto.
  6642. if (column_start_style_value)
  6643. column_start = column_start_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6644. else
  6645. column_start = row_start;
  6646. // When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that
  6647. // <custom-ident>; otherwise, it is set to auto.
  6648. if (row_end_style_value)
  6649. row_end = row_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6650. else
  6651. row_end = column_start;
  6652. // When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to
  6653. // that <custom-ident>; otherwise, it is set to auto.
  6654. if (column_end_style_value)
  6655. column_end = column_end_style_value.release_nonnull()->as_grid_track_placement().grid_track_placement();
  6656. else
  6657. column_end = row_end;
  6658. transaction.commit();
  6659. return ShorthandStyleValue::create(PropertyID::GridArea,
  6660. { PropertyID::GridRowStart, PropertyID::GridColumnStart, PropertyID::GridRowEnd, PropertyID::GridColumnEnd },
  6661. { GridTrackPlacementStyleValue::create(row_start), GridTrackPlacementStyleValue::create(column_start), GridTrackPlacementStyleValue::create(row_end), GridTrackPlacementStyleValue::create(column_end) });
  6662. }
  6663. RefPtr<CSSStyleValue> Parser::parse_grid_shorthand_value(TokenStream<ComponentValue>& tokens)
  6664. {
  6665. // <'grid-template'> |
  6666. // FIXME: <'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>? |
  6667. // FIXME: [ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
  6668. return parse_grid_track_size_list_shorthand_value(PropertyID::Grid, tokens);
  6669. }
  6670. // https://www.w3.org/TR/css-grid-1/#grid-template-areas-property
  6671. RefPtr<CSSStyleValue> Parser::parse_grid_template_areas_value(TokenStream<ComponentValue>& tokens)
  6672. {
  6673. // none | <string>+
  6674. Vector<Vector<String>> grid_area_rows;
  6675. if (auto none = parse_all_as_single_keyword_value(tokens, Keyword::None))
  6676. return GridTemplateAreaStyleValue::create(move(grid_area_rows));
  6677. auto transaction = tokens.begin_transaction();
  6678. while (tokens.has_next_token() && tokens.next_token().is(Token::Type::String)) {
  6679. Vector<String> grid_area_columns;
  6680. auto const parts = MUST(tokens.consume_a_token().token().string().to_string().split(' '));
  6681. for (auto& part : parts) {
  6682. grid_area_columns.append(part);
  6683. }
  6684. grid_area_rows.append(move(grid_area_columns));
  6685. }
  6686. transaction.commit();
  6687. return GridTemplateAreaStyleValue::create(grid_area_rows);
  6688. }
  6689. static bool block_contains_var_or_attr(SimpleBlock const& block);
  6690. static bool function_contains_var_or_attr(Function const& function)
  6691. {
  6692. if (function.name.equals_ignoring_ascii_case("var"sv) || function.name.equals_ignoring_ascii_case("attr"sv))
  6693. return true;
  6694. for (auto const& token : function.value) {
  6695. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6696. return true;
  6697. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6698. return true;
  6699. }
  6700. return false;
  6701. }
  6702. bool block_contains_var_or_attr(SimpleBlock const& block)
  6703. {
  6704. for (auto const& token : block.value) {
  6705. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6706. return true;
  6707. if (token.is_block() && block_contains_var_or_attr(token.block()))
  6708. return true;
  6709. }
  6710. return false;
  6711. }
  6712. Parser::ParseErrorOr<NonnullRefPtr<CSSStyleValue>> Parser::parse_css_value(PropertyID property_id, TokenStream<ComponentValue>& unprocessed_tokens, Optional<String> original_source_text)
  6713. {
  6714. m_context.set_current_property_id(property_id);
  6715. Vector<ComponentValue> component_values;
  6716. bool contains_var_or_attr = false;
  6717. bool const property_accepts_custom_ident = property_accepts_type(property_id, ValueType::CustomIdent);
  6718. while (unprocessed_tokens.has_next_token()) {
  6719. auto const& token = unprocessed_tokens.consume_a_token();
  6720. if (token.is(Token::Type::Semicolon)) {
  6721. unprocessed_tokens.reconsume_current_input_token();
  6722. break;
  6723. }
  6724. if (property_id != PropertyID::Custom) {
  6725. if (token.is(Token::Type::Whitespace))
  6726. continue;
  6727. if (!property_accepts_custom_ident && token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  6728. return ParseError::IncludesIgnoredVendorPrefix;
  6729. }
  6730. if (!contains_var_or_attr) {
  6731. if (token.is_function() && function_contains_var_or_attr(token.function()))
  6732. contains_var_or_attr = true;
  6733. else if (token.is_block() && block_contains_var_or_attr(token.block()))
  6734. contains_var_or_attr = true;
  6735. }
  6736. component_values.append(token);
  6737. }
  6738. if (property_id == PropertyID::Custom || contains_var_or_attr)
  6739. return UnresolvedStyleValue::create(move(component_values), contains_var_or_attr, original_source_text);
  6740. if (component_values.is_empty())
  6741. return ParseError::SyntaxError;
  6742. auto tokens = TokenStream { component_values };
  6743. if (component_values.size() == 1) {
  6744. if (auto parsed_value = parse_builtin_value(tokens))
  6745. return parsed_value.release_nonnull();
  6746. }
  6747. // Special-case property handling
  6748. switch (property_id) {
  6749. case PropertyID::AspectRatio:
  6750. if (auto parsed_value = parse_aspect_ratio_value(tokens); parsed_value && !tokens.has_next_token())
  6751. return parsed_value.release_nonnull();
  6752. return ParseError::SyntaxError;
  6753. case PropertyID::BackdropFilter:
  6754. if (auto parsed_value = parse_filter_value_list_value(tokens); parsed_value && !tokens.has_next_token())
  6755. return parsed_value.release_nonnull();
  6756. return ParseError::SyntaxError;
  6757. case PropertyID::Background:
  6758. if (auto parsed_value = parse_background_value(tokens); parsed_value && !tokens.has_next_token())
  6759. return parsed_value.release_nonnull();
  6760. return ParseError::SyntaxError;
  6761. case PropertyID::BackgroundAttachment:
  6762. case PropertyID::BackgroundClip:
  6763. case PropertyID::BackgroundImage:
  6764. case PropertyID::BackgroundOrigin:
  6765. if (auto parsed_value = parse_simple_comma_separated_value_list(property_id, tokens))
  6766. return parsed_value.release_nonnull();
  6767. return ParseError::SyntaxError;
  6768. case PropertyID::BackgroundPosition:
  6769. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_position_value(tokens, PositionParsingMode::BackgroundPosition); }))
  6770. return parsed_value.release_nonnull();
  6771. return ParseError::SyntaxError;
  6772. case PropertyID::BackgroundPositionX:
  6773. case PropertyID::BackgroundPositionY:
  6774. 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); }))
  6775. return parsed_value.release_nonnull();
  6776. return ParseError::SyntaxError;
  6777. case PropertyID::BackgroundRepeat:
  6778. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  6779. return parsed_value.release_nonnull();
  6780. return ParseError::SyntaxError;
  6781. case PropertyID::BackgroundSize:
  6782. if (auto parsed_value = parse_comma_separated_value_list(tokens, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  6783. return parsed_value.release_nonnull();
  6784. return ParseError::SyntaxError;
  6785. case PropertyID::Border:
  6786. case PropertyID::BorderBottom:
  6787. case PropertyID::BorderLeft:
  6788. case PropertyID::BorderRight:
  6789. case PropertyID::BorderTop:
  6790. if (auto parsed_value = parse_border_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6791. return parsed_value.release_nonnull();
  6792. return ParseError::SyntaxError;
  6793. case PropertyID::BorderTopLeftRadius:
  6794. case PropertyID::BorderTopRightRadius:
  6795. case PropertyID::BorderBottomRightRadius:
  6796. case PropertyID::BorderBottomLeftRadius:
  6797. if (auto parsed_value = parse_border_radius_value(tokens); parsed_value && !tokens.has_next_token())
  6798. return parsed_value.release_nonnull();
  6799. return ParseError::SyntaxError;
  6800. case PropertyID::BorderRadius:
  6801. if (auto parsed_value = parse_border_radius_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6802. return parsed_value.release_nonnull();
  6803. return ParseError::SyntaxError;
  6804. case PropertyID::BoxShadow:
  6805. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::Yes); parsed_value && !tokens.has_next_token())
  6806. return parsed_value.release_nonnull();
  6807. return ParseError::SyntaxError;
  6808. case PropertyID::Columns:
  6809. if (auto parsed_value = parse_columns_value(tokens); parsed_value && !tokens.has_next_token())
  6810. return parsed_value.release_nonnull();
  6811. return ParseError::SyntaxError;
  6812. case PropertyID::Content:
  6813. if (auto parsed_value = parse_content_value(tokens); parsed_value && !tokens.has_next_token())
  6814. return parsed_value.release_nonnull();
  6815. return ParseError::SyntaxError;
  6816. case PropertyID::CounterIncrement:
  6817. if (auto parsed_value = parse_counter_increment_value(tokens); parsed_value && !tokens.has_next_token())
  6818. return parsed_value.release_nonnull();
  6819. return ParseError::SyntaxError;
  6820. case PropertyID::CounterReset:
  6821. if (auto parsed_value = parse_counter_reset_value(tokens); parsed_value && !tokens.has_next_token())
  6822. return parsed_value.release_nonnull();
  6823. return ParseError::SyntaxError;
  6824. case PropertyID::CounterSet:
  6825. if (auto parsed_value = parse_counter_set_value(tokens); parsed_value && !tokens.has_next_token())
  6826. return parsed_value.release_nonnull();
  6827. return ParseError::SyntaxError;
  6828. case PropertyID::Display:
  6829. if (auto parsed_value = parse_display_value(tokens); parsed_value && !tokens.has_next_token())
  6830. return parsed_value.release_nonnull();
  6831. return ParseError::SyntaxError;
  6832. case PropertyID::Flex:
  6833. if (auto parsed_value = parse_flex_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6834. return parsed_value.release_nonnull();
  6835. return ParseError::SyntaxError;
  6836. case PropertyID::FlexFlow:
  6837. if (auto parsed_value = parse_flex_flow_value(tokens); parsed_value && !tokens.has_next_token())
  6838. return parsed_value.release_nonnull();
  6839. return ParseError::SyntaxError;
  6840. case PropertyID::Font:
  6841. if (auto parsed_value = parse_font_value(tokens); parsed_value && !tokens.has_next_token())
  6842. return parsed_value.release_nonnull();
  6843. return ParseError::SyntaxError;
  6844. case PropertyID::FontFamily:
  6845. if (auto parsed_value = parse_font_family_value(tokens); parsed_value && !tokens.has_next_token())
  6846. return parsed_value.release_nonnull();
  6847. return ParseError::SyntaxError;
  6848. case PropertyID::FontFeatureSettings:
  6849. if (auto parsed_value = parse_font_feature_settings_value(tokens); parsed_value && !tokens.has_next_token())
  6850. return parsed_value.release_nonnull();
  6851. return ParseError::SyntaxError;
  6852. case PropertyID::FontLanguageOverride:
  6853. if (auto parsed_value = parse_font_language_override_value(tokens); parsed_value && !tokens.has_next_token())
  6854. return parsed_value.release_nonnull();
  6855. return ParseError::SyntaxError;
  6856. case PropertyID::FontVariationSettings:
  6857. if (auto parsed_value = parse_font_variation_settings_value(tokens); parsed_value && !tokens.has_next_token())
  6858. return parsed_value.release_nonnull();
  6859. return ParseError::SyntaxError;
  6860. case PropertyID::GridArea:
  6861. if (auto parsed_value = parse_grid_area_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6862. return parsed_value.release_nonnull();
  6863. return ParseError::SyntaxError;
  6864. case PropertyID::GridAutoFlow:
  6865. if (auto parsed_value = parse_grid_auto_flow_value(tokens); parsed_value && !tokens.has_next_token())
  6866. return parsed_value.release_nonnull();
  6867. return ParseError::SyntaxError;
  6868. case PropertyID::GridColumn:
  6869. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6870. return parsed_value.release_nonnull();
  6871. return ParseError::SyntaxError;
  6872. case PropertyID::GridColumnEnd:
  6873. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6874. return parsed_value.release_nonnull();
  6875. return ParseError::SyntaxError;
  6876. case PropertyID::GridColumnStart:
  6877. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6878. return parsed_value.release_nonnull();
  6879. return ParseError::SyntaxError;
  6880. case PropertyID::GridRow:
  6881. if (auto parsed_value = parse_grid_track_placement_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6882. return parsed_value.release_nonnull();
  6883. return ParseError::SyntaxError;
  6884. case PropertyID::GridRowEnd:
  6885. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6886. return parsed_value.release_nonnull();
  6887. return ParseError::SyntaxError;
  6888. case PropertyID::GridRowStart:
  6889. if (auto parsed_value = parse_grid_track_placement(tokens); parsed_value && !tokens.has_next_token())
  6890. return parsed_value.release_nonnull();
  6891. return ParseError::SyntaxError;
  6892. case PropertyID::Grid:
  6893. if (auto parsed_value = parse_grid_shorthand_value(tokens); parsed_value && !tokens.has_next_token())
  6894. return parsed_value.release_nonnull();
  6895. return ParseError::SyntaxError;
  6896. case PropertyID::GridTemplate:
  6897. if (auto parsed_value = parse_grid_track_size_list_shorthand_value(property_id, tokens); parsed_value && !tokens.has_next_token())
  6898. return parsed_value.release_nonnull();
  6899. return ParseError::SyntaxError;
  6900. case PropertyID::GridTemplateAreas:
  6901. if (auto parsed_value = parse_grid_template_areas_value(tokens); parsed_value && !tokens.has_next_token())
  6902. return parsed_value.release_nonnull();
  6903. return ParseError::SyntaxError;
  6904. case PropertyID::GridTemplateColumns:
  6905. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  6906. return parsed_value.release_nonnull();
  6907. return ParseError::SyntaxError;
  6908. case PropertyID::GridTemplateRows:
  6909. if (auto parsed_value = parse_grid_track_size_list(tokens); parsed_value && !tokens.has_next_token())
  6910. return parsed_value.release_nonnull();
  6911. return ParseError::SyntaxError;
  6912. case PropertyID::GridAutoColumns:
  6913. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  6914. return parsed_value.release_nonnull();
  6915. return ParseError::SyntaxError;
  6916. case PropertyID::GridAutoRows:
  6917. if (auto parsed_value = parse_grid_auto_track_sizes(tokens); parsed_value && !tokens.has_next_token())
  6918. return parsed_value.release_nonnull();
  6919. return ParseError::SyntaxError;
  6920. case PropertyID::ListStyle:
  6921. if (auto parsed_value = parse_list_style_value(tokens); parsed_value && !tokens.has_next_token())
  6922. return parsed_value.release_nonnull();
  6923. return ParseError::SyntaxError;
  6924. case PropertyID::MathDepth:
  6925. if (auto parsed_value = parse_math_depth_value(tokens); parsed_value && !tokens.has_next_token())
  6926. return parsed_value.release_nonnull();
  6927. return ParseError::SyntaxError;
  6928. case PropertyID::Overflow:
  6929. if (auto parsed_value = parse_overflow_value(tokens); parsed_value && !tokens.has_next_token())
  6930. return parsed_value.release_nonnull();
  6931. return ParseError::SyntaxError;
  6932. case PropertyID::PlaceContent:
  6933. if (auto parsed_value = parse_place_content_value(tokens); parsed_value && !tokens.has_next_token())
  6934. return parsed_value.release_nonnull();
  6935. return ParseError::SyntaxError;
  6936. case PropertyID::PlaceItems:
  6937. if (auto parsed_value = parse_place_items_value(tokens); parsed_value && !tokens.has_next_token())
  6938. return parsed_value.release_nonnull();
  6939. return ParseError::SyntaxError;
  6940. case PropertyID::PlaceSelf:
  6941. if (auto parsed_value = parse_place_self_value(tokens); parsed_value && !tokens.has_next_token())
  6942. return parsed_value.release_nonnull();
  6943. return ParseError::SyntaxError;
  6944. case PropertyID::Quotes:
  6945. if (auto parsed_value = parse_quotes_value(tokens); parsed_value && !tokens.has_next_token())
  6946. return parsed_value.release_nonnull();
  6947. return ParseError::SyntaxError;
  6948. case PropertyID::ScrollbarGutter:
  6949. if (auto parsed_value = parse_scrollbar_gutter_value(tokens); parsed_value && !tokens.has_next_token())
  6950. return parsed_value.release_nonnull();
  6951. return ParseError::SyntaxError;
  6952. case PropertyID::TextDecoration:
  6953. if (auto parsed_value = parse_text_decoration_value(tokens); parsed_value && !tokens.has_next_token())
  6954. return parsed_value.release_nonnull();
  6955. return ParseError::SyntaxError;
  6956. case PropertyID::TextDecorationLine:
  6957. if (auto parsed_value = parse_text_decoration_line_value(tokens); parsed_value && !tokens.has_next_token())
  6958. return parsed_value.release_nonnull();
  6959. return ParseError::SyntaxError;
  6960. case PropertyID::TextShadow:
  6961. if (auto parsed_value = parse_shadow_value(tokens, AllowInsetKeyword::No); parsed_value && !tokens.has_next_token())
  6962. return parsed_value.release_nonnull();
  6963. return ParseError::SyntaxError;
  6964. case PropertyID::Transform:
  6965. if (auto parsed_value = parse_transform_value(tokens); parsed_value && !tokens.has_next_token())
  6966. return parsed_value.release_nonnull();
  6967. return ParseError::SyntaxError;
  6968. case PropertyID::TransformOrigin:
  6969. if (auto parsed_value = parse_transform_origin_value(tokens); parsed_value && !tokens.has_next_token())
  6970. return parsed_value.release_nonnull();
  6971. return ParseError::SyntaxError;
  6972. case PropertyID::Transition:
  6973. if (auto parsed_value = parse_transition_value(tokens); parsed_value && !tokens.has_next_token())
  6974. return parsed_value.release_nonnull();
  6975. return ParseError::SyntaxError;
  6976. default:
  6977. break;
  6978. }
  6979. // If there's only 1 ComponentValue, we can only produce a single CSSStyleValue.
  6980. if (component_values.size() == 1) {
  6981. auto stream = TokenStream { component_values };
  6982. if (auto parsed_value = parse_css_value_for_property(property_id, stream))
  6983. return parsed_value.release_nonnull();
  6984. } else {
  6985. StyleValueVector parsed_values;
  6986. auto stream = TokenStream { component_values };
  6987. while (auto parsed_value = parse_css_value_for_property(property_id, stream)) {
  6988. parsed_values.append(parsed_value.release_nonnull());
  6989. if (!stream.has_next_token())
  6990. break;
  6991. }
  6992. // Some types (such as <ratio>) can be made from multiple ComponentValues, so if we only made 1 CSSStyleValue, return it directly.
  6993. if (parsed_values.size() == 1)
  6994. return *parsed_values.take_first();
  6995. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  6996. return StyleValueList::create(move(parsed_values), StyleValueList::Separator::Space);
  6997. }
  6998. // We have multiple values, but the property claims to accept only a single one, check if it's a shorthand property.
  6999. auto unassigned_properties = longhands_for_shorthand(property_id);
  7000. if (unassigned_properties.is_empty())
  7001. return ParseError::SyntaxError;
  7002. auto stream = TokenStream { component_values };
  7003. HashMap<UnderlyingType<PropertyID>, Vector<ValueComparingNonnullRefPtr<CSSStyleValue const>>> assigned_values;
  7004. while (stream.has_next_token() && !unassigned_properties.is_empty()) {
  7005. auto property_and_value = parse_css_value_for_properties(unassigned_properties, stream);
  7006. if (property_and_value.has_value()) {
  7007. auto property = property_and_value->property;
  7008. auto value = property_and_value->style_value;
  7009. auto& values = assigned_values.ensure(to_underlying(property));
  7010. if (values.size() + 1 == property_maximum_value_count(property)) {
  7011. // We're done with this property, move on to the next one.
  7012. unassigned_properties.remove_first_matching([&](auto& unassigned_property) { return unassigned_property == property; });
  7013. }
  7014. values.append(value.release_nonnull());
  7015. continue;
  7016. }
  7017. // No property matched, so we're done.
  7018. dbgln("No property (from {} properties) matched {}", unassigned_properties.size(), stream.next_token().to_debug_string());
  7019. for (auto id : unassigned_properties)
  7020. dbgln(" {}", string_from_property_id(id));
  7021. break;
  7022. }
  7023. for (auto& property : unassigned_properties)
  7024. assigned_values.ensure(to_underlying(property)).append(property_initial_value(m_context.realm(), property));
  7025. stream.discard_whitespace();
  7026. if (stream.has_next_token())
  7027. return ParseError::SyntaxError;
  7028. Vector<PropertyID> longhand_properties;
  7029. longhand_properties.ensure_capacity(assigned_values.size());
  7030. for (auto& it : assigned_values)
  7031. longhand_properties.unchecked_append(static_cast<PropertyID>(it.key));
  7032. StyleValueVector longhand_values;
  7033. longhand_values.ensure_capacity(assigned_values.size());
  7034. for (auto& it : assigned_values) {
  7035. if (it.value.size() == 1)
  7036. longhand_values.unchecked_append(it.value.take_first());
  7037. else
  7038. longhand_values.unchecked_append(StyleValueList::create(move(it.value), StyleValueList::Separator::Space));
  7039. }
  7040. return { ShorthandStyleValue::create(property_id, move(longhand_properties), move(longhand_values)) };
  7041. }
  7042. RefPtr<CSSStyleValue> Parser::parse_css_value_for_property(PropertyID property_id, TokenStream<ComponentValue>& tokens)
  7043. {
  7044. return parse_css_value_for_properties({ &property_id, 1 }, tokens)
  7045. .map([](auto& it) { return it.style_value; })
  7046. .value_or(nullptr);
  7047. }
  7048. Optional<Parser::PropertyAndValue> Parser::parse_css_value_for_properties(ReadonlySpan<PropertyID> property_ids, TokenStream<ComponentValue>& tokens)
  7049. {
  7050. auto any_property_accepts_type = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  7051. for (auto const& property : property_ids) {
  7052. if (property_accepts_type(property, value_type))
  7053. return property;
  7054. }
  7055. return {};
  7056. };
  7057. auto any_property_accepts_type_percentage = [](ReadonlySpan<PropertyID> property_ids, ValueType value_type) -> Optional<PropertyID> {
  7058. for (auto const& property : property_ids) {
  7059. if (property_accepts_type(property, value_type) && property_accepts_type(property, ValueType::Percentage))
  7060. return property;
  7061. }
  7062. return {};
  7063. };
  7064. auto any_property_accepts_keyword = [](ReadonlySpan<PropertyID> property_ids, Keyword keyword) -> Optional<PropertyID> {
  7065. for (auto const& property : property_ids) {
  7066. if (property_accepts_keyword(property, keyword))
  7067. return property;
  7068. }
  7069. return {};
  7070. };
  7071. auto& peek_token = tokens.next_token();
  7072. if (auto property = any_property_accepts_type(property_ids, ValueType::EasingFunction); property.has_value()) {
  7073. if (auto maybe_easing_function = parse_easing_value(tokens))
  7074. return PropertyAndValue { *property, maybe_easing_function };
  7075. }
  7076. if (peek_token.is(Token::Type::Ident)) {
  7077. // NOTE: We do not try to parse "CSS-wide keywords" here. https://www.w3.org/TR/css-values-4/#common-keywords
  7078. // These are only valid on their own, and so should be parsed directly in `parse_css_value()`.
  7079. auto keyword = keyword_from_string(peek_token.token().ident());
  7080. if (keyword.has_value()) {
  7081. if (auto property = any_property_accepts_keyword(property_ids, keyword.value()); property.has_value()) {
  7082. tokens.discard_a_token();
  7083. return PropertyAndValue { *property, CSSKeywordValue::create(keyword.value()) };
  7084. }
  7085. }
  7086. // Custom idents
  7087. if (auto property = any_property_accepts_type(property_ids, ValueType::CustomIdent); property.has_value()) {
  7088. if (auto custom_ident = parse_custom_ident_value(tokens, {}))
  7089. return PropertyAndValue { *property, custom_ident };
  7090. }
  7091. }
  7092. if (auto property = any_property_accepts_type(property_ids, ValueType::Color); property.has_value()) {
  7093. if (auto maybe_color = parse_color_value(tokens))
  7094. return PropertyAndValue { *property, maybe_color };
  7095. }
  7096. if (auto property = any_property_accepts_type(property_ids, ValueType::Counter); property.has_value()) {
  7097. if (auto maybe_counter = parse_counter_value(tokens))
  7098. return PropertyAndValue { *property, maybe_counter };
  7099. }
  7100. if (auto property = any_property_accepts_type(property_ids, ValueType::Image); property.has_value()) {
  7101. if (auto maybe_image = parse_image_value(tokens))
  7102. return PropertyAndValue { *property, maybe_image };
  7103. }
  7104. if (auto property = any_property_accepts_type(property_ids, ValueType::Position); property.has_value()) {
  7105. if (auto maybe_position = parse_position_value(tokens))
  7106. return PropertyAndValue { *property, maybe_position };
  7107. }
  7108. if (auto property = any_property_accepts_type(property_ids, ValueType::BackgroundPosition); property.has_value()) {
  7109. if (auto maybe_position = parse_position_value(tokens, PositionParsingMode::BackgroundPosition))
  7110. return PropertyAndValue { *property, maybe_position };
  7111. }
  7112. if (auto property = any_property_accepts_type(property_ids, ValueType::BasicShape); property.has_value()) {
  7113. if (auto maybe_basic_shape = parse_basic_shape_value(tokens))
  7114. return PropertyAndValue { *property, maybe_basic_shape };
  7115. }
  7116. if (auto property = any_property_accepts_type(property_ids, ValueType::Ratio); property.has_value()) {
  7117. if (auto maybe_ratio = parse_ratio_value(tokens))
  7118. return PropertyAndValue { *property, maybe_ratio };
  7119. }
  7120. auto property_accepting_integer = any_property_accepts_type(property_ids, ValueType::Integer);
  7121. auto property_accepting_number = any_property_accepts_type(property_ids, ValueType::Number);
  7122. bool property_accepts_numeric = property_accepting_integer.has_value() || property_accepting_number.has_value();
  7123. if (peek_token.is(Token::Type::Number) && property_accepts_numeric) {
  7124. if (peek_token.token().number().is_integer() && property_accepting_integer.has_value()) {
  7125. auto integer = IntegerStyleValue::create(peek_token.token().number().integer_value());
  7126. if (property_accepts_integer(*property_accepting_integer, integer->as_integer().integer())) {
  7127. tokens.discard_a_token(); // integer
  7128. return PropertyAndValue { *property_accepting_integer, integer };
  7129. }
  7130. }
  7131. if (property_accepting_number.has_value()) {
  7132. auto number = NumberStyleValue::create(peek_token.token().number().value());
  7133. if (property_accepts_number(*property_accepting_number, number->as_number().number())) {
  7134. tokens.discard_a_token(); // number
  7135. return PropertyAndValue { *property_accepting_number, number };
  7136. }
  7137. }
  7138. }
  7139. if (auto property = any_property_accepts_type(property_ids, ValueType::OpenTypeTag); property.has_value()) {
  7140. if (auto maybe_rect = parse_opentype_tag_value(tokens))
  7141. return PropertyAndValue { *property, maybe_rect };
  7142. }
  7143. if (peek_token.is(Token::Type::Percentage)) {
  7144. auto percentage = Percentage(peek_token.token().percentage());
  7145. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value() && property_accepts_percentage(*property, percentage)) {
  7146. tokens.discard_a_token();
  7147. return PropertyAndValue { *property, PercentageStyleValue::create(percentage) };
  7148. }
  7149. }
  7150. if (auto property = any_property_accepts_type(property_ids, ValueType::Rect); property.has_value()) {
  7151. if (auto maybe_rect = parse_rect_value(tokens))
  7152. return PropertyAndValue { *property, maybe_rect };
  7153. }
  7154. if (peek_token.is(Token::Type::String)) {
  7155. if (auto property = any_property_accepts_type(property_ids, ValueType::String); property.has_value())
  7156. return PropertyAndValue { *property, StringStyleValue::create(tokens.consume_a_token().token().string()) };
  7157. }
  7158. if (auto property = any_property_accepts_type(property_ids, ValueType::Url); property.has_value()) {
  7159. if (auto url = parse_url_value(tokens))
  7160. return PropertyAndValue { *property, url };
  7161. }
  7162. bool property_accepts_dimension = any_property_accepts_type(property_ids, ValueType::Angle).has_value()
  7163. || any_property_accepts_type(property_ids, ValueType::Flex).has_value()
  7164. || any_property_accepts_type(property_ids, ValueType::Frequency).has_value()
  7165. || any_property_accepts_type(property_ids, ValueType::Length).has_value()
  7166. || any_property_accepts_type(property_ids, ValueType::Percentage).has_value()
  7167. || any_property_accepts_type(property_ids, ValueType::Resolution).has_value()
  7168. || any_property_accepts_type(property_ids, ValueType::Time).has_value();
  7169. if (property_accepts_dimension) {
  7170. if (peek_token.is(Token::Type::Number) && m_context.is_parsing_svg_presentation_attribute()) {
  7171. auto transaction = tokens.begin_transaction();
  7172. auto token = tokens.consume_a_token();
  7173. // https://svgwg.org/svg2-draft/types.html#presentation-attribute-css-value
  7174. // We need to allow <number> in any place that expects a <length> or <angle>.
  7175. // FIXME: How should these numbers be interpreted? https://github.com/w3c/svgwg/issues/792
  7176. // For now: Convert them to px lengths, or deg angles.
  7177. auto angle = Angle::make_degrees(token.token().number_value());
  7178. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  7179. transaction.commit();
  7180. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  7181. }
  7182. auto length = Length::make_px(CSSPixels::nearest_value_for(token.token().number_value()));
  7183. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  7184. transaction.commit();
  7185. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  7186. }
  7187. }
  7188. auto transaction = tokens.begin_transaction();
  7189. if (auto maybe_dimension = parse_dimension(peek_token); maybe_dimension.has_value()) {
  7190. tokens.discard_a_token();
  7191. auto dimension = maybe_dimension.release_value();
  7192. if (dimension.is_angle()) {
  7193. auto angle = dimension.angle();
  7194. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value() && property_accepts_angle(*property, angle)) {
  7195. transaction.commit();
  7196. return PropertyAndValue { *property, AngleStyleValue::create(angle) };
  7197. }
  7198. }
  7199. if (dimension.is_flex()) {
  7200. auto flex = dimension.flex();
  7201. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value() && property_accepts_flex(*property, flex)) {
  7202. transaction.commit();
  7203. return PropertyAndValue { *property, FlexStyleValue::create(flex) };
  7204. }
  7205. }
  7206. if (dimension.is_frequency()) {
  7207. auto frequency = dimension.frequency();
  7208. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value() && property_accepts_frequency(*property, frequency)) {
  7209. transaction.commit();
  7210. return PropertyAndValue { *property, FrequencyStyleValue::create(frequency) };
  7211. }
  7212. }
  7213. if (dimension.is_length()) {
  7214. auto length = dimension.length();
  7215. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value() && property_accepts_length(*property, length)) {
  7216. transaction.commit();
  7217. return PropertyAndValue { *property, LengthStyleValue::create(length) };
  7218. }
  7219. }
  7220. if (dimension.is_resolution()) {
  7221. auto resolution = dimension.resolution();
  7222. if (auto property = any_property_accepts_type(property_ids, ValueType::Resolution); property.has_value() && property_accepts_resolution(*property, resolution)) {
  7223. transaction.commit();
  7224. return PropertyAndValue { *property, ResolutionStyleValue::create(resolution) };
  7225. }
  7226. }
  7227. if (dimension.is_time()) {
  7228. auto time = dimension.time();
  7229. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value() && property_accepts_time(*property, time)) {
  7230. transaction.commit();
  7231. return PropertyAndValue { *property, TimeStyleValue::create(time) };
  7232. }
  7233. }
  7234. }
  7235. }
  7236. // In order to not end up parsing `calc()` and other math expressions multiple times,
  7237. // we parse it once, and then see if its resolved type matches what the property accepts.
  7238. if (peek_token.is_function() && (property_accepts_dimension || property_accepts_numeric)) {
  7239. if (auto maybe_calculated = parse_calculated_value(peek_token); maybe_calculated) {
  7240. tokens.discard_a_token();
  7241. auto& calculated = *maybe_calculated;
  7242. // This is a bit sensitive to ordering: `<foo>` and `<percentage>` have to be checked before `<foo-percentage>`.
  7243. // FIXME: When parsing SVG presentation attributes, <number> is permitted wherever <length>, <length-percentage>, or <angle> are.
  7244. // The specifics are unclear, so I'm ignoring this for calculated values for now.
  7245. // See https://github.com/w3c/svgwg/issues/792
  7246. if (calculated.resolves_to_percentage()) {
  7247. if (auto property = any_property_accepts_type(property_ids, ValueType::Percentage); property.has_value())
  7248. return PropertyAndValue { *property, calculated };
  7249. } else if (calculated.resolves_to_angle()) {
  7250. if (auto property = any_property_accepts_type(property_ids, ValueType::Angle); property.has_value())
  7251. return PropertyAndValue { *property, calculated };
  7252. } else if (calculated.resolves_to_angle_percentage()) {
  7253. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Angle); property.has_value())
  7254. return PropertyAndValue { *property, calculated };
  7255. } else if (calculated.resolves_to_flex()) {
  7256. if (auto property = any_property_accepts_type(property_ids, ValueType::Flex); property.has_value())
  7257. return PropertyAndValue { *property, calculated };
  7258. } else if (calculated.resolves_to_frequency()) {
  7259. if (auto property = any_property_accepts_type(property_ids, ValueType::Frequency); property.has_value())
  7260. return PropertyAndValue { *property, calculated };
  7261. } else if (calculated.resolves_to_frequency_percentage()) {
  7262. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Frequency); property.has_value())
  7263. return PropertyAndValue { *property, calculated };
  7264. } else if (calculated.resolves_to_number()) {
  7265. if (property_accepts_numeric) {
  7266. auto property_or_resolved = property_accepting_integer.value_or_lazy_evaluated([property_accepting_number]() { return property_accepting_number.value(); });
  7267. return PropertyAndValue { property_or_resolved, calculated };
  7268. }
  7269. } else if (calculated.resolves_to_number_percentage()) {
  7270. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Number); property.has_value())
  7271. return PropertyAndValue { *property, calculated };
  7272. } else if (calculated.resolves_to_length()) {
  7273. if (auto property = any_property_accepts_type(property_ids, ValueType::Length); property.has_value())
  7274. return PropertyAndValue { *property, calculated };
  7275. } else if (calculated.resolves_to_length_percentage()) {
  7276. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Length); property.has_value())
  7277. return PropertyAndValue { *property, calculated };
  7278. } else if (calculated.resolves_to_time()) {
  7279. if (auto property = any_property_accepts_type(property_ids, ValueType::Time); property.has_value())
  7280. return PropertyAndValue { *property, calculated };
  7281. } else if (calculated.resolves_to_time_percentage()) {
  7282. if (auto property = any_property_accepts_type_percentage(property_ids, ValueType::Time); property.has_value())
  7283. return PropertyAndValue { *property, calculated };
  7284. }
  7285. }
  7286. }
  7287. if (auto property = any_property_accepts_type(property_ids, ValueType::Paint); property.has_value()) {
  7288. if (auto value = parse_paint_value(tokens))
  7289. return PropertyAndValue { *property, value.release_nonnull() };
  7290. }
  7291. return OptionalNone {};
  7292. }
  7293. class UnparsedCalculationNode final : public CalculationNode {
  7294. public:
  7295. static NonnullOwnPtr<UnparsedCalculationNode> create(ComponentValue component_value)
  7296. {
  7297. return adopt_own(*new (nothrow) UnparsedCalculationNode(move(component_value)));
  7298. }
  7299. virtual ~UnparsedCalculationNode() = default;
  7300. ComponentValue& component_value() { return m_component_value; }
  7301. virtual String to_string() const override { VERIFY_NOT_REACHED(); }
  7302. virtual Optional<CSSMathValue::ResolvedType> resolved_type() const override { VERIFY_NOT_REACHED(); }
  7303. virtual Optional<CSSNumericType> determine_type(Web::CSS::PropertyID) const override { VERIFY_NOT_REACHED(); }
  7304. virtual bool contains_percentage() const override { VERIFY_NOT_REACHED(); }
  7305. virtual CSSMathValue::CalculationResult resolve(Optional<Length::ResolutionContext const&>, CSSMathValue::PercentageBasis const&) const override { VERIFY_NOT_REACHED(); }
  7306. virtual void for_each_child_node(AK::Function<void(NonnullOwnPtr<CalculationNode>&)> const&) override { }
  7307. virtual void dump(StringBuilder& builder, int indent) const override
  7308. {
  7309. builder.appendff("{: >{}}UNPARSED({})\n", "", indent, m_component_value.to_debug_string());
  7310. }
  7311. virtual bool equals(CalculationNode const&) const override { return false; }
  7312. private:
  7313. UnparsedCalculationNode(ComponentValue component_value)
  7314. : CalculationNode(Type::Unparsed)
  7315. , m_component_value(move(component_value))
  7316. {
  7317. }
  7318. ComponentValue m_component_value;
  7319. };
  7320. // https://html.spec.whatwg.org/multipage/images.html#parsing-a-sizes-attribute
  7321. LengthOrCalculated Parser::Parser::parse_as_sizes_attribute(DOM::Element const& element, HTML::HTMLImageElement const* img)
  7322. {
  7323. // When asked to parse a sizes attribute from an element element, with an img element or null img:
  7324. // AD-HOC: If element has no sizes attribute, this algorithm always logs a parse error and then returns 100vw.
  7325. // The attribute is optional, so avoid spamming the debug log with false positives by just returning early.
  7326. if (!element.has_attribute(HTML::AttributeNames::sizes))
  7327. return Length(100, Length::Type::Vw);
  7328. // 1. Let unparsed sizes list be the result of parsing a comma-separated list of component values
  7329. // from the value of element's sizes attribute (or the empty string, if the attribute is absent).
  7330. // NOTE: The sizes attribute has already been tokenized into m_token_stream by this point.
  7331. auto unparsed_sizes_list = parse_a_comma_separated_list_of_component_values(m_token_stream);
  7332. // 2. Let size be null.
  7333. Optional<LengthOrCalculated> size;
  7334. auto size_is_auto = [&size]() {
  7335. return !size->is_calculated() && size->value().is_auto();
  7336. };
  7337. auto remove_all_consecutive_whitespace_tokens_from_the_end_of = [](auto& tokens) {
  7338. while (!tokens.is_empty() && tokens.last().is_token() && tokens.last().token().is(Token::Type::Whitespace))
  7339. tokens.take_last();
  7340. };
  7341. // 3. For each unparsed size in unparsed sizes list:
  7342. for (auto i = 0u; i < unparsed_sizes_list.size(); i++) {
  7343. auto& unparsed_size = unparsed_sizes_list[i];
  7344. // 1. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7345. // If unparsed size is now empty, that is a parse error; continue.
  7346. remove_all_consecutive_whitespace_tokens_from_the_end_of(unparsed_size);
  7347. if (unparsed_size.is_empty()) {
  7348. log_parse_error();
  7349. dbgln_if(CSS_PARSER_DEBUG, "-> Failed in step 3.1; all whitespace");
  7350. continue;
  7351. }
  7352. // 2. If the last component value in unparsed size is a valid non-negative <source-size-value>,
  7353. // then set size to its value and remove the component value from unparsed size.
  7354. // Any CSS function other than the math functions is invalid.
  7355. // Otherwise, there is a parse error; continue.
  7356. auto last_value_stream = TokenStream<ComponentValue>::of_single_token(unparsed_size.last());
  7357. if (auto source_size_value = parse_source_size_value(last_value_stream); source_size_value.has_value()) {
  7358. size = source_size_value.value();
  7359. unparsed_size.take_last();
  7360. } else {
  7361. log_parse_error();
  7362. dbgln_if(CSS_PARSER_DEBUG, "-> Failed in step 3.2; couldn't parse {} as a <source-size-value>", unparsed_size.last().to_debug_string());
  7363. continue;
  7364. }
  7365. // 3. If size is auto, and img is not null, and img is being rendered, and img allows auto-sizes,
  7366. // then set size to the concrete object size width of img, in CSS pixels.
  7367. // FIXME: "img is being rendered" - we just see if it has a bitmap for now
  7368. if (size_is_auto() && img && img->immutable_bitmap() && img->allows_auto_sizes()) {
  7369. // FIXME: The spec doesn't seem to tell us how to determine the concrete size of an <img>, so use the default sizing algorithm.
  7370. // Should this use some of the methods from FormattingContext?
  7371. auto concrete_size = run_default_sizing_algorithm(
  7372. img->width(), img->height(),
  7373. img->natural_width(), img->natural_height(), img->intrinsic_aspect_ratio(),
  7374. // NOTE: https://html.spec.whatwg.org/multipage/rendering.html#img-contain-size
  7375. CSSPixelSize { 300, 150 });
  7376. size = Length::make_px(concrete_size.width());
  7377. }
  7378. // 4. Remove all consecutive <whitespace-token>s from the end of unparsed size.
  7379. // If unparsed size is now empty:
  7380. remove_all_consecutive_whitespace_tokens_from_the_end_of(unparsed_size);
  7381. if (unparsed_size.is_empty()) {
  7382. // 1. If this was not the last item in unparsed sizes list, that is a parse error.
  7383. if (i != unparsed_sizes_list.size() - 1) {
  7384. log_parse_error();
  7385. dbgln_if(CSS_PARSER_DEBUG, "-> Failed in step 3.4.1; is unparsed size #{}, count {}", i, unparsed_sizes_list.size());
  7386. }
  7387. // 2. If size is not auto, then return size. Otherwise, continue.
  7388. if (!size_is_auto())
  7389. return size.release_value();
  7390. continue;
  7391. }
  7392. // 5. Parse the remaining component values in unparsed size as a <media-condition>.
  7393. // If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue.
  7394. TokenStream<ComponentValue> token_stream { unparsed_size };
  7395. auto media_condition = parse_media_condition(token_stream, MediaCondition::AllowOr::Yes);
  7396. auto const* context_window = m_context.window();
  7397. if (!media_condition || (context_window && media_condition->evaluate(*context_window) == MatchResult::False)) {
  7398. continue;
  7399. }
  7400. // 5. If size is not auto, then return size. Otherwise, continue.
  7401. if (!size_is_auto())
  7402. return size.value();
  7403. }
  7404. // 4. Return 100vw.
  7405. return Length(100, Length::Type::Vw);
  7406. }
  7407. // https://www.w3.org/TR/css-values-4/#parse-a-calculation
  7408. OwnPtr<CalculationNode> Parser::parse_a_calculation(Vector<ComponentValue> const& original_values)
  7409. {
  7410. // 1. Discard any <whitespace-token>s from values.
  7411. // 2. An item in values is an “operator” if it’s a <delim-token> with the value "+", "-", "*", or "/". Otherwise, it’s a “value”.
  7412. struct Operator {
  7413. char delim;
  7414. };
  7415. using Value = Variant<NonnullOwnPtr<CalculationNode>, Operator>;
  7416. Vector<Value> values;
  7417. for (auto& value : original_values) {
  7418. if (value.is(Token::Type::Whitespace))
  7419. continue;
  7420. if (value.is(Token::Type::Delim)) {
  7421. if (first_is_one_of(value.token().delim(), static_cast<u32>('+'), static_cast<u32>('-'), static_cast<u32>('*'), static_cast<u32>('/'))) {
  7422. // NOTE: Sequential operators are invalid syntax.
  7423. if (!values.is_empty() && values.last().has<Operator>())
  7424. return nullptr;
  7425. values.append(Operator { static_cast<char>(value.token().delim()) });
  7426. continue;
  7427. }
  7428. }
  7429. if (value.is(Token::Type::Ident)) {
  7430. auto maybe_constant = CalculationNode::constant_type_from_string(value.token().ident());
  7431. if (maybe_constant.has_value()) {
  7432. values.append({ ConstantCalculationNode::create(maybe_constant.value()) });
  7433. continue;
  7434. }
  7435. }
  7436. if (value.is(Token::Type::Number)) {
  7437. values.append({ NumericCalculationNode::create(value.token().number()) });
  7438. continue;
  7439. }
  7440. if (auto dimension = parse_dimension(value); dimension.has_value()) {
  7441. if (dimension->is_angle())
  7442. values.append({ NumericCalculationNode::create(dimension->angle()) });
  7443. else if (dimension->is_frequency())
  7444. values.append({ NumericCalculationNode::create(dimension->frequency()) });
  7445. else if (dimension->is_length())
  7446. values.append({ NumericCalculationNode::create(dimension->length()) });
  7447. else if (dimension->is_percentage())
  7448. values.append({ NumericCalculationNode::create(dimension->percentage()) });
  7449. else if (dimension->is_resolution())
  7450. values.append({ NumericCalculationNode::create(dimension->resolution()) });
  7451. else if (dimension->is_time())
  7452. values.append({ NumericCalculationNode::create(dimension->time()) });
  7453. else if (dimension->is_flex()) {
  7454. // https://www.w3.org/TR/css3-grid-layout/#fr-unit
  7455. // NOTE: <flex> values are not <length>s (nor are they compatible with <length>s, like some <percentage> values),
  7456. // so they cannot be represented in or combined with other unit types in calc() expressions.
  7457. return nullptr;
  7458. } else {
  7459. VERIFY_NOT_REACHED();
  7460. }
  7461. continue;
  7462. }
  7463. values.append({ UnparsedCalculationNode::create(value) });
  7464. }
  7465. // If we have no values, the syntax is invalid.
  7466. if (values.is_empty())
  7467. return nullptr;
  7468. // NOTE: If the first or last value is an operator, the syntax is invalid.
  7469. if (values.first().has<Operator>() || values.last().has<Operator>())
  7470. return nullptr;
  7471. // 3. Collect children into Product and Invert nodes.
  7472. // For every consecutive run of value items in values separated by "*" or "/" operators:
  7473. while (true) {
  7474. Optional<size_t> first_product_operator = values.find_first_index_if([](auto const& item) {
  7475. return item.template has<Operator>()
  7476. && first_is_one_of(item.template get<Operator>().delim, '*', '/');
  7477. });
  7478. if (!first_product_operator.has_value())
  7479. break;
  7480. auto start_of_run = first_product_operator.value() - 1;
  7481. auto end_of_run = first_product_operator.value() + 1;
  7482. for (auto i = start_of_run + 1; i < values.size(); i += 2) {
  7483. auto& item = values[i];
  7484. if (!item.has<Operator>()) {
  7485. end_of_run = i - 1;
  7486. break;
  7487. }
  7488. auto delim = item.get<Operator>().delim;
  7489. if (!first_is_one_of(delim, '*', '/')) {
  7490. end_of_run = i - 1;
  7491. break;
  7492. }
  7493. }
  7494. // 1. For each "/" operator in the run, replace its right-hand value item rhs with an Invert node containing rhs as its child.
  7495. Vector<NonnullOwnPtr<CalculationNode>> run_values;
  7496. run_values.append(move(values[start_of_run].get<NonnullOwnPtr<CalculationNode>>()));
  7497. for (auto i = start_of_run + 1; i <= end_of_run; i += 2) {
  7498. auto& operator_ = values[i].get<Operator>().delim;
  7499. auto& rhs = values[i + 1];
  7500. if (operator_ == '/') {
  7501. run_values.append(InvertCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>())));
  7502. continue;
  7503. }
  7504. VERIFY(operator_ == '*');
  7505. run_values.append(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  7506. }
  7507. // 2. Replace the entire run with a Product node containing the value items of the run as its children.
  7508. auto product_node = ProductCalculationNode::create(move(run_values));
  7509. values.remove(start_of_run, end_of_run - start_of_run + 1);
  7510. values.insert(start_of_run, { move(product_node) });
  7511. }
  7512. // 4. Collect children into Sum and Negate nodes.
  7513. Optional<NonnullOwnPtr<CalculationNode>> single_value;
  7514. {
  7515. // 1. For each "-" operator item in values, replace its right-hand value item rhs with a Negate node containing rhs as its child.
  7516. for (auto i = 0u; i < values.size(); ++i) {
  7517. auto& maybe_minus_operator = values[i];
  7518. if (!maybe_minus_operator.has<Operator>() || maybe_minus_operator.get<Operator>().delim != '-')
  7519. continue;
  7520. auto rhs_index = ++i;
  7521. auto& rhs = values[rhs_index];
  7522. NonnullOwnPtr<CalculationNode> negate_node = NegateCalculationNode::create(move(rhs.get<NonnullOwnPtr<CalculationNode>>()));
  7523. values.remove(rhs_index);
  7524. values.insert(rhs_index, move(negate_node));
  7525. }
  7526. // 2. If values has only one item, and it is a Product node or a parenthesized simple block, replace values with that item.
  7527. if (values.size() == 1) {
  7528. values.first().visit(
  7529. [&](ComponentValue& component_value) {
  7530. if (component_value.is_block() && component_value.block().is_paren())
  7531. single_value = UnparsedCalculationNode::create(component_value);
  7532. },
  7533. [&](NonnullOwnPtr<CalculationNode>& node) {
  7534. if (node->type() == CalculationNode::Type::Product)
  7535. single_value = move(node);
  7536. },
  7537. [](auto&) {});
  7538. }
  7539. // Otherwise, replace values with a Sum node containing the value items of values as its children.
  7540. if (!single_value.has_value()) {
  7541. values.remove_all_matching([](Value& value) { return value.has<Operator>(); });
  7542. Vector<NonnullOwnPtr<CalculationNode>> value_items;
  7543. value_items.ensure_capacity(values.size());
  7544. for (auto& value : values) {
  7545. if (value.has<Operator>())
  7546. continue;
  7547. value_items.unchecked_append(move(value.get<NonnullOwnPtr<CalculationNode>>()));
  7548. }
  7549. single_value = SumCalculationNode::create(move(value_items));
  7550. }
  7551. }
  7552. // 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.
  7553. // For every leaf node leaf in values:
  7554. bool parsing_failed_for_child_node = false;
  7555. single_value.value()->for_each_child_node([&](NonnullOwnPtr<CalculationNode>& node) {
  7556. if (node->type() != CalculationNode::Type::Unparsed)
  7557. return;
  7558. auto& unparsed_node = static_cast<UnparsedCalculationNode&>(*node);
  7559. auto& component_value = unparsed_node.component_value();
  7560. // 1. If leaf is a parenthesized simple block, replace leaf with the result of parsing a calculation from leaf’s contents.
  7561. if (component_value.is_block() && component_value.block().is_paren()) {
  7562. auto leaf_calculation = parse_a_calculation(component_value.block().value);
  7563. if (!leaf_calculation) {
  7564. parsing_failed_for_child_node = true;
  7565. return;
  7566. }
  7567. node = leaf_calculation.release_nonnull();
  7568. return;
  7569. }
  7570. // 2. If leaf is a math function, replace leaf with the internal representation of that math function.
  7571. // NOTE: All function tokens at this point should be math functions.
  7572. else if (component_value.is_function()) {
  7573. auto& function = component_value.function();
  7574. auto leaf_calculation = parse_a_calc_function_node(function);
  7575. if (!leaf_calculation) {
  7576. parsing_failed_for_child_node = true;
  7577. return;
  7578. }
  7579. node = leaf_calculation.release_nonnull();
  7580. return;
  7581. }
  7582. // NOTE: If we get here, then we have an UnparsedCalculationNode that didn't get replaced with something else.
  7583. // So, the calc() is invalid.
  7584. 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());
  7585. parsing_failed_for_child_node = true;
  7586. return;
  7587. });
  7588. if (parsing_failed_for_child_node)
  7589. return nullptr;
  7590. // FIXME: 6. Return the result of simplifying a calculation tree from values.
  7591. return single_value.release_value();
  7592. }
  7593. bool Parser::has_ignored_vendor_prefix(StringView string)
  7594. {
  7595. if (!string.starts_with('-'))
  7596. return false;
  7597. if (string.starts_with("--"sv))
  7598. return false;
  7599. if (string.starts_with("-libweb-"sv))
  7600. return false;
  7601. return true;
  7602. }
  7603. 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)
  7604. {
  7605. // Unresolved always contains a var() or attr(), unless it is a custom property's value, in which case we shouldn't be trying
  7606. // to produce a different CSSStyleValue from it.
  7607. VERIFY(unresolved.contains_var_or_attr());
  7608. // If the value is invalid, we fall back to `unset`: https://www.w3.org/TR/css-variables-1/#invalid-at-computed-value-time
  7609. auto parser = Parser::create(context, ""sv);
  7610. return parser.resolve_unresolved_style_value(element, pseudo_element, property_id, unresolved);
  7611. }
  7612. class PropertyDependencyNode : public RefCounted<PropertyDependencyNode> {
  7613. public:
  7614. static NonnullRefPtr<PropertyDependencyNode> create(FlyString name)
  7615. {
  7616. return adopt_ref(*new PropertyDependencyNode(move(name)));
  7617. }
  7618. void add_child(NonnullRefPtr<PropertyDependencyNode> new_child)
  7619. {
  7620. for (auto const& child : m_children) {
  7621. if (child->m_name == new_child->m_name)
  7622. return;
  7623. }
  7624. // We detect self-reference already.
  7625. VERIFY(new_child->m_name != m_name);
  7626. m_children.append(move(new_child));
  7627. }
  7628. bool has_cycles()
  7629. {
  7630. if (m_marked)
  7631. return true;
  7632. TemporaryChange change { m_marked, true };
  7633. for (auto& child : m_children) {
  7634. if (child->has_cycles())
  7635. return true;
  7636. }
  7637. return false;
  7638. }
  7639. private:
  7640. explicit PropertyDependencyNode(FlyString name)
  7641. : m_name(move(name))
  7642. {
  7643. }
  7644. FlyString m_name;
  7645. Vector<NonnullRefPtr<PropertyDependencyNode>> m_children;
  7646. bool m_marked { false };
  7647. };
  7648. NonnullRefPtr<CSSStyleValue> Parser::resolve_unresolved_style_value(DOM::Element& element, Optional<Selector::PseudoElement::Type> pseudo_element, PropertyID property_id, UnresolvedStyleValue const& unresolved)
  7649. {
  7650. TokenStream unresolved_values_without_variables_expanded { unresolved.values() };
  7651. Vector<ComponentValue> values_with_variables_expanded;
  7652. HashMap<FlyString, NonnullRefPtr<PropertyDependencyNode>> dependencies;
  7653. if (!expand_variables(element, pseudo_element, string_from_property_id(property_id), dependencies, unresolved_values_without_variables_expanded, values_with_variables_expanded))
  7654. return CSSKeywordValue::create(Keyword::Unset);
  7655. TokenStream unresolved_values_with_variables_expanded { values_with_variables_expanded };
  7656. Vector<ComponentValue> expanded_values;
  7657. if (!expand_unresolved_values(element, string_from_property_id(property_id), unresolved_values_with_variables_expanded, expanded_values))
  7658. return CSSKeywordValue::create(Keyword::Unset);
  7659. auto expanded_value_tokens = TokenStream { expanded_values };
  7660. if (auto parsed_value = parse_css_value(property_id, expanded_value_tokens); !parsed_value.is_error())
  7661. return parsed_value.release_value();
  7662. return CSSKeywordValue::create(Keyword::Unset);
  7663. }
  7664. static RefPtr<CSSStyleValue const> get_custom_property(DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, FlyString const& custom_property_name)
  7665. {
  7666. if (pseudo_element.has_value()) {
  7667. if (auto it = element.custom_properties(pseudo_element).find(custom_property_name); it != element.custom_properties(pseudo_element).end())
  7668. return it->value.value;
  7669. }
  7670. for (auto const* current_element = &element; current_element; current_element = current_element->parent_or_shadow_host_element()) {
  7671. if (auto it = current_element->custom_properties({}).find(custom_property_name); it != current_element->custom_properties({}).end())
  7672. return it->value.value;
  7673. }
  7674. return nullptr;
  7675. }
  7676. 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)
  7677. {
  7678. // Arbitrary large value chosen to avoid the billion-laughs attack.
  7679. // https://www.w3.org/TR/css-variables-1/#long-variables
  7680. size_t const MAX_VALUE_COUNT = 16384;
  7681. if (source.remaining_token_count() + dest.size() > MAX_VALUE_COUNT) {
  7682. dbgln("Stopped expanding CSS variables: maximum length reached.");
  7683. return false;
  7684. }
  7685. auto get_dependency_node = [&](FlyString const& name) -> NonnullRefPtr<PropertyDependencyNode> {
  7686. if (auto existing = dependencies.get(name); existing.has_value())
  7687. return *existing.value();
  7688. auto new_node = PropertyDependencyNode::create(name);
  7689. dependencies.set(name, new_node);
  7690. return new_node;
  7691. };
  7692. while (source.has_next_token()) {
  7693. auto const& value = source.consume_a_token();
  7694. if (value.is_block()) {
  7695. auto const& source_block = value.block();
  7696. Vector<ComponentValue> block_values;
  7697. TokenStream source_block_contents { source_block.value };
  7698. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_block_contents, block_values))
  7699. return false;
  7700. dest.empend(SimpleBlock { source_block.token, move(block_values) });
  7701. continue;
  7702. }
  7703. if (!value.is_function()) {
  7704. dest.empend(value);
  7705. continue;
  7706. }
  7707. if (!value.function().name.equals_ignoring_ascii_case("var"sv)) {
  7708. auto const& source_function = value.function();
  7709. Vector<ComponentValue> function_values;
  7710. TokenStream source_function_contents { source_function.value };
  7711. if (!expand_variables(element, pseudo_element, property_name, dependencies, source_function_contents, function_values))
  7712. return false;
  7713. dest.empend(Function { source_function.name, move(function_values) });
  7714. continue;
  7715. }
  7716. TokenStream var_contents { value.function().value };
  7717. var_contents.discard_whitespace();
  7718. if (!var_contents.has_next_token())
  7719. return false;
  7720. auto const& custom_property_name_token = var_contents.consume_a_token();
  7721. if (!custom_property_name_token.is(Token::Type::Ident))
  7722. return false;
  7723. auto custom_property_name = custom_property_name_token.token().ident();
  7724. if (!custom_property_name.bytes_as_string_view().starts_with("--"sv))
  7725. return false;
  7726. // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles
  7727. // We do not do this by the spec, since we are not keeping a graph of var dependencies around,
  7728. // but rebuilding it every time.
  7729. if (custom_property_name == property_name)
  7730. return false;
  7731. auto parent = get_dependency_node(property_name);
  7732. auto child = get_dependency_node(custom_property_name);
  7733. parent->add_child(child);
  7734. if (parent->has_cycles())
  7735. return false;
  7736. if (auto custom_property_value = get_custom_property(element, pseudo_element, custom_property_name)) {
  7737. VERIFY(custom_property_value->is_unresolved());
  7738. TokenStream custom_property_tokens { custom_property_value->as_unresolved().values() };
  7739. if (!expand_variables(element, pseudo_element, custom_property_name, dependencies, custom_property_tokens, dest))
  7740. return false;
  7741. continue;
  7742. }
  7743. // Use the provided fallback value, if any.
  7744. var_contents.discard_whitespace();
  7745. if (var_contents.has_next_token()) {
  7746. auto const& comma_token = var_contents.consume_a_token();
  7747. if (!comma_token.is(Token::Type::Comma))
  7748. return false;
  7749. var_contents.discard_whitespace();
  7750. if (!expand_variables(element, pseudo_element, property_name, dependencies, var_contents, dest))
  7751. return false;
  7752. }
  7753. }
  7754. return true;
  7755. }
  7756. bool Parser::expand_unresolved_values(DOM::Element& element, FlyString const& property_name, TokenStream<ComponentValue>& source, Vector<ComponentValue>& dest)
  7757. {
  7758. auto property = property_id_from_string(property_name);
  7759. while (source.has_next_token()) {
  7760. auto const& value = source.consume_a_token();
  7761. if (value.is_function()) {
  7762. if (value.function().name.equals_ignoring_ascii_case("attr"sv)) {
  7763. if (!substitute_attr_function(element, property_name, value.function(), dest))
  7764. return false;
  7765. continue;
  7766. }
  7767. if (property.has_value()) {
  7768. if (auto maybe_calc_value = parse_calculated_value(value); maybe_calc_value && maybe_calc_value->is_math()) {
  7769. // FIXME: Run the actual simplification algorithm
  7770. auto& calc_value = maybe_calc_value->as_math();
  7771. if (property_accepts_type(*property, ValueType::Angle) && calc_value.resolves_to_angle()) {
  7772. auto resolved_value = calc_value.resolve_angle();
  7773. dest.empend(Token::create_dimension(resolved_value->to_degrees(), "deg"_fly_string));
  7774. continue;
  7775. }
  7776. if (property_accepts_type(*property, ValueType::Frequency) && calc_value.resolves_to_frequency()) {
  7777. auto resolved_value = calc_value.resolve_frequency();
  7778. dest.empend(Token::create_dimension(resolved_value->to_hertz(), "hz"_fly_string));
  7779. continue;
  7780. }
  7781. if (property_accepts_type(*property, ValueType::Length) && calc_value.resolves_to_length()) {
  7782. // FIXME: In order to resolve lengths, we need to know the font metrics in case a font-relative unit
  7783. // is used. So... we can't do that until style is computed?
  7784. // This might be easier once we have calc-simplification implemented.
  7785. }
  7786. if (property_accepts_type(*property, ValueType::Percentage) && calc_value.resolves_to_percentage()) {
  7787. auto resolved_value = calc_value.resolve_percentage();
  7788. dest.empend(Token::create_percentage(resolved_value.value().value()));
  7789. continue;
  7790. }
  7791. if (property_accepts_type(*property, ValueType::Time) && calc_value.resolves_to_time()) {
  7792. auto resolved_value = calc_value.resolve_time();
  7793. dest.empend(Token::create_dimension(resolved_value->to_seconds(), "s"_fly_string));
  7794. continue;
  7795. }
  7796. if (property_accepts_type(*property, ValueType::Number) && calc_value.resolves_to_number()) {
  7797. auto resolved_value = calc_value.resolve_number();
  7798. dest.empend(Token::create_number(resolved_value.value(), Number::Type::Number));
  7799. continue;
  7800. }
  7801. if (property_accepts_type(*property, ValueType::Integer) && calc_value.resolves_to_number()) {
  7802. auto resolved_value = calc_value.resolve_integer();
  7803. dest.empend(Token::create_number(resolved_value.value(), Number::Type::Integer));
  7804. continue;
  7805. }
  7806. }
  7807. }
  7808. auto const& source_function = value.function();
  7809. Vector<ComponentValue> function_values;
  7810. TokenStream source_function_contents { source_function.value };
  7811. if (!expand_unresolved_values(element, property_name, source_function_contents, function_values))
  7812. return false;
  7813. dest.empend(Function { source_function.name, move(function_values) });
  7814. continue;
  7815. }
  7816. if (value.is_block()) {
  7817. auto const& source_block = value.block();
  7818. TokenStream source_block_values { source_block.value };
  7819. Vector<ComponentValue> block_values;
  7820. if (!expand_unresolved_values(element, property_name, source_block_values, block_values))
  7821. return false;
  7822. dest.empend(SimpleBlock { source_block.token, move(block_values) });
  7823. continue;
  7824. }
  7825. dest.empend(value.token());
  7826. }
  7827. return true;
  7828. }
  7829. // https://drafts.csswg.org/css-values-5/#attr-substitution
  7830. bool Parser::substitute_attr_function(DOM::Element& element, FlyString const& property_name, Function const& attr_function, Vector<ComponentValue>& dest)
  7831. {
  7832. // First, parse the arguments to attr():
  7833. // attr() = attr( <q-name> <attr-type>? , <declaration-value>?)
  7834. // <attr-type> = string | url | ident | color | number | percentage | length | angle | time | frequency | flex | <dimension-unit>
  7835. TokenStream attr_contents { attr_function.value };
  7836. attr_contents.discard_whitespace();
  7837. if (!attr_contents.has_next_token())
  7838. return false;
  7839. // - Attribute name
  7840. // FIXME: Support optional attribute namespace
  7841. if (!attr_contents.next_token().is(Token::Type::Ident))
  7842. return false;
  7843. auto attribute_name = attr_contents.consume_a_token().token().ident();
  7844. attr_contents.discard_whitespace();
  7845. // - Attribute type (optional)
  7846. auto attribute_type = "string"_fly_string;
  7847. if (attr_contents.next_token().is(Token::Type::Ident)) {
  7848. attribute_type = attr_contents.consume_a_token().token().ident();
  7849. attr_contents.discard_whitespace();
  7850. }
  7851. // - Comma, then fallback values (optional)
  7852. bool has_fallback_values = false;
  7853. if (attr_contents.has_next_token()) {
  7854. if (!attr_contents.next_token().is(Token::Type::Comma))
  7855. return false;
  7856. (void)attr_contents.consume_a_token(); // Comma
  7857. has_fallback_values = true;
  7858. }
  7859. // Then, run the substitution algorithm:
  7860. // 1. If the attr() function has a substitution value, replace the attr() function by the substitution value.
  7861. // https://drafts.csswg.org/css-values-5/#attr-types
  7862. if (element.has_attribute(attribute_name)) {
  7863. auto attribute_value = element.get_attribute_value(attribute_name);
  7864. if (attribute_type.equals_ignoring_ascii_case("angle"_fly_string)) {
  7865. // Parse a component value from the attribute’s value.
  7866. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7867. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7868. // Otherwise, there is no substitution value.
  7869. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7870. if (Angle::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7871. dest.append(component_value.release_value());
  7872. return true;
  7873. }
  7874. }
  7875. } else if (attribute_type.equals_ignoring_ascii_case("color"_fly_string)) {
  7876. // Parse a component value from the attribute’s value.
  7877. // If the result is a <hex-color> or a named color ident, the substitution value is that result as a <color>.
  7878. // Otherwise there is no substitution value.
  7879. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7880. if (component_value.has_value()) {
  7881. if ((component_value->is(Token::Type::Hash)
  7882. && Color::from_string(MUST(String::formatted("#{}", component_value->token().hash_value()))).has_value())
  7883. || (component_value->is(Token::Type::Ident)
  7884. && Color::from_string(component_value->token().ident()).has_value())) {
  7885. dest.append(component_value.release_value());
  7886. return true;
  7887. }
  7888. }
  7889. } else if (attribute_type.equals_ignoring_ascii_case("flex"_fly_string)) {
  7890. // Parse a component value from the attribute’s value.
  7891. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7892. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7893. // Otherwise, there is no substitution value.
  7894. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7895. if (Flex::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7896. dest.append(component_value.release_value());
  7897. return true;
  7898. }
  7899. }
  7900. } else if (attribute_type.equals_ignoring_ascii_case("frequency"_fly_string)) {
  7901. // Parse a component value from the attribute’s value.
  7902. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7903. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7904. // Otherwise, there is no substitution value.
  7905. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7906. if (Frequency::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7907. dest.append(component_value.release_value());
  7908. return true;
  7909. }
  7910. }
  7911. } else if (attribute_type.equals_ignoring_ascii_case("ident"_fly_string)) {
  7912. // The substitution value is a CSS <custom-ident>, whose value is the literal value of the attribute,
  7913. // with leading and trailing ASCII whitespace stripped. (No CSS parsing of the value is performed.)
  7914. // If the attribute value, after trimming, is the empty string, there is instead no substitution value.
  7915. // If the <custom-ident>’s value is a CSS-wide keyword or `default`, there is instead no substitution value.
  7916. auto substitution_value = MUST(attribute_value.trim(Infra::ASCII_WHITESPACE));
  7917. if (!substitution_value.is_empty()
  7918. && !substitution_value.equals_ignoring_ascii_case("default"sv)
  7919. && !is_css_wide_keyword(substitution_value)) {
  7920. dest.empend(Token::create_ident(substitution_value));
  7921. return true;
  7922. }
  7923. } else if (attribute_type.equals_ignoring_ascii_case("length"_fly_string)) {
  7924. // Parse a component value from the attribute’s value.
  7925. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7926. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7927. // Otherwise, there is no substitution value.
  7928. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7929. if (Length::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7930. dest.append(component_value.release_value());
  7931. return true;
  7932. }
  7933. }
  7934. } else if (attribute_type.equals_ignoring_ascii_case("number"_fly_string)) {
  7935. // Parse a component value from the attribute’s value.
  7936. // If the result is a <number-token>, the result is the substitution value.
  7937. // Otherwise, there is no substitution value.
  7938. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7939. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  7940. dest.append(component_value.release_value());
  7941. return true;
  7942. }
  7943. } else if (attribute_type.equals_ignoring_ascii_case("percentage"_fly_string)) {
  7944. // Parse a component value from the attribute’s value.
  7945. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7946. // If the result is a <percentage-token>, the result is the substitution value.
  7947. // Otherwise, there is no substitution value.
  7948. if (component_value.has_value() && component_value->is(Token::Type::Percentage)) {
  7949. dest.append(component_value.release_value());
  7950. return true;
  7951. }
  7952. } else if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  7953. // The substitution value is a CSS string, whose value is the literal value of the attribute.
  7954. // (No CSS parsing or "cleanup" of the value is performed.)
  7955. // No value triggers fallback.
  7956. dest.empend(Token::create_string(attribute_value));
  7957. return true;
  7958. } else if (attribute_type.equals_ignoring_ascii_case("time"_fly_string)) {
  7959. // Parse a component value from the attribute’s value.
  7960. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7961. // If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.
  7962. // Otherwise, there is no substitution value.
  7963. if (component_value.has_value() && component_value->is(Token::Type::Dimension)) {
  7964. if (Time::unit_from_name(component_value->token().dimension_unit()).has_value()) {
  7965. dest.append(component_value.release_value());
  7966. return true;
  7967. }
  7968. }
  7969. } else if (attribute_type.equals_ignoring_ascii_case("url"_fly_string)) {
  7970. // The substitution value is a CSS <url> value, whose url is the literal value of the attribute.
  7971. // (No CSS parsing or "cleanup" of the value is performed.)
  7972. // No value triggers fallback.
  7973. dest.empend(Token::create_url(attribute_value));
  7974. return true;
  7975. } else {
  7976. // Dimension units
  7977. // Parse a component value from the attribute’s value.
  7978. // If the result is a <number-token>, the substitution value is a dimension with the result’s value, and the given unit.
  7979. // Otherwise, there is no substitution value.
  7980. auto component_value = Parser::Parser::create(m_context, attribute_value).parse_as_component_value();
  7981. if (component_value.has_value() && component_value->is(Token::Type::Number)) {
  7982. if (attribute_value == "%"sv) {
  7983. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7984. return true;
  7985. } else if (auto angle_unit = Angle::unit_from_name(attribute_type); angle_unit.has_value()) {
  7986. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7987. return true;
  7988. } else if (auto flex_unit = Flex::unit_from_name(attribute_type); flex_unit.has_value()) {
  7989. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7990. return true;
  7991. } else if (auto frequency_unit = Frequency::unit_from_name(attribute_type); frequency_unit.has_value()) {
  7992. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7993. return true;
  7994. } else if (auto length_unit = Length::unit_from_name(attribute_type); length_unit.has_value()) {
  7995. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7996. return true;
  7997. } else if (auto time_unit = Time::unit_from_name(attribute_type); time_unit.has_value()) {
  7998. dest.empend(Token::create_dimension(component_value->token().number_value(), attribute_type));
  7999. return true;
  8000. } else {
  8001. // Not a dimension unit.
  8002. return false;
  8003. }
  8004. }
  8005. }
  8006. }
  8007. // 2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value.
  8008. // If there are any var() or attr() references in the fallback, substitute them as well.
  8009. if (has_fallback_values)
  8010. return expand_unresolved_values(element, property_name, attr_contents, dest);
  8011. if (attribute_type.equals_ignoring_ascii_case("string"_fly_string)) {
  8012. // If the <attr-type> argument is string, defaults to the empty string if omitted
  8013. dest.empend(Token::create_string({}));
  8014. return true;
  8015. }
  8016. // 3. Otherwise, the property containing the attr() function is invalid at computed-value time.
  8017. return false;
  8018. }
  8019. // https://drafts.csswg.org/css-fonts/#typedef-opentype-tag
  8020. RefPtr<StringStyleValue> Parser::parse_opentype_tag_value(TokenStream<ComponentValue>& tokens)
  8021. {
  8022. // <opentype-tag> = <string>
  8023. // The <opentype-tag> is a case-sensitive OpenType feature tag.
  8024. // As specified in the OpenType specification [OPENTYPE], feature tags contain four ASCII characters.
  8025. // Tag strings longer or shorter than four characters, or containing characters outside the U+20–7E codepoint range are invalid.
  8026. auto transaction = tokens.begin_transaction();
  8027. auto string_value = parse_string_value(tokens);
  8028. if (string_value == nullptr)
  8029. return nullptr;
  8030. auto string = string_value->string_value().bytes_as_string_view();
  8031. if (string.length() != 4)
  8032. return nullptr;
  8033. for (char c : string) {
  8034. if (c < 0x20 || c > 0x7E)
  8035. return nullptr;
  8036. }
  8037. transaction.commit();
  8038. return string_value;
  8039. }
  8040. }