Parser.cpp 299 KB

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