Parser.cpp 306 KB

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