Parser.cpp 316 KB

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