Parser.cpp 355 KB

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