Parser.cpp 306 KB

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