Parser.cpp 124 KB

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