Parser.cpp 261 KB

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