Parser.cpp 378 KB

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