Parser.cpp 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, the SerenityOS developers.
  4. * Copyright (c) 2021, 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/CSSImportRule.h>
  14. #include <LibWeb/CSS/CSSMediaRule.h>
  15. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  16. #include <LibWeb/CSS/CSSStyleRule.h>
  17. #include <LibWeb/CSS/CSSStyleSheet.h>
  18. #include <LibWeb/CSS/CSSSupportsRule.h>
  19. #include <LibWeb/CSS/Parser/DeclarationOrAtRule.h>
  20. #include <LibWeb/CSS/Parser/Parser.h>
  21. #include <LibWeb/CSS/Parser/StyleBlockRule.h>
  22. #include <LibWeb/CSS/Parser/StyleComponentValueRule.h>
  23. #include <LibWeb/CSS/Parser/StyleFunctionRule.h>
  24. #include <LibWeb/CSS/Parser/StyleRule.h>
  25. #include <LibWeb/CSS/Selector.h>
  26. #include <LibWeb/DOM/Document.h>
  27. #include <LibWeb/Dump.h>
  28. static void log_parse_error(const SourceLocation& location = SourceLocation::current())
  29. {
  30. dbgln_if(CSS_PARSER_DEBUG, "Parse error (CSS) {}", location);
  31. }
  32. namespace Web::CSS {
  33. ParsingContext::ParsingContext(DOM::Document& document)
  34. : m_document(&document)
  35. {
  36. }
  37. ParsingContext::ParsingContext(DOM::ParentNode& parent_node)
  38. : m_document(&parent_node.document())
  39. {
  40. }
  41. bool ParsingContext::in_quirks_mode() const
  42. {
  43. return m_document ? m_document->in_quirks_mode() : false;
  44. }
  45. AK::URL ParsingContext::complete_url(String const& addr) const
  46. {
  47. return m_document ? m_document->url().complete_url(addr) : AK::URL::create_with_url_or_path(addr);
  48. }
  49. template<typename T>
  50. TokenStream<T>::TokenStream(Vector<T> const& tokens)
  51. : m_tokens(tokens)
  52. , m_eof(make_eof())
  53. {
  54. }
  55. template<typename T>
  56. TokenStream<T>::~TokenStream()
  57. {
  58. }
  59. template<typename T>
  60. bool TokenStream<T>::has_next_token()
  61. {
  62. return (size_t)(m_iterator_offset + 1) < m_tokens.size();
  63. }
  64. template<typename T>
  65. T const& TokenStream<T>::peek_token(int offset)
  66. {
  67. if (!has_next_token())
  68. return m_eof;
  69. return m_tokens.at(m_iterator_offset + offset + 1);
  70. }
  71. template<typename T>
  72. T const& TokenStream<T>::next_token()
  73. {
  74. if (!has_next_token())
  75. return m_eof;
  76. ++m_iterator_offset;
  77. return m_tokens.at(m_iterator_offset);
  78. }
  79. template<typename T>
  80. T const& TokenStream<T>::current_token()
  81. {
  82. if ((size_t)m_iterator_offset >= m_tokens.size())
  83. return m_eof;
  84. return m_tokens.at(m_iterator_offset);
  85. }
  86. template<typename T>
  87. void TokenStream<T>::reconsume_current_input_token()
  88. {
  89. if (m_iterator_offset >= 0)
  90. --m_iterator_offset;
  91. }
  92. template<typename T>
  93. void TokenStream<T>::rewind_to_position(int position)
  94. {
  95. VERIFY(position <= m_iterator_offset);
  96. m_iterator_offset = position;
  97. }
  98. template<typename T>
  99. void TokenStream<T>::skip_whitespace()
  100. {
  101. while (peek_token().is(Token::Type::Whitespace))
  102. next_token();
  103. }
  104. template<>
  105. Token TokenStream<Token>::make_eof()
  106. {
  107. return Tokenizer::create_eof_token();
  108. }
  109. template<>
  110. StyleComponentValueRule TokenStream<StyleComponentValueRule>::make_eof()
  111. {
  112. return StyleComponentValueRule(Tokenizer::create_eof_token());
  113. }
  114. template<typename T>
  115. void TokenStream<T>::dump_all_tokens()
  116. {
  117. dbgln("Dumping all tokens:");
  118. for (size_t i = 0; i < m_tokens.size(); ++i) {
  119. auto& token = m_tokens[i];
  120. if ((i - 1) == (size_t)m_iterator_offset)
  121. dbgln("-> {}", token.to_debug_string());
  122. else
  123. dbgln(" {}", token.to_debug_string());
  124. }
  125. }
  126. Parser::Parser(ParsingContext const& context, StringView const& input, String const& encoding)
  127. : m_context(context)
  128. , m_tokenizer(input, encoding)
  129. , m_tokens(m_tokenizer.parse())
  130. , m_token_stream(TokenStream(m_tokens))
  131. {
  132. }
  133. Parser::~Parser()
  134. {
  135. }
  136. NonnullRefPtr<CSSStyleSheet> Parser::parse_as_stylesheet()
  137. {
  138. return parse_a_stylesheet(m_token_stream);
  139. }
  140. template<typename T>
  141. NonnullRefPtr<CSSStyleSheet> Parser::parse_a_stylesheet(TokenStream<T>& tokens)
  142. {
  143. auto parser_rules = consume_a_list_of_rules(tokens, true);
  144. NonnullRefPtrVector<CSSRule> rules;
  145. for (auto& raw_rule : parser_rules) {
  146. auto rule = convert_to_rule(raw_rule);
  147. if (rule)
  148. rules.append(*rule);
  149. }
  150. auto stylesheet = CSSStyleSheet::create(rules);
  151. if constexpr (CSS_PARSER_DEBUG) {
  152. dump_sheet(stylesheet);
  153. }
  154. return stylesheet;
  155. }
  156. Optional<SelectorList> Parser::parse_as_selector()
  157. {
  158. auto selector_list = parse_a_selector(m_token_stream);
  159. if (!selector_list.is_error())
  160. return selector_list.release_value();
  161. return {};
  162. }
  163. template<typename T>
  164. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector(TokenStream<T>& tokens)
  165. {
  166. return parse_a_selector_list(tokens);
  167. }
  168. Optional<SelectorList> Parser::parse_as_relative_selector()
  169. {
  170. auto selector_list = parse_a_relative_selector(m_token_stream);
  171. if (!selector_list.is_error())
  172. return selector_list.release_value();
  173. return {};
  174. }
  175. template<typename T>
  176. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector(TokenStream<T>& tokens)
  177. {
  178. return parse_a_relative_selector_list(tokens);
  179. }
  180. template<typename T>
  181. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_selector_list(TokenStream<T>& tokens)
  182. {
  183. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  184. NonnullRefPtrVector<Selector> selectors;
  185. for (auto& selector_parts : comma_separated_lists) {
  186. auto stream = TokenStream(selector_parts);
  187. auto selector = parse_complex_selector(stream, false);
  188. if (selector.is_error())
  189. return selector.error();
  190. selectors.append(selector.release_value());
  191. }
  192. if (selectors.is_empty())
  193. return ParsingResult::SyntaxError;
  194. return selectors;
  195. }
  196. template<typename T>
  197. Result<SelectorList, Parser::ParsingResult> Parser::parse_a_relative_selector_list(TokenStream<T>& tokens)
  198. {
  199. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  200. NonnullRefPtrVector<Selector> selectors;
  201. for (auto& selector_parts : comma_separated_lists) {
  202. auto stream = TokenStream(selector_parts);
  203. auto selector = parse_complex_selector(stream, true);
  204. if (selector.is_error())
  205. return selector.error();
  206. selectors.append(selector.release_value());
  207. }
  208. if (selectors.is_empty())
  209. return ParsingResult::SyntaxError;
  210. return selectors;
  211. }
  212. Result<NonnullRefPtr<Selector>, Parser::ParsingResult> Parser::parse_complex_selector(TokenStream<StyleComponentValueRule>& tokens, bool allow_starting_combinator)
  213. {
  214. Vector<Selector::CompoundSelector> compound_selectors;
  215. auto first_selector = parse_compound_selector(tokens);
  216. if (first_selector.is_error())
  217. return first_selector.error();
  218. if (!allow_starting_combinator) {
  219. if (first_selector.value().combinator != Selector::Combinator::Descendant)
  220. return ParsingResult::SyntaxError;
  221. first_selector.value().combinator = Selector::Combinator::None;
  222. }
  223. compound_selectors.append(first_selector.value());
  224. while (tokens.has_next_token()) {
  225. auto compound_selector = parse_compound_selector(tokens);
  226. if (compound_selector.is_error()) {
  227. if (compound_selector.error() == ParsingResult::Done)
  228. break;
  229. else
  230. return compound_selector.error();
  231. }
  232. compound_selectors.append(compound_selector.value());
  233. }
  234. if (compound_selectors.is_empty())
  235. return ParsingResult::SyntaxError;
  236. return Selector::create(move(compound_selectors));
  237. }
  238. Result<Selector::CompoundSelector, Parser::ParsingResult> Parser::parse_compound_selector(TokenStream<StyleComponentValueRule>& tokens)
  239. {
  240. tokens.skip_whitespace();
  241. auto combinator = parse_selector_combinator(tokens).value_or(Selector::Combinator::Descendant);
  242. tokens.skip_whitespace();
  243. Vector<Selector::SimpleSelector> simple_selectors;
  244. while (tokens.has_next_token()) {
  245. auto component = parse_simple_selector(tokens);
  246. if (component.is_error()) {
  247. if (component.error() == ParsingResult::Done)
  248. break;
  249. else
  250. return component.error();
  251. }
  252. simple_selectors.append(component.value());
  253. }
  254. if (simple_selectors.is_empty())
  255. return ParsingResult::Done;
  256. return Selector::CompoundSelector { combinator, move(simple_selectors) };
  257. }
  258. Optional<Selector::Combinator> Parser::parse_selector_combinator(TokenStream<StyleComponentValueRule>& tokens)
  259. {
  260. auto& current_value = tokens.next_token();
  261. if (current_value.is(Token::Type::Delim)) {
  262. auto delim = current_value.token().delim();
  263. if (delim == ">"sv) {
  264. return Selector::Combinator::ImmediateChild;
  265. } else if (delim == "+"sv) {
  266. return Selector::Combinator::NextSibling;
  267. } else if (delim == "~"sv) {
  268. return Selector::Combinator::SubsequentSibling;
  269. } else if (delim == "|"sv) {
  270. auto& next = tokens.peek_token();
  271. if (next.is(Token::Type::EndOfFile))
  272. return {};
  273. if (next.is(Token::Type::Delim) && next.token().delim() == "|"sv) {
  274. tokens.next_token();
  275. return Selector::Combinator::Column;
  276. }
  277. }
  278. }
  279. tokens.reconsume_current_input_token();
  280. return {};
  281. }
  282. Result<Selector::SimpleSelector, Parser::ParsingResult> Parser::parse_simple_selector(TokenStream<StyleComponentValueRule>& tokens)
  283. {
  284. auto peek_token_ends_selector = [&]() -> bool {
  285. auto& value = tokens.peek_token();
  286. return (value.is(Token::Type::EndOfFile) || value.is(Token::Type::Whitespace) || value.is(Token::Type::Comma));
  287. };
  288. if (peek_token_ends_selector())
  289. return ParsingResult::Done;
  290. auto& first_value = tokens.next_token();
  291. if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "*"sv) {
  292. return Selector::SimpleSelector {
  293. .type = Selector::SimpleSelector::Type::Universal
  294. };
  295. } else if (first_value.is(Token::Type::Hash)) {
  296. if (first_value.token().hash_type() != Token::HashType::Id) {
  297. dbgln_if(CSS_PARSER_DEBUG, "Selector contains hash token that is not an id: {}", first_value.to_debug_string());
  298. return ParsingResult::SyntaxError;
  299. }
  300. return Selector::SimpleSelector {
  301. .type = Selector::SimpleSelector::Type::Id,
  302. .value = first_value.token().hash_value()
  303. };
  304. } else if (first_value.is(Token::Type::Delim) && first_value.token().delim() == "."sv) {
  305. if (peek_token_ends_selector())
  306. return ParsingResult::SyntaxError;
  307. auto& class_name_value = tokens.next_token();
  308. if (!class_name_value.is(Token::Type::Ident)) {
  309. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident after '.', got: {}", class_name_value.to_debug_string());
  310. return ParsingResult::SyntaxError;
  311. }
  312. return Selector::SimpleSelector {
  313. .type = Selector::SimpleSelector::Type::Class,
  314. .value = class_name_value.token().ident()
  315. };
  316. } else if (first_value.is(Token::Type::Ident)) {
  317. return Selector::SimpleSelector {
  318. .type = Selector::SimpleSelector::Type::TagName,
  319. .value = first_value.token().ident()
  320. };
  321. } else if (first_value.is_block() && first_value.block().is_square()) {
  322. auto& attribute_parts = first_value.block().values();
  323. if (attribute_parts.is_empty()) {
  324. dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
  325. return ParsingResult::SyntaxError;
  326. }
  327. // FIXME: Handle namespace prefix for attribute name.
  328. auto& attribute_part = attribute_parts.first();
  329. if (!attribute_part.is(Token::Type::Ident)) {
  330. dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  331. return ParsingResult::SyntaxError;
  332. }
  333. Selector::SimpleSelector simple_selector {
  334. .type = Selector::SimpleSelector::Type::Attribute,
  335. .attribute = {
  336. .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
  337. // FIXME: Case-sensitivity is defined by the document language.
  338. // HTML is insensitive with attribute names, and our code generally assumes
  339. // they are converted to lowercase, so we do that here too. If we want to be
  340. // correct with XML later, we'll need to keep the original case and then do
  341. // a case-insensitive compare later.
  342. .name = attribute_part.token().ident().to_lowercase_string(),
  343. }
  344. };
  345. if (attribute_parts.size() == 1)
  346. return simple_selector;
  347. size_t attribute_index = 1;
  348. auto& delim_part = attribute_parts.at(attribute_index);
  349. if (!delim_part.is(Token::Type::Delim)) {
  350. dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  351. return ParsingResult::SyntaxError;
  352. }
  353. if (delim_part.token().delim() == "="sv) {
  354. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
  355. attribute_index++;
  356. } else {
  357. attribute_index++;
  358. if (attribute_index >= attribute_parts.size()) {
  359. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
  360. return ParsingResult::SyntaxError;
  361. }
  362. auto& delim_second_part = attribute_parts.at(attribute_index);
  363. if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == "=")) {
  364. dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  365. return ParsingResult::SyntaxError;
  366. }
  367. if (delim_part.token().delim() == "~"sv) {
  368. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
  369. attribute_index++;
  370. } else if (delim_part.token().delim() == "*"sv) {
  371. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
  372. attribute_index++;
  373. } else if (delim_part.token().delim() == "|"sv) {
  374. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
  375. attribute_index++;
  376. } else if (delim_part.token().delim() == "^"sv) {
  377. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
  378. attribute_index++;
  379. } else if (delim_part.token().delim() == "$"sv) {
  380. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
  381. attribute_index++;
  382. }
  383. }
  384. if (attribute_index >= attribute_parts.size()) {
  385. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
  386. return ParsingResult::SyntaxError;
  387. }
  388. auto& value_part = attribute_parts.at(attribute_index);
  389. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  390. dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  391. return ParsingResult::SyntaxError;
  392. }
  393. simple_selector.attribute.value = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  394. // FIXME: Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  395. return simple_selector;
  396. } else if (first_value.is(Token::Type::Colon)) {
  397. if (peek_token_ends_selector())
  398. return ParsingResult::SyntaxError;
  399. bool is_pseudo = false;
  400. if (tokens.peek_token().is(Token::Type::Colon)) {
  401. is_pseudo = true;
  402. tokens.next_token();
  403. if (peek_token_ends_selector())
  404. return ParsingResult::SyntaxError;
  405. }
  406. if (is_pseudo) {
  407. Selector::SimpleSelector simple_selector {
  408. .type = Selector::SimpleSelector::Type::PseudoElement
  409. };
  410. auto& name_token = tokens.next_token();
  411. if (!name_token.is(Token::Type::Ident)) {
  412. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
  413. return ParsingResult::SyntaxError;
  414. }
  415. auto pseudo_name = name_token.token().ident();
  416. if (has_ignored_vendor_prefix(pseudo_name))
  417. return ParsingResult::IncludesIgnoredVendorPrefix;
  418. if (pseudo_name.equals_ignoring_case("after")) {
  419. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  420. } else if (pseudo_name.equals_ignoring_case("before")) {
  421. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  422. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  423. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  424. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  425. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  426. } else {
  427. dbgln("Unrecognized pseudo-element: '::{}'", pseudo_name);
  428. return ParsingResult::SyntaxError;
  429. }
  430. return simple_selector;
  431. }
  432. if (peek_token_ends_selector())
  433. return ParsingResult::SyntaxError;
  434. auto& pseudo_class_token = tokens.next_token();
  435. Selector::SimpleSelector simple_selector {
  436. .type = Selector::SimpleSelector::Type::PseudoClass
  437. };
  438. if (pseudo_class_token.is(Token::Type::Ident)) {
  439. auto pseudo_name = pseudo_class_token.token().ident();
  440. if (has_ignored_vendor_prefix(pseudo_name))
  441. return ParsingResult::IncludesIgnoredVendorPrefix;
  442. if (pseudo_name.equals_ignoring_case("active")) {
  443. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Active;
  444. } else if (pseudo_name.equals_ignoring_case("checked")) {
  445. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Checked;
  446. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  447. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Disabled;
  448. } else if (pseudo_name.equals_ignoring_case("empty")) {
  449. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Empty;
  450. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  451. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Enabled;
  452. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  453. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstChild;
  454. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  455. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstOfType;
  456. } else if (pseudo_name.equals_ignoring_case("focus")) {
  457. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Focus;
  458. } else if (pseudo_name.equals_ignoring_case("hover")) {
  459. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Hover;
  460. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  461. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastChild;
  462. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  463. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastOfType;
  464. } else if (pseudo_name.equals_ignoring_case("link")) {
  465. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Link;
  466. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  467. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::OnlyChild;
  468. } else if (pseudo_name.equals_ignoring_case("root")) {
  469. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Root;
  470. } else if (pseudo_name.equals_ignoring_case("visited")) {
  471. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Visited;
  472. } else if (pseudo_name.equals_ignoring_case("after")) {
  473. // Single-colon syntax allowed for compatibility. https://www.w3.org/TR/selectors/#pseudo-element-syntax
  474. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  475. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  476. } else if (pseudo_name.equals_ignoring_case("before")) {
  477. // See :after
  478. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  479. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  480. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  481. // See :after
  482. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  483. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  484. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  485. // See :after
  486. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  487. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  488. } else {
  489. dbgln("Unrecognized pseudo-class: ':{}'", pseudo_name);
  490. return ParsingResult::SyntaxError;
  491. }
  492. return simple_selector;
  493. } else if (pseudo_class_token.is_function()) {
  494. auto& pseudo_function = pseudo_class_token.function();
  495. if (pseudo_function.name().equals_ignoring_case("not")) {
  496. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Not;
  497. auto function_token_stream = TokenStream(pseudo_function.values());
  498. auto not_selector = parse_a_selector(function_token_stream);
  499. if (not_selector.is_error()) {
  500. dbgln_if(CSS_PARSER_DEBUG, "Invalid selector in :not() clause");
  501. return ParsingResult::SyntaxError;
  502. }
  503. simple_selector.pseudo_class.not_selector = not_selector.release_value();
  504. } else if (pseudo_function.name().equals_ignoring_case("nth-child")) {
  505. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthChild;
  506. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  507. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  508. if (nth_child_pattern.has_value()) {
  509. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  510. } else {
  511. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  512. return ParsingResult::SyntaxError;
  513. }
  514. } else if (pseudo_function.name().equals_ignoring_case("nth-last-child")) {
  515. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthLastChild;
  516. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  517. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  518. if (nth_child_pattern.has_value()) {
  519. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  520. } else {
  521. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  522. return ParsingResult::SyntaxError;
  523. }
  524. } else {
  525. dbgln("Unrecognized pseudo-class function: ':{}'()", pseudo_function.name());
  526. return ParsingResult::SyntaxError;
  527. }
  528. return simple_selector;
  529. } else {
  530. dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
  531. return ParsingResult::SyntaxError;
  532. }
  533. }
  534. // Whitespace is not required between the compound-selector and a combinator.
  535. // So, if we see a combinator, return that this compound-selector is done, instead of a syntax error.
  536. if (first_value.is(Token::Type::Delim)) {
  537. auto delim = first_value.token().delim();
  538. if ((delim == ">"sv) || (delim == "+"sv) || (delim == "~"sv) || (delim == "|"sv)) {
  539. tokens.reconsume_current_input_token();
  540. return ParsingResult::Done;
  541. }
  542. }
  543. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  544. return ParsingResult::SyntaxError;
  545. }
  546. NonnullRefPtrVector<MediaQuery> Parser::parse_as_media_query_list()
  547. {
  548. return parse_a_media_query_list(m_token_stream);
  549. }
  550. template<typename T>
  551. NonnullRefPtrVector<MediaQuery> Parser::parse_a_media_query_list(TokenStream<T>& tokens)
  552. {
  553. // https://www.w3.org/TR/mediaqueries-4/#mq-list
  554. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  555. AK::NonnullRefPtrVector<MediaQuery> media_queries;
  556. for (auto& media_query_parts : comma_separated_lists) {
  557. auto stream = TokenStream(media_query_parts);
  558. media_queries.append(parse_media_query(stream));
  559. }
  560. return media_queries;
  561. }
  562. RefPtr<MediaQuery> Parser::parse_as_media_query()
  563. {
  564. // https://www.w3.org/TR/cssom-1/#parse-a-media-query
  565. auto media_query_list = parse_as_media_query_list();
  566. if (media_query_list.is_empty())
  567. return MediaQuery::create_not_all();
  568. if (media_query_list.size() == 1)
  569. return media_query_list.first();
  570. return nullptr;
  571. }
  572. NonnullRefPtr<MediaQuery> Parser::parse_media_query(TokenStream<StyleComponentValueRule>& tokens)
  573. {
  574. // Returns whether to negate the query
  575. auto consume_initial_modifier = [](auto& tokens) -> Optional<bool> {
  576. auto& token = tokens.next_token();
  577. if (!token.is(Token::Type::Ident)) {
  578. tokens.reconsume_current_input_token();
  579. return {};
  580. }
  581. auto ident = token.token().ident();
  582. if (ident.equals_ignoring_case("not")) {
  583. return true;
  584. } else if (ident.equals_ignoring_case("only")) {
  585. return false;
  586. }
  587. tokens.reconsume_current_input_token();
  588. return {};
  589. };
  590. auto invalid_media_query = [&]() {
  591. // "A media query that does not match the grammar in the previous section must be replaced by `not all`
  592. // during parsing." - https://www.w3.org/TR/mediaqueries-5/#error-handling
  593. if constexpr (CSS_PARSER_DEBUG) {
  594. dbgln("Invalid media query:");
  595. tokens.dump_all_tokens();
  596. }
  597. return MediaQuery::create_not_all();
  598. };
  599. auto media_query = MediaQuery::create();
  600. tokens.skip_whitespace();
  601. // Only `<media-condition>`
  602. if (auto media_condition = consume_media_condition(tokens)) {
  603. tokens.skip_whitespace();
  604. if (tokens.has_next_token())
  605. return invalid_media_query();
  606. media_query->m_media_condition = move(media_condition);
  607. return media_query;
  608. }
  609. // Optional `"only" | "not"`
  610. if (auto modifier = consume_initial_modifier(tokens); modifier.has_value()) {
  611. media_query->m_negated = modifier.value();
  612. tokens.skip_whitespace();
  613. }
  614. // `<media-type>`
  615. if (auto media_type = consume_media_type(tokens); media_type.has_value()) {
  616. media_query->m_media_type = media_type.value();
  617. tokens.skip_whitespace();
  618. } else {
  619. return invalid_media_query();
  620. }
  621. if (!tokens.has_next_token())
  622. return media_query;
  623. // Optional "and <media-condition>"
  624. if (auto maybe_and = tokens.next_token(); maybe_and.is(Token::Type::Ident) && maybe_and.token().ident().equals_ignoring_case("and")) {
  625. if (auto media_condition = consume_media_condition(tokens)) {
  626. tokens.skip_whitespace();
  627. if (tokens.has_next_token())
  628. return invalid_media_query();
  629. media_query->m_media_condition = move(media_condition);
  630. return media_query;
  631. }
  632. return invalid_media_query();
  633. }
  634. return invalid_media_query();
  635. }
  636. OwnPtr<MediaQuery::MediaCondition> Parser::consume_media_condition(TokenStream<StyleComponentValueRule>& tokens)
  637. {
  638. // "not <media-condition>"
  639. auto position = tokens.position();
  640. auto& first_token = tokens.peek_token();
  641. if (first_token.is(Token::Type::Ident) && first_token.token().ident().equals_ignoring_case("not"sv)) {
  642. tokens.next_token();
  643. auto condition = new MediaQuery::MediaCondition;
  644. condition->type = MediaQuery::MediaCondition::Type::Not;
  645. if (auto child_condition = consume_media_condition(tokens)) {
  646. condition->conditions.append(child_condition.release_nonnull());
  647. return adopt_own(*condition);
  648. }
  649. tokens.rewind_to_position(position);
  650. return {};
  651. }
  652. // "<media-condition> ([and | or] <media-condition>)*"
  653. NonnullOwnPtrVector<MediaQuery::MediaCondition> child_conditions;
  654. Optional<MediaQuery::MediaCondition::Type> condition_type {};
  655. auto as_condition_type = [](auto& token) -> Optional<MediaQuery::MediaCondition::Type> {
  656. if (!token.is(Token::Type::Ident))
  657. return {};
  658. auto ident = token.token().ident();
  659. if (ident.equals_ignoring_case("and"))
  660. return MediaQuery::MediaCondition::Type::And;
  661. if (ident.equals_ignoring_case("or"))
  662. return MediaQuery::MediaCondition::Type::Or;
  663. return {};
  664. };
  665. bool is_invalid = false;
  666. tokens.skip_whitespace();
  667. while (tokens.has_next_token()) {
  668. if (!child_conditions.is_empty()) {
  669. // Expect an "and" or "or" here
  670. auto maybe_combination = as_condition_type(tokens.next_token());
  671. if (!maybe_combination.has_value()) {
  672. is_invalid = true;
  673. break;
  674. }
  675. if (!condition_type.has_value()) {
  676. condition_type = maybe_combination.value();
  677. } else if (maybe_combination != condition_type) {
  678. is_invalid = true;
  679. break;
  680. }
  681. }
  682. tokens.skip_whitespace();
  683. if (auto child_feature = consume_media_feature(tokens); child_feature.has_value()) {
  684. auto child = new MediaQuery::MediaCondition;
  685. child->type = MediaQuery::MediaCondition::Type::Single;
  686. child->feature = child_feature.value();
  687. child_conditions.append(adopt_own(*child));
  688. } else {
  689. auto& token = tokens.next_token();
  690. if (!token.is_block() || !token.block().is_paren()) {
  691. is_invalid = true;
  692. break;
  693. }
  694. auto block_tokens = TokenStream { token.block().values() };
  695. if (auto child = consume_media_condition(block_tokens)) {
  696. child_conditions.append(child.release_nonnull());
  697. } else {
  698. is_invalid = true;
  699. break;
  700. }
  701. }
  702. tokens.skip_whitespace();
  703. }
  704. if (!is_invalid && !child_conditions.is_empty()) {
  705. if (child_conditions.size() == 1)
  706. return move(child_conditions.ptr_at(0));
  707. auto condition = new MediaQuery::MediaCondition;
  708. condition->type = condition_type.value();
  709. condition->conditions = move(child_conditions);
  710. return adopt_own(*condition);
  711. }
  712. // "<media-feature>"
  713. tokens.rewind_to_position(position);
  714. if (auto feature = consume_media_feature(tokens); feature.has_value()) {
  715. auto condition = new MediaQuery::MediaCondition;
  716. condition->type = MediaQuery::MediaCondition::Type::Single;
  717. condition->feature = feature.value();
  718. return adopt_own(*condition);
  719. }
  720. tokens.rewind_to_position(position);
  721. return {};
  722. }
  723. Optional<MediaQuery::MediaFeature> Parser::consume_media_feature(TokenStream<StyleComponentValueRule>& outer_tokens)
  724. {
  725. outer_tokens.skip_whitespace();
  726. auto invalid_feature = [&]() -> Optional<MediaQuery::MediaFeature> {
  727. outer_tokens.reconsume_current_input_token();
  728. return {};
  729. };
  730. auto& block_token = outer_tokens.next_token();
  731. if (block_token.is_block() && block_token.block().is_paren()) {
  732. TokenStream tokens { block_token.block().values() };
  733. tokens.skip_whitespace();
  734. auto& name_token = tokens.next_token();
  735. // FIXME: Range syntax allows a value to come before the name
  736. // https://www.w3.org/TR/mediaqueries-4/#mq-range-context
  737. if (!name_token.is(Token::Type::Ident))
  738. return invalid_feature();
  739. auto feature_name = name_token.token().ident();
  740. tokens.skip_whitespace();
  741. if (!tokens.has_next_token()) {
  742. return MediaQuery::MediaFeature {
  743. .type = MediaQuery::MediaFeature::Type::IsTrue,
  744. .name = feature_name,
  745. };
  746. }
  747. if (!tokens.next_token().is(Token::Type::Colon))
  748. return invalid_feature();
  749. tokens.skip_whitespace();
  750. auto value = parse_css_value(PropertyID::Custom, tokens);
  751. if (value.is_error())
  752. return invalid_feature();
  753. if (tokens.has_next_token())
  754. return invalid_feature();
  755. if (feature_name.starts_with("min-", CaseSensitivity::CaseInsensitive)) {
  756. return MediaQuery::MediaFeature {
  757. .type = MediaQuery::MediaFeature::Type::MinValue,
  758. .name = feature_name.substring_view(4),
  759. .value = value.release_value(),
  760. };
  761. } else if (feature_name.starts_with("max-", CaseSensitivity::CaseInsensitive)) {
  762. return MediaQuery::MediaFeature {
  763. .type = MediaQuery::MediaFeature::Type::MaxValue,
  764. .name = feature_name.substring_view(4),
  765. .value = value.release_value(),
  766. };
  767. }
  768. return MediaQuery::MediaFeature {
  769. .type = MediaQuery::MediaFeature::Type::ExactValue,
  770. .name = feature_name,
  771. .value = value.release_value(),
  772. };
  773. }
  774. return invalid_feature();
  775. }
  776. Optional<MediaQuery::MediaType> Parser::consume_media_type(TokenStream<StyleComponentValueRule>& tokens)
  777. {
  778. auto& token = tokens.next_token();
  779. if (!token.is(Token::Type::Ident)) {
  780. tokens.reconsume_current_input_token();
  781. return {};
  782. }
  783. auto ident = token.token().ident();
  784. if (ident.equals_ignoring_case("all")) {
  785. return MediaQuery::MediaType::All;
  786. } else if (ident.equals_ignoring_case("aural")) {
  787. return MediaQuery::MediaType::Aural;
  788. } else if (ident.equals_ignoring_case("braille")) {
  789. return MediaQuery::MediaType::Braille;
  790. } else if (ident.equals_ignoring_case("embossed")) {
  791. return MediaQuery::MediaType::Embossed;
  792. } else if (ident.equals_ignoring_case("handheld")) {
  793. return MediaQuery::MediaType::Handheld;
  794. } else if (ident.equals_ignoring_case("print")) {
  795. return MediaQuery::MediaType::Print;
  796. } else if (ident.equals_ignoring_case("projection")) {
  797. return MediaQuery::MediaType::Projection;
  798. } else if (ident.equals_ignoring_case("screen")) {
  799. return MediaQuery::MediaType::Screen;
  800. } else if (ident.equals_ignoring_case("speech")) {
  801. return MediaQuery::MediaType::Speech;
  802. } else if (ident.equals_ignoring_case("tty")) {
  803. return MediaQuery::MediaType::TTY;
  804. } else if (ident.equals_ignoring_case("tv")) {
  805. return MediaQuery::MediaType::TV;
  806. }
  807. tokens.reconsume_current_input_token();
  808. return {};
  809. }
  810. RefPtr<Supports> Parser::parse_as_supports()
  811. {
  812. return parse_a_supports(m_token_stream);
  813. }
  814. template<typename T>
  815. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  816. {
  817. auto component_values = parse_a_list_of_component_values(tokens);
  818. TokenStream<StyleComponentValueRule> token_stream { component_values };
  819. auto maybe_condition = parse_supports_condition(token_stream);
  820. token_stream.skip_whitespace();
  821. if (maybe_condition && !token_stream.has_next_token())
  822. return Supports::create(maybe_condition.release_nonnull());
  823. return {};
  824. }
  825. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<StyleComponentValueRule>& tokens)
  826. {
  827. tokens.skip_whitespace();
  828. auto start_position = tokens.position();
  829. auto& peeked_token = tokens.peek_token();
  830. // `not <supports-in-parens>`
  831. if (peeked_token.is(Token::Type::Ident) && peeked_token.token().ident().equals_ignoring_case("not")) {
  832. tokens.next_token();
  833. tokens.skip_whitespace();
  834. auto child = parse_supports_in_parens(tokens);
  835. if (child.has_value()) {
  836. auto* condition = new Supports::Condition;
  837. condition->type = Supports::Condition::Type::Not;
  838. condition->children.append(child.release_value());
  839. return adopt_own(*condition);
  840. }
  841. tokens.rewind_to_position(start_position);
  842. return {};
  843. }
  844. // ` <supports-in-parens> [ and <supports-in-parens> ]*
  845. // | <supports-in-parens> [ or <supports-in-parens> ]*`
  846. Vector<Supports::InParens> children;
  847. Optional<Supports::Condition::Type> condition_type {};
  848. auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
  849. if (!token.is(Token::Type::Ident))
  850. return {};
  851. auto ident = token.token().ident();
  852. if (ident.equals_ignoring_case("and"))
  853. return Supports::Condition::Type::And;
  854. if (ident.equals_ignoring_case("or"))
  855. return Supports::Condition::Type::Or;
  856. return {};
  857. };
  858. bool is_invalid = false;
  859. while (tokens.has_next_token()) {
  860. if (!children.is_empty()) {
  861. // Expect `and` or `or` here
  862. auto maybe_combination = as_condition_type(tokens.next_token());
  863. if (!maybe_combination.has_value()) {
  864. is_invalid = true;
  865. break;
  866. }
  867. if (!condition_type.has_value()) {
  868. condition_type = maybe_combination.value();
  869. } else if (maybe_combination != condition_type) {
  870. is_invalid = true;
  871. break;
  872. }
  873. }
  874. tokens.skip_whitespace();
  875. if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
  876. children.append(in_parens.release_value());
  877. } else {
  878. is_invalid = true;
  879. break;
  880. }
  881. tokens.skip_whitespace();
  882. }
  883. if (!is_invalid && !children.is_empty()) {
  884. auto* condition = new Supports::Condition;
  885. condition->type = condition_type.value_or(Supports::Condition::Type::Or);
  886. condition->children = move(children);
  887. return adopt_own(*condition);
  888. }
  889. tokens.rewind_to_position(start_position);
  890. return {};
  891. }
  892. Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<StyleComponentValueRule>& tokens)
  893. {
  894. tokens.skip_whitespace();
  895. auto start_position = tokens.position();
  896. auto& first_token = tokens.peek_token();
  897. // `( <supports-condition> )`
  898. if (first_token.is_block() && first_token.block().is_paren()) {
  899. tokens.next_token();
  900. tokens.skip_whitespace();
  901. TokenStream child_tokens { first_token.block().values() };
  902. if (auto condition = parse_supports_condition(child_tokens)) {
  903. if (child_tokens.has_next_token()) {
  904. tokens.rewind_to_position(start_position);
  905. return {};
  906. }
  907. return Supports::InParens {
  908. .value = { condition.release_nonnull() }
  909. };
  910. }
  911. tokens.rewind_to_position(start_position);
  912. }
  913. // `<supports-feature>`
  914. if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
  915. return Supports::InParens {
  916. .value = { feature.release_value() }
  917. };
  918. }
  919. // `<general-enclosed>`
  920. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  921. return Supports::InParens {
  922. .value = Supports::GeneralEnclosed {}
  923. };
  924. }
  925. tokens.rewind_to_position(start_position);
  926. return {};
  927. }
  928. Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<StyleComponentValueRule>& tokens)
  929. {
  930. tokens.skip_whitespace();
  931. auto start_position = tokens.position();
  932. auto& first_token = tokens.next_token();
  933. // `<supports-decl>`
  934. if (first_token.is_block() && first_token.block().is_paren()) {
  935. TokenStream block_tokens { first_token.block().values() };
  936. if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
  937. return Supports::Feature {
  938. .declaration = declaration.release_value()
  939. };
  940. }
  941. }
  942. tokens.rewind_to_position(start_position);
  943. return {};
  944. }
  945. Optional<Parser::GeneralEnclosed> Parser::parse_general_enclosed()
  946. {
  947. return parse_general_enclosed(m_token_stream);
  948. }
  949. template<typename T>
  950. Optional<Parser::GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<T>&)
  951. {
  952. // FIXME: Actually parse this! https://www.w3.org/TR/mediaqueries-5/#typedef-general-enclosed
  953. return {};
  954. }
  955. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(bool top_level)
  956. {
  957. return consume_a_list_of_rules(m_token_stream, top_level);
  958. }
  959. template<typename T>
  960. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  961. {
  962. NonnullRefPtrVector<StyleRule> rules;
  963. for (;;) {
  964. auto& token = tokens.next_token();
  965. if (token.is(Token::Type::Whitespace)) {
  966. continue;
  967. }
  968. if (token.is(Token::Type::EndOfFile)) {
  969. break;
  970. }
  971. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  972. if (top_level) {
  973. continue;
  974. }
  975. tokens.reconsume_current_input_token();
  976. auto maybe_qualified = consume_a_qualified_rule(tokens);
  977. if (maybe_qualified) {
  978. rules.append(maybe_qualified.release_nonnull());
  979. }
  980. continue;
  981. }
  982. if (token.is(Token::Type::AtKeyword)) {
  983. tokens.reconsume_current_input_token();
  984. rules.append(consume_an_at_rule(tokens));
  985. continue;
  986. }
  987. tokens.reconsume_current_input_token();
  988. auto maybe_qualified = consume_a_qualified_rule(tokens);
  989. if (maybe_qualified) {
  990. rules.append(maybe_qualified.release_nonnull());
  991. }
  992. }
  993. return rules;
  994. }
  995. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule()
  996. {
  997. return consume_an_at_rule(m_token_stream);
  998. }
  999. template<typename T>
  1000. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  1001. {
  1002. auto& name_ident = tokens.next_token();
  1003. VERIFY(name_ident.is(Token::Type::AtKeyword));
  1004. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::At);
  1005. rule->m_name = ((Token)name_ident).at_keyword();
  1006. for (;;) {
  1007. auto& token = tokens.next_token();
  1008. if (token.is(Token::Type::Semicolon)) {
  1009. return rule;
  1010. }
  1011. if (token.is(Token::Type::EndOfFile)) {
  1012. log_parse_error();
  1013. return rule;
  1014. }
  1015. if (token.is(Token::Type::OpenCurly)) {
  1016. rule->m_block = consume_a_simple_block(tokens);
  1017. return rule;
  1018. }
  1019. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1020. StyleComponentValueRule const& component_value = token;
  1021. if (component_value.is_block() && component_value.block().is_curly()) {
  1022. rule->m_block = component_value.block();
  1023. return rule;
  1024. }
  1025. }
  1026. tokens.reconsume_current_input_token();
  1027. auto value = consume_a_component_value(tokens);
  1028. rule->m_prelude.append(value);
  1029. }
  1030. }
  1031. RefPtr<StyleRule> Parser::consume_a_qualified_rule()
  1032. {
  1033. return consume_a_qualified_rule(m_token_stream);
  1034. }
  1035. template<typename T>
  1036. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  1037. {
  1038. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::Qualified);
  1039. for (;;) {
  1040. auto& token = tokens.next_token();
  1041. if (token.is(Token::Type::EndOfFile)) {
  1042. log_parse_error();
  1043. return {};
  1044. }
  1045. if (token.is(Token::Type::OpenCurly)) {
  1046. rule->m_block = consume_a_simple_block(tokens);
  1047. return rule;
  1048. }
  1049. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1050. StyleComponentValueRule const& component_value = token;
  1051. if (component_value.is_block() && component_value.block().is_curly()) {
  1052. rule->m_block = component_value.block();
  1053. return rule;
  1054. }
  1055. }
  1056. tokens.reconsume_current_input_token();
  1057. auto value = consume_a_component_value(tokens);
  1058. rule->m_prelude.append(value);
  1059. }
  1060. return rule;
  1061. }
  1062. template<>
  1063. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  1064. {
  1065. return tokens.next_token();
  1066. }
  1067. template<typename T>
  1068. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  1069. {
  1070. auto& token = tokens.next_token();
  1071. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  1072. return StyleComponentValueRule(consume_a_simple_block(tokens));
  1073. if (token.is(Token::Type::Function))
  1074. return StyleComponentValueRule(consume_a_function(tokens));
  1075. return StyleComponentValueRule(token);
  1076. }
  1077. StyleComponentValueRule Parser::consume_a_component_value()
  1078. {
  1079. return consume_a_component_value(m_token_stream);
  1080. }
  1081. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block()
  1082. {
  1083. return consume_a_simple_block(m_token_stream);
  1084. }
  1085. template<typename T>
  1086. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  1087. {
  1088. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  1089. auto block = make_ref_counted<StyleBlockRule>();
  1090. block->m_token = tokens.current_token();
  1091. for (;;) {
  1092. auto& token = tokens.next_token();
  1093. if (token.is(ending_token)) {
  1094. return block;
  1095. }
  1096. if (token.is(Token::Type::EndOfFile)) {
  1097. log_parse_error();
  1098. return block;
  1099. }
  1100. tokens.reconsume_current_input_token();
  1101. auto value = consume_a_component_value(tokens);
  1102. block->m_values.append(value);
  1103. }
  1104. }
  1105. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function()
  1106. {
  1107. return consume_a_function(m_token_stream);
  1108. }
  1109. template<typename T>
  1110. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  1111. {
  1112. auto name_ident = tokens.current_token();
  1113. VERIFY(name_ident.is(Token::Type::Function));
  1114. auto function = make_ref_counted<StyleFunctionRule>(((Token)name_ident).m_value.to_string());
  1115. for (;;) {
  1116. auto& token = tokens.next_token();
  1117. if (token.is(Token::Type::CloseParen)) {
  1118. return function;
  1119. }
  1120. if (token.is(Token::Type::EndOfFile)) {
  1121. log_parse_error();
  1122. return function;
  1123. }
  1124. tokens.reconsume_current_input_token();
  1125. auto value = consume_a_component_value(tokens);
  1126. function->m_values.append(value);
  1127. }
  1128. return function;
  1129. }
  1130. Optional<StyleDeclarationRule> Parser::consume_a_declaration()
  1131. {
  1132. return consume_a_declaration(m_token_stream);
  1133. }
  1134. template<typename T>
  1135. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  1136. {
  1137. tokens.skip_whitespace();
  1138. auto start_position = tokens.position();
  1139. auto& token = tokens.next_token();
  1140. if (!token.is(Token::Type::Ident)) {
  1141. tokens.rewind_to_position(start_position);
  1142. return {};
  1143. }
  1144. StyleDeclarationRule declaration;
  1145. declaration.m_name = ((Token)token).ident();
  1146. tokens.skip_whitespace();
  1147. auto& maybe_colon = tokens.next_token();
  1148. if (!maybe_colon.is(Token::Type::Colon)) {
  1149. log_parse_error();
  1150. tokens.rewind_to_position(start_position);
  1151. return {};
  1152. }
  1153. tokens.skip_whitespace();
  1154. for (;;) {
  1155. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1156. break;
  1157. }
  1158. declaration.m_values.append(consume_a_component_value(tokens));
  1159. }
  1160. if (declaration.m_values.size() >= 2) {
  1161. auto second_last = declaration.m_values.at(declaration.m_values.size() - 2);
  1162. auto last = declaration.m_values.at(declaration.m_values.size() - 1);
  1163. if (second_last.m_type == StyleComponentValueRule::ComponentType::Token && last.m_type == StyleComponentValueRule::ComponentType::Token) {
  1164. auto last_token = last.m_token;
  1165. auto second_last_token = second_last.m_token;
  1166. if (second_last_token.is(Token::Type::Delim) && second_last_token.m_value.to_string().equals_ignoring_case("!")) {
  1167. if (last_token.is(Token::Type::Ident) && last_token.m_value.to_string().equals_ignoring_case("important")) {
  1168. declaration.m_values.remove(declaration.m_values.size() - 2);
  1169. declaration.m_values.remove(declaration.m_values.size() - 1);
  1170. declaration.m_important = true;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. while (!declaration.m_values.is_empty()) {
  1176. auto maybe_whitespace = declaration.m_values.last();
  1177. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  1178. break;
  1179. }
  1180. declaration.m_values.take_last();
  1181. }
  1182. return declaration;
  1183. }
  1184. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations()
  1185. {
  1186. return consume_a_list_of_declarations(m_token_stream);
  1187. }
  1188. template<typename T>
  1189. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  1190. {
  1191. Vector<DeclarationOrAtRule> list;
  1192. for (;;) {
  1193. auto& token = tokens.next_token();
  1194. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  1195. continue;
  1196. }
  1197. if (token.is(Token::Type::EndOfFile)) {
  1198. return list;
  1199. }
  1200. if (token.is(Token::Type::AtKeyword)) {
  1201. tokens.reconsume_current_input_token();
  1202. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  1203. continue;
  1204. }
  1205. if (token.is(Token::Type::Ident)) {
  1206. Vector<StyleComponentValueRule> temp;
  1207. temp.append(token);
  1208. for (;;) {
  1209. auto& peek = tokens.peek_token();
  1210. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  1211. break;
  1212. }
  1213. temp.append(consume_a_component_value(tokens));
  1214. }
  1215. auto token_stream = TokenStream(temp);
  1216. auto maybe_declaration = consume_a_declaration(token_stream);
  1217. if (maybe_declaration.has_value()) {
  1218. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  1219. }
  1220. continue;
  1221. }
  1222. log_parse_error();
  1223. tokens.reconsume_current_input_token();
  1224. for (;;) {
  1225. auto& peek = tokens.peek_token();
  1226. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  1227. break;
  1228. dbgln("Discarding token: '{}'", peek.to_debug_string());
  1229. (void)consume_a_component_value(tokens);
  1230. }
  1231. }
  1232. return list;
  1233. }
  1234. RefPtr<CSSRule> Parser::parse_as_rule()
  1235. {
  1236. return parse_a_rule(m_token_stream);
  1237. }
  1238. template<typename T>
  1239. RefPtr<CSSRule> Parser::parse_a_rule(TokenStream<T>& tokens)
  1240. {
  1241. RefPtr<CSSRule> rule;
  1242. tokens.skip_whitespace();
  1243. auto& token = tokens.peek_token();
  1244. if (token.is(Token::Type::EndOfFile)) {
  1245. return {};
  1246. } else if (token.is(Token::Type::AtKeyword)) {
  1247. auto at_rule = consume_an_at_rule();
  1248. rule = convert_to_rule(at_rule);
  1249. } else {
  1250. auto qualified_rule = consume_a_qualified_rule(tokens);
  1251. if (!qualified_rule)
  1252. return {};
  1253. rule = convert_to_rule(*qualified_rule);
  1254. }
  1255. tokens.skip_whitespace();
  1256. auto& maybe_eof = tokens.peek_token();
  1257. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1258. return rule;
  1259. }
  1260. return {};
  1261. }
  1262. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  1263. {
  1264. return parse_a_list_of_rules(m_token_stream);
  1265. }
  1266. template<typename T>
  1267. NonnullRefPtrVector<CSSRule> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  1268. {
  1269. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  1270. NonnullRefPtrVector<CSSRule> rules;
  1271. for (auto& rule : parsed_rules) {
  1272. auto converted_rule = convert_to_rule(rule);
  1273. if (converted_rule)
  1274. rules.append(*converted_rule);
  1275. }
  1276. return rules;
  1277. }
  1278. Optional<StyleProperty> Parser::parse_as_declaration()
  1279. {
  1280. return parse_a_declaration(m_token_stream);
  1281. }
  1282. template<typename T>
  1283. Optional<StyleProperty> Parser::parse_a_declaration(TokenStream<T>& tokens)
  1284. {
  1285. tokens.skip_whitespace();
  1286. auto& token = tokens.peek_token();
  1287. if (!token.is(Token::Type::Ident)) {
  1288. return {};
  1289. }
  1290. auto declaration = consume_a_declaration(tokens);
  1291. if (declaration.has_value())
  1292. return convert_to_style_property(declaration.value());
  1293. return {};
  1294. }
  1295. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  1296. {
  1297. return parse_a_list_of_declarations(m_token_stream);
  1298. }
  1299. template<typename T>
  1300. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  1301. {
  1302. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  1303. Vector<StyleProperty> properties;
  1304. HashMap<String, StyleProperty> custom_properties;
  1305. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  1306. if (declaration_or_at_rule.is_at_rule()) {
  1307. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  1308. continue;
  1309. }
  1310. auto& declaration = declaration_or_at_rule.m_declaration;
  1311. auto maybe_property = convert_to_style_property(declaration);
  1312. if (maybe_property.has_value()) {
  1313. auto property = maybe_property.value();
  1314. if (property.property_id == PropertyID::Custom) {
  1315. custom_properties.set(property.custom_name, property);
  1316. } else {
  1317. properties.append(property);
  1318. }
  1319. }
  1320. }
  1321. return PropertyOwningCSSStyleDeclaration::create(move(properties), move(custom_properties));
  1322. }
  1323. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  1324. {
  1325. return parse_a_component_value(m_token_stream);
  1326. }
  1327. template<typename T>
  1328. Optional<StyleComponentValueRule> Parser::parse_a_component_value(TokenStream<T>& tokens)
  1329. {
  1330. tokens.skip_whitespace();
  1331. auto& token = tokens.peek_token();
  1332. if (token.is(Token::Type::EndOfFile)) {
  1333. return {};
  1334. }
  1335. auto value = consume_a_component_value(tokens);
  1336. tokens.skip_whitespace();
  1337. auto& maybe_eof = tokens.peek_token();
  1338. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1339. return value;
  1340. }
  1341. return {};
  1342. }
  1343. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  1344. {
  1345. return parse_a_list_of_component_values(m_token_stream);
  1346. }
  1347. template<typename T>
  1348. Vector<StyleComponentValueRule> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  1349. {
  1350. Vector<StyleComponentValueRule> rules;
  1351. for (;;) {
  1352. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1353. break;
  1354. }
  1355. rules.append(consume_a_component_value(tokens));
  1356. }
  1357. return rules;
  1358. }
  1359. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  1360. {
  1361. return parse_a_comma_separated_list_of_component_values(m_token_stream);
  1362. }
  1363. template<typename T>
  1364. Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  1365. {
  1366. Vector<Vector<StyleComponentValueRule>> lists;
  1367. lists.append({});
  1368. for (;;) {
  1369. auto& next = tokens.next_token();
  1370. if (next.is(Token::Type::Comma)) {
  1371. lists.append({});
  1372. continue;
  1373. } else if (next.is(Token::Type::EndOfFile)) {
  1374. break;
  1375. }
  1376. tokens.reconsume_current_input_token();
  1377. auto component_value = consume_a_component_value(tokens);
  1378. lists.last().append(component_value);
  1379. }
  1380. return lists;
  1381. }
  1382. Optional<AK::URL> Parser::parse_url_function(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1383. {
  1384. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1385. // FIXME: Handle data: urls (RFC2397)
  1386. auto is_data_url = [](StringView& url_string) -> bool {
  1387. return url_string.starts_with("data:", CaseSensitivity::CaseInsensitive);
  1388. };
  1389. if (component_value.is(Token::Type::Url)) {
  1390. auto url_string = component_value.token().url();
  1391. if (is_data_url(url_string))
  1392. return {};
  1393. return context.complete_url(url_string);
  1394. }
  1395. if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) {
  1396. auto& function_values = component_value.function().values();
  1397. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  1398. for (size_t i = 0; i < function_values.size(); ++i) {
  1399. auto& value = function_values[i];
  1400. if (value.is(Token::Type::Whitespace))
  1401. continue;
  1402. if (value.is(Token::Type::String)) {
  1403. auto url_string = value.token().string();
  1404. if (is_data_url(url_string))
  1405. return {};
  1406. return context.complete_url(url_string);
  1407. }
  1408. break;
  1409. }
  1410. }
  1411. return {};
  1412. }
  1413. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  1414. {
  1415. if (rule->m_type == StyleRule::Type::At) {
  1416. if (has_ignored_vendor_prefix(rule->m_name)) {
  1417. return {};
  1418. } else if (rule->m_name.equals_ignoring_case("media"sv)) {
  1419. auto media_query_tokens = TokenStream { rule->prelude() };
  1420. auto media_query_list = parse_a_media_query_list(media_query_tokens);
  1421. auto child_tokens = TokenStream { rule->block().values() };
  1422. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1423. NonnullRefPtrVector<CSSRule> child_rules;
  1424. for (auto& raw_rule : parser_rules) {
  1425. if (auto child_rule = convert_to_rule(raw_rule))
  1426. child_rules.append(*child_rule);
  1427. }
  1428. return CSSMediaRule::create(MediaList::create(move(media_query_list)), move(child_rules));
  1429. } else if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  1430. Optional<AK::URL> url;
  1431. for (auto& token : rule->prelude()) {
  1432. if (token.is(Token::Type::Whitespace))
  1433. continue;
  1434. if (token.is(Token::Type::String)) {
  1435. url = m_context.complete_url(token.token().string());
  1436. } else {
  1437. url = parse_url_function(m_context, token);
  1438. }
  1439. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1440. if (url.has_value())
  1441. break;
  1442. }
  1443. if (url.has_value())
  1444. return CSSImportRule::create(url.value());
  1445. else
  1446. dbgln("Unable to parse url from @import rule");
  1447. } else if (rule->m_name.equals_ignoring_case("supports"sv)) {
  1448. auto supports_tokens = TokenStream { rule->prelude() };
  1449. auto supports = parse_a_supports(supports_tokens);
  1450. if (!supports) {
  1451. if constexpr (CSS_PARSER_DEBUG) {
  1452. dbgln("CSSParser: @supports rule invalid; discarding.");
  1453. supports_tokens.dump_all_tokens();
  1454. }
  1455. return {};
  1456. }
  1457. auto child_tokens = TokenStream { rule->block().values() };
  1458. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1459. NonnullRefPtrVector<CSSRule> child_rules;
  1460. for (auto& raw_rule : parser_rules) {
  1461. if (auto child_rule = convert_to_rule(raw_rule))
  1462. child_rules.append(*child_rule);
  1463. }
  1464. return CSSSupportsRule::create(supports.release_nonnull(), move(child_rules));
  1465. } else {
  1466. dbgln("Unrecognized CSS at-rule: @{}", rule->m_name);
  1467. }
  1468. // FIXME: More at rules!
  1469. } else {
  1470. auto prelude_stream = TokenStream(rule->m_prelude);
  1471. auto selectors = parse_a_selector(prelude_stream);
  1472. if (selectors.is_error()) {
  1473. if (selectors.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1474. dbgln("CSSParser: style rule selectors invalid; discarding.");
  1475. if constexpr (CSS_PARSER_DEBUG) {
  1476. prelude_stream.dump_all_tokens();
  1477. }
  1478. }
  1479. return {};
  1480. }
  1481. if (selectors.value().is_empty()) {
  1482. dbgln("CSSParser: empty selector; discarding.");
  1483. return {};
  1484. }
  1485. auto declaration = convert_to_declaration(*rule->m_block);
  1486. if (!declaration) {
  1487. dbgln("CSSParser: style rule declaration invalid; discarding.");
  1488. return {};
  1489. }
  1490. return CSSStyleRule::create(move(selectors.value()), move(*declaration));
  1491. }
  1492. return {};
  1493. }
  1494. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  1495. {
  1496. if (!block->is_curly())
  1497. return {};
  1498. auto stream = TokenStream(block->m_values);
  1499. return parse_a_list_of_declarations(stream);
  1500. }
  1501. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule const& declaration)
  1502. {
  1503. auto& property_name = declaration.m_name;
  1504. auto property_id = property_id_from_string(property_name);
  1505. if (property_id == PropertyID::Invalid) {
  1506. if (property_name.starts_with("--")) {
  1507. property_id = PropertyID::Custom;
  1508. } else if (has_ignored_vendor_prefix(property_name)) {
  1509. return {};
  1510. } else if (!property_name.starts_with("-")) {
  1511. dbgln("Unrecognized CSS property '{}'", property_name);
  1512. return {};
  1513. }
  1514. }
  1515. auto value_token_stream = TokenStream(declaration.m_values);
  1516. auto value = parse_css_value(property_id, value_token_stream);
  1517. if (value.is_error()) {
  1518. if (value.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1519. dbgln("Unable to parse value for CSS property '{}'.", property_name);
  1520. if constexpr (CSS_PARSER_DEBUG) {
  1521. value_token_stream.dump_all_tokens();
  1522. }
  1523. }
  1524. return {};
  1525. }
  1526. if (property_id == PropertyID::Custom) {
  1527. return StyleProperty { declaration.m_important, property_id, value.release_value(), declaration.m_name };
  1528. } else {
  1529. return StyleProperty { declaration.m_important, property_id, value.release_value(), {} };
  1530. }
  1531. }
  1532. Optional<float> Parser::try_parse_float(StringView string)
  1533. {
  1534. // FIXME: This is copied from DeprecatedCSSParser, so may not be to spec.
  1535. const char* str = string.characters_without_null_termination();
  1536. size_t len = string.length();
  1537. size_t weight = 1;
  1538. int exp_val = 0;
  1539. float value = 0.0f;
  1540. float fraction = 0.0f;
  1541. bool has_sign = false;
  1542. bool is_negative = false;
  1543. bool is_fractional = false;
  1544. bool is_scientific = false;
  1545. if (str[0] == '-') {
  1546. is_negative = true;
  1547. has_sign = true;
  1548. }
  1549. if (str[0] == '+') {
  1550. has_sign = true;
  1551. }
  1552. for (size_t i = has_sign; i < len; i++) {
  1553. // Looks like we're about to start working on the fractional part
  1554. if (str[i] == '.') {
  1555. is_fractional = true;
  1556. continue;
  1557. }
  1558. if (str[i] == 'e' || str[i] == 'E') {
  1559. if (str[i + 1] == '-' || str[i + 1] == '+')
  1560. exp_val = atoi(str + i + 2);
  1561. else
  1562. exp_val = atoi(str + i + 1);
  1563. is_scientific = true;
  1564. continue;
  1565. }
  1566. if (str[i] < '0' || str[i] > '9' || exp_val != 0)
  1567. return {};
  1568. if (is_fractional) {
  1569. fraction *= 10;
  1570. fraction += str[i] - '0';
  1571. weight *= 10;
  1572. } else {
  1573. value = value * 10;
  1574. value += str[i] - '0';
  1575. }
  1576. }
  1577. fraction /= weight;
  1578. value += fraction;
  1579. if (is_scientific) {
  1580. bool divide = exp_val < 0;
  1581. if (divide)
  1582. exp_val *= -1;
  1583. for (int i = 0; i < exp_val; i++) {
  1584. if (divide)
  1585. value /= 10;
  1586. else
  1587. value *= 10;
  1588. }
  1589. }
  1590. return is_negative ? -value : value;
  1591. }
  1592. RefPtr<StyleValue> Parser::parse_builtin_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1593. {
  1594. if (component_value.is(Token::Type::Ident)) {
  1595. auto ident = component_value.token().ident();
  1596. if (ident.equals_ignoring_case("inherit"))
  1597. return InheritStyleValue::the();
  1598. if (ident.equals_ignoring_case("initial"))
  1599. return InitialStyleValue::the();
  1600. if (ident.equals_ignoring_case("unset"))
  1601. return UnsetStyleValue::the();
  1602. // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
  1603. }
  1604. return {};
  1605. }
  1606. RefPtr<StyleValue> Parser::parse_dynamic_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1607. {
  1608. if (component_value.is_function()) {
  1609. auto& function = component_value.function();
  1610. if (function.name().equals_ignoring_case("calc")) {
  1611. auto calc_expression = parse_calc_expression(context, function.values());
  1612. // FIXME: Either produce a string value of calc() here, or do so in CalculatedStyleValue::to_string().
  1613. if (calc_expression)
  1614. return CalculatedStyleValue::create("(FIXME:calc to string)", calc_expression.release_nonnull());
  1615. } else if (function.name().equals_ignoring_case("var")) {
  1616. // FIXME: Handle fallback value as second parameter
  1617. // https://www.w3.org/TR/css-variables-1/#using-variables
  1618. if (!component_value.function().values().is_empty()) {
  1619. auto& property_name_token = component_value.function().values().first();
  1620. if (property_name_token.is(Token::Type::Ident))
  1621. return CustomStyleValue::create(property_name_token.token().ident());
  1622. else
  1623. dbgln("First argument to var() function was not an ident: '{}'", property_name_token.to_debug_string());
  1624. }
  1625. }
  1626. }
  1627. return {};
  1628. }
  1629. Optional<Length> Parser::parse_length(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1630. {
  1631. Length::Type type = Length::Type::Undefined;
  1632. Optional<float> numeric_value;
  1633. if (component_value.is(Token::Type::Dimension)) {
  1634. auto length_string = component_value.token().m_value.string_view();
  1635. auto unit_string = component_value.token().m_unit.string_view();
  1636. if (unit_string.equals_ignoring_case("%")) {
  1637. type = Length::Type::Percentage;
  1638. } else if (unit_string.equals_ignoring_case("px")) {
  1639. type = Length::Type::Px;
  1640. } else if (unit_string.equals_ignoring_case("pt")) {
  1641. type = Length::Type::Pt;
  1642. } else if (unit_string.equals_ignoring_case("pc")) {
  1643. type = Length::Type::Pc;
  1644. } else if (unit_string.equals_ignoring_case("mm")) {
  1645. type = Length::Type::Mm;
  1646. } else if (unit_string.equals_ignoring_case("rem")) {
  1647. type = Length::Type::Rem;
  1648. } else if (unit_string.equals_ignoring_case("em")) {
  1649. type = Length::Type::Em;
  1650. } else if (unit_string.equals_ignoring_case("ex")) {
  1651. type = Length::Type::Ex;
  1652. } else if (unit_string.equals_ignoring_case("ch")) {
  1653. type = Length::Type::Ch;
  1654. } else if (unit_string.equals_ignoring_case("vw")) {
  1655. type = Length::Type::Vw;
  1656. } else if (unit_string.equals_ignoring_case("vh")) {
  1657. type = Length::Type::Vh;
  1658. } else if (unit_string.equals_ignoring_case("vmax")) {
  1659. type = Length::Type::Vmax;
  1660. } else if (unit_string.equals_ignoring_case("vmin")) {
  1661. type = Length::Type::Vmin;
  1662. } else if (unit_string.equals_ignoring_case("cm")) {
  1663. type = Length::Type::Cm;
  1664. } else if (unit_string.equals_ignoring_case("in")) {
  1665. type = Length::Type::In;
  1666. } else if (unit_string.equals_ignoring_case("Q")) {
  1667. type = Length::Type::Q;
  1668. } else {
  1669. return {};
  1670. }
  1671. numeric_value = try_parse_float(length_string);
  1672. } else if (component_value.is(Token::Type::Percentage)) {
  1673. type = Length::Type::Percentage;
  1674. auto value_string = component_value.token().m_value.string_view();
  1675. numeric_value = try_parse_float(value_string);
  1676. } else if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto")) {
  1677. return Length::make_auto();
  1678. } else if (component_value.is(Token::Type::Number)) {
  1679. auto value_string = component_value.token().m_value.string_view();
  1680. if (value_string == "0") {
  1681. type = Length::Type::Px;
  1682. numeric_value = 0;
  1683. } else if (context.in_quirks_mode() && property_has_quirk(context.current_property_id(), Quirk::UnitlessLength)) {
  1684. // https://quirks.spec.whatwg.org/#quirky-length-value
  1685. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1686. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1687. // expression, and must not be supported in the supports() static method of the CSS interface."
  1688. type = Length::Type::Px;
  1689. numeric_value = try_parse_float(value_string);
  1690. }
  1691. }
  1692. if (!numeric_value.has_value())
  1693. return {};
  1694. return Length(numeric_value.value(), type);
  1695. }
  1696. RefPtr<StyleValue> Parser::parse_length_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1697. {
  1698. // Numbers with no units can be lengths, in two situations:
  1699. // 1) We're in quirks mode, and it's an integer.
  1700. // 2) It's a 0.
  1701. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1702. // FIXME: "auto" is also treated as a Length, and most of the time that is how it is used, but not always.
  1703. // Possibly it should always be an Identifier, and then quietly converted to a Length when needed, like 0 above.
  1704. // Right now, it instead is quietly converted to an Identifier when needed.
  1705. if (component_value.is(Token::Type::Dimension) || component_value.is(Token::Type::Percentage)
  1706. || (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"sv))
  1707. || (context.in_quirks_mode() && component_value.is(Token::Type::Number) && component_value.token().m_value.string_view() != "0"sv)) {
  1708. auto length = parse_length(context, component_value);
  1709. if (length.has_value())
  1710. return LengthStyleValue::create(length.value());
  1711. }
  1712. return {};
  1713. }
  1714. RefPtr<StyleValue> Parser::parse_numeric_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1715. {
  1716. if (component_value.is(Token::Type::Number)) {
  1717. auto number = component_value.token();
  1718. if (number.m_number_type == Token::NumberType::Integer) {
  1719. return NumericStyleValue::create(number.to_integer());
  1720. } else {
  1721. auto float_value = try_parse_float(number.m_value.string_view());
  1722. if (float_value.has_value())
  1723. return NumericStyleValue::create(float_value.value());
  1724. }
  1725. }
  1726. return {};
  1727. }
  1728. RefPtr<StyleValue> Parser::parse_identifier_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1729. {
  1730. if (component_value.is(Token::Type::Ident)) {
  1731. auto value_id = value_id_from_string(component_value.token().ident());
  1732. if (value_id != ValueID::Invalid)
  1733. return IdentifierStyleValue::create(value_id);
  1734. }
  1735. return {};
  1736. }
  1737. Optional<Color> Parser::parse_color(ParsingContext const&, StyleComponentValueRule const& component_value)
  1738. {
  1739. // https://www.w3.org/TR/css-color-3/
  1740. if (component_value.is(Token::Type::Ident)) {
  1741. auto ident = component_value.token().ident();
  1742. if (ident.equals_ignoring_case("transparent"))
  1743. return Color::from_rgba(0x00000000);
  1744. auto color = Color::from_string(ident.to_string().to_lowercase());
  1745. if (color.has_value())
  1746. return color;
  1747. } else if (component_value.is(Token::Type::Hash)) {
  1748. // FIXME: Read it directly
  1749. auto color = Color::from_string(String::formatted("#{}", component_value.token().m_value.to_string().to_lowercase()));
  1750. if (color.has_value())
  1751. return color;
  1752. } else if (component_value.is_function()) {
  1753. auto& function = component_value.function();
  1754. auto& values = function.values();
  1755. Vector<Token> params;
  1756. for (size_t i = 0; i < values.size(); ++i) {
  1757. auto& value = values.at(i);
  1758. if (value.is(Token::Type::Whitespace))
  1759. continue;
  1760. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  1761. params.append(value.token());
  1762. // Eat following comma and whitespace
  1763. while ((i + 1) < values.size()) {
  1764. auto& next = values.at(i + 1);
  1765. if (next.is(Token::Type::Whitespace))
  1766. i++;
  1767. else if (next.is(Token::Type::Comma))
  1768. break;
  1769. return {};
  1770. }
  1771. }
  1772. }
  1773. if (function.name().equals_ignoring_case("rgb")) {
  1774. if (params.size() != 3)
  1775. return {};
  1776. auto r_val = params[0];
  1777. auto g_val = params[1];
  1778. auto b_val = params[2];
  1779. if (r_val.is(Token::NumberType::Integer)
  1780. && g_val.is(Token::NumberType::Integer)
  1781. && b_val.is(Token::NumberType::Integer)) {
  1782. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1783. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1784. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1785. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value())
  1786. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value());
  1787. } else if (r_val.is(Token::Type::Percentage)
  1788. && g_val.is(Token::Type::Percentage)
  1789. && b_val.is(Token::Type::Percentage)) {
  1790. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1791. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1792. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1793. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value()) {
  1794. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1795. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1796. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1797. return Color(r, g, b);
  1798. }
  1799. }
  1800. } else if (function.name().equals_ignoring_case("rgba")) {
  1801. if (params.size() != 4)
  1802. return {};
  1803. auto r_val = params[0];
  1804. auto g_val = params[1];
  1805. auto b_val = params[2];
  1806. auto a_val = params[3];
  1807. if (r_val.is(Token::NumberType::Integer)
  1808. && g_val.is(Token::NumberType::Integer)
  1809. && b_val.is(Token::NumberType::Integer)
  1810. && a_val.is(Token::Type::Number)) {
  1811. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1812. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1813. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1814. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1815. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1816. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1817. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value(), a);
  1818. }
  1819. } else if (r_val.is(Token::Type::Percentage)
  1820. && g_val.is(Token::Type::Percentage)
  1821. && b_val.is(Token::Type::Percentage)
  1822. && a_val.is(Token::Type::Number)) {
  1823. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1824. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1825. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1826. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1827. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1828. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1829. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1830. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1831. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1832. return Color(r, g, b, a);
  1833. }
  1834. }
  1835. } else if (function.name().equals_ignoring_case("hsl")) {
  1836. if (params.size() != 3)
  1837. return {};
  1838. auto h_val = params[0];
  1839. auto s_val = params[1];
  1840. auto l_val = params[2];
  1841. if (h_val.is(Token::Type::Number)
  1842. && s_val.is(Token::Type::Percentage)
  1843. && l_val.is(Token::Type::Percentage)) {
  1844. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1845. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1846. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1847. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value()) {
  1848. float h = maybe_h.value();
  1849. float s = maybe_s.value() / 100.0f;
  1850. float l = maybe_l.value() / 100.0f;
  1851. return Color::from_hsl(h, s, l);
  1852. }
  1853. }
  1854. } else if (function.name().equals_ignoring_case("hsla")) {
  1855. if (params.size() != 4)
  1856. return {};
  1857. auto h_val = params[0];
  1858. auto s_val = params[1];
  1859. auto l_val = params[2];
  1860. auto a_val = params[3];
  1861. if (h_val.is(Token::Type::Number)
  1862. && s_val.is(Token::Type::Percentage)
  1863. && l_val.is(Token::Type::Percentage)
  1864. && a_val.is(Token::Type::Number)) {
  1865. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1866. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1867. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1868. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1869. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value() && maybe_a.has_value()) {
  1870. float h = maybe_h.value();
  1871. float s = maybe_s.value() / 100.0f;
  1872. float l = maybe_l.value() / 100.0f;
  1873. float a = maybe_a.value();
  1874. return Color::from_hsla(h, s, l, a);
  1875. }
  1876. }
  1877. }
  1878. return {};
  1879. }
  1880. return {};
  1881. }
  1882. RefPtr<StyleValue> Parser::parse_color_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1883. {
  1884. auto color = parse_color(context, component_value);
  1885. if (color.has_value())
  1886. return ColorStyleValue::create(color.value());
  1887. return {};
  1888. }
  1889. RefPtr<StyleValue> Parser::parse_string_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1890. {
  1891. if (component_value.is(Token::Type::String))
  1892. return StringStyleValue::create(component_value.token().string());
  1893. return {};
  1894. }
  1895. RefPtr<StyleValue> Parser::parse_image_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1896. {
  1897. auto url = parse_url_function(context, component_value);
  1898. if (url.has_value())
  1899. return ImageStyleValue::create(url.value(), context.document());
  1900. // FIXME: Handle gradients.
  1901. return {};
  1902. }
  1903. RefPtr<StyleValue> Parser::parse_background_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1904. {
  1905. RefPtr<StyleValue> background_color;
  1906. RefPtr<StyleValue> background_image;
  1907. RefPtr<StyleValue> repeat_x;
  1908. RefPtr<StyleValue> repeat_y;
  1909. // FIXME: Implement background-position.
  1910. // FIXME: Implement background-size.
  1911. // FIXME: Implement background-attachment.
  1912. // FIXME: Implement background-clip.
  1913. // FIXME: Implement background-origin.
  1914. for (size_t i = 0; i < component_values.size(); ++i) {
  1915. auto& part = component_values[i];
  1916. // FIXME: Handle multiple backgrounds, by returning a List of BackgroundStyleValues.
  1917. if (part.is(Token::Type::Comma)) {
  1918. dbgln("CSS Parser does not yet support multiple comma-separated values for background.");
  1919. break;
  1920. }
  1921. auto value = parse_css_value(context, part);
  1922. if (!value) {
  1923. return nullptr;
  1924. }
  1925. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  1926. if (background_color)
  1927. return nullptr;
  1928. background_color = value.release_nonnull();
  1929. continue;
  1930. }
  1931. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  1932. if (background_image)
  1933. return nullptr;
  1934. background_image = value.release_nonnull();
  1935. continue;
  1936. }
  1937. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  1938. if (repeat_x)
  1939. return nullptr;
  1940. auto value_id = value->to_identifier();
  1941. if (value_id == ValueID::RepeatX || value_id == ValueID::RepeatY) {
  1942. repeat_x = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat);
  1943. repeat_y = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat);
  1944. continue;
  1945. }
  1946. // Check following value, if it's also a repeat, set both.
  1947. if (i + 1 < component_values.size()) {
  1948. auto next_value = parse_css_value(context, component_values[i + 1]);
  1949. if (next_value && property_accepts_value(PropertyID::BackgroundRepeat, *next_value)) {
  1950. ++i;
  1951. repeat_x = value.release_nonnull();
  1952. repeat_y = next_value.release_nonnull();
  1953. continue;
  1954. }
  1955. }
  1956. auto repeat = value.release_nonnull();
  1957. repeat_x = repeat;
  1958. repeat_y = repeat;
  1959. continue;
  1960. }
  1961. return nullptr;
  1962. }
  1963. if (!background_color)
  1964. background_color = property_initial_value(PropertyID::BackgroundColor);
  1965. if (!background_image)
  1966. background_image = property_initial_value(PropertyID::BackgroundImage);
  1967. if (!repeat_x)
  1968. repeat_x = property_initial_value(PropertyID::BackgroundRepeatX);
  1969. if (!repeat_y)
  1970. repeat_y = property_initial_value(PropertyID::BackgroundRepeatY);
  1971. return BackgroundStyleValue::create(background_color.release_nonnull(), background_image.release_nonnull(), repeat_x.release_nonnull(), repeat_y.release_nonnull());
  1972. }
  1973. RefPtr<StyleValue> Parser::parse_background_image_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1974. {
  1975. if (component_values.size() == 1) {
  1976. auto maybe_value = parse_css_value(context, component_values.first());
  1977. if (!maybe_value)
  1978. return nullptr;
  1979. auto value = maybe_value.release_nonnull();
  1980. if (property_accepts_value(PropertyID::BackgroundImage, *value))
  1981. return value;
  1982. return nullptr;
  1983. }
  1984. // FIXME: Handle multiple sets of comma-separated values.
  1985. dbgln("CSS Parser does not yet support multiple comma-separated values for background-image.");
  1986. return nullptr;
  1987. }
  1988. RefPtr<StyleValue> Parser::parse_background_repeat_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1989. {
  1990. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  1991. auto value_id = value.to_identifier();
  1992. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  1993. };
  1994. if (component_values.size() == 1) {
  1995. auto maybe_value = parse_css_value(context, component_values.first());
  1996. if (!maybe_value)
  1997. return nullptr;
  1998. auto value = maybe_value.release_nonnull();
  1999. if (!property_accepts_value(PropertyID::BackgroundRepeat, *value))
  2000. return nullptr;
  2001. if (is_directional_repeat(value)) {
  2002. auto value_id = value->to_identifier();
  2003. return BackgroundRepeatStyleValue::create(
  2004. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat),
  2005. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat));
  2006. }
  2007. return BackgroundRepeatStyleValue::create(value, value);
  2008. }
  2009. if (component_values.size() == 2) {
  2010. auto maybe_x_value = parse_css_value(context, component_values[0]);
  2011. auto maybe_y_value = parse_css_value(context, component_values[1]);
  2012. if (!maybe_x_value || !maybe_y_value)
  2013. return nullptr;
  2014. auto x_value = maybe_x_value.release_nonnull();
  2015. auto y_value = maybe_y_value.release_nonnull();
  2016. if (!property_accepts_value(PropertyID::BackgroundRepeat, x_value) || !property_accepts_value(PropertyID::BackgroundRepeat, y_value))
  2017. return nullptr;
  2018. if (is_directional_repeat(x_value) || is_directional_repeat(y_value))
  2019. return nullptr;
  2020. return BackgroundRepeatStyleValue::create(x_value, y_value);
  2021. }
  2022. // FIXME: Handle multiple sets of comma-separated values.
  2023. dbgln("CSS Parser does not yet support multiple comma-separated values for background-repeat.");
  2024. return nullptr;
  2025. }
  2026. RefPtr<StyleValue> Parser::parse_border_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2027. {
  2028. if (component_values.size() > 3)
  2029. return nullptr;
  2030. RefPtr<StyleValue> border_width;
  2031. RefPtr<StyleValue> border_color;
  2032. RefPtr<StyleValue> border_style;
  2033. for (auto& part : component_values) {
  2034. auto value = parse_css_value(context, part);
  2035. if (!value)
  2036. return nullptr;
  2037. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  2038. if (border_width)
  2039. return nullptr;
  2040. border_width = value.release_nonnull();
  2041. continue;
  2042. }
  2043. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  2044. if (border_color)
  2045. return nullptr;
  2046. border_color = value.release_nonnull();
  2047. continue;
  2048. }
  2049. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  2050. if (border_style)
  2051. return nullptr;
  2052. border_style = value.release_nonnull();
  2053. continue;
  2054. }
  2055. return nullptr;
  2056. }
  2057. if (!border_width)
  2058. border_width = property_initial_value(PropertyID::BorderWidth);
  2059. if (!border_style)
  2060. border_style = property_initial_value(PropertyID::BorderStyle);
  2061. if (!border_color)
  2062. border_color = property_initial_value(PropertyID::BorderColor);
  2063. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  2064. }
  2065. RefPtr<StyleValue> Parser::parse_border_radius_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2066. {
  2067. if (component_values.size() == 2) {
  2068. auto horizontal = parse_length(context, component_values[0]);
  2069. auto vertical = parse_length(context, component_values[1]);
  2070. if (horizontal.has_value() && vertical.has_value())
  2071. return BorderRadiusStyleValue::create(horizontal.value(), vertical.value());
  2072. return nullptr;
  2073. }
  2074. if (component_values.size() == 1) {
  2075. auto radius = parse_length(context, component_values[0]);
  2076. if (radius.has_value())
  2077. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  2078. return nullptr;
  2079. }
  2080. return nullptr;
  2081. }
  2082. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2083. {
  2084. auto top_left = [&](Vector<Length>& radii) { return radii[0]; };
  2085. auto top_right = [&](Vector<Length>& radii) {
  2086. switch (radii.size()) {
  2087. case 4:
  2088. case 3:
  2089. case 2:
  2090. return radii[1];
  2091. case 1:
  2092. return radii[0];
  2093. default:
  2094. VERIFY_NOT_REACHED();
  2095. }
  2096. };
  2097. auto bottom_right = [&](Vector<Length>& radii) {
  2098. switch (radii.size()) {
  2099. case 4:
  2100. case 3:
  2101. return radii[2];
  2102. case 2:
  2103. case 1:
  2104. return radii[0];
  2105. default:
  2106. VERIFY_NOT_REACHED();
  2107. }
  2108. };
  2109. auto bottom_left = [&](Vector<Length>& radii) {
  2110. switch (radii.size()) {
  2111. case 4:
  2112. return radii[3];
  2113. case 3:
  2114. case 2:
  2115. return radii[1];
  2116. case 1:
  2117. return radii[0];
  2118. default:
  2119. VERIFY_NOT_REACHED();
  2120. }
  2121. };
  2122. Vector<Length> horizontal_radii;
  2123. Vector<Length> vertical_radii;
  2124. bool reading_vertical = false;
  2125. for (auto& value : component_values) {
  2126. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  2127. if (reading_vertical || horizontal_radii.is_empty())
  2128. return nullptr;
  2129. reading_vertical = true;
  2130. continue;
  2131. }
  2132. auto maybe_length = parse_length(context, value);
  2133. if (!maybe_length.has_value())
  2134. return nullptr;
  2135. if (reading_vertical) {
  2136. vertical_radii.append(maybe_length.value());
  2137. } else {
  2138. horizontal_radii.append(maybe_length.value());
  2139. }
  2140. }
  2141. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2142. || horizontal_radii.is_empty()
  2143. || (reading_vertical && vertical_radii.is_empty()))
  2144. return nullptr;
  2145. NonnullRefPtrVector<StyleValue> border_radii;
  2146. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2147. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  2148. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2149. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  2150. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2151. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  2152. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2153. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  2154. return StyleValueList::create(move(border_radii));
  2155. }
  2156. RefPtr<StyleValue> Parser::parse_box_shadow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2157. {
  2158. // "none"
  2159. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  2160. auto ident = parse_identifier_value(context, component_values.first());
  2161. if (ident && ident->to_identifier() == ValueID::None)
  2162. return ident;
  2163. }
  2164. // FIXME: Also support inset, spread-radius and multiple comma-separated box-shadows
  2165. Length offset_x {};
  2166. Length offset_y {};
  2167. Length blur_radius {};
  2168. Color color {};
  2169. if (component_values.size() < 3 || component_values.size() > 4)
  2170. return nullptr;
  2171. auto maybe_x = parse_length(context, component_values[0]);
  2172. if (!maybe_x.has_value())
  2173. return nullptr;
  2174. offset_x = maybe_x.value();
  2175. auto maybe_y = parse_length(context, component_values[1]);
  2176. if (!maybe_y.has_value())
  2177. return nullptr;
  2178. offset_y = maybe_y.value();
  2179. if (component_values.size() == 3) {
  2180. auto parsed_color = parse_color(context, component_values[2]);
  2181. if (!parsed_color.has_value())
  2182. return nullptr;
  2183. color = parsed_color.value();
  2184. } else if (component_values.size() == 4) {
  2185. auto maybe_blur_radius = parse_length(context, component_values[2]);
  2186. if (!maybe_blur_radius.has_value())
  2187. return nullptr;
  2188. blur_radius = maybe_blur_radius.value();
  2189. auto parsed_color = parse_color(context, component_values[3]);
  2190. if (!parsed_color.has_value())
  2191. return nullptr;
  2192. color = parsed_color.value();
  2193. }
  2194. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  2195. }
  2196. RefPtr<StyleValue> Parser::parse_flex_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2197. {
  2198. if (component_values.size() == 1) {
  2199. auto value = parse_css_value(context, component_values[0]);
  2200. if (!value)
  2201. return nullptr;
  2202. switch (value->to_identifier()) {
  2203. case ValueID::Auto: {
  2204. auto one = NumericStyleValue::create(1);
  2205. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  2206. }
  2207. case ValueID::None: {
  2208. auto zero = NumericStyleValue::create(0);
  2209. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  2210. }
  2211. default:
  2212. break;
  2213. }
  2214. }
  2215. RefPtr<StyleValue> flex_grow;
  2216. RefPtr<StyleValue> flex_shrink;
  2217. RefPtr<StyleValue> flex_basis;
  2218. for (size_t i = 0; i < component_values.size(); ++i) {
  2219. auto value = parse_css_value(context, component_values[i]);
  2220. if (!value)
  2221. return nullptr;
  2222. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  2223. if (value->has_number() && value->to_number() == 0) {
  2224. if (flex_grow && flex_shrink && !flex_basis) {
  2225. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  2226. continue;
  2227. }
  2228. }
  2229. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  2230. if (flex_grow)
  2231. return nullptr;
  2232. flex_grow = value.release_nonnull();
  2233. // Flex-shrink may optionally follow directly after.
  2234. if (i + 1 < component_values.size()) {
  2235. auto second_value = parse_css_value(context, component_values[i + 1]);
  2236. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  2237. flex_shrink = second_value.release_nonnull();
  2238. i++;
  2239. }
  2240. }
  2241. continue;
  2242. }
  2243. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  2244. if (flex_basis)
  2245. return nullptr;
  2246. flex_basis = value.release_nonnull();
  2247. continue;
  2248. }
  2249. return nullptr;
  2250. }
  2251. if (!flex_grow)
  2252. flex_grow = property_initial_value(PropertyID::FlexGrow);
  2253. if (!flex_shrink)
  2254. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  2255. if (!flex_basis)
  2256. flex_basis = property_initial_value(PropertyID::FlexBasis);
  2257. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  2258. }
  2259. RefPtr<StyleValue> Parser::parse_flex_flow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2260. {
  2261. if (component_values.size() > 2)
  2262. return nullptr;
  2263. RefPtr<StyleValue> flex_direction;
  2264. RefPtr<StyleValue> flex_wrap;
  2265. for (auto& part : component_values) {
  2266. auto value = parse_css_value(context, part);
  2267. if (!value)
  2268. return nullptr;
  2269. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  2270. if (flex_direction)
  2271. return nullptr;
  2272. flex_direction = value.release_nonnull();
  2273. continue;
  2274. }
  2275. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  2276. if (flex_wrap)
  2277. return nullptr;
  2278. flex_wrap = value.release_nonnull();
  2279. continue;
  2280. }
  2281. }
  2282. if (!flex_direction)
  2283. flex_direction = property_initial_value(PropertyID::FlexDirection);
  2284. if (!flex_wrap)
  2285. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  2286. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  2287. }
  2288. RefPtr<StyleValue> Parser::parse_font_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2289. {
  2290. RefPtr<StyleValue> font_style;
  2291. RefPtr<StyleValue> font_weight;
  2292. RefPtr<StyleValue> font_size;
  2293. RefPtr<StyleValue> line_height;
  2294. RefPtr<StyleValue> font_families;
  2295. // FIXME: Implement font-stretch and font-variant.
  2296. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  2297. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  2298. // So, we have to handle that separately.
  2299. int normal_count = 0;
  2300. for (size_t i = 0; i < component_values.size(); ++i) {
  2301. auto value = parse_css_value(context, component_values[i]);
  2302. if (!value)
  2303. return nullptr;
  2304. if (value->to_identifier() == ValueID::Normal) {
  2305. normal_count++;
  2306. continue;
  2307. }
  2308. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  2309. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  2310. if (font_style)
  2311. return nullptr;
  2312. font_style = value.release_nonnull();
  2313. continue;
  2314. }
  2315. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  2316. if (font_weight)
  2317. return nullptr;
  2318. font_weight = value.release_nonnull();
  2319. continue;
  2320. }
  2321. if (property_accepts_value(PropertyID::FontSize, *value)) {
  2322. if (font_size)
  2323. return nullptr;
  2324. font_size = value.release_nonnull();
  2325. // Consume `/ line-height` if present
  2326. if (i + 2 < component_values.size()) {
  2327. auto maybe_solidus = component_values[i + 1];
  2328. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  2329. auto maybe_line_height = parse_css_value(context, component_values[i + 2]);
  2330. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  2331. return nullptr;
  2332. line_height = maybe_line_height.release_nonnull();
  2333. i += 2;
  2334. }
  2335. }
  2336. // Consume font-families
  2337. auto maybe_font_families = parse_font_family_value(context, component_values, i + 1);
  2338. if (!maybe_font_families)
  2339. return nullptr;
  2340. font_families = maybe_font_families.release_nonnull();
  2341. break;
  2342. }
  2343. return nullptr;
  2344. }
  2345. // Since normal is the default value for all the properties that can have it, we don't have to actually
  2346. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  2347. // We just need to make sure we were not given more normals than will fit.
  2348. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  2349. if (unset_value_count < normal_count)
  2350. return nullptr;
  2351. if (!font_size || !font_families)
  2352. return nullptr;
  2353. if (!font_style)
  2354. font_style = property_initial_value(PropertyID::FontStyle);
  2355. if (!font_weight)
  2356. font_weight = property_initial_value(PropertyID::FontWeight);
  2357. if (!line_height)
  2358. line_height = property_initial_value(PropertyID::LineHeight);
  2359. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  2360. }
  2361. RefPtr<StyleValue> Parser::parse_font_family_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  2362. {
  2363. auto is_generic_font_family = [](ValueID identifier) -> bool {
  2364. switch (identifier) {
  2365. case ValueID::Cursive:
  2366. case ValueID::Fantasy:
  2367. case ValueID::Monospace:
  2368. case ValueID::Serif:
  2369. case ValueID::SansSerif:
  2370. case ValueID::UiMonospace:
  2371. case ValueID::UiRounded:
  2372. case ValueID::UiSerif:
  2373. case ValueID::UiSansSerif:
  2374. return true;
  2375. default:
  2376. return false;
  2377. }
  2378. };
  2379. auto is_comma_or_eof = [&](size_t i) -> bool {
  2380. if (i < component_values.size()) {
  2381. auto& maybe_comma = component_values[i];
  2382. if (!maybe_comma.is(Token::Type::Comma))
  2383. return false;
  2384. }
  2385. return true;
  2386. };
  2387. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  2388. // eg, these are equivalent:
  2389. // font-family: my cool font\!, serif;
  2390. // font-family: "my cool font!", serif;
  2391. NonnullRefPtrVector<StyleValue> font_families;
  2392. Vector<String> current_name_parts;
  2393. for (size_t i = start_index; i < component_values.size(); ++i) {
  2394. auto& part = component_values[i];
  2395. if (part.is(Token::Type::String)) {
  2396. // `font-family: my cool "font";` is invalid.
  2397. if (!current_name_parts.is_empty())
  2398. return nullptr;
  2399. if (!is_comma_or_eof(i + 1))
  2400. return nullptr;
  2401. font_families.append(StringStyleValue::create(part.token().string()));
  2402. i++;
  2403. continue;
  2404. }
  2405. if (part.is(Token::Type::Ident)) {
  2406. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  2407. auto maybe_ident = parse_css_value(context, part);
  2408. if (maybe_ident) {
  2409. // CSS-wide keywords are not allowed
  2410. if (maybe_ident->is_builtin())
  2411. return nullptr;
  2412. if (is_generic_font_family(maybe_ident->to_identifier())) {
  2413. // Can't have a generic-font-name as a token in an unquoted font name.
  2414. if (!current_name_parts.is_empty())
  2415. return nullptr;
  2416. if (!is_comma_or_eof(i + 1))
  2417. return nullptr;
  2418. font_families.append(maybe_ident.release_nonnull());
  2419. i++;
  2420. continue;
  2421. }
  2422. }
  2423. current_name_parts.append(part.token().ident());
  2424. continue;
  2425. }
  2426. if (part.is(Token::Type::Comma)) {
  2427. if (current_name_parts.is_empty())
  2428. return nullptr;
  2429. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2430. current_name_parts.clear();
  2431. // Can't have a trailing comma
  2432. if (i + 1 == component_values.size())
  2433. return nullptr;
  2434. continue;
  2435. }
  2436. }
  2437. if (!current_name_parts.is_empty()) {
  2438. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2439. current_name_parts.clear();
  2440. }
  2441. if (font_families.is_empty())
  2442. return nullptr;
  2443. return StyleValueList::create(move(font_families));
  2444. }
  2445. RefPtr<StyleValue> Parser::parse_list_style_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2446. {
  2447. if (component_values.size() > 3)
  2448. return nullptr;
  2449. RefPtr<StyleValue> list_position;
  2450. RefPtr<StyleValue> list_image;
  2451. RefPtr<StyleValue> list_type;
  2452. int found_nones = 0;
  2453. for (auto& part : component_values) {
  2454. auto value = parse_css_value(context, part);
  2455. if (!value)
  2456. return nullptr;
  2457. if (value->to_identifier() == ValueID::None) {
  2458. found_nones++;
  2459. continue;
  2460. }
  2461. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  2462. if (list_position)
  2463. return nullptr;
  2464. list_position = value.release_nonnull();
  2465. continue;
  2466. }
  2467. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  2468. if (list_image)
  2469. return nullptr;
  2470. list_image = value.release_nonnull();
  2471. continue;
  2472. }
  2473. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  2474. if (list_type)
  2475. return nullptr;
  2476. list_type = value.release_nonnull();
  2477. continue;
  2478. }
  2479. }
  2480. if (found_nones > 2)
  2481. return nullptr;
  2482. if (found_nones == 2) {
  2483. if (list_image || list_type)
  2484. return nullptr;
  2485. auto none = IdentifierStyleValue::create(ValueID::None);
  2486. list_image = none;
  2487. list_type = none;
  2488. } else if (found_nones == 1) {
  2489. if (list_image && list_type)
  2490. return nullptr;
  2491. auto none = IdentifierStyleValue::create(ValueID::None);
  2492. if (!list_image)
  2493. list_image = none;
  2494. if (!list_type)
  2495. list_type = none;
  2496. }
  2497. if (!list_position)
  2498. list_position = property_initial_value(PropertyID::ListStylePosition);
  2499. if (!list_image)
  2500. list_image = property_initial_value(PropertyID::ListStyleImage);
  2501. if (!list_type)
  2502. list_type = property_initial_value(PropertyID::ListStyleType);
  2503. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  2504. }
  2505. RefPtr<StyleValue> Parser::parse_overflow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2506. {
  2507. if (component_values.size() == 1) {
  2508. auto maybe_value = parse_css_value(context, component_values.first());
  2509. if (!maybe_value)
  2510. return nullptr;
  2511. auto value = maybe_value.release_nonnull();
  2512. if (property_accepts_value(PropertyID::Overflow, *value))
  2513. return OverflowStyleValue::create(value, value);
  2514. return nullptr;
  2515. }
  2516. if (component_values.size() == 2) {
  2517. auto maybe_x_value = parse_css_value(context, component_values[0]);
  2518. auto maybe_y_value = parse_css_value(context, component_values[1]);
  2519. if (!maybe_x_value || !maybe_y_value)
  2520. return nullptr;
  2521. auto x_value = maybe_x_value.release_nonnull();
  2522. auto y_value = maybe_y_value.release_nonnull();
  2523. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  2524. return nullptr;
  2525. }
  2526. return OverflowStyleValue::create(x_value, y_value);
  2527. }
  2528. return nullptr;
  2529. }
  2530. RefPtr<StyleValue> Parser::parse_text_decoration_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2531. {
  2532. if (component_values.size() > 3)
  2533. return nullptr;
  2534. RefPtr<StyleValue> decoration_line;
  2535. RefPtr<StyleValue> decoration_style;
  2536. RefPtr<StyleValue> decoration_color;
  2537. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  2538. for (auto& part : component_values) {
  2539. auto value = parse_css_value(context, part);
  2540. if (!value)
  2541. return nullptr;
  2542. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  2543. if (decoration_color)
  2544. return nullptr;
  2545. decoration_color = value.release_nonnull();
  2546. continue;
  2547. }
  2548. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  2549. if (decoration_line)
  2550. return nullptr;
  2551. decoration_line = value.release_nonnull();
  2552. continue;
  2553. }
  2554. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  2555. if (decoration_style)
  2556. return nullptr;
  2557. decoration_style = value.release_nonnull();
  2558. continue;
  2559. }
  2560. return nullptr;
  2561. }
  2562. if (!decoration_line)
  2563. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  2564. if (!decoration_style)
  2565. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  2566. if (!decoration_color)
  2567. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  2568. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  2569. }
  2570. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  2571. {
  2572. if (name == "translateY")
  2573. return CSS::TransformFunction::TranslateY;
  2574. return {};
  2575. }
  2576. RefPtr<StyleValue> Parser::parse_transform_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2577. {
  2578. NonnullRefPtrVector<StyleValue> transformations;
  2579. for (auto& part : component_values) {
  2580. if (!part.is_function())
  2581. return nullptr;
  2582. auto maybe_function = parse_transform_function_name(part.function().name());
  2583. if (!maybe_function.has_value())
  2584. return nullptr;
  2585. NonnullRefPtrVector<StyleValue> values;
  2586. for (auto& value : part.function().values()) {
  2587. if (value.is(Token::Type::Dimension)) {
  2588. auto maybe_length = parse_length(context, value);
  2589. if (!maybe_length.has_value())
  2590. return nullptr;
  2591. values.append(LengthStyleValue::create(maybe_length.release_value()));
  2592. } else if (value.is(Token::Type::Number)) {
  2593. auto number = parse_numeric_value(context, value);
  2594. values.append(number.release_nonnull());
  2595. } else {
  2596. dbgln("FIXME: Unsupported value type for transformation!");
  2597. return nullptr;
  2598. }
  2599. }
  2600. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  2601. }
  2602. return StyleValueList::create(move(transformations));
  2603. }
  2604. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2605. {
  2606. auto component_values = parse_as_list_of_component_values();
  2607. auto tokens = TokenStream(component_values);
  2608. auto parsed_value = parse_css_value(property_id, tokens);
  2609. if (parsed_value.is_error())
  2610. return {};
  2611. return parsed_value.release_value();
  2612. }
  2613. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2614. {
  2615. m_context.set_current_property_id(property_id);
  2616. Vector<StyleComponentValueRule> component_values;
  2617. while (tokens.has_next_token()) {
  2618. auto& token = tokens.next_token();
  2619. if (token.is(Token::Type::Semicolon)) {
  2620. tokens.reconsume_current_input_token();
  2621. break;
  2622. }
  2623. if (token.is(Token::Type::Whitespace))
  2624. continue;
  2625. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2626. return ParsingResult::IncludesIgnoredVendorPrefix;
  2627. component_values.append(token);
  2628. }
  2629. if (component_values.is_empty())
  2630. return ParsingResult::SyntaxError;
  2631. if (component_values.size() == 1) {
  2632. if (auto parsed_value = parse_builtin_value(m_context, component_values.first()))
  2633. return parsed_value.release_nonnull();
  2634. }
  2635. // Special-case property handling
  2636. switch (property_id) {
  2637. case PropertyID::Background:
  2638. if (auto parsed_value = parse_background_value(m_context, component_values))
  2639. return parsed_value.release_nonnull();
  2640. return ParsingResult::SyntaxError;
  2641. case PropertyID::BackgroundImage:
  2642. if (auto parsed_value = parse_background_image_value(m_context, component_values))
  2643. return parsed_value.release_nonnull();
  2644. return ParsingResult::SyntaxError;
  2645. case PropertyID::BackgroundRepeat:
  2646. if (auto parsed_value = parse_background_repeat_value(m_context, component_values))
  2647. return parsed_value.release_nonnull();
  2648. return ParsingResult::SyntaxError;
  2649. case PropertyID::Border:
  2650. case PropertyID::BorderBottom:
  2651. case PropertyID::BorderLeft:
  2652. case PropertyID::BorderRight:
  2653. case PropertyID::BorderTop:
  2654. if (auto parsed_value = parse_border_value(m_context, component_values))
  2655. return parsed_value.release_nonnull();
  2656. return ParsingResult::SyntaxError;
  2657. case PropertyID::BorderTopLeftRadius:
  2658. case PropertyID::BorderTopRightRadius:
  2659. case PropertyID::BorderBottomRightRadius:
  2660. case PropertyID::BorderBottomLeftRadius:
  2661. if (auto parsed_value = parse_border_radius_value(m_context, component_values))
  2662. return parsed_value.release_nonnull();
  2663. return ParsingResult::SyntaxError;
  2664. case PropertyID::BorderRadius:
  2665. if (auto parsed_value = parse_border_radius_shorthand_value(m_context, component_values))
  2666. return parsed_value.release_nonnull();
  2667. return ParsingResult::SyntaxError;
  2668. case PropertyID::BoxShadow:
  2669. if (auto parsed_value = parse_box_shadow_value(m_context, component_values))
  2670. return parsed_value.release_nonnull();
  2671. return ParsingResult::SyntaxError;
  2672. case PropertyID::Flex:
  2673. if (auto parsed_value = parse_flex_value(m_context, component_values))
  2674. return parsed_value.release_nonnull();
  2675. return ParsingResult::SyntaxError;
  2676. case PropertyID::FlexFlow:
  2677. if (auto parsed_value = parse_flex_flow_value(m_context, component_values))
  2678. return parsed_value.release_nonnull();
  2679. return ParsingResult::SyntaxError;
  2680. case PropertyID::Font:
  2681. if (auto parsed_value = parse_font_value(m_context, component_values))
  2682. return parsed_value.release_nonnull();
  2683. return ParsingResult::SyntaxError;
  2684. case PropertyID::FontFamily:
  2685. if (auto parsed_value = parse_font_family_value(m_context, component_values))
  2686. return parsed_value.release_nonnull();
  2687. return ParsingResult::SyntaxError;
  2688. case PropertyID::ListStyle:
  2689. if (auto parsed_value = parse_list_style_value(m_context, component_values))
  2690. return parsed_value.release_nonnull();
  2691. return ParsingResult::SyntaxError;
  2692. case PropertyID::Overflow:
  2693. if (auto parsed_value = parse_overflow_value(m_context, component_values))
  2694. return parsed_value.release_nonnull();
  2695. return ParsingResult::SyntaxError;
  2696. case PropertyID::TextDecoration:
  2697. if (auto parsed_value = parse_text_decoration_value(m_context, component_values))
  2698. return parsed_value.release_nonnull();
  2699. return ParsingResult::SyntaxError;
  2700. case PropertyID::Transform:
  2701. if (auto parsed_value = parse_transform_value(m_context, component_values))
  2702. return parsed_value.release_nonnull();
  2703. return ParsingResult::SyntaxError;
  2704. default:
  2705. break;
  2706. }
  2707. if (component_values.size() == 1) {
  2708. if (auto parsed_value = parse_css_value(m_context, component_values.first())) {
  2709. if (property_accepts_value(property_id, *parsed_value))
  2710. return parsed_value.release_nonnull();
  2711. }
  2712. return ParsingResult::SyntaxError;
  2713. }
  2714. // We have multiple values, so treat them as a StyleValueList.
  2715. if (property_maximum_value_count(property_id) > 1) {
  2716. NonnullRefPtrVector<StyleValue> parsed_values;
  2717. for (auto& component_value : component_values) {
  2718. auto parsed_value = parse_css_value(m_context, component_value);
  2719. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  2720. return ParsingResult::SyntaxError;
  2721. parsed_values.append(parsed_value.release_nonnull());
  2722. }
  2723. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  2724. return { StyleValueList::create(move(parsed_values)) };
  2725. }
  2726. return ParsingResult::SyntaxError;
  2727. }
  2728. RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  2729. {
  2730. if (auto builtin = parse_builtin_value(context, component_value))
  2731. return builtin;
  2732. if (auto dynamic = parse_dynamic_value(context, component_value))
  2733. return dynamic;
  2734. if (auto length = parse_length_value(context, component_value))
  2735. return length;
  2736. if (auto numeric = parse_numeric_value(context, component_value))
  2737. return numeric;
  2738. if (auto identifier = parse_identifier_value(context, component_value))
  2739. return identifier;
  2740. if (auto color = parse_color_value(context, component_value))
  2741. return color;
  2742. if (auto string = parse_string_value(context, component_value))
  2743. return string;
  2744. if (auto image = parse_image_value(context, component_value))
  2745. return image;
  2746. return {};
  2747. }
  2748. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  2749. {
  2750. int a = 0;
  2751. int b = 0;
  2752. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2753. if constexpr (CSS_PARSER_DEBUG) {
  2754. dbgln("Invalid An+B value:");
  2755. values.dump_all_tokens();
  2756. }
  2757. return {};
  2758. };
  2759. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2760. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  2761. values.skip_whitespace();
  2762. if (values.has_next_token()) {
  2763. if constexpr (CSS_PARSER_DEBUG) {
  2764. dbgln("Extra tokens at end of An+B value:");
  2765. values.dump_all_tokens();
  2766. }
  2767. return syntax_error();
  2768. } else {
  2769. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  2770. }
  2771. };
  2772. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  2773. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  2774. };
  2775. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  2776. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  2777. };
  2778. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  2779. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  2780. };
  2781. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  2782. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  2783. };
  2784. auto is_delim = [](StyleComponentValueRule const& value, StringView const& delim) -> bool {
  2785. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  2786. };
  2787. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  2788. if (!value.is(Token::Type::Dimension))
  2789. return false;
  2790. if (value.token().number_type() != Token::NumberType::Integer)
  2791. return false;
  2792. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  2793. return false;
  2794. return true;
  2795. };
  2796. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  2797. if (!value.is(Token::Type::Dimension))
  2798. return false;
  2799. if (value.token().number_type() != Token::NumberType::Integer)
  2800. return false;
  2801. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  2802. return false;
  2803. return true;
  2804. };
  2805. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  2806. if (!value.is(Token::Type::Dimension))
  2807. return false;
  2808. if (value.token().number_type() != Token::NumberType::Integer)
  2809. return false;
  2810. auto dimension_unit = value.token().dimension_unit();
  2811. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2812. return false;
  2813. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  2814. if (!is_ascii_digit(dimension_unit[i]))
  2815. return false;
  2816. }
  2817. return true;
  2818. };
  2819. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2820. if (!value.is(Token::Type::Ident))
  2821. return false;
  2822. auto ident = value.token().ident();
  2823. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2824. return false;
  2825. for (size_t i = 2; i < ident.length(); ++i) {
  2826. if (!is_ascii_digit(ident[i]))
  2827. return false;
  2828. }
  2829. return true;
  2830. };
  2831. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2832. if (!value.is(Token::Type::Ident))
  2833. return false;
  2834. auto ident = value.token().ident();
  2835. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  2836. return false;
  2837. for (size_t i = 3; i < ident.length(); ++i) {
  2838. if (!is_ascii_digit(ident[i]))
  2839. return false;
  2840. }
  2841. return true;
  2842. };
  2843. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  2844. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  2845. };
  2846. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2847. return is_integer(value) && value.token().is_integer_value_signed();
  2848. };
  2849. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2850. return is_integer(value) && !value.token().is_integer_value_signed();
  2851. };
  2852. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  2853. // Unfortunately these can't be in the same order as in the spec.
  2854. values.skip_whitespace();
  2855. auto& first_value = values.next_token();
  2856. // odd | even
  2857. if (first_value.is(Token::Type::Ident)) {
  2858. auto ident = first_value.token().ident();
  2859. if (ident.equals_ignoring_case("odd")) {
  2860. a = 2;
  2861. b = 1;
  2862. return make_return_value();
  2863. } else if (ident.equals_ignoring_case("even")) {
  2864. a = 2;
  2865. return make_return_value();
  2866. }
  2867. }
  2868. // <integer>
  2869. if (is_integer(first_value)) {
  2870. b = first_value.token().to_integer();
  2871. return make_return_value();
  2872. }
  2873. // <n-dimension>
  2874. // <n-dimension> <signed-integer>
  2875. // <n-dimension> ['+' | '-'] <signless-integer>
  2876. if (is_n_dimension(first_value)) {
  2877. a = first_value.token().dimension_value_int();
  2878. values.skip_whitespace();
  2879. auto& second_value = values.next_token();
  2880. if (second_value.is(Token::Type::EndOfFile)) {
  2881. // <n-dimension>
  2882. return make_return_value();
  2883. } else if (is_signed_integer(second_value)) {
  2884. // <n-dimension> <signed-integer>
  2885. b = second_value.token().to_integer();
  2886. return make_return_value();
  2887. }
  2888. values.skip_whitespace();
  2889. auto& third_value = values.next_token();
  2890. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2891. // <n-dimension> ['+' | '-'] <signless-integer>
  2892. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2893. return make_return_value();
  2894. }
  2895. return syntax_error();
  2896. }
  2897. // <ndash-dimension> <signless-integer>
  2898. if (is_ndash_dimension(first_value)) {
  2899. values.skip_whitespace();
  2900. auto& second_value = values.next_token();
  2901. if (is_signless_integer(second_value)) {
  2902. a = first_value.token().dimension_value_int();
  2903. b = -second_value.token().to_integer();
  2904. return make_return_value();
  2905. }
  2906. return syntax_error();
  2907. }
  2908. // <ndashdigit-dimension>
  2909. if (is_ndashdigit_dimension(first_value)) {
  2910. auto& dimension = first_value.token();
  2911. a = dimension.dimension_value_int();
  2912. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  2913. if (maybe_b.has_value()) {
  2914. b = maybe_b.value();
  2915. return make_return_value();
  2916. }
  2917. return syntax_error();
  2918. }
  2919. // <dashndashdigit-ident>
  2920. if (is_dashndashdigit_ident(first_value)) {
  2921. a = -1;
  2922. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  2923. if (maybe_b.has_value()) {
  2924. b = maybe_b.value();
  2925. return make_return_value();
  2926. }
  2927. return syntax_error();
  2928. }
  2929. // -n
  2930. // -n <signed-integer>
  2931. // -n ['+' | '-'] <signless-integer>
  2932. if (is_dashn(first_value)) {
  2933. a = -1;
  2934. values.skip_whitespace();
  2935. auto& second_value = values.next_token();
  2936. if (second_value.is(Token::Type::EndOfFile)) {
  2937. // -n
  2938. return make_return_value();
  2939. } else if (is_signed_integer(second_value)) {
  2940. // -n <signed-integer>
  2941. b = second_value.token().to_integer();
  2942. return make_return_value();
  2943. }
  2944. values.skip_whitespace();
  2945. auto& third_value = values.next_token();
  2946. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2947. // -n ['+' | '-'] <signless-integer>
  2948. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2949. return make_return_value();
  2950. }
  2951. return syntax_error();
  2952. }
  2953. // -n- <signless-integer>
  2954. if (is_dashndash(first_value)) {
  2955. values.skip_whitespace();
  2956. auto& second_value = values.next_token();
  2957. if (is_signless_integer(second_value)) {
  2958. a = -1;
  2959. b = -second_value.token().to_integer();
  2960. return make_return_value();
  2961. }
  2962. return syntax_error();
  2963. }
  2964. // All that's left now are these:
  2965. // '+'?† n
  2966. // '+'?† n <signed-integer>
  2967. // '+'?† n ['+' | '-'] <signless-integer>
  2968. // '+'?† n- <signless-integer>
  2969. // '+'?† <ndashdigit-ident>
  2970. // In all of these cases, the + is optional, and has no effect.
  2971. // So, we just skip the +, and carry on.
  2972. if (!is_delim(first_value, "+"sv)) {
  2973. values.reconsume_current_input_token();
  2974. // We do *not* skip whitespace here.
  2975. }
  2976. auto& first_after_plus = values.next_token();
  2977. // '+'?† n
  2978. // '+'?† n <signed-integer>
  2979. // '+'?† n ['+' | '-'] <signless-integer>
  2980. if (is_n(first_after_plus)) {
  2981. a = 1;
  2982. values.skip_whitespace();
  2983. auto& second_value = values.next_token();
  2984. if (second_value.is(Token::Type::EndOfFile)) {
  2985. // '+'?† n
  2986. return make_return_value();
  2987. } else if (is_signed_integer(second_value)) {
  2988. // '+'?† n <signed-integer>
  2989. b = second_value.token().to_integer();
  2990. return make_return_value();
  2991. }
  2992. values.skip_whitespace();
  2993. auto& third_value = values.next_token();
  2994. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2995. // '+'?† n ['+' | '-'] <signless-integer>
  2996. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2997. return make_return_value();
  2998. }
  2999. return syntax_error();
  3000. }
  3001. // '+'?† n- <signless-integer>
  3002. if (is_ndash(first_after_plus)) {
  3003. values.skip_whitespace();
  3004. auto& second_value = values.next_token();
  3005. if (is_signless_integer(second_value)) {
  3006. a = 1;
  3007. b = -second_value.token().to_integer();
  3008. return make_return_value();
  3009. }
  3010. return syntax_error();
  3011. }
  3012. // '+'?† <ndashdigit-ident>
  3013. if (is_ndashdigit_ident(first_after_plus)) {
  3014. a = 1;
  3015. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  3016. if (maybe_b.has_value()) {
  3017. b = maybe_b.value();
  3018. return make_return_value();
  3019. }
  3020. return syntax_error();
  3021. }
  3022. return syntax_error();
  3023. }
  3024. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(ParsingContext const& context, Vector<StyleComponentValueRule> const& values)
  3025. {
  3026. auto tokens = TokenStream(values);
  3027. return parse_calc_sum(context, tokens);
  3028. }
  3029. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3030. {
  3031. auto current_token = tokens.next_token();
  3032. if (current_token.is_block() && current_token.block().is_paren()) {
  3033. auto block_values = TokenStream(current_token.block().values());
  3034. auto parsed_calc_sum = parse_calc_sum(context, block_values);
  3035. if (!parsed_calc_sum)
  3036. return {};
  3037. return (CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() };
  3038. }
  3039. if (current_token.is(Token::Type::Number)) {
  3040. auto try_the_number = try_parse_float(current_token.token().number_string_value());
  3041. if (try_the_number.has_value())
  3042. return (CalculatedStyleValue::CalcValue) { try_the_number.value() };
  3043. return {};
  3044. }
  3045. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  3046. auto maybe_length = parse_length(context, current_token);
  3047. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  3048. return (CalculatedStyleValue::CalcValue) { maybe_length.value() };
  3049. return {};
  3050. }
  3051. return {};
  3052. }
  3053. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3054. {
  3055. // Note: The default value is not used or passed around.
  3056. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  3057. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  3058. CalculatedStyleValue::CalcNumberValue(0));
  3059. tokens.skip_whitespace();
  3060. auto& op_token = tokens.peek_token();
  3061. if (!op_token.is(Token::Type::Delim))
  3062. return nullptr;
  3063. auto op = op_token.token().delim();
  3064. if (op == "*"sv) {
  3065. tokens.next_token();
  3066. tokens.skip_whitespace();
  3067. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  3068. auto parsed_calc_value = parse_calc_value(context, tokens);
  3069. if (!parsed_calc_value.has_value())
  3070. return nullptr;
  3071. product_with_operator->value = { parsed_calc_value.release_value() };
  3072. } else if (op == "/"sv) {
  3073. tokens.next_token();
  3074. tokens.skip_whitespace();
  3075. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  3076. auto parsed_calc_number_value = parse_calc_number_value(context, tokens);
  3077. if (!parsed_calc_number_value.has_value())
  3078. return nullptr;
  3079. product_with_operator->value = { parsed_calc_number_value.release_value() };
  3080. } else {
  3081. return nullptr;
  3082. }
  3083. return product_with_operator;
  3084. }
  3085. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3086. {
  3087. // Note: The default value is not used or passed around.
  3088. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  3089. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  3090. CalculatedStyleValue::CalcNumberValue(0));
  3091. tokens.skip_whitespace();
  3092. auto& op_token = tokens.peek_token();
  3093. if (!op_token.is(Token::Type::Delim))
  3094. return nullptr;
  3095. auto op = op_token.token().delim();
  3096. if (op == "*"sv) {
  3097. tokens.next_token();
  3098. tokens.skip_whitespace();
  3099. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  3100. } else if (op == "/"sv) {
  3101. tokens.next_token();
  3102. tokens.skip_whitespace();
  3103. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  3104. } else {
  3105. return nullptr;
  3106. }
  3107. auto parsed_calc_value = parse_calc_number_value(context, tokens);
  3108. if (!parsed_calc_value.has_value())
  3109. return nullptr;
  3110. number_product_with_operator->value = parsed_calc_value.release_value();
  3111. return number_product_with_operator;
  3112. }
  3113. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3114. {
  3115. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  3116. CalculatedStyleValue::CalcNumberValue(0),
  3117. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  3118. auto first_calc_number_value_or_error = parse_calc_number_value(context, tokens);
  3119. if (!first_calc_number_value_or_error.has_value())
  3120. return nullptr;
  3121. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  3122. while (tokens.has_next_token()) {
  3123. auto number_product_with_operator = parse_calc_number_product_part_with_operator(context, tokens);
  3124. if (!number_product_with_operator)
  3125. break;
  3126. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  3127. }
  3128. return calc_number_product;
  3129. }
  3130. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3131. {
  3132. if (!(tokens.peek_token().is(Token::Type::Delim)
  3133. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3134. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3135. return nullptr;
  3136. auto& token = tokens.next_token();
  3137. tokens.skip_whitespace();
  3138. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  3139. auto delim = token.token().delim();
  3140. if (delim == "+"sv)
  3141. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  3142. else if (delim == "-"sv)
  3143. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  3144. else
  3145. return nullptr;
  3146. auto calc_number_product = parse_calc_number_product(context, tokens);
  3147. if (!calc_number_product)
  3148. return nullptr;
  3149. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  3150. }
  3151. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3152. {
  3153. auto first_calc_number_product_or_error = parse_calc_number_product(context, tokens);
  3154. if (!first_calc_number_product_or_error)
  3155. return nullptr;
  3156. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  3157. while (tokens.has_next_token()) {
  3158. auto calc_sum_part = parse_calc_number_sum_part_with_operator(context, tokens);
  3159. if (!calc_sum_part)
  3160. return nullptr;
  3161. additional.append(calc_sum_part.release_nonnull());
  3162. }
  3163. tokens.skip_whitespace();
  3164. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  3165. return calc_number_sum;
  3166. }
  3167. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3168. {
  3169. auto& first = tokens.peek_token();
  3170. if (first.is_block() && first.block().is_paren()) {
  3171. tokens.next_token();
  3172. auto block_values = TokenStream(first.block().values());
  3173. auto calc_number_sum = parse_calc_number_sum(context, block_values);
  3174. if (calc_number_sum)
  3175. return { calc_number_sum.release_nonnull() };
  3176. }
  3177. if (!first.is(Token::Type::Number))
  3178. return {};
  3179. tokens.next_token();
  3180. auto try_the_number = try_parse_float(first.token().number_string_value());
  3181. if (!try_the_number.has_value())
  3182. return {};
  3183. return try_the_number.value();
  3184. }
  3185. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3186. {
  3187. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  3188. CalculatedStyleValue::CalcValue(0),
  3189. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  3190. auto first_calc_value_or_error = parse_calc_value(context, tokens);
  3191. if (!first_calc_value_or_error.has_value())
  3192. return nullptr;
  3193. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  3194. while (tokens.has_next_token()) {
  3195. auto product_with_operator = parse_calc_product_part_with_operator(context, tokens);
  3196. if (!product_with_operator)
  3197. break;
  3198. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  3199. }
  3200. return calc_product;
  3201. }
  3202. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3203. {
  3204. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  3205. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  3206. if (!(tokens.peek_token().is(Token::Type::Delim)
  3207. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3208. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3209. return nullptr;
  3210. auto& token = tokens.next_token();
  3211. tokens.skip_whitespace();
  3212. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  3213. auto delim = token.token().delim();
  3214. if (delim == "+"sv)
  3215. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  3216. else if (delim == "-"sv)
  3217. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  3218. else
  3219. return nullptr;
  3220. auto calc_product = parse_calc_product(context, tokens);
  3221. if (!calc_product)
  3222. return nullptr;
  3223. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  3224. };
  3225. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3226. {
  3227. auto parsed_calc_product = parse_calc_product(context, tokens);
  3228. if (!parsed_calc_product)
  3229. return nullptr;
  3230. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  3231. while (tokens.has_next_token()) {
  3232. auto calc_sum_part = parse_calc_sum_part_with_operator(context, tokens);
  3233. if (!calc_sum_part)
  3234. return nullptr;
  3235. additional.append(calc_sum_part.release_nonnull());
  3236. }
  3237. tokens.skip_whitespace();
  3238. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  3239. }
  3240. bool Parser::has_ignored_vendor_prefix(StringView const& string)
  3241. {
  3242. if (!string.starts_with('-'))
  3243. return false;
  3244. if (string.starts_with("--"))
  3245. return false;
  3246. if (string.starts_with("-libweb-"))
  3247. return false;
  3248. return true;
  3249. }
  3250. }
  3251. namespace Web {
  3252. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView const& css)
  3253. {
  3254. if (css.is_empty())
  3255. return CSS::CSSStyleSheet::create({});
  3256. CSS::Parser parser(context, css);
  3257. return parser.parse_as_stylesheet();
  3258. }
  3259. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView const& css)
  3260. {
  3261. if (css.is_empty())
  3262. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  3263. CSS::Parser parser(context, css);
  3264. return parser.parse_as_list_of_declarations();
  3265. }
  3266. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView const& string, CSS::PropertyID property_id)
  3267. {
  3268. if (string.is_empty())
  3269. return {};
  3270. CSS::Parser parser(context, string);
  3271. return parser.parse_as_css_value(property_id);
  3272. }
  3273. RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
  3274. {
  3275. CSS::Parser parser(context, css_text);
  3276. return parser.parse_as_rule();
  3277. }
  3278. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView const& selector_text)
  3279. {
  3280. CSS::Parser parser(context, selector_text);
  3281. return parser.parse_as_selector();
  3282. }
  3283. RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView const& string)
  3284. {
  3285. CSS::Parser parser(context, string);
  3286. return parser.parse_as_media_query();
  3287. }
  3288. NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView const& string)
  3289. {
  3290. CSS::Parser parser(context, string);
  3291. return parser.parse_as_media_query_list();
  3292. }
  3293. RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const& context, StringView const& string)
  3294. {
  3295. if (string.is_empty())
  3296. return {};
  3297. CSS::Parser parser(context, string);
  3298. return parser.parse_as_supports();
  3299. }
  3300. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView const& string)
  3301. {
  3302. auto integer = string.to_int();
  3303. if (integer.has_value())
  3304. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  3305. // FIXME: The const_cast is a hack.
  3306. return parse_css_value(CSS::ParsingContext(const_cast<DOM::Document&>(document)), string);
  3307. }
  3308. }