Parser.cpp 301 KB

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