Parser.cpp 374 KB

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