Parser.cpp 296 KB

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