Parser.cpp 300 KB

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