Parser.cpp 127 KB

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