Parser.cpp 260 KB

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