Parser.cpp 122 KB

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