Parser.cpp 376 KB

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