Parser.cpp 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316
  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. RefPtr<StyleValue> Parser::parse_background_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1441. {
  1442. RefPtr<StyleValue> background_color;
  1443. RefPtr<StyleValue> background_image;
  1444. RefPtr<StyleValue> repeat_x;
  1445. RefPtr<StyleValue> repeat_y;
  1446. // FIXME: Implement background-position.
  1447. // FIXME: Implement background-size.
  1448. // FIXME: Implement background-attachment.
  1449. // FIXME: Implement background-clip.
  1450. // FIXME: Implement background-origin.
  1451. for (size_t i = 0; i < component_values.size(); ++i) {
  1452. auto& part = component_values[i];
  1453. // FIXME: Handle multiple backgrounds, by returning a List of BackgroundStyleValues.
  1454. if (part.is(Token::Type::Comma)) {
  1455. dbgln("CSS Parser does not yet support multiple comma-separated values for background.");
  1456. break;
  1457. }
  1458. auto value = parse_css_value(context, part);
  1459. if (!value) {
  1460. return nullptr;
  1461. }
  1462. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  1463. if (background_color)
  1464. return nullptr;
  1465. background_color = value.release_nonnull();
  1466. continue;
  1467. }
  1468. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  1469. if (background_image)
  1470. return nullptr;
  1471. background_image = value.release_nonnull();
  1472. continue;
  1473. }
  1474. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  1475. if (repeat_x)
  1476. return nullptr;
  1477. auto value_id = value->to_identifier();
  1478. if (value_id == ValueID::RepeatX || value_id == ValueID::RepeatY) {
  1479. repeat_x = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat);
  1480. repeat_y = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat);
  1481. continue;
  1482. }
  1483. // Check following value, if it's also a repeat, set both.
  1484. if (i + 1 < component_values.size()) {
  1485. auto next_value = parse_css_value(context, component_values[i + 1]);
  1486. if (next_value && property_accepts_value(PropertyID::BackgroundRepeat, *next_value)) {
  1487. ++i;
  1488. repeat_x = value.release_nonnull();
  1489. repeat_y = next_value.release_nonnull();
  1490. continue;
  1491. }
  1492. }
  1493. auto repeat = value.release_nonnull();
  1494. repeat_x = repeat;
  1495. repeat_y = repeat;
  1496. continue;
  1497. }
  1498. return nullptr;
  1499. }
  1500. if (!background_color)
  1501. background_color = property_initial_value(PropertyID::BackgroundColor);
  1502. if (!background_image)
  1503. background_image = property_initial_value(PropertyID::BackgroundImage);
  1504. if (!repeat_x)
  1505. repeat_x = property_initial_value(PropertyID::BackgroundRepeatX);
  1506. if (!repeat_y)
  1507. repeat_y = property_initial_value(PropertyID::BackgroundRepeatY);
  1508. return BackgroundStyleValue::create(background_color.release_nonnull(), background_image.release_nonnull(), repeat_x.release_nonnull(), repeat_y.release_nonnull());
  1509. }
  1510. RefPtr<StyleValue> Parser::parse_background_image_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1511. {
  1512. if (component_values.size() == 1) {
  1513. auto maybe_value = parse_css_value(context, component_values.first());
  1514. if (!maybe_value)
  1515. return nullptr;
  1516. auto value = maybe_value.release_nonnull();
  1517. if (property_accepts_value(PropertyID::BackgroundImage, *value))
  1518. return value;
  1519. return nullptr;
  1520. }
  1521. // FIXME: Handle multiple sets of comma-separated values.
  1522. dbgln("CSS Parser does not yet support multiple comma-separated values for background-image.");
  1523. return nullptr;
  1524. }
  1525. RefPtr<StyleValue> Parser::parse_background_repeat_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1526. {
  1527. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  1528. auto value_id = value.to_identifier();
  1529. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  1530. };
  1531. if (component_values.size() == 1) {
  1532. auto maybe_value = parse_css_value(context, component_values.first());
  1533. if (!maybe_value)
  1534. return nullptr;
  1535. auto value = maybe_value.release_nonnull();
  1536. if (!property_accepts_value(PropertyID::BackgroundRepeat, *value))
  1537. return nullptr;
  1538. if (is_directional_repeat(value)) {
  1539. auto value_id = value->to_identifier();
  1540. return BackgroundRepeatStyleValue::create(
  1541. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat),
  1542. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat));
  1543. }
  1544. return BackgroundRepeatStyleValue::create(value, value);
  1545. }
  1546. if (component_values.size() == 2) {
  1547. auto maybe_x_value = parse_css_value(context, component_values[0]);
  1548. auto maybe_y_value = parse_css_value(context, component_values[1]);
  1549. if (!maybe_x_value || !maybe_y_value)
  1550. return nullptr;
  1551. auto x_value = maybe_x_value.release_nonnull();
  1552. auto y_value = maybe_y_value.release_nonnull();
  1553. if (!property_accepts_value(PropertyID::BackgroundRepeat, x_value) || !property_accepts_value(PropertyID::BackgroundRepeat, y_value))
  1554. return nullptr;
  1555. if (is_directional_repeat(x_value) || is_directional_repeat(y_value))
  1556. return nullptr;
  1557. return BackgroundRepeatStyleValue::create(x_value, y_value);
  1558. }
  1559. // FIXME: Handle multiple sets of comma-separated values.
  1560. dbgln("CSS Parser does not yet support multiple comma-separated values for background-repeat.");
  1561. return nullptr;
  1562. }
  1563. RefPtr<StyleValue> Parser::parse_border_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1564. {
  1565. if (component_values.size() > 3)
  1566. return nullptr;
  1567. RefPtr<StyleValue> border_width;
  1568. RefPtr<StyleValue> border_color;
  1569. RefPtr<StyleValue> border_style;
  1570. for (auto& part : component_values) {
  1571. auto value = parse_css_value(context, part);
  1572. if (!value)
  1573. return nullptr;
  1574. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  1575. if (border_width)
  1576. return nullptr;
  1577. border_width = value.release_nonnull();
  1578. continue;
  1579. }
  1580. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  1581. if (border_color)
  1582. return nullptr;
  1583. border_color = value.release_nonnull();
  1584. continue;
  1585. }
  1586. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  1587. if (border_style)
  1588. return nullptr;
  1589. border_style = value.release_nonnull();
  1590. continue;
  1591. }
  1592. return nullptr;
  1593. }
  1594. if (!border_width)
  1595. border_width = property_initial_value(PropertyID::BorderWidth);
  1596. if (!border_style)
  1597. border_style = property_initial_value(PropertyID::BorderStyle);
  1598. if (!border_color)
  1599. border_color = property_initial_value(PropertyID::BorderColor);
  1600. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  1601. }
  1602. RefPtr<StyleValue> Parser::parse_border_radius_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1603. {
  1604. if (component_values.size() == 2) {
  1605. auto horizontal = parse_length(context, component_values[0]);
  1606. auto vertical = parse_length(context, component_values[1]);
  1607. if (horizontal.has_value() && vertical.has_value())
  1608. return BorderRadiusStyleValue::create(horizontal.value(), vertical.value());
  1609. return nullptr;
  1610. }
  1611. if (component_values.size() == 1) {
  1612. auto radius = parse_length(context, component_values[0]);
  1613. if (radius.has_value())
  1614. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  1615. return nullptr;
  1616. }
  1617. return nullptr;
  1618. }
  1619. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1620. {
  1621. auto top_left = [&](Vector<Length>& radii) { return radii[0]; };
  1622. auto top_right = [&](Vector<Length>& radii) {
  1623. switch (radii.size()) {
  1624. case 4:
  1625. case 3:
  1626. case 2:
  1627. return radii[1];
  1628. case 1:
  1629. return radii[0];
  1630. default:
  1631. VERIFY_NOT_REACHED();
  1632. }
  1633. };
  1634. auto bottom_right = [&](Vector<Length>& radii) {
  1635. switch (radii.size()) {
  1636. case 4:
  1637. case 3:
  1638. return radii[2];
  1639. case 2:
  1640. case 1:
  1641. return radii[0];
  1642. default:
  1643. VERIFY_NOT_REACHED();
  1644. }
  1645. };
  1646. auto bottom_left = [&](Vector<Length>& radii) {
  1647. switch (radii.size()) {
  1648. case 4:
  1649. return radii[3];
  1650. case 3:
  1651. case 2:
  1652. return radii[1];
  1653. case 1:
  1654. return radii[0];
  1655. default:
  1656. VERIFY_NOT_REACHED();
  1657. }
  1658. };
  1659. Vector<Length> horizontal_radii;
  1660. Vector<Length> vertical_radii;
  1661. bool reading_vertical = false;
  1662. for (auto& value : component_values) {
  1663. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  1664. if (reading_vertical || horizontal_radii.is_empty())
  1665. return nullptr;
  1666. reading_vertical = true;
  1667. continue;
  1668. }
  1669. auto maybe_length = parse_length(context, value);
  1670. if (!maybe_length.has_value())
  1671. return nullptr;
  1672. if (reading_vertical) {
  1673. vertical_radii.append(maybe_length.value());
  1674. } else {
  1675. horizontal_radii.append(maybe_length.value());
  1676. }
  1677. }
  1678. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  1679. || horizontal_radii.is_empty()
  1680. || (reading_vertical && vertical_radii.is_empty()))
  1681. return nullptr;
  1682. NonnullRefPtrVector<StyleValue> border_radii;
  1683. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  1684. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  1685. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  1686. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  1687. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  1688. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  1689. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  1690. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  1691. return StyleValueList::create(move(border_radii));
  1692. }
  1693. RefPtr<StyleValue> Parser::parse_box_shadow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1694. {
  1695. // FIXME: Also support inset, spread-radius and multiple comma-seperated box-shadows
  1696. Length offset_x {};
  1697. Length offset_y {};
  1698. Length blur_radius {};
  1699. Color color {};
  1700. if (component_values.size() < 3 || component_values.size() > 4)
  1701. return nullptr;
  1702. auto maybe_x = parse_length(context, component_values[0]);
  1703. if (!maybe_x.has_value())
  1704. return nullptr;
  1705. offset_x = maybe_x.value();
  1706. auto maybe_y = parse_length(context, component_values[1]);
  1707. if (!maybe_y.has_value())
  1708. return nullptr;
  1709. offset_y = maybe_y.value();
  1710. if (component_values.size() == 3) {
  1711. auto parsed_color = parse_color(context, component_values[2]);
  1712. if (!parsed_color.has_value())
  1713. return nullptr;
  1714. color = parsed_color.value();
  1715. } else if (component_values.size() == 4) {
  1716. auto maybe_blur_radius = parse_length(context, component_values[2]);
  1717. if (!maybe_blur_radius.has_value())
  1718. return nullptr;
  1719. blur_radius = maybe_blur_radius.value();
  1720. auto parsed_color = parse_color(context, component_values[3]);
  1721. if (!parsed_color.has_value())
  1722. return nullptr;
  1723. color = parsed_color.value();
  1724. }
  1725. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  1726. }
  1727. RefPtr<StyleValue> Parser::parse_flex_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1728. {
  1729. if (component_values.size() == 1) {
  1730. auto value = parse_css_value(context, component_values[0]);
  1731. if (!value)
  1732. return nullptr;
  1733. switch (value->to_identifier()) {
  1734. case ValueID::Auto: {
  1735. auto one = NumericStyleValue::create(1);
  1736. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  1737. }
  1738. case ValueID::None: {
  1739. auto zero = NumericStyleValue::create(0);
  1740. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  1741. }
  1742. default:
  1743. break;
  1744. }
  1745. }
  1746. RefPtr<StyleValue> flex_grow;
  1747. RefPtr<StyleValue> flex_shrink;
  1748. RefPtr<StyleValue> flex_basis;
  1749. for (size_t i = 0; i < component_values.size(); ++i) {
  1750. auto value = parse_css_value(context, component_values[i]);
  1751. if (!value)
  1752. return nullptr;
  1753. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  1754. if (value->is_numeric() && static_cast<NumericStyleValue&>(*value).value() == 0) {
  1755. if (flex_grow && flex_shrink && !flex_basis) {
  1756. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  1757. continue;
  1758. }
  1759. }
  1760. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  1761. if (flex_grow)
  1762. return nullptr;
  1763. flex_grow = value.release_nonnull();
  1764. // Flex-shrink may optionally follow directly after.
  1765. if (i + 1 < component_values.size()) {
  1766. auto second_value = parse_css_value(context, component_values[i + 1]);
  1767. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  1768. flex_shrink = second_value.release_nonnull();
  1769. i++;
  1770. }
  1771. }
  1772. continue;
  1773. }
  1774. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  1775. if (flex_basis)
  1776. return nullptr;
  1777. flex_basis = value.release_nonnull();
  1778. continue;
  1779. }
  1780. return nullptr;
  1781. }
  1782. if (!flex_grow)
  1783. flex_grow = property_initial_value(PropertyID::FlexGrow);
  1784. if (!flex_shrink)
  1785. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  1786. if (!flex_basis)
  1787. flex_basis = property_initial_value(PropertyID::FlexBasis);
  1788. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  1789. }
  1790. RefPtr<StyleValue> Parser::parse_flex_flow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1791. {
  1792. if (component_values.size() > 2)
  1793. return nullptr;
  1794. RefPtr<StyleValue> flex_direction;
  1795. RefPtr<StyleValue> flex_wrap;
  1796. for (auto& part : component_values) {
  1797. auto value = parse_css_value(context, part);
  1798. if (!value)
  1799. return nullptr;
  1800. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  1801. if (flex_direction)
  1802. return nullptr;
  1803. flex_direction = value.release_nonnull();
  1804. continue;
  1805. }
  1806. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  1807. if (flex_wrap)
  1808. return nullptr;
  1809. flex_wrap = value.release_nonnull();
  1810. continue;
  1811. }
  1812. }
  1813. if (!flex_direction)
  1814. flex_direction = property_initial_value(PropertyID::FlexDirection);
  1815. if (!flex_wrap)
  1816. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  1817. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  1818. }
  1819. RefPtr<StyleValue> Parser::parse_font_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1820. {
  1821. RefPtr<StyleValue> font_style;
  1822. RefPtr<StyleValue> font_weight;
  1823. RefPtr<StyleValue> font_size;
  1824. RefPtr<StyleValue> line_height;
  1825. RefPtr<StyleValue> font_families;
  1826. // FIXME: Implement font-stretch and font-variant.
  1827. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  1828. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  1829. // So, we have to handle that separately.
  1830. int normal_count = 0;
  1831. for (size_t i = 0; i < component_values.size(); ++i) {
  1832. auto value = parse_css_value(context, component_values[i]);
  1833. if (!value)
  1834. return nullptr;
  1835. if (value->to_identifier() == ValueID::Normal) {
  1836. normal_count++;
  1837. continue;
  1838. }
  1839. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  1840. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  1841. if (font_style)
  1842. return nullptr;
  1843. font_style = value.release_nonnull();
  1844. continue;
  1845. }
  1846. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  1847. if (font_weight)
  1848. return nullptr;
  1849. font_weight = value.release_nonnull();
  1850. continue;
  1851. }
  1852. if (property_accepts_value(PropertyID::FontSize, *value)) {
  1853. if (font_size)
  1854. return nullptr;
  1855. font_size = value.release_nonnull();
  1856. // Consume `/ line-height` if present
  1857. if (i + 2 < component_values.size()) {
  1858. auto maybe_solidus = component_values[i + 1];
  1859. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  1860. auto maybe_line_height = parse_css_value(context, component_values[i + 2]);
  1861. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  1862. return nullptr;
  1863. line_height = maybe_line_height.release_nonnull();
  1864. i += 2;
  1865. }
  1866. }
  1867. // Consume font-families
  1868. auto maybe_font_families = parse_font_family_value(context, component_values, i + 1);
  1869. if (!maybe_font_families)
  1870. return nullptr;
  1871. font_families = maybe_font_families.release_nonnull();
  1872. break;
  1873. }
  1874. return nullptr;
  1875. }
  1876. // Since normal is the default value for all the properties that can have it, we don't have to actually
  1877. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  1878. // We just need to make sure we were not given more normals than will fit.
  1879. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  1880. if (unset_value_count < normal_count)
  1881. return nullptr;
  1882. if (!font_size || !font_families)
  1883. return nullptr;
  1884. if (!font_style)
  1885. font_style = property_initial_value(PropertyID::FontStyle);
  1886. if (!font_weight)
  1887. font_weight = property_initial_value(PropertyID::FontWeight);
  1888. if (!line_height)
  1889. line_height = property_initial_value(PropertyID::LineHeight);
  1890. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  1891. }
  1892. RefPtr<StyleValue> Parser::parse_font_family_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  1893. {
  1894. auto is_generic_font_family = [](ValueID identifier) -> bool {
  1895. switch (identifier) {
  1896. case ValueID::Cursive:
  1897. case ValueID::Fantasy:
  1898. case ValueID::Monospace:
  1899. case ValueID::Serif:
  1900. case ValueID::SansSerif:
  1901. case ValueID::UiMonospace:
  1902. case ValueID::UiRounded:
  1903. case ValueID::UiSerif:
  1904. case ValueID::UiSansSerif:
  1905. return true;
  1906. default:
  1907. return false;
  1908. }
  1909. };
  1910. auto is_comma_or_eof = [&](size_t i) -> bool {
  1911. if (i < component_values.size()) {
  1912. auto& maybe_comma = component_values[i];
  1913. if (!maybe_comma.is(Token::Type::Comma))
  1914. return false;
  1915. }
  1916. return true;
  1917. };
  1918. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  1919. // eg, these are equivalent:
  1920. // font-family: my cool font\!, serif;
  1921. // font-family: "my cool font!", serif;
  1922. NonnullRefPtrVector<StyleValue> font_families;
  1923. Vector<String> current_name_parts;
  1924. for (size_t i = start_index; i < component_values.size(); ++i) {
  1925. auto& part = component_values[i];
  1926. if (part.is(Token::Type::String)) {
  1927. // `font-family: my cool "font";` is invalid.
  1928. if (!current_name_parts.is_empty())
  1929. return nullptr;
  1930. if (!is_comma_or_eof(i + 1))
  1931. return nullptr;
  1932. font_families.append(StringStyleValue::create(part.token().string()));
  1933. i++;
  1934. continue;
  1935. }
  1936. if (part.is(Token::Type::Ident)) {
  1937. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  1938. auto maybe_ident = parse_css_value(context, part);
  1939. if (maybe_ident) {
  1940. // CSS-wide keywords are not allowed
  1941. if (maybe_ident->is_builtin())
  1942. return nullptr;
  1943. if (is_generic_font_family(maybe_ident->to_identifier())) {
  1944. // Can't have a generic-font-name as a token in an unquoted font name.
  1945. if (!current_name_parts.is_empty())
  1946. return nullptr;
  1947. if (!is_comma_or_eof(i + 1))
  1948. return nullptr;
  1949. font_families.append(maybe_ident.release_nonnull());
  1950. i++;
  1951. continue;
  1952. }
  1953. }
  1954. current_name_parts.append(part.token().ident());
  1955. continue;
  1956. }
  1957. if (part.is(Token::Type::Comma)) {
  1958. if (current_name_parts.is_empty())
  1959. return nullptr;
  1960. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  1961. current_name_parts.clear();
  1962. // Can't have a trailing comma
  1963. if (i + 1 == component_values.size())
  1964. return nullptr;
  1965. continue;
  1966. }
  1967. }
  1968. if (!current_name_parts.is_empty()) {
  1969. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  1970. current_name_parts.clear();
  1971. }
  1972. if (font_families.is_empty())
  1973. return nullptr;
  1974. return StyleValueList::create(move(font_families));
  1975. }
  1976. RefPtr<StyleValue> Parser::parse_list_style_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1977. {
  1978. if (component_values.size() > 3)
  1979. return nullptr;
  1980. RefPtr<StyleValue> list_position;
  1981. RefPtr<StyleValue> list_image;
  1982. RefPtr<StyleValue> list_type;
  1983. int found_nones = 0;
  1984. for (auto& part : component_values) {
  1985. auto value = parse_css_value(context, part);
  1986. if (!value)
  1987. return nullptr;
  1988. if (value->to_identifier() == ValueID::None) {
  1989. found_nones++;
  1990. continue;
  1991. }
  1992. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  1993. if (list_position)
  1994. return nullptr;
  1995. list_position = value.release_nonnull();
  1996. continue;
  1997. }
  1998. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  1999. if (list_image)
  2000. return nullptr;
  2001. list_image = value.release_nonnull();
  2002. continue;
  2003. }
  2004. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  2005. if (list_type)
  2006. return nullptr;
  2007. list_type = value.release_nonnull();
  2008. continue;
  2009. }
  2010. }
  2011. if (found_nones > 2)
  2012. return nullptr;
  2013. if (found_nones == 2) {
  2014. if (list_image || list_type)
  2015. return nullptr;
  2016. auto none = IdentifierStyleValue::create(ValueID::None);
  2017. list_image = none;
  2018. list_type = none;
  2019. } else if (found_nones == 1) {
  2020. if (list_image && list_type)
  2021. return nullptr;
  2022. auto none = IdentifierStyleValue::create(ValueID::None);
  2023. if (!list_image)
  2024. list_image = none;
  2025. if (!list_type)
  2026. list_type = none;
  2027. }
  2028. if (!list_position)
  2029. list_position = property_initial_value(PropertyID::ListStylePosition);
  2030. if (!list_image)
  2031. list_image = property_initial_value(PropertyID::ListStyleImage);
  2032. if (!list_type)
  2033. list_type = property_initial_value(PropertyID::ListStyleType);
  2034. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  2035. }
  2036. RefPtr<StyleValue> Parser::parse_overflow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2037. {
  2038. if (component_values.size() == 1) {
  2039. auto maybe_value = parse_css_value(context, component_values.first());
  2040. if (!maybe_value)
  2041. return nullptr;
  2042. auto value = maybe_value.release_nonnull();
  2043. if (property_accepts_value(PropertyID::Overflow, *value))
  2044. return OverflowStyleValue::create(value, value);
  2045. return nullptr;
  2046. }
  2047. if (component_values.size() == 2) {
  2048. auto maybe_x_value = parse_css_value(context, component_values[0]);
  2049. auto maybe_y_value = parse_css_value(context, component_values[1]);
  2050. if (!maybe_x_value || !maybe_y_value)
  2051. return nullptr;
  2052. auto x_value = maybe_x_value.release_nonnull();
  2053. auto y_value = maybe_y_value.release_nonnull();
  2054. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  2055. return nullptr;
  2056. }
  2057. return OverflowStyleValue::create(x_value, y_value);
  2058. }
  2059. return nullptr;
  2060. }
  2061. RefPtr<StyleValue> Parser::parse_text_decoration_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2062. {
  2063. if (component_values.size() > 3)
  2064. return nullptr;
  2065. RefPtr<StyleValue> decoration_line;
  2066. RefPtr<StyleValue> decoration_style;
  2067. RefPtr<StyleValue> decoration_color;
  2068. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  2069. for (auto& part : component_values) {
  2070. auto value = parse_css_value(context, part);
  2071. if (!value)
  2072. return nullptr;
  2073. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  2074. if (decoration_color)
  2075. return nullptr;
  2076. decoration_color = value.release_nonnull();
  2077. continue;
  2078. }
  2079. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  2080. if (decoration_line)
  2081. return nullptr;
  2082. decoration_line = value.release_nonnull();
  2083. continue;
  2084. }
  2085. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  2086. if (decoration_style)
  2087. return nullptr;
  2088. decoration_style = value.release_nonnull();
  2089. continue;
  2090. }
  2091. return nullptr;
  2092. }
  2093. if (!decoration_line)
  2094. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  2095. if (!decoration_style)
  2096. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  2097. if (!decoration_color)
  2098. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  2099. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  2100. }
  2101. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  2102. {
  2103. if (name == "translateY")
  2104. return CSS::TransformFunction::TranslateY;
  2105. return {};
  2106. }
  2107. RefPtr<StyleValue> Parser::parse_transform_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2108. {
  2109. NonnullRefPtrVector<StyleValue> transformations;
  2110. for (auto& part : component_values) {
  2111. if (!part.is_function())
  2112. return nullptr;
  2113. auto maybe_function = parse_transform_function_name(part.function().name());
  2114. if (!maybe_function.has_value())
  2115. return nullptr;
  2116. NonnullRefPtrVector<StyleValue> values;
  2117. for (auto& value : part.function().values()) {
  2118. if (value.is(Token::Type::Dimension)) {
  2119. auto maybe_length = parse_length(context, value);
  2120. if (!maybe_length.has_value())
  2121. return nullptr;
  2122. values.append(LengthStyleValue::create(maybe_length.release_value()));
  2123. } else if (value.is(Token::Type::Number)) {
  2124. auto number = parse_numeric_value(context, value);
  2125. values.append(number.release_nonnull());
  2126. } else {
  2127. dbgln("FIXME: Unsupported value type for transformation!");
  2128. return nullptr;
  2129. }
  2130. }
  2131. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  2132. }
  2133. return StyleValueList::create(move(transformations));
  2134. }
  2135. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2136. {
  2137. auto component_values = parse_as_list_of_component_values();
  2138. auto tokens = TokenStream(component_values);
  2139. auto parsed_value = parse_css_value(property_id, tokens);
  2140. if (parsed_value.is_error())
  2141. return {};
  2142. return parsed_value.release_value();
  2143. }
  2144. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2145. {
  2146. m_context.set_current_property_id(property_id);
  2147. Vector<StyleComponentValueRule> component_values;
  2148. while (tokens.has_next_token()) {
  2149. auto& token = tokens.next_token();
  2150. if (token.is(Token::Type::Semicolon)) {
  2151. tokens.reconsume_current_input_token();
  2152. break;
  2153. }
  2154. if (token.is(Token::Type::Whitespace))
  2155. continue;
  2156. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2157. return ParsingResult::IncludesIgnoredVendorPrefix;
  2158. component_values.append(token);
  2159. }
  2160. if (component_values.is_empty())
  2161. return ParsingResult::SyntaxError;
  2162. if (component_values.size() == 1) {
  2163. if (auto parsed_value = parse_builtin_value(m_context, component_values.first()))
  2164. return parsed_value.release_nonnull();
  2165. }
  2166. // Special-case property handling
  2167. switch (property_id) {
  2168. case PropertyID::Background:
  2169. if (auto parsed_value = parse_background_value(m_context, component_values))
  2170. return parsed_value.release_nonnull();
  2171. return ParsingResult::SyntaxError;
  2172. case PropertyID::BackgroundImage:
  2173. if (auto parsed_value = parse_background_image_value(m_context, component_values))
  2174. return parsed_value.release_nonnull();
  2175. return ParsingResult::SyntaxError;
  2176. case PropertyID::BackgroundRepeat:
  2177. if (auto parsed_value = parse_background_repeat_value(m_context, component_values))
  2178. return parsed_value.release_nonnull();
  2179. return ParsingResult::SyntaxError;
  2180. case PropertyID::Border:
  2181. case PropertyID::BorderBottom:
  2182. case PropertyID::BorderLeft:
  2183. case PropertyID::BorderRight:
  2184. case PropertyID::BorderTop:
  2185. if (auto parsed_value = parse_border_value(m_context, component_values))
  2186. return parsed_value.release_nonnull();
  2187. return ParsingResult::SyntaxError;
  2188. case PropertyID::BorderTopLeftRadius:
  2189. case PropertyID::BorderTopRightRadius:
  2190. case PropertyID::BorderBottomRightRadius:
  2191. case PropertyID::BorderBottomLeftRadius:
  2192. if (auto parsed_value = parse_border_radius_value(m_context, component_values))
  2193. return parsed_value.release_nonnull();
  2194. return ParsingResult::SyntaxError;
  2195. case PropertyID::BorderRadius:
  2196. if (auto parsed_value = parse_border_radius_shorthand_value(m_context, component_values))
  2197. return parsed_value.release_nonnull();
  2198. return ParsingResult::SyntaxError;
  2199. case PropertyID::BoxShadow:
  2200. if (auto parsed_value = parse_box_shadow_value(m_context, component_values))
  2201. return parsed_value.release_nonnull();
  2202. return ParsingResult::SyntaxError;
  2203. case PropertyID::Flex:
  2204. if (auto parsed_value = parse_flex_value(m_context, component_values))
  2205. return parsed_value.release_nonnull();
  2206. return ParsingResult::SyntaxError;
  2207. case PropertyID::FlexFlow:
  2208. if (auto parsed_value = parse_flex_flow_value(m_context, component_values))
  2209. return parsed_value.release_nonnull();
  2210. return ParsingResult::SyntaxError;
  2211. case PropertyID::Font:
  2212. if (auto parsed_value = parse_font_value(m_context, component_values))
  2213. return parsed_value.release_nonnull();
  2214. return ParsingResult::SyntaxError;
  2215. case PropertyID::FontFamily:
  2216. if (auto parsed_value = parse_font_family_value(m_context, component_values))
  2217. return parsed_value.release_nonnull();
  2218. return ParsingResult::SyntaxError;
  2219. case PropertyID::ListStyle:
  2220. if (auto parsed_value = parse_list_style_value(m_context, component_values))
  2221. return parsed_value.release_nonnull();
  2222. return ParsingResult::SyntaxError;
  2223. case PropertyID::Overflow:
  2224. if (auto parsed_value = parse_overflow_value(m_context, component_values))
  2225. return parsed_value.release_nonnull();
  2226. return ParsingResult::SyntaxError;
  2227. case PropertyID::TextDecoration:
  2228. if (auto parsed_value = parse_text_decoration_value(m_context, component_values))
  2229. return parsed_value.release_nonnull();
  2230. return ParsingResult::SyntaxError;
  2231. case PropertyID::Transform:
  2232. if (auto parsed_value = parse_transform_value(m_context, component_values))
  2233. return parsed_value.release_nonnull();
  2234. return ParsingResult::SyntaxError;
  2235. default:
  2236. break;
  2237. }
  2238. if (component_values.size() == 1) {
  2239. if (auto parsed_value = parse_css_value(m_context, component_values.first())) {
  2240. if (property_accepts_value(property_id, *parsed_value))
  2241. return parsed_value.release_nonnull();
  2242. }
  2243. return ParsingResult::SyntaxError;
  2244. }
  2245. // We have multiple values, so treat them as a StyleValueList.
  2246. if (property_maximum_value_count(property_id) > 1) {
  2247. NonnullRefPtrVector<StyleValue> parsed_values;
  2248. for (auto& component_value : component_values) {
  2249. auto parsed_value = parse_css_value(m_context, component_value);
  2250. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  2251. return ParsingResult::SyntaxError;
  2252. parsed_values.append(parsed_value.release_nonnull());
  2253. }
  2254. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  2255. return { StyleValueList::create(move(parsed_values)) };
  2256. }
  2257. return ParsingResult::SyntaxError;
  2258. }
  2259. RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  2260. {
  2261. if (auto builtin = parse_builtin_value(context, component_value))
  2262. return builtin;
  2263. if (auto dynamic = parse_dynamic_value(context, component_value))
  2264. return dynamic;
  2265. if (auto length = parse_length_value(context, component_value))
  2266. return length;
  2267. if (auto numeric = parse_numeric_value(context, component_value))
  2268. return numeric;
  2269. if (auto identifier = parse_identifier_value(context, component_value))
  2270. return identifier;
  2271. if (auto color = parse_color_value(context, component_value))
  2272. return color;
  2273. if (auto string = parse_string_value(context, component_value))
  2274. return string;
  2275. if (auto image = parse_image_value(context, component_value))
  2276. return image;
  2277. return {};
  2278. }
  2279. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  2280. {
  2281. int a = 0;
  2282. int b = 0;
  2283. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2284. if constexpr (CSS_PARSER_DEBUG) {
  2285. dbgln("Invalid An+B value:");
  2286. values.dump_all_tokens();
  2287. }
  2288. return {};
  2289. };
  2290. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2291. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  2292. values.skip_whitespace();
  2293. if (values.has_next_token()) {
  2294. if constexpr (CSS_PARSER_DEBUG) {
  2295. dbgln("Extra tokens at end of An+B value:");
  2296. values.dump_all_tokens();
  2297. }
  2298. return syntax_error();
  2299. } else {
  2300. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  2301. }
  2302. };
  2303. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  2304. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  2305. };
  2306. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  2307. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  2308. };
  2309. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  2310. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  2311. };
  2312. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  2313. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  2314. };
  2315. auto is_delim = [](StyleComponentValueRule const& value, StringView const& delim) -> bool {
  2316. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  2317. };
  2318. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  2319. if (!value.is(Token::Type::Dimension))
  2320. return false;
  2321. if (value.token().number_type() != Token::NumberType::Integer)
  2322. return false;
  2323. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  2324. return false;
  2325. return true;
  2326. };
  2327. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  2328. if (!value.is(Token::Type::Dimension))
  2329. return false;
  2330. if (value.token().number_type() != Token::NumberType::Integer)
  2331. return false;
  2332. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  2333. return false;
  2334. return true;
  2335. };
  2336. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  2337. if (!value.is(Token::Type::Dimension))
  2338. return false;
  2339. if (value.token().number_type() != Token::NumberType::Integer)
  2340. return false;
  2341. auto dimension_unit = value.token().dimension_unit();
  2342. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2343. return false;
  2344. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  2345. if (!is_ascii_digit(dimension_unit[i]))
  2346. return false;
  2347. }
  2348. return true;
  2349. };
  2350. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2351. if (!value.is(Token::Type::Ident))
  2352. return false;
  2353. auto ident = value.token().ident();
  2354. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2355. return false;
  2356. for (size_t i = 2; i < ident.length(); ++i) {
  2357. if (!is_ascii_digit(ident[i]))
  2358. return false;
  2359. }
  2360. return true;
  2361. };
  2362. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2363. if (!value.is(Token::Type::Ident))
  2364. return false;
  2365. auto ident = value.token().ident();
  2366. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  2367. return false;
  2368. for (size_t i = 3; i < ident.length(); ++i) {
  2369. if (!is_ascii_digit(ident[i]))
  2370. return false;
  2371. }
  2372. return true;
  2373. };
  2374. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  2375. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  2376. };
  2377. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2378. return is_integer(value) && value.token().is_integer_value_signed();
  2379. };
  2380. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2381. return is_integer(value) && !value.token().is_integer_value_signed();
  2382. };
  2383. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  2384. // Unfortunately these can't be in the same order as in the spec.
  2385. values.skip_whitespace();
  2386. auto& first_value = values.next_token();
  2387. // odd | even
  2388. if (first_value.is(Token::Type::Ident)) {
  2389. auto ident = first_value.token().ident();
  2390. if (ident.equals_ignoring_case("odd")) {
  2391. a = 2;
  2392. b = 1;
  2393. return make_return_value();
  2394. } else if (ident.equals_ignoring_case("even")) {
  2395. a = 2;
  2396. return make_return_value();
  2397. }
  2398. }
  2399. // <integer>
  2400. if (is_integer(first_value)) {
  2401. b = first_value.token().to_integer();
  2402. return make_return_value();
  2403. }
  2404. // <n-dimension>
  2405. // <n-dimension> <signed-integer>
  2406. // <n-dimension> ['+' | '-'] <signless-integer>
  2407. if (is_n_dimension(first_value)) {
  2408. a = first_value.token().dimension_value_int();
  2409. values.skip_whitespace();
  2410. auto& second_value = values.next_token();
  2411. if (second_value.is(Token::Type::EndOfFile)) {
  2412. // <n-dimension>
  2413. return make_return_value();
  2414. } else if (is_signed_integer(second_value)) {
  2415. // <n-dimension> <signed-integer>
  2416. b = second_value.token().to_integer();
  2417. return make_return_value();
  2418. }
  2419. values.skip_whitespace();
  2420. auto& third_value = values.next_token();
  2421. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2422. // <n-dimension> ['+' | '-'] <signless-integer>
  2423. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2424. return make_return_value();
  2425. }
  2426. return syntax_error();
  2427. }
  2428. // <ndash-dimension> <signless-integer>
  2429. if (is_ndash_dimension(first_value)) {
  2430. values.skip_whitespace();
  2431. auto& second_value = values.next_token();
  2432. if (is_signless_integer(second_value)) {
  2433. a = first_value.token().dimension_value_int();
  2434. b = -second_value.token().to_integer();
  2435. return make_return_value();
  2436. }
  2437. return syntax_error();
  2438. }
  2439. // <ndashdigit-dimension>
  2440. if (is_ndashdigit_dimension(first_value)) {
  2441. auto& dimension = first_value.token();
  2442. a = dimension.dimension_value_int();
  2443. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  2444. if (maybe_b.has_value()) {
  2445. b = maybe_b.value();
  2446. return make_return_value();
  2447. }
  2448. return syntax_error();
  2449. }
  2450. // <dashndashdigit-ident>
  2451. if (is_dashndashdigit_ident(first_value)) {
  2452. a = -1;
  2453. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  2454. if (maybe_b.has_value()) {
  2455. b = maybe_b.value();
  2456. return make_return_value();
  2457. }
  2458. return syntax_error();
  2459. }
  2460. // -n
  2461. // -n <signed-integer>
  2462. // -n ['+' | '-'] <signless-integer>
  2463. if (is_dashn(first_value)) {
  2464. a = -1;
  2465. values.skip_whitespace();
  2466. auto& second_value = values.next_token();
  2467. if (second_value.is(Token::Type::EndOfFile)) {
  2468. // -n
  2469. return make_return_value();
  2470. } else if (is_signed_integer(second_value)) {
  2471. // -n <signed-integer>
  2472. b = second_value.token().to_integer();
  2473. return make_return_value();
  2474. }
  2475. values.skip_whitespace();
  2476. auto& third_value = values.next_token();
  2477. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2478. // -n ['+' | '-'] <signless-integer>
  2479. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2480. return make_return_value();
  2481. }
  2482. return syntax_error();
  2483. }
  2484. // -n- <signless-integer>
  2485. if (is_dashndash(first_value)) {
  2486. values.skip_whitespace();
  2487. auto& second_value = values.next_token();
  2488. if (is_signless_integer(second_value)) {
  2489. a = -1;
  2490. b = -second_value.token().to_integer();
  2491. return make_return_value();
  2492. }
  2493. return syntax_error();
  2494. }
  2495. // All that's left now are these:
  2496. // '+'?† n
  2497. // '+'?† n <signed-integer>
  2498. // '+'?† n ['+' | '-'] <signless-integer>
  2499. // '+'?† n- <signless-integer>
  2500. // '+'?† <ndashdigit-ident>
  2501. // In all of these cases, the + is optional, and has no effect.
  2502. // So, we just skip the +, and carry on.
  2503. if (!is_delim(first_value, "+"sv)) {
  2504. values.reconsume_current_input_token();
  2505. // We do *not* skip whitespace here.
  2506. }
  2507. auto& first_after_plus = values.next_token();
  2508. // '+'?† n
  2509. // '+'?† n <signed-integer>
  2510. // '+'?† n ['+' | '-'] <signless-integer>
  2511. if (is_n(first_after_plus)) {
  2512. a = 1;
  2513. values.skip_whitespace();
  2514. auto& second_value = values.next_token();
  2515. if (second_value.is(Token::Type::EndOfFile)) {
  2516. // '+'?† n
  2517. return make_return_value();
  2518. } else if (is_signed_integer(second_value)) {
  2519. // '+'?† n <signed-integer>
  2520. b = second_value.token().to_integer();
  2521. return make_return_value();
  2522. }
  2523. values.skip_whitespace();
  2524. auto& third_value = values.next_token();
  2525. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2526. // '+'?† n ['+' | '-'] <signless-integer>
  2527. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2528. return make_return_value();
  2529. }
  2530. return syntax_error();
  2531. }
  2532. // '+'?† n- <signless-integer>
  2533. if (is_ndash(first_after_plus)) {
  2534. values.skip_whitespace();
  2535. auto& second_value = values.next_token();
  2536. if (is_signless_integer(second_value)) {
  2537. a = 1;
  2538. b = -second_value.token().to_integer();
  2539. return make_return_value();
  2540. }
  2541. return syntax_error();
  2542. }
  2543. // '+'?† <ndashdigit-ident>
  2544. if (is_ndashdigit_ident(first_after_plus)) {
  2545. a = 1;
  2546. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  2547. if (maybe_b.has_value()) {
  2548. b = maybe_b.value();
  2549. return make_return_value();
  2550. }
  2551. return syntax_error();
  2552. }
  2553. return syntax_error();
  2554. }
  2555. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(ParsingContext const& context, Vector<StyleComponentValueRule> const& values)
  2556. {
  2557. auto tokens = TokenStream(values);
  2558. return parse_calc_sum(context, tokens);
  2559. }
  2560. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2561. {
  2562. auto current_token = tokens.next_token();
  2563. if (current_token.is_block() && current_token.block().is_paren()) {
  2564. auto block_values = TokenStream(current_token.block().values());
  2565. auto parsed_calc_sum = parse_calc_sum(context, block_values);
  2566. if (!parsed_calc_sum)
  2567. return {};
  2568. return (CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() };
  2569. }
  2570. if (current_token.is(Token::Type::Number)) {
  2571. auto try_the_number = try_parse_float(current_token.token().number_string_value());
  2572. if (try_the_number.has_value())
  2573. return (CalculatedStyleValue::CalcValue) { try_the_number.value() };
  2574. return {};
  2575. }
  2576. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  2577. auto maybe_length = parse_length(context, current_token);
  2578. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  2579. return (CalculatedStyleValue::CalcValue) { maybe_length.value() };
  2580. return {};
  2581. }
  2582. return {};
  2583. }
  2584. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2585. {
  2586. // Note: The default value is not used or passed around.
  2587. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  2588. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  2589. CalculatedStyleValue::CalcNumberValue(0));
  2590. tokens.skip_whitespace();
  2591. auto& op_token = tokens.peek_token();
  2592. if (!op_token.is(Token::Type::Delim))
  2593. return nullptr;
  2594. auto op = op_token.token().delim();
  2595. if (op == "*"sv) {
  2596. tokens.next_token();
  2597. tokens.skip_whitespace();
  2598. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  2599. auto parsed_calc_value = parse_calc_value(context, tokens);
  2600. if (!parsed_calc_value.has_value())
  2601. return nullptr;
  2602. product_with_operator->value = { parsed_calc_value.release_value() };
  2603. } else if (op == "/"sv) {
  2604. tokens.next_token();
  2605. tokens.skip_whitespace();
  2606. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  2607. auto parsed_calc_number_value = parse_calc_number_value(context, tokens);
  2608. if (!parsed_calc_number_value.has_value())
  2609. return nullptr;
  2610. product_with_operator->value = { parsed_calc_number_value.release_value() };
  2611. } else {
  2612. return nullptr;
  2613. }
  2614. return product_with_operator;
  2615. }
  2616. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2617. {
  2618. // Note: The default value is not used or passed around.
  2619. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  2620. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  2621. CalculatedStyleValue::CalcNumberValue(0));
  2622. tokens.skip_whitespace();
  2623. auto& op_token = tokens.peek_token();
  2624. if (!op_token.is(Token::Type::Delim))
  2625. return nullptr;
  2626. auto op = op_token.token().delim();
  2627. if (op == "*"sv) {
  2628. tokens.next_token();
  2629. tokens.skip_whitespace();
  2630. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  2631. } else if (op == "/"sv) {
  2632. tokens.next_token();
  2633. tokens.skip_whitespace();
  2634. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  2635. } else {
  2636. return nullptr;
  2637. }
  2638. auto parsed_calc_value = parse_calc_number_value(context, tokens);
  2639. if (!parsed_calc_value.has_value())
  2640. return nullptr;
  2641. number_product_with_operator->value = parsed_calc_value.release_value();
  2642. return number_product_with_operator;
  2643. }
  2644. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2645. {
  2646. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  2647. CalculatedStyleValue::CalcNumberValue(0),
  2648. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  2649. auto first_calc_number_value_or_error = parse_calc_number_value(context, tokens);
  2650. if (!first_calc_number_value_or_error.has_value())
  2651. return nullptr;
  2652. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  2653. while (tokens.has_next_token()) {
  2654. auto number_product_with_operator = parse_calc_number_product_part_with_operator(context, tokens);
  2655. if (!number_product_with_operator)
  2656. break;
  2657. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  2658. }
  2659. return calc_number_product;
  2660. }
  2661. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2662. {
  2663. if (!(tokens.peek_token().is(Token::Type::Delim)
  2664. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2665. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2666. return nullptr;
  2667. auto& token = tokens.next_token();
  2668. tokens.skip_whitespace();
  2669. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  2670. auto delim = token.token().delim();
  2671. if (delim == "+"sv)
  2672. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  2673. else if (delim == "-"sv)
  2674. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  2675. else
  2676. return nullptr;
  2677. auto calc_number_product = parse_calc_number_product(context, tokens);
  2678. if (!calc_number_product)
  2679. return nullptr;
  2680. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  2681. }
  2682. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2683. {
  2684. auto first_calc_number_product_or_error = parse_calc_number_product(context, tokens);
  2685. if (!first_calc_number_product_or_error)
  2686. return nullptr;
  2687. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  2688. while (tokens.has_next_token()) {
  2689. auto calc_sum_part = parse_calc_number_sum_part_with_operator(context, tokens);
  2690. if (!calc_sum_part)
  2691. return nullptr;
  2692. additional.append(calc_sum_part.release_nonnull());
  2693. }
  2694. tokens.skip_whitespace();
  2695. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  2696. return calc_number_sum;
  2697. }
  2698. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2699. {
  2700. auto& first = tokens.peek_token();
  2701. if (first.is_block() && first.block().is_paren()) {
  2702. tokens.next_token();
  2703. auto block_values = TokenStream(first.block().values());
  2704. auto calc_number_sum = parse_calc_number_sum(context, block_values);
  2705. if (calc_number_sum)
  2706. return { calc_number_sum.release_nonnull() };
  2707. }
  2708. if (!first.is(Token::Type::Number))
  2709. return {};
  2710. tokens.next_token();
  2711. auto try_the_number = try_parse_float(first.token().number_string_value());
  2712. if (!try_the_number.has_value())
  2713. return {};
  2714. return try_the_number.value();
  2715. }
  2716. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2717. {
  2718. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  2719. CalculatedStyleValue::CalcValue(0),
  2720. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  2721. auto first_calc_value_or_error = parse_calc_value(context, tokens);
  2722. if (!first_calc_value_or_error.has_value())
  2723. return nullptr;
  2724. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  2725. while (tokens.has_next_token()) {
  2726. auto product_with_operator = parse_calc_product_part_with_operator(context, tokens);
  2727. if (!product_with_operator)
  2728. break;
  2729. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  2730. }
  2731. return calc_product;
  2732. }
  2733. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2734. {
  2735. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  2736. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  2737. if (!(tokens.peek_token().is(Token::Type::Delim)
  2738. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2739. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2740. return nullptr;
  2741. auto& token = tokens.next_token();
  2742. tokens.skip_whitespace();
  2743. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  2744. auto delim = token.token().delim();
  2745. if (delim == "+"sv)
  2746. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  2747. else if (delim == "-"sv)
  2748. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  2749. else
  2750. return nullptr;
  2751. auto calc_product = parse_calc_product(context, tokens);
  2752. if (!calc_product)
  2753. return nullptr;
  2754. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  2755. };
  2756. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2757. {
  2758. auto parsed_calc_product = parse_calc_product(context, tokens);
  2759. if (!parsed_calc_product)
  2760. return nullptr;
  2761. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  2762. while (tokens.has_next_token()) {
  2763. auto calc_sum_part = parse_calc_sum_part_with_operator(context, tokens);
  2764. if (!calc_sum_part)
  2765. return nullptr;
  2766. additional.append(calc_sum_part.release_nonnull());
  2767. }
  2768. tokens.skip_whitespace();
  2769. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  2770. }
  2771. bool Parser::has_ignored_vendor_prefix(StringView const& string)
  2772. {
  2773. if (!string.starts_with('-'))
  2774. return false;
  2775. if (string.starts_with("--"))
  2776. return false;
  2777. if (string.starts_with("-libweb-"))
  2778. return false;
  2779. return true;
  2780. }
  2781. }
  2782. namespace Web {
  2783. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView const& css)
  2784. {
  2785. if (css.is_empty())
  2786. return CSS::CSSStyleSheet::create({});
  2787. CSS::Parser parser(context, css);
  2788. return parser.parse_as_stylesheet();
  2789. }
  2790. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView const& css)
  2791. {
  2792. if (css.is_empty())
  2793. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  2794. CSS::Parser parser(context, css);
  2795. return parser.parse_as_list_of_declarations();
  2796. }
  2797. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView const& string, CSS::PropertyID property_id)
  2798. {
  2799. if (string.is_empty())
  2800. return {};
  2801. CSS::Parser parser(context, string);
  2802. return parser.parse_as_css_value(property_id);
  2803. }
  2804. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView const& selector_text)
  2805. {
  2806. CSS::Parser parser(context, selector_text);
  2807. return parser.parse_as_selector();
  2808. }
  2809. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView const& string)
  2810. {
  2811. auto integer = string.to_int();
  2812. if (integer.has_value())
  2813. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  2814. // FIXME: The const_cast is a hack.
  2815. return parse_css_value(CSS::ParsingContext(const_cast<DOM::Document&>(document)), string);
  2816. }
  2817. }