Parser.cpp 270 KB

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