Parser.cpp 341 KB

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