Parser.cpp 271 KB

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