Parser.cpp 302 KB

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