Parser.cpp 376 KB

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