Parser.cpp 362 KB

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