Parser.cpp 297 KB

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