Parser.cpp 201 KB

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