Parser.cpp 302 KB

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