Parser.cpp 231 KB

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