Parser.cpp 328 KB

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