Parser.cpp 302 KB

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