Parser.cpp 302 KB

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