Parser.cpp 230 KB

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