Parser.cpp 296 KB

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