Parser.cpp 300 KB

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