Parser.cpp 302 KB

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