Parser.cpp 300 KB

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