Parser.cpp 390 KB

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