Parser.cpp 369 KB

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