Parser.cpp 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609
  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. return {};
  1056. }
  1057. if (property_id == PropertyID::Custom) {
  1058. return StyleProperty { property_id, value.release_value(), declaration.m_name, declaration.m_important };
  1059. } else {
  1060. return StyleProperty { property_id, value.release_value(), {}, declaration.m_important };
  1061. }
  1062. }
  1063. Optional<float> Parser::try_parse_float(StringView string)
  1064. {
  1065. // FIXME: This is copied from DeprecatedCSSParser, so may not be to spec.
  1066. const char* str = string.characters_without_null_termination();
  1067. size_t len = string.length();
  1068. size_t weight = 1;
  1069. int exp_val = 0;
  1070. float value = 0.0f;
  1071. float fraction = 0.0f;
  1072. bool has_sign = false;
  1073. bool is_negative = false;
  1074. bool is_fractional = false;
  1075. bool is_scientific = false;
  1076. if (str[0] == '-') {
  1077. is_negative = true;
  1078. has_sign = true;
  1079. }
  1080. if (str[0] == '+') {
  1081. has_sign = true;
  1082. }
  1083. for (size_t i = has_sign; i < len; i++) {
  1084. // Looks like we're about to start working on the fractional part
  1085. if (str[i] == '.') {
  1086. is_fractional = true;
  1087. continue;
  1088. }
  1089. if (str[i] == 'e' || str[i] == 'E') {
  1090. if (str[i + 1] == '-' || str[i + 1] == '+')
  1091. exp_val = atoi(str + i + 2);
  1092. else
  1093. exp_val = atoi(str + i + 1);
  1094. is_scientific = true;
  1095. continue;
  1096. }
  1097. if (str[i] < '0' || str[i] > '9' || exp_val != 0) {
  1098. return {};
  1099. continue;
  1100. }
  1101. if (is_fractional) {
  1102. fraction *= 10;
  1103. fraction += str[i] - '0';
  1104. weight *= 10;
  1105. } else {
  1106. value = value * 10;
  1107. value += str[i] - '0';
  1108. }
  1109. }
  1110. fraction /= weight;
  1111. value += fraction;
  1112. if (is_scientific) {
  1113. bool divide = exp_val < 0;
  1114. if (divide)
  1115. exp_val *= -1;
  1116. for (int i = 0; i < exp_val; i++) {
  1117. if (divide)
  1118. value /= 10;
  1119. else
  1120. value *= 10;
  1121. }
  1122. }
  1123. return is_negative ? -value : value;
  1124. }
  1125. static bool is_color(StyleValue& style_value)
  1126. {
  1127. if (style_value.is_color())
  1128. return true;
  1129. switch (style_value.to_identifier()) {
  1130. case ValueID::Currentcolor:
  1131. case ValueID::LibwebLink:
  1132. case ValueID::LibwebPaletteActiveLink:
  1133. case ValueID::LibwebPaletteActiveWindowBorder1:
  1134. case ValueID::LibwebPaletteActiveWindowBorder2:
  1135. case ValueID::LibwebPaletteActiveWindowTitle:
  1136. case ValueID::LibwebPaletteBase:
  1137. case ValueID::LibwebPaletteBaseText:
  1138. case ValueID::LibwebPaletteButton:
  1139. case ValueID::LibwebPaletteButtonText:
  1140. case ValueID::LibwebPaletteDesktopBackground:
  1141. case ValueID::LibwebPaletteFocusOutline:
  1142. case ValueID::LibwebPaletteHighlightWindowBorder1:
  1143. case ValueID::LibwebPaletteHighlightWindowBorder2:
  1144. case ValueID::LibwebPaletteHighlightWindowTitle:
  1145. case ValueID::LibwebPaletteHoverHighlight:
  1146. case ValueID::LibwebPaletteInactiveSelection:
  1147. case ValueID::LibwebPaletteInactiveSelectionText:
  1148. case ValueID::LibwebPaletteInactiveWindowBorder1:
  1149. case ValueID::LibwebPaletteInactiveWindowBorder2:
  1150. case ValueID::LibwebPaletteInactiveWindowTitle:
  1151. case ValueID::LibwebPaletteLink:
  1152. case ValueID::LibwebPaletteMenuBase:
  1153. case ValueID::LibwebPaletteMenuBaseText:
  1154. case ValueID::LibwebPaletteMenuSelection:
  1155. case ValueID::LibwebPaletteMenuSelectionText:
  1156. case ValueID::LibwebPaletteMenuStripe:
  1157. case ValueID::LibwebPaletteMovingWindowBorder1:
  1158. case ValueID::LibwebPaletteMovingWindowBorder2:
  1159. case ValueID::LibwebPaletteMovingWindowTitle:
  1160. case ValueID::LibwebPaletteRubberBandBorder:
  1161. case ValueID::LibwebPaletteRubberBandFill:
  1162. case ValueID::LibwebPaletteRuler:
  1163. case ValueID::LibwebPaletteRulerActiveText:
  1164. case ValueID::LibwebPaletteRulerBorder:
  1165. case ValueID::LibwebPaletteRulerInactiveText:
  1166. case ValueID::LibwebPaletteSelection:
  1167. case ValueID::LibwebPaletteSelectionText:
  1168. case ValueID::LibwebPaletteSyntaxComment:
  1169. case ValueID::LibwebPaletteSyntaxControlKeyword:
  1170. case ValueID::LibwebPaletteSyntaxIdentifier:
  1171. case ValueID::LibwebPaletteSyntaxKeyword:
  1172. case ValueID::LibwebPaletteSyntaxNumber:
  1173. case ValueID::LibwebPaletteSyntaxOperator:
  1174. case ValueID::LibwebPaletteSyntaxPreprocessorStatement:
  1175. case ValueID::LibwebPaletteSyntaxPreprocessorValue:
  1176. case ValueID::LibwebPaletteSyntaxPunctuation:
  1177. case ValueID::LibwebPaletteSyntaxString:
  1178. case ValueID::LibwebPaletteSyntaxType:
  1179. case ValueID::LibwebPaletteTextCursor:
  1180. case ValueID::LibwebPaletteThreedHighlight:
  1181. case ValueID::LibwebPaletteThreedShadow1:
  1182. case ValueID::LibwebPaletteThreedShadow2:
  1183. case ValueID::LibwebPaletteVisitedLink:
  1184. case ValueID::LibwebPaletteWindow:
  1185. case ValueID::LibwebPaletteWindowText:
  1186. return true;
  1187. default:
  1188. break;
  1189. }
  1190. return false;
  1191. }
  1192. RefPtr<StyleValue> Parser::parse_builtin_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1193. {
  1194. if (component_value.is(Token::Type::Ident)) {
  1195. auto ident = component_value.token().ident();
  1196. if (ident.equals_ignoring_case("inherit"))
  1197. return InheritStyleValue::the();
  1198. if (ident.equals_ignoring_case("initial"))
  1199. return InitialStyleValue::the();
  1200. if (ident.equals_ignoring_case("unset"))
  1201. return UnsetStyleValue::the();
  1202. // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
  1203. }
  1204. return {};
  1205. }
  1206. RefPtr<StyleValue> Parser::parse_dynamic_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1207. {
  1208. if (component_value.is_function()) {
  1209. auto& function = component_value.function();
  1210. if (function.name().equals_ignoring_case("calc")) {
  1211. auto calc_expression = parse_calc_expression(context, function.values());
  1212. // FIXME: Either produce a string value of calc() here, or do so in CalculatedStyleValue::to_string().
  1213. if (calc_expression)
  1214. return CalculatedStyleValue::create("(FIXME:calc to string)", calc_expression.release_nonnull());
  1215. } else if (function.name().equals_ignoring_case("var")) {
  1216. // FIXME: Handle fallback value as second parameter
  1217. // https://www.w3.org/TR/css-variables-1/#using-variables
  1218. if (!component_value.function().values().is_empty()) {
  1219. auto& property_name_token = component_value.function().values().first();
  1220. if (property_name_token.is(Token::Type::Ident))
  1221. return CustomStyleValue::create(property_name_token.token().ident());
  1222. else
  1223. dbgln("First argument to var() function was not an ident: '{}'", property_name_token.to_debug_string());
  1224. }
  1225. }
  1226. }
  1227. return {};
  1228. }
  1229. Optional<Length> Parser::parse_length(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1230. {
  1231. Length::Type type = Length::Type::Undefined;
  1232. Optional<float> numeric_value;
  1233. if (component_value.is(Token::Type::Dimension)) {
  1234. auto length_string = component_value.token().m_value.string_view();
  1235. auto unit_string = component_value.token().m_unit.string_view();
  1236. if (unit_string.equals_ignoring_case("%")) {
  1237. type = Length::Type::Percentage;
  1238. } else if (unit_string.equals_ignoring_case("px")) {
  1239. type = Length::Type::Px;
  1240. } else if (unit_string.equals_ignoring_case("pt")) {
  1241. type = Length::Type::Pt;
  1242. } else if (unit_string.equals_ignoring_case("pc")) {
  1243. type = Length::Type::Pc;
  1244. } else if (unit_string.equals_ignoring_case("mm")) {
  1245. type = Length::Type::Mm;
  1246. } else if (unit_string.equals_ignoring_case("rem")) {
  1247. type = Length::Type::Rem;
  1248. } else if (unit_string.equals_ignoring_case("em")) {
  1249. type = Length::Type::Em;
  1250. } else if (unit_string.equals_ignoring_case("ex")) {
  1251. type = Length::Type::Ex;
  1252. } else if (unit_string.equals_ignoring_case("ch")) {
  1253. type = Length::Type::Ch;
  1254. } else if (unit_string.equals_ignoring_case("vw")) {
  1255. type = Length::Type::Vw;
  1256. } else if (unit_string.equals_ignoring_case("vh")) {
  1257. type = Length::Type::Vh;
  1258. } else if (unit_string.equals_ignoring_case("vmax")) {
  1259. type = Length::Type::Vmax;
  1260. } else if (unit_string.equals_ignoring_case("vmin")) {
  1261. type = Length::Type::Vmin;
  1262. } else if (unit_string.equals_ignoring_case("cm")) {
  1263. type = Length::Type::Cm;
  1264. } else if (unit_string.equals_ignoring_case("in")) {
  1265. type = Length::Type::In;
  1266. } else if (unit_string.equals_ignoring_case("Q")) {
  1267. type = Length::Type::Q;
  1268. } else {
  1269. return {};
  1270. }
  1271. numeric_value = try_parse_float(length_string);
  1272. } else if (component_value.is(Token::Type::Percentage)) {
  1273. type = Length::Type::Percentage;
  1274. auto value_string = component_value.token().m_value.string_view();
  1275. numeric_value = try_parse_float(value_string);
  1276. } else if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto")) {
  1277. return Length::make_auto();
  1278. } else if (component_value.is(Token::Type::Number)) {
  1279. auto value_string = component_value.token().m_value.string_view();
  1280. if (value_string == "0") {
  1281. type = Length::Type::Px;
  1282. numeric_value = 0;
  1283. } else if (context.in_quirks_mode() && property_has_quirk(context.current_property_id(), Quirk::UnitlessLength)) {
  1284. // https://quirks.spec.whatwg.org/#quirky-length-value
  1285. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1286. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1287. // expression, and must not be supported in the supports() static method of the CSS interface."
  1288. type = Length::Type::Px;
  1289. numeric_value = try_parse_float(value_string);
  1290. }
  1291. }
  1292. if (!numeric_value.has_value())
  1293. return {};
  1294. return Length(numeric_value.value(), type);
  1295. }
  1296. RefPtr<StyleValue> Parser::parse_length_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1297. {
  1298. // Numbers with no units can be lengths, in two situations:
  1299. // 1) We're in quirks mode, and it's an integer.
  1300. // 2) It's a 0.
  1301. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1302. // FIXME: "auto" is also treated as a Length, and most of the time that is how it is used, but not always.
  1303. // Possibly it should always be an Identifier, and then quietly converted to a Length when needed, like 0 above.
  1304. // Right now, it instead is quietly converted to an Identifier when needed.
  1305. if (component_value.is(Token::Type::Dimension) || component_value.is(Token::Type::Percentage)
  1306. || (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"sv))
  1307. || (context.in_quirks_mode() && component_value.is(Token::Type::Number) && component_value.token().m_value.string_view() != "0"sv)) {
  1308. auto length = parse_length(context, component_value);
  1309. if (length.has_value())
  1310. return LengthStyleValue::create(length.value());
  1311. }
  1312. return {};
  1313. }
  1314. RefPtr<StyleValue> Parser::parse_numeric_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1315. {
  1316. if (component_value.is(Token::Type::Number)) {
  1317. auto number = component_value.token();
  1318. if (number.m_number_type == Token::NumberType::Integer) {
  1319. return NumericStyleValue::create(number.to_integer());
  1320. } else {
  1321. auto float_value = try_parse_float(number.m_value.string_view());
  1322. if (float_value.has_value())
  1323. return NumericStyleValue::create(float_value.value());
  1324. }
  1325. }
  1326. return {};
  1327. }
  1328. RefPtr<StyleValue> Parser::parse_identifier_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1329. {
  1330. if (component_value.is(Token::Type::Ident)) {
  1331. auto value_id = value_id_from_string(component_value.token().ident());
  1332. if (value_id != ValueID::Invalid)
  1333. return IdentifierStyleValue::create(value_id);
  1334. }
  1335. return {};
  1336. }
  1337. Optional<Color> Parser::parse_color(ParsingContext const&, StyleComponentValueRule const& component_value)
  1338. {
  1339. // https://www.w3.org/TR/css-color-3/
  1340. if (component_value.is(Token::Type::Ident)) {
  1341. auto ident = component_value.token().ident();
  1342. if (ident.equals_ignoring_case("transparent"))
  1343. return Color::from_rgba(0x00000000);
  1344. auto color = Color::from_string(ident.to_string().to_lowercase());
  1345. if (color.has_value())
  1346. return color;
  1347. } else if (component_value.is(Token::Type::Hash)) {
  1348. // FIXME: Read it directly
  1349. auto color = Color::from_string(String::formatted("#{}", component_value.token().m_value.to_string().to_lowercase()));
  1350. if (color.has_value())
  1351. return color;
  1352. } else if (component_value.is_function()) {
  1353. auto& function = component_value.function();
  1354. auto& values = function.values();
  1355. Vector<Token> params;
  1356. for (size_t i = 0; i < values.size(); ++i) {
  1357. auto& value = values.at(i);
  1358. if (value.is(Token::Type::Whitespace))
  1359. continue;
  1360. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  1361. params.append(value.token());
  1362. // Eat following comma and whitespace
  1363. while ((i + 1) < values.size()) {
  1364. auto& next = values.at(i + 1);
  1365. if (next.is(Token::Type::Whitespace))
  1366. i++;
  1367. else if (next.is(Token::Type::Comma))
  1368. break;
  1369. return {};
  1370. }
  1371. }
  1372. }
  1373. if (function.name().equals_ignoring_case("rgb")) {
  1374. if (params.size() != 3)
  1375. return {};
  1376. auto r_val = params[0];
  1377. auto g_val = params[1];
  1378. auto b_val = params[2];
  1379. if (r_val.is(Token::NumberType::Integer)
  1380. && g_val.is(Token::NumberType::Integer)
  1381. && b_val.is(Token::NumberType::Integer)) {
  1382. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1383. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1384. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1385. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value())
  1386. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value());
  1387. } else if (r_val.is(Token::Type::Percentage)
  1388. && g_val.is(Token::Type::Percentage)
  1389. && b_val.is(Token::Type::Percentage)) {
  1390. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1391. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1392. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1393. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value()) {
  1394. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1395. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1396. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1397. return Color(r, g, b);
  1398. }
  1399. }
  1400. } else if (function.name().equals_ignoring_case("rgba")) {
  1401. if (params.size() != 4)
  1402. return {};
  1403. auto r_val = params[0];
  1404. auto g_val = params[1];
  1405. auto b_val = params[2];
  1406. auto a_val = params[3];
  1407. if (r_val.is(Token::NumberType::Integer)
  1408. && g_val.is(Token::NumberType::Integer)
  1409. && b_val.is(Token::NumberType::Integer)
  1410. && a_val.is(Token::Type::Number)) {
  1411. auto maybe_r = r_val.m_value.string_view().to_uint<u8>();
  1412. auto maybe_g = g_val.m_value.string_view().to_uint<u8>();
  1413. auto maybe_b = b_val.m_value.string_view().to_uint<u8>();
  1414. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1415. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1416. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1417. return Color(maybe_r.value(), maybe_g.value(), maybe_b.value(), a);
  1418. }
  1419. } else if (r_val.is(Token::Type::Percentage)
  1420. && g_val.is(Token::Type::Percentage)
  1421. && b_val.is(Token::Type::Percentage)
  1422. && a_val.is(Token::Type::Number)) {
  1423. auto maybe_r = try_parse_float(r_val.m_value.string_view());
  1424. auto maybe_g = try_parse_float(g_val.m_value.string_view());
  1425. auto maybe_b = try_parse_float(b_val.m_value.string_view());
  1426. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1427. if (maybe_r.has_value() && maybe_g.has_value() && maybe_b.has_value() && maybe_a.has_value()) {
  1428. u8 r = clamp(lroundf(maybe_r.value() * 2.55f), 0, 255);
  1429. u8 g = clamp(lroundf(maybe_g.value() * 2.55f), 0, 255);
  1430. u8 b = clamp(lroundf(maybe_b.value() * 2.55f), 0, 255);
  1431. u8 a = clamp(lroundf(maybe_a.value() * 255.0f), 0, 255);
  1432. return Color(r, g, b, a);
  1433. }
  1434. }
  1435. } else if (function.name().equals_ignoring_case("hsl")) {
  1436. if (params.size() != 3)
  1437. return {};
  1438. auto h_val = params[0];
  1439. auto s_val = params[1];
  1440. auto l_val = params[2];
  1441. if (h_val.is(Token::Type::Number)
  1442. && s_val.is(Token::Type::Percentage)
  1443. && l_val.is(Token::Type::Percentage)) {
  1444. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1445. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1446. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1447. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value()) {
  1448. float h = maybe_h.value();
  1449. float s = maybe_s.value() / 100.0f;
  1450. float l = maybe_l.value() / 100.0f;
  1451. return Color::from_hsl(h, s, l);
  1452. }
  1453. }
  1454. } else if (function.name().equals_ignoring_case("hsla")) {
  1455. if (params.size() != 4)
  1456. return {};
  1457. auto h_val = params[0];
  1458. auto s_val = params[1];
  1459. auto l_val = params[2];
  1460. auto a_val = params[3];
  1461. if (h_val.is(Token::Type::Number)
  1462. && s_val.is(Token::Type::Percentage)
  1463. && l_val.is(Token::Type::Percentage)
  1464. && a_val.is(Token::Type::Number)) {
  1465. auto maybe_h = try_parse_float(h_val.m_value.string_view());
  1466. auto maybe_s = try_parse_float(s_val.m_value.string_view());
  1467. auto maybe_l = try_parse_float(l_val.m_value.string_view());
  1468. auto maybe_a = try_parse_float(a_val.m_value.string_view());
  1469. if (maybe_h.has_value() && maybe_s.has_value() && maybe_l.has_value() && maybe_a.has_value()) {
  1470. float h = maybe_h.value();
  1471. float s = maybe_s.value() / 100.0f;
  1472. float l = maybe_l.value() / 100.0f;
  1473. float a = maybe_a.value();
  1474. return Color::from_hsla(h, s, l, a);
  1475. }
  1476. }
  1477. }
  1478. return {};
  1479. }
  1480. return {};
  1481. }
  1482. RefPtr<StyleValue> Parser::parse_color_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1483. {
  1484. auto color = parse_color(context, component_value);
  1485. if (color.has_value())
  1486. return ColorStyleValue::create(color.value());
  1487. return {};
  1488. }
  1489. RefPtr<StyleValue> Parser::parse_string_value(ParsingContext const&, StyleComponentValueRule const& component_value)
  1490. {
  1491. if (component_value.is(Token::Type::String))
  1492. return StringStyleValue::create(component_value.token().string());
  1493. return {};
  1494. }
  1495. RefPtr<StyleValue> Parser::parse_image_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  1496. {
  1497. auto url = parse_url_function(context, component_value);
  1498. if (url.has_value())
  1499. return ImageStyleValue::create(url.value(), *context.document());
  1500. // FIXME: Handle gradients.
  1501. return {};
  1502. }
  1503. static inline bool is_background_repeat(StyleValue const& value)
  1504. {
  1505. switch (value.to_identifier()) {
  1506. case ValueID::NoRepeat:
  1507. case ValueID::Repeat:
  1508. case ValueID::RepeatX:
  1509. case ValueID::RepeatY:
  1510. case ValueID::Round:
  1511. case ValueID::Space:
  1512. return true;
  1513. default:
  1514. return false;
  1515. }
  1516. }
  1517. static inline bool is_background_image(StyleValue const& value)
  1518. {
  1519. if (value.is_image())
  1520. return true;
  1521. if (value.to_identifier() == ValueID::None)
  1522. return true;
  1523. return false;
  1524. }
  1525. RefPtr<StyleValue> Parser::parse_background_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1526. {
  1527. RefPtr<StyleValue> background_color;
  1528. RefPtr<StyleValue> background_image;
  1529. RefPtr<StyleValue> repeat_x;
  1530. RefPtr<StyleValue> repeat_y;
  1531. // FIXME: Implement background-position.
  1532. // FIXME: Implement background-size.
  1533. // FIXME: Implement background-attachment.
  1534. // FIXME: Implement background-clip.
  1535. // FIXME: Implement background-origin.
  1536. for (size_t i = 0; i < component_values.size(); ++i) {
  1537. auto& part = component_values[i];
  1538. // FIXME: Handle multiple backgrounds, by returning a List of BackgroundStyleValues.
  1539. if (part.is(Token::Type::Comma)) {
  1540. dbgln("CSS Parser does not yet support multiple comma-separated values for background.");
  1541. break;
  1542. }
  1543. auto value = parse_css_value(context, part);
  1544. if (!value) {
  1545. return nullptr;
  1546. }
  1547. if (is_color(*value)) {
  1548. if (background_color)
  1549. return nullptr;
  1550. background_color = value.release_nonnull();
  1551. continue;
  1552. }
  1553. if (is_background_image(*value)) {
  1554. if (background_image)
  1555. return nullptr;
  1556. background_image = value.release_nonnull();
  1557. continue;
  1558. }
  1559. if (is_background_repeat(*value)) {
  1560. if (repeat_x)
  1561. return nullptr;
  1562. auto value_id = value->to_identifier();
  1563. if (value_id == ValueID::RepeatX || value_id == ValueID::RepeatY) {
  1564. repeat_x = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat);
  1565. repeat_y = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat);
  1566. continue;
  1567. }
  1568. // Check following value, if it's also a repeat, set both.
  1569. if (i + 1 < component_values.size()) {
  1570. auto next_value = parse_css_value(context, component_values[i + 1]);
  1571. if (next_value && is_background_repeat(*next_value)) {
  1572. ++i;
  1573. repeat_x = value.release_nonnull();
  1574. repeat_y = next_value.release_nonnull();
  1575. continue;
  1576. }
  1577. }
  1578. auto repeat = value.release_nonnull();
  1579. repeat_x = repeat;
  1580. repeat_y = repeat;
  1581. continue;
  1582. }
  1583. return nullptr;
  1584. }
  1585. if (!background_color)
  1586. background_color = property_initial_value(PropertyID::BackgroundColor);
  1587. if (!background_image)
  1588. background_image = property_initial_value(PropertyID::BackgroundImage);
  1589. if (!repeat_x)
  1590. repeat_x = property_initial_value(PropertyID::BackgroundRepeatX);
  1591. if (!repeat_y)
  1592. repeat_y = property_initial_value(PropertyID::BackgroundRepeatY);
  1593. return BackgroundStyleValue::create(background_color.release_nonnull(), background_image.release_nonnull(), repeat_x.release_nonnull(), repeat_y.release_nonnull());
  1594. }
  1595. RefPtr<StyleValue> Parser::parse_background_image_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1596. {
  1597. if (component_values.size() == 1) {
  1598. auto maybe_value = parse_css_value(context, component_values.first());
  1599. if (!maybe_value)
  1600. return nullptr;
  1601. auto value = maybe_value.release_nonnull();
  1602. if (is_background_image(*value))
  1603. return value;
  1604. return nullptr;
  1605. }
  1606. // FIXME: Handle multiple sets of comma-separated values.
  1607. dbgln("CSS Parser does not yet support multiple comma-separated values for background-image.");
  1608. return nullptr;
  1609. }
  1610. RefPtr<StyleValue> Parser::parse_background_repeat_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1611. {
  1612. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  1613. auto value_id = value.to_identifier();
  1614. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  1615. };
  1616. if (component_values.size() == 1) {
  1617. auto maybe_value = parse_css_value(context, component_values.first());
  1618. if (!maybe_value)
  1619. return nullptr;
  1620. auto value = maybe_value.release_nonnull();
  1621. if (!is_background_repeat(*value))
  1622. return nullptr;
  1623. if (is_directional_repeat(value)) {
  1624. auto value_id = value->to_identifier();
  1625. return BackgroundRepeatStyleValue::create(
  1626. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat),
  1627. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat));
  1628. }
  1629. return BackgroundRepeatStyleValue::create(value, value);
  1630. }
  1631. if (component_values.size() == 2) {
  1632. auto maybe_x_value = parse_css_value(context, component_values[0]);
  1633. auto maybe_y_value = parse_css_value(context, component_values[1]);
  1634. if (!maybe_x_value || !maybe_y_value)
  1635. return nullptr;
  1636. auto x_value = maybe_x_value.release_nonnull();
  1637. auto y_value = maybe_y_value.release_nonnull();
  1638. if (!is_background_repeat(x_value) || !is_background_repeat(y_value))
  1639. return nullptr;
  1640. if (is_directional_repeat(x_value) || is_directional_repeat(y_value))
  1641. return nullptr;
  1642. return BackgroundRepeatStyleValue::create(x_value, y_value);
  1643. }
  1644. // FIXME: Handle multiple sets of comma-separated values.
  1645. dbgln("CSS Parser does not yet support multiple comma-separated values for background-repeat.");
  1646. return nullptr;
  1647. }
  1648. RefPtr<StyleValue> Parser::parse_border_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1649. {
  1650. auto is_line_style = [](StyleValue const& value) -> bool {
  1651. switch (value.to_identifier()) {
  1652. case ValueID::Dotted:
  1653. case ValueID::Dashed:
  1654. case ValueID::Solid:
  1655. case ValueID::Double:
  1656. case ValueID::Groove:
  1657. case ValueID::Ridge:
  1658. case ValueID::None:
  1659. case ValueID::Hidden:
  1660. case ValueID::Inset:
  1661. case ValueID::Outset:
  1662. return true;
  1663. default:
  1664. return false;
  1665. }
  1666. };
  1667. auto is_line_width = [](StyleValue const& value) -> bool {
  1668. if (value.is_length())
  1669. return true;
  1670. // FIXME: Implement thin/medium/thick
  1671. switch (value.to_identifier()) {
  1672. case ValueID::None:
  1673. return true;
  1674. default:
  1675. return false;
  1676. }
  1677. };
  1678. if (component_values.size() > 3)
  1679. return nullptr;
  1680. RefPtr<StyleValue> border_width;
  1681. RefPtr<StyleValue> border_color;
  1682. RefPtr<StyleValue> border_style;
  1683. for (auto& part : component_values) {
  1684. auto value = parse_css_value(context, part);
  1685. if (!value)
  1686. return nullptr;
  1687. if (is_line_width(*value)) {
  1688. if (border_width)
  1689. return nullptr;
  1690. border_width = value.release_nonnull();
  1691. continue;
  1692. }
  1693. if (is_color(*value)) {
  1694. if (border_color)
  1695. return nullptr;
  1696. border_color = value.release_nonnull();
  1697. continue;
  1698. }
  1699. if (is_line_style(*value)) {
  1700. if (border_style)
  1701. return nullptr;
  1702. border_style = value.release_nonnull();
  1703. continue;
  1704. }
  1705. return nullptr;
  1706. }
  1707. if (!border_width)
  1708. border_width = property_initial_value(PropertyID::BorderWidth);
  1709. if (!border_style)
  1710. border_style = property_initial_value(PropertyID::BorderStyle);
  1711. if (!border_color)
  1712. border_color = property_initial_value(PropertyID::BorderColor);
  1713. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  1714. }
  1715. RefPtr<StyleValue> Parser::parse_border_radius_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1716. {
  1717. if (component_values.size() == 2) {
  1718. auto horizontal = parse_length(context, component_values[0]);
  1719. auto vertical = parse_length(context, component_values[1]);
  1720. if (horizontal.has_value() && vertical.has_value())
  1721. return BorderRadiusStyleValue::create(horizontal.value(), vertical.value());
  1722. return nullptr;
  1723. }
  1724. if (component_values.size() == 1) {
  1725. auto radius = parse_length(context, component_values[0]);
  1726. if (radius.has_value())
  1727. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  1728. return nullptr;
  1729. }
  1730. return nullptr;
  1731. }
  1732. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1733. {
  1734. auto top_left = [&](Vector<Length>& radii) { return radii[0]; };
  1735. auto top_right = [&](Vector<Length>& radii) {
  1736. switch (radii.size()) {
  1737. case 4:
  1738. case 3:
  1739. case 2:
  1740. return radii[1];
  1741. case 1:
  1742. return radii[0];
  1743. default:
  1744. VERIFY_NOT_REACHED();
  1745. }
  1746. };
  1747. auto bottom_right = [&](Vector<Length>& radii) {
  1748. switch (radii.size()) {
  1749. case 4:
  1750. case 3:
  1751. return radii[2];
  1752. case 2:
  1753. case 1:
  1754. return radii[0];
  1755. default:
  1756. VERIFY_NOT_REACHED();
  1757. }
  1758. };
  1759. auto bottom_left = [&](Vector<Length>& radii) {
  1760. switch (radii.size()) {
  1761. case 4:
  1762. return radii[3];
  1763. case 3:
  1764. case 2:
  1765. return radii[1];
  1766. case 1:
  1767. return radii[0];
  1768. default:
  1769. VERIFY_NOT_REACHED();
  1770. }
  1771. };
  1772. Vector<Length> horizontal_radii;
  1773. Vector<Length> vertical_radii;
  1774. bool reading_vertical = false;
  1775. for (auto& value : component_values) {
  1776. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  1777. if (reading_vertical || horizontal_radii.is_empty())
  1778. return nullptr;
  1779. reading_vertical = true;
  1780. continue;
  1781. }
  1782. auto maybe_length = parse_length(context, value);
  1783. if (!maybe_length.has_value())
  1784. return nullptr;
  1785. if (reading_vertical) {
  1786. vertical_radii.append(maybe_length.value());
  1787. } else {
  1788. horizontal_radii.append(maybe_length.value());
  1789. }
  1790. }
  1791. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  1792. || horizontal_radii.is_empty()
  1793. || (reading_vertical && vertical_radii.is_empty()))
  1794. return nullptr;
  1795. NonnullRefPtrVector<StyleValue> border_radii;
  1796. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  1797. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  1798. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  1799. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  1800. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  1801. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  1802. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  1803. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  1804. return StyleValueList::create(move(border_radii));
  1805. }
  1806. RefPtr<StyleValue> Parser::parse_box_shadow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1807. {
  1808. // FIXME: Also support inset, spread-radius and multiple comma-seperated box-shadows
  1809. Length offset_x {};
  1810. Length offset_y {};
  1811. Length blur_radius {};
  1812. Color color {};
  1813. if (component_values.size() < 3 || component_values.size() > 4)
  1814. return nullptr;
  1815. auto maybe_x = parse_length(context, component_values[0]);
  1816. if (!maybe_x.has_value())
  1817. return nullptr;
  1818. offset_x = maybe_x.value();
  1819. auto maybe_y = parse_length(context, component_values[1]);
  1820. if (!maybe_y.has_value())
  1821. return nullptr;
  1822. offset_y = maybe_y.value();
  1823. if (component_values.size() == 3) {
  1824. auto parsed_color = parse_color(context, component_values[2]);
  1825. if (!parsed_color.has_value())
  1826. return nullptr;
  1827. color = parsed_color.value();
  1828. } else if (component_values.size() == 4) {
  1829. auto maybe_blur_radius = parse_length(context, component_values[2]);
  1830. if (!maybe_blur_radius.has_value())
  1831. return nullptr;
  1832. blur_radius = maybe_blur_radius.value();
  1833. auto parsed_color = parse_color(context, component_values[3]);
  1834. if (!parsed_color.has_value())
  1835. return nullptr;
  1836. color = parsed_color.value();
  1837. }
  1838. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  1839. }
  1840. RefPtr<StyleValue> Parser::parse_flex_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1841. {
  1842. auto is_flex_grow_or_shrink = [](StyleValue const& value) -> bool {
  1843. if (value.is_numeric())
  1844. return true;
  1845. return false;
  1846. };
  1847. auto is_flex_basis = [](StyleValue const& value) -> bool {
  1848. if (value.is_length())
  1849. return true;
  1850. switch (value.to_identifier()) {
  1851. case ValueID::Auto:
  1852. case ValueID::Content:
  1853. return true;
  1854. default:
  1855. return false;
  1856. }
  1857. };
  1858. if (component_values.size() == 1) {
  1859. auto value = parse_css_value(context, component_values[0]);
  1860. if (!value)
  1861. return nullptr;
  1862. switch (value->to_identifier()) {
  1863. case ValueID::Auto: {
  1864. auto one = NumericStyleValue::create(1);
  1865. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  1866. }
  1867. case ValueID::None: {
  1868. auto zero = NumericStyleValue::create(0);
  1869. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  1870. }
  1871. default:
  1872. break;
  1873. }
  1874. }
  1875. RefPtr<StyleValue> flex_grow;
  1876. RefPtr<StyleValue> flex_shrink;
  1877. RefPtr<StyleValue> flex_basis;
  1878. for (size_t i = 0; i < component_values.size(); ++i) {
  1879. auto value = parse_css_value(context, component_values[i]);
  1880. if (!value)
  1881. return nullptr;
  1882. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  1883. if (value->is_numeric() && static_cast<NumericStyleValue&>(*value).value() == 0) {
  1884. if (flex_grow && flex_shrink && !flex_basis) {
  1885. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  1886. continue;
  1887. }
  1888. }
  1889. if (is_flex_grow_or_shrink(*value)) {
  1890. if (flex_grow)
  1891. return nullptr;
  1892. flex_grow = value.release_nonnull();
  1893. // Flex-shrink may optionally follow directly after.
  1894. if (i + 1 < component_values.size()) {
  1895. auto second_value = parse_css_value(context, component_values[i + 1]);
  1896. if (second_value && is_flex_grow_or_shrink(*second_value)) {
  1897. flex_shrink = second_value.release_nonnull();
  1898. i++;
  1899. }
  1900. }
  1901. continue;
  1902. }
  1903. if (is_flex_basis(*value)) {
  1904. if (flex_basis)
  1905. return nullptr;
  1906. flex_basis = value.release_nonnull();
  1907. continue;
  1908. }
  1909. return nullptr;
  1910. }
  1911. if (!flex_grow)
  1912. flex_grow = property_initial_value(PropertyID::FlexGrow);
  1913. if (!flex_shrink)
  1914. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  1915. if (!flex_basis)
  1916. flex_basis = property_initial_value(PropertyID::FlexBasis);
  1917. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  1918. }
  1919. RefPtr<StyleValue> Parser::parse_flex_flow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1920. {
  1921. auto is_flex_direction = [](StyleValue const& value) -> bool {
  1922. switch (value.to_identifier()) {
  1923. case ValueID::Row:
  1924. case ValueID::RowReverse:
  1925. case ValueID::Column:
  1926. case ValueID::ColumnReverse:
  1927. return true;
  1928. default:
  1929. return false;
  1930. }
  1931. };
  1932. auto is_flex_wrap = [](StyleValue const& value) -> bool {
  1933. switch (value.to_identifier()) {
  1934. case ValueID::Wrap:
  1935. case ValueID::Nowrap:
  1936. case ValueID::WrapReverse:
  1937. return true;
  1938. default:
  1939. return false;
  1940. }
  1941. };
  1942. if (component_values.size() > 2)
  1943. return nullptr;
  1944. RefPtr<StyleValue> flex_direction;
  1945. RefPtr<StyleValue> flex_wrap;
  1946. for (auto& part : component_values) {
  1947. auto value = parse_css_value(context, part);
  1948. if (!value)
  1949. return nullptr;
  1950. if (is_flex_direction(*value)) {
  1951. if (flex_direction)
  1952. return nullptr;
  1953. flex_direction = value.release_nonnull();
  1954. continue;
  1955. }
  1956. if (is_flex_wrap(*value)) {
  1957. if (flex_wrap)
  1958. return nullptr;
  1959. flex_wrap = value.release_nonnull();
  1960. continue;
  1961. }
  1962. }
  1963. if (!flex_direction)
  1964. flex_direction = property_initial_value(PropertyID::FlexDirection);
  1965. if (!flex_wrap)
  1966. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  1967. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  1968. }
  1969. RefPtr<StyleValue> Parser::parse_font_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  1970. {
  1971. auto is_font_size = [](StyleValue const& value) -> bool {
  1972. if (value.is_length())
  1973. return true;
  1974. switch (value.to_identifier()) {
  1975. case ValueID::XxSmall:
  1976. case ValueID::XSmall:
  1977. case ValueID::Small:
  1978. case ValueID::Medium:
  1979. case ValueID::Large:
  1980. case ValueID::XLarge:
  1981. case ValueID::XxLarge:
  1982. case ValueID::XxxLarge:
  1983. case ValueID::Smaller:
  1984. case ValueID::Larger:
  1985. return true;
  1986. default:
  1987. return false;
  1988. }
  1989. };
  1990. auto is_font_style = [](StyleValue const& value) -> bool {
  1991. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  1992. switch (value.to_identifier()) {
  1993. case ValueID::Normal:
  1994. case ValueID::Italic:
  1995. case ValueID::Oblique:
  1996. return true;
  1997. default:
  1998. return false;
  1999. }
  2000. };
  2001. auto is_font_weight = [](StyleValue const& value) -> bool {
  2002. if (value.is_numeric()) {
  2003. auto weight = static_cast<NumericStyleValue const&>(value).value();
  2004. return (weight >= 1 && weight <= 1000);
  2005. }
  2006. switch (value.to_identifier()) {
  2007. case ValueID::Normal:
  2008. case ValueID::Bold:
  2009. case ValueID::Bolder:
  2010. case ValueID::Lighter:
  2011. return true;
  2012. default:
  2013. return false;
  2014. }
  2015. };
  2016. auto is_line_height = [](StyleValue const& value) -> bool {
  2017. if (value.is_numeric())
  2018. return true;
  2019. if (value.is_length())
  2020. return true;
  2021. if (value.to_identifier() == ValueID::Normal)
  2022. return true;
  2023. return false;
  2024. };
  2025. RefPtr<StyleValue> font_style;
  2026. RefPtr<StyleValue> font_weight;
  2027. RefPtr<StyleValue> font_size;
  2028. RefPtr<StyleValue> line_height;
  2029. RefPtr<StyleValue> font_families;
  2030. // FIXME: Implement font-stretch and font-variant.
  2031. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  2032. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  2033. // So, we have to handle that separately.
  2034. int normal_count = 0;
  2035. for (size_t i = 0; i < component_values.size(); ++i) {
  2036. auto value = parse_css_value(context, component_values[i]);
  2037. if (!value)
  2038. return nullptr;
  2039. if (value->to_identifier() == ValueID::Normal) {
  2040. normal_count++;
  2041. continue;
  2042. }
  2043. if (is_font_style(*value)) {
  2044. if (font_style)
  2045. return nullptr;
  2046. font_style = value.release_nonnull();
  2047. continue;
  2048. }
  2049. if (is_font_weight(*value)) {
  2050. if (font_weight)
  2051. return nullptr;
  2052. font_weight = value.release_nonnull();
  2053. continue;
  2054. }
  2055. if (is_font_size(*value)) {
  2056. if (font_size)
  2057. return nullptr;
  2058. font_size = value.release_nonnull();
  2059. // Consume `/ line-height` if present
  2060. if (i + 2 < component_values.size()) {
  2061. auto maybe_solidus = component_values[i + 1];
  2062. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  2063. auto maybe_line_height = parse_css_value(context, component_values[i + 2]);
  2064. if (!(maybe_line_height && is_line_height(*maybe_line_height)))
  2065. return nullptr;
  2066. line_height = maybe_line_height.release_nonnull();
  2067. i += 2;
  2068. }
  2069. }
  2070. // Consume font-families
  2071. auto maybe_font_families = parse_font_family_value(context, component_values, i + 1);
  2072. if (!maybe_font_families)
  2073. return nullptr;
  2074. font_families = maybe_font_families.release_nonnull();
  2075. break;
  2076. }
  2077. return nullptr;
  2078. }
  2079. // Since normal is the default value for all the properties that can have it, we don't have to actually
  2080. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  2081. // We just need to make sure we were not given more normals than will fit.
  2082. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  2083. if (unset_value_count < normal_count)
  2084. return nullptr;
  2085. if (!font_size || !font_families)
  2086. return nullptr;
  2087. if (!font_style)
  2088. font_style = property_initial_value(PropertyID::FontStyle);
  2089. if (!font_weight)
  2090. font_weight = property_initial_value(PropertyID::FontWeight);
  2091. if (!line_height)
  2092. line_height = property_initial_value(PropertyID::LineHeight);
  2093. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  2094. }
  2095. RefPtr<StyleValue> Parser::parse_font_family_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  2096. {
  2097. auto is_generic_font_family = [](ValueID identifier) -> bool {
  2098. switch (identifier) {
  2099. case ValueID::Cursive:
  2100. case ValueID::Fantasy:
  2101. case ValueID::Monospace:
  2102. case ValueID::Serif:
  2103. case ValueID::SansSerif:
  2104. case ValueID::UiMonospace:
  2105. case ValueID::UiRounded:
  2106. case ValueID::UiSerif:
  2107. case ValueID::UiSansSerif:
  2108. return true;
  2109. default:
  2110. return false;
  2111. }
  2112. };
  2113. auto is_comma_or_eof = [&](size_t i) -> bool {
  2114. if (i < component_values.size()) {
  2115. auto& maybe_comma = component_values[i];
  2116. if (!maybe_comma.is(Token::Type::Comma))
  2117. return false;
  2118. }
  2119. return true;
  2120. };
  2121. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  2122. // eg, these are equivalent:
  2123. // font-family: my cool font\!, serif;
  2124. // font-family: "my cool font!", serif;
  2125. NonnullRefPtrVector<StyleValue> font_families;
  2126. Vector<String> current_name_parts;
  2127. for (size_t i = start_index; i < component_values.size(); ++i) {
  2128. auto& part = component_values[i];
  2129. if (part.is(Token::Type::String)) {
  2130. // `font-family: my cool "font";` is invalid.
  2131. if (!current_name_parts.is_empty())
  2132. return nullptr;
  2133. if (!is_comma_or_eof(i + 1))
  2134. return nullptr;
  2135. font_families.append(StringStyleValue::create(part.token().string()));
  2136. i++;
  2137. continue;
  2138. }
  2139. if (part.is(Token::Type::Ident)) {
  2140. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  2141. auto maybe_ident = parse_css_value(context, part);
  2142. if (maybe_ident) {
  2143. // CSS-wide keywords are not allowed
  2144. if (maybe_ident->is_builtin())
  2145. return nullptr;
  2146. if (is_generic_font_family(maybe_ident->to_identifier())) {
  2147. // Can't have a generic-font-name as a token in an unquoted font name.
  2148. if (!current_name_parts.is_empty())
  2149. return nullptr;
  2150. if (!is_comma_or_eof(i + 1))
  2151. return nullptr;
  2152. font_families.append(maybe_ident.release_nonnull());
  2153. i++;
  2154. continue;
  2155. }
  2156. }
  2157. current_name_parts.append(part.token().ident());
  2158. continue;
  2159. }
  2160. if (part.is(Token::Type::Comma)) {
  2161. if (current_name_parts.is_empty())
  2162. return nullptr;
  2163. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2164. current_name_parts.clear();
  2165. // Can't have a trailing comma
  2166. if (i + 1 == component_values.size())
  2167. return nullptr;
  2168. continue;
  2169. }
  2170. }
  2171. if (!current_name_parts.is_empty()) {
  2172. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2173. current_name_parts.clear();
  2174. }
  2175. if (font_families.is_empty())
  2176. return nullptr;
  2177. return StyleValueList::create(move(font_families));
  2178. }
  2179. RefPtr<StyleValue> Parser::parse_list_style_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2180. {
  2181. auto is_list_style_image = [](StyleValue const& value) -> bool {
  2182. if (value.is_image())
  2183. return true;
  2184. if (value.is_identifier() && value.to_identifier() == ValueID::None)
  2185. return true;
  2186. return false;
  2187. };
  2188. auto is_list_style_position = [](StyleValue const& value) -> bool {
  2189. switch (value.to_identifier()) {
  2190. case ValueID::Inside:
  2191. case ValueID::Outside:
  2192. return true;
  2193. default:
  2194. return false;
  2195. }
  2196. };
  2197. auto is_list_style_type = [](StyleValue const& value) -> bool {
  2198. // FIXME: Handle strings and symbols("...") syntax
  2199. switch (value.to_identifier()) {
  2200. case CSS::ValueID::None:
  2201. case CSS::ValueID::Disc:
  2202. case CSS::ValueID::Circle:
  2203. case CSS::ValueID::Square:
  2204. case CSS::ValueID::Decimal:
  2205. case CSS::ValueID::DecimalLeadingZero:
  2206. case CSS::ValueID::LowerAlpha:
  2207. case CSS::ValueID::LowerLatin:
  2208. case CSS::ValueID::UpperAlpha:
  2209. case CSS::ValueID::UpperLatin:
  2210. case CSS::ValueID::UpperRoman:
  2211. case CSS::ValueID::LowerRoman:
  2212. return true;
  2213. default:
  2214. return false;
  2215. }
  2216. };
  2217. if (component_values.size() > 3)
  2218. return nullptr;
  2219. RefPtr<StyleValue> list_position;
  2220. RefPtr<StyleValue> list_image;
  2221. RefPtr<StyleValue> list_type;
  2222. int found_nones = 0;
  2223. for (auto& part : component_values) {
  2224. auto value = parse_css_value(context, part);
  2225. if (!value)
  2226. return nullptr;
  2227. if (value->to_identifier() == ValueID::None) {
  2228. found_nones++;
  2229. continue;
  2230. }
  2231. if (is_list_style_position(*value)) {
  2232. if (list_position)
  2233. return nullptr;
  2234. list_position = value.release_nonnull();
  2235. continue;
  2236. }
  2237. if (is_list_style_image(*value)) {
  2238. if (list_image)
  2239. return nullptr;
  2240. list_image = value.release_nonnull();
  2241. continue;
  2242. }
  2243. if (is_list_style_type(*value)) {
  2244. if (list_type)
  2245. return nullptr;
  2246. list_type = value.release_nonnull();
  2247. continue;
  2248. }
  2249. }
  2250. if (found_nones > 2)
  2251. return nullptr;
  2252. if (found_nones == 2) {
  2253. if (list_image || list_type)
  2254. return nullptr;
  2255. auto none = IdentifierStyleValue::create(ValueID::None);
  2256. list_image = none;
  2257. list_type = none;
  2258. } else if (found_nones == 1) {
  2259. if (list_image && list_type)
  2260. return nullptr;
  2261. auto none = IdentifierStyleValue::create(ValueID::None);
  2262. if (!list_image)
  2263. list_image = none;
  2264. if (!list_type)
  2265. list_type = none;
  2266. }
  2267. if (!list_position)
  2268. list_position = property_initial_value(PropertyID::ListStylePosition);
  2269. if (!list_image)
  2270. list_image = property_initial_value(PropertyID::ListStyleImage);
  2271. if (!list_type)
  2272. list_type = property_initial_value(PropertyID::ListStyleType);
  2273. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  2274. }
  2275. RefPtr<StyleValue> Parser::parse_overflow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2276. {
  2277. auto is_overflow = [](StyleValue const& value) -> bool {
  2278. switch (value.to_identifier()) {
  2279. case ValueID::Auto:
  2280. case ValueID::Clip:
  2281. case ValueID::Hidden:
  2282. case ValueID::Scroll:
  2283. case ValueID::Visible:
  2284. return true;
  2285. default:
  2286. return false;
  2287. }
  2288. };
  2289. if (component_values.size() == 1) {
  2290. auto maybe_value = parse_css_value(context, component_values.first());
  2291. if (!maybe_value)
  2292. return nullptr;
  2293. auto value = maybe_value.release_nonnull();
  2294. if (is_overflow(*value))
  2295. return OverflowStyleValue::create(value, value);
  2296. return nullptr;
  2297. }
  2298. if (component_values.size() == 2) {
  2299. auto maybe_x_value = parse_css_value(context, component_values[0]);
  2300. auto maybe_y_value = parse_css_value(context, component_values[1]);
  2301. if (!maybe_x_value || !maybe_y_value)
  2302. return nullptr;
  2303. auto x_value = maybe_x_value.release_nonnull();
  2304. auto y_value = maybe_y_value.release_nonnull();
  2305. if (!is_overflow(x_value) || !is_overflow(y_value))
  2306. return nullptr;
  2307. return OverflowStyleValue::create(x_value, y_value);
  2308. }
  2309. return nullptr;
  2310. }
  2311. RefPtr<StyleValue> Parser::parse_text_decoration_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2312. {
  2313. auto is_text_decoration_line = [](StyleValue const& value) -> bool {
  2314. switch (value.to_identifier()) {
  2315. case ValueID::None:
  2316. case ValueID::Underline:
  2317. case ValueID::Overline:
  2318. case ValueID::LineThrough:
  2319. case ValueID::Blink:
  2320. return true;
  2321. default:
  2322. return false;
  2323. }
  2324. };
  2325. auto is_text_decoration_style = [](StyleValue const& value) -> bool {
  2326. switch (value.to_identifier()) {
  2327. case ValueID::Solid:
  2328. case ValueID::Double:
  2329. case ValueID::Dotted:
  2330. case ValueID::Dashed:
  2331. case ValueID::Wavy:
  2332. return true;
  2333. default:
  2334. return false;
  2335. }
  2336. };
  2337. if (component_values.size() > 3)
  2338. return nullptr;
  2339. RefPtr<StyleValue> decoration_line;
  2340. RefPtr<StyleValue> decoration_style;
  2341. RefPtr<StyleValue> decoration_color;
  2342. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  2343. for (auto& part : component_values) {
  2344. auto value = parse_css_value(context, part);
  2345. if (!value)
  2346. return nullptr;
  2347. if (is_color(*value)) {
  2348. if (decoration_color)
  2349. return nullptr;
  2350. decoration_color = value.release_nonnull();
  2351. continue;
  2352. }
  2353. if (is_text_decoration_line(*value)) {
  2354. if (decoration_line)
  2355. return nullptr;
  2356. decoration_line = value.release_nonnull();
  2357. continue;
  2358. }
  2359. if (is_text_decoration_style(*value)) {
  2360. if (decoration_style)
  2361. return nullptr;
  2362. decoration_style = value.release_nonnull();
  2363. continue;
  2364. }
  2365. return nullptr;
  2366. }
  2367. if (!decoration_line)
  2368. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  2369. if (!decoration_style)
  2370. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  2371. if (!decoration_color)
  2372. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  2373. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  2374. }
  2375. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  2376. {
  2377. if (name == "translateY")
  2378. return CSS::TransformFunction::TranslateY;
  2379. return {};
  2380. }
  2381. RefPtr<StyleValue> Parser::parse_transform_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2382. {
  2383. NonnullRefPtrVector<StyleValue> transformations;
  2384. for (auto& part : component_values) {
  2385. if (!part.is_function())
  2386. return nullptr;
  2387. auto maybe_function = parse_transform_function_name(part.function().name());
  2388. if (!maybe_function.has_value())
  2389. return nullptr;
  2390. NonnullRefPtrVector<StyleValue> values;
  2391. for (auto& value : part.function().values()) {
  2392. if (value.is(Token::Type::Dimension)) {
  2393. auto maybe_length = parse_length(context, value);
  2394. if (!maybe_length.has_value())
  2395. return nullptr;
  2396. values.append(LengthStyleValue::create(maybe_length.release_value()));
  2397. } else if (value.is(Token::Type::Number)) {
  2398. auto number = parse_numeric_value(context, value);
  2399. values.append(number.release_nonnull());
  2400. } else {
  2401. dbgln("FIXME: Unsupported value type for transformation!");
  2402. return nullptr;
  2403. }
  2404. }
  2405. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  2406. }
  2407. return StyleValueList::create(move(transformations));
  2408. }
  2409. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2410. {
  2411. auto component_values = parse_as_list_of_component_values();
  2412. auto tokens = TokenStream(component_values);
  2413. auto parsed_value = parse_css_value(property_id, tokens);
  2414. if (parsed_value.is_error())
  2415. return {};
  2416. return parsed_value.release_value();
  2417. }
  2418. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2419. {
  2420. m_context.set_current_property_id(property_id);
  2421. Vector<StyleComponentValueRule> component_values;
  2422. while (tokens.has_next_token()) {
  2423. auto& token = tokens.next_token();
  2424. if (token.is(Token::Type::Semicolon)) {
  2425. tokens.reconsume_current_input_token();
  2426. break;
  2427. }
  2428. if (token.is(Token::Type::Whitespace))
  2429. continue;
  2430. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2431. return ParsingResult::IncludesIgnoredVendorPrefix;
  2432. component_values.append(token);
  2433. }
  2434. if (component_values.is_empty())
  2435. return ParsingResult::SyntaxError;
  2436. if (component_values.size() == 1) {
  2437. if (auto parsed_value = parse_builtin_value(m_context, component_values.first()))
  2438. return parsed_value.release_nonnull();
  2439. }
  2440. // Special-case property handling
  2441. switch (property_id) {
  2442. case PropertyID::Background:
  2443. if (auto parsed_value = parse_background_value(m_context, component_values))
  2444. return parsed_value.release_nonnull();
  2445. return ParsingResult::SyntaxError;
  2446. case PropertyID::BackgroundImage:
  2447. if (auto parsed_value = parse_background_image_value(m_context, component_values))
  2448. return parsed_value.release_nonnull();
  2449. return ParsingResult::SyntaxError;
  2450. case PropertyID::BackgroundRepeat:
  2451. if (auto parsed_value = parse_background_repeat_value(m_context, component_values))
  2452. return parsed_value.release_nonnull();
  2453. return ParsingResult::SyntaxError;
  2454. case PropertyID::Border:
  2455. case PropertyID::BorderBottom:
  2456. case PropertyID::BorderLeft:
  2457. case PropertyID::BorderRight:
  2458. case PropertyID::BorderTop:
  2459. if (auto parsed_value = parse_border_value(m_context, component_values))
  2460. return parsed_value.release_nonnull();
  2461. return ParsingResult::SyntaxError;
  2462. case PropertyID::BorderTopLeftRadius:
  2463. case PropertyID::BorderTopRightRadius:
  2464. case PropertyID::BorderBottomRightRadius:
  2465. case PropertyID::BorderBottomLeftRadius:
  2466. if (auto parsed_value = parse_border_radius_value(m_context, component_values))
  2467. return parsed_value.release_nonnull();
  2468. return ParsingResult::SyntaxError;
  2469. case PropertyID::BorderRadius:
  2470. if (auto parsed_value = parse_border_radius_shorthand_value(m_context, component_values))
  2471. return parsed_value.release_nonnull();
  2472. return ParsingResult::SyntaxError;
  2473. case PropertyID::BoxShadow:
  2474. if (auto parsed_value = parse_box_shadow_value(m_context, component_values))
  2475. return parsed_value.release_nonnull();
  2476. return ParsingResult::SyntaxError;
  2477. case PropertyID::Flex:
  2478. if (auto parsed_value = parse_flex_value(m_context, component_values))
  2479. return parsed_value.release_nonnull();
  2480. return ParsingResult::SyntaxError;
  2481. case PropertyID::FlexFlow:
  2482. if (auto parsed_value = parse_flex_flow_value(m_context, component_values))
  2483. return parsed_value.release_nonnull();
  2484. return ParsingResult::SyntaxError;
  2485. case PropertyID::Font:
  2486. if (auto parsed_value = parse_font_value(m_context, component_values))
  2487. return parsed_value.release_nonnull();
  2488. return ParsingResult::SyntaxError;
  2489. case PropertyID::FontFamily:
  2490. if (auto parsed_value = parse_font_family_value(m_context, component_values))
  2491. return parsed_value.release_nonnull();
  2492. return ParsingResult::SyntaxError;
  2493. case PropertyID::ListStyle:
  2494. if (auto parsed_value = parse_list_style_value(m_context, component_values))
  2495. return parsed_value.release_nonnull();
  2496. return ParsingResult::SyntaxError;
  2497. case PropertyID::Overflow:
  2498. if (auto parsed_value = parse_overflow_value(m_context, component_values))
  2499. return parsed_value.release_nonnull();
  2500. return ParsingResult::SyntaxError;
  2501. case PropertyID::TextDecoration:
  2502. if (auto parsed_value = parse_text_decoration_value(m_context, component_values))
  2503. return parsed_value.release_nonnull();
  2504. return ParsingResult::SyntaxError;
  2505. case PropertyID::Transform:
  2506. if (auto parsed_value = parse_transform_value(m_context, component_values))
  2507. return parsed_value.release_nonnull();
  2508. return ParsingResult::SyntaxError;
  2509. default:
  2510. break;
  2511. }
  2512. if (component_values.size() == 1) {
  2513. if (auto parsed_value = parse_css_value(m_context, component_values.first()))
  2514. return parsed_value.release_nonnull();
  2515. return ParsingResult::SyntaxError;
  2516. }
  2517. // We have multiple values, so treat them as a StyleValueList.
  2518. // FIXME: Specify in Properties.json whether to permit this for each property.
  2519. NonnullRefPtrVector<StyleValue> parsed_values;
  2520. for (auto& component_value : component_values) {
  2521. auto parsed = parse_css_value(m_context, component_value);
  2522. if (!parsed)
  2523. return ParsingResult::SyntaxError;
  2524. parsed_values.append(parsed.release_nonnull());
  2525. }
  2526. if (!parsed_values.is_empty())
  2527. return { StyleValueList::create(move(parsed_values)) };
  2528. return ParsingResult::SyntaxError;
  2529. }
  2530. RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  2531. {
  2532. if (auto builtin = parse_builtin_value(context, component_value))
  2533. return builtin;
  2534. if (auto dynamic = parse_dynamic_value(context, component_value))
  2535. return dynamic;
  2536. if (auto length = parse_length_value(context, component_value))
  2537. return length;
  2538. if (auto numeric = parse_numeric_value(context, component_value))
  2539. return numeric;
  2540. if (auto identifier = parse_identifier_value(context, component_value))
  2541. return identifier;
  2542. if (auto color = parse_color_value(context, component_value))
  2543. return color;
  2544. if (auto string = parse_string_value(context, component_value))
  2545. return string;
  2546. if (auto image = parse_image_value(context, component_value))
  2547. return image;
  2548. return {};
  2549. }
  2550. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  2551. {
  2552. int a = 0;
  2553. int b = 0;
  2554. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2555. if constexpr (CSS_PARSER_DEBUG) {
  2556. dbgln("Invalid An+B value:");
  2557. values.dump_all_tokens();
  2558. }
  2559. return {};
  2560. };
  2561. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2562. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  2563. values.skip_whitespace();
  2564. if (values.has_next_token()) {
  2565. if constexpr (CSS_PARSER_DEBUG) {
  2566. dbgln("Extra tokens at end of An+B value:");
  2567. values.dump_all_tokens();
  2568. }
  2569. return syntax_error();
  2570. } else {
  2571. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  2572. }
  2573. };
  2574. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  2575. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  2576. };
  2577. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  2578. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  2579. };
  2580. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  2581. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  2582. };
  2583. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  2584. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  2585. };
  2586. auto is_delim = [](StyleComponentValueRule const& value, StringView const& delim) -> bool {
  2587. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  2588. };
  2589. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  2590. if (!value.is(Token::Type::Dimension))
  2591. return false;
  2592. if (value.token().number_type() != Token::NumberType::Integer)
  2593. return false;
  2594. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  2595. return false;
  2596. return true;
  2597. };
  2598. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  2599. if (!value.is(Token::Type::Dimension))
  2600. return false;
  2601. if (value.token().number_type() != Token::NumberType::Integer)
  2602. return false;
  2603. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  2604. return false;
  2605. return true;
  2606. };
  2607. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  2608. if (!value.is(Token::Type::Dimension))
  2609. return false;
  2610. if (value.token().number_type() != Token::NumberType::Integer)
  2611. return false;
  2612. auto dimension_unit = value.token().dimension_unit();
  2613. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2614. return false;
  2615. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  2616. if (!is_ascii_digit(dimension_unit[i]))
  2617. return false;
  2618. }
  2619. return true;
  2620. };
  2621. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2622. if (!value.is(Token::Type::Ident))
  2623. return false;
  2624. auto ident = value.token().ident();
  2625. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2626. return false;
  2627. for (size_t i = 2; i < ident.length(); ++i) {
  2628. if (!is_ascii_digit(ident[i]))
  2629. return false;
  2630. }
  2631. return true;
  2632. };
  2633. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2634. if (!value.is(Token::Type::Ident))
  2635. return false;
  2636. auto ident = value.token().ident();
  2637. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  2638. return false;
  2639. for (size_t i = 3; i < ident.length(); ++i) {
  2640. if (!is_ascii_digit(ident[i]))
  2641. return false;
  2642. }
  2643. return true;
  2644. };
  2645. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  2646. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  2647. };
  2648. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2649. return is_integer(value) && value.token().is_integer_value_signed();
  2650. };
  2651. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2652. return is_integer(value) && !value.token().is_integer_value_signed();
  2653. };
  2654. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  2655. // Unfortunately these can't be in the same order as in the spec.
  2656. values.skip_whitespace();
  2657. auto& first_value = values.next_token();
  2658. // odd | even
  2659. if (first_value.is(Token::Type::Ident)) {
  2660. auto ident = first_value.token().ident();
  2661. if (ident.equals_ignoring_case("odd")) {
  2662. a = 2;
  2663. b = 1;
  2664. return make_return_value();
  2665. } else if (ident.equals_ignoring_case("even")) {
  2666. a = 2;
  2667. return make_return_value();
  2668. }
  2669. }
  2670. // <integer>
  2671. if (is_integer(first_value)) {
  2672. b = first_value.token().to_integer();
  2673. return make_return_value();
  2674. }
  2675. // <n-dimension>
  2676. // <n-dimension> <signed-integer>
  2677. // <n-dimension> ['+' | '-'] <signless-integer>
  2678. if (is_n_dimension(first_value)) {
  2679. a = first_value.token().dimension_value_int();
  2680. values.skip_whitespace();
  2681. auto& second_value = values.next_token();
  2682. if (second_value.is(Token::Type::EndOfFile)) {
  2683. // <n-dimension>
  2684. return make_return_value();
  2685. } else if (is_signed_integer(second_value)) {
  2686. // <n-dimension> <signed-integer>
  2687. b = second_value.token().to_integer();
  2688. return make_return_value();
  2689. }
  2690. values.skip_whitespace();
  2691. auto& third_value = values.next_token();
  2692. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2693. // <n-dimension> ['+' | '-'] <signless-integer>
  2694. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2695. return make_return_value();
  2696. }
  2697. return syntax_error();
  2698. }
  2699. // <ndash-dimension> <signless-integer>
  2700. if (is_ndash_dimension(first_value)) {
  2701. values.skip_whitespace();
  2702. auto& second_value = values.next_token();
  2703. if (is_signless_integer(second_value)) {
  2704. a = first_value.token().dimension_value_int();
  2705. b = -second_value.token().to_integer();
  2706. return make_return_value();
  2707. }
  2708. return syntax_error();
  2709. }
  2710. // <ndashdigit-dimension>
  2711. if (is_ndashdigit_dimension(first_value)) {
  2712. auto& dimension = first_value.token();
  2713. a = dimension.dimension_value_int();
  2714. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  2715. if (maybe_b.has_value()) {
  2716. b = maybe_b.value();
  2717. return make_return_value();
  2718. }
  2719. return syntax_error();
  2720. }
  2721. // <dashndashdigit-ident>
  2722. if (is_dashndashdigit_ident(first_value)) {
  2723. a = -1;
  2724. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  2725. if (maybe_b.has_value()) {
  2726. b = maybe_b.value();
  2727. return make_return_value();
  2728. }
  2729. return syntax_error();
  2730. }
  2731. // -n
  2732. // -n <signed-integer>
  2733. // -n ['+' | '-'] <signless-integer>
  2734. if (is_dashn(first_value)) {
  2735. a = -1;
  2736. values.skip_whitespace();
  2737. auto& second_value = values.next_token();
  2738. if (second_value.is(Token::Type::EndOfFile)) {
  2739. // -n
  2740. return make_return_value();
  2741. } else if (is_signed_integer(second_value)) {
  2742. // -n <signed-integer>
  2743. b = second_value.token().to_integer();
  2744. return make_return_value();
  2745. }
  2746. values.skip_whitespace();
  2747. auto& third_value = values.next_token();
  2748. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2749. // -n ['+' | '-'] <signless-integer>
  2750. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2751. return make_return_value();
  2752. }
  2753. return syntax_error();
  2754. }
  2755. // -n- <signless-integer>
  2756. if (is_dashndash(first_value)) {
  2757. values.skip_whitespace();
  2758. auto& second_value = values.next_token();
  2759. if (is_signless_integer(second_value)) {
  2760. a = -1;
  2761. b = -second_value.token().to_integer();
  2762. return make_return_value();
  2763. }
  2764. return syntax_error();
  2765. }
  2766. // All that's left now are these:
  2767. // '+'?† n
  2768. // '+'?† n <signed-integer>
  2769. // '+'?† n ['+' | '-'] <signless-integer>
  2770. // '+'?† n- <signless-integer>
  2771. // '+'?† <ndashdigit-ident>
  2772. // In all of these cases, the + is optional, and has no effect.
  2773. // So, we just skip the +, and carry on.
  2774. if (!is_delim(first_value, "+"sv)) {
  2775. values.reconsume_current_input_token();
  2776. // We do *not* skip whitespace here.
  2777. }
  2778. auto& first_after_plus = values.next_token();
  2779. // '+'?† n
  2780. // '+'?† n <signed-integer>
  2781. // '+'?† n ['+' | '-'] <signless-integer>
  2782. if (is_n(first_after_plus)) {
  2783. a = 1;
  2784. values.skip_whitespace();
  2785. auto& second_value = values.next_token();
  2786. if (second_value.is(Token::Type::EndOfFile)) {
  2787. // '+'?† n
  2788. return make_return_value();
  2789. } else if (is_signed_integer(second_value)) {
  2790. // '+'?† n <signed-integer>
  2791. b = second_value.token().to_integer();
  2792. return make_return_value();
  2793. }
  2794. values.skip_whitespace();
  2795. auto& third_value = values.next_token();
  2796. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2797. // '+'?† n ['+' | '-'] <signless-integer>
  2798. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2799. return make_return_value();
  2800. }
  2801. return syntax_error();
  2802. }
  2803. // '+'?† n- <signless-integer>
  2804. if (is_ndash(first_after_plus)) {
  2805. values.skip_whitespace();
  2806. auto& second_value = values.next_token();
  2807. if (is_signless_integer(second_value)) {
  2808. a = 1;
  2809. b = -second_value.token().to_integer();
  2810. return make_return_value();
  2811. }
  2812. return syntax_error();
  2813. }
  2814. // '+'?† <ndashdigit-ident>
  2815. if (is_ndashdigit_ident(first_after_plus)) {
  2816. a = 1;
  2817. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  2818. if (maybe_b.has_value()) {
  2819. b = maybe_b.value();
  2820. return make_return_value();
  2821. }
  2822. return syntax_error();
  2823. }
  2824. return syntax_error();
  2825. }
  2826. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(ParsingContext const& context, Vector<StyleComponentValueRule> const& values)
  2827. {
  2828. auto tokens = TokenStream(values);
  2829. return parse_calc_sum(context, tokens);
  2830. }
  2831. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2832. {
  2833. auto current_token = tokens.next_token();
  2834. if (current_token.is_block() && current_token.block().is_paren()) {
  2835. auto block_values = TokenStream(current_token.block().values());
  2836. auto parsed_calc_sum = parse_calc_sum(context, block_values);
  2837. if (!parsed_calc_sum)
  2838. return {};
  2839. return (CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() };
  2840. }
  2841. if (current_token.is(Token::Type::Number)) {
  2842. auto try_the_number = try_parse_float(current_token.token().number_string_value());
  2843. if (try_the_number.has_value())
  2844. return (CalculatedStyleValue::CalcValue) { try_the_number.value() };
  2845. return {};
  2846. }
  2847. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  2848. auto maybe_length = parse_length(context, current_token);
  2849. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  2850. return (CalculatedStyleValue::CalcValue) { maybe_length.value() };
  2851. return {};
  2852. }
  2853. return {};
  2854. }
  2855. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2856. {
  2857. // Note: The default value is not used or passed around.
  2858. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  2859. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  2860. CalculatedStyleValue::CalcNumberValue(0));
  2861. tokens.skip_whitespace();
  2862. auto& op_token = tokens.peek_token();
  2863. if (!op_token.is(Token::Type::Delim))
  2864. return nullptr;
  2865. auto op = op_token.token().delim();
  2866. if (op == "*"sv) {
  2867. tokens.next_token();
  2868. tokens.skip_whitespace();
  2869. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  2870. auto parsed_calc_value = parse_calc_value(context, tokens);
  2871. if (!parsed_calc_value.has_value())
  2872. return nullptr;
  2873. product_with_operator->value = { parsed_calc_value.release_value() };
  2874. } else if (op == "/"sv) {
  2875. tokens.next_token();
  2876. tokens.skip_whitespace();
  2877. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  2878. auto parsed_calc_number_value = parse_calc_number_value(context, tokens);
  2879. if (!parsed_calc_number_value.has_value())
  2880. return nullptr;
  2881. product_with_operator->value = { parsed_calc_number_value.release_value() };
  2882. } else {
  2883. return nullptr;
  2884. }
  2885. return product_with_operator;
  2886. }
  2887. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2888. {
  2889. // Note: The default value is not used or passed around.
  2890. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  2891. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  2892. CalculatedStyleValue::CalcNumberValue(0));
  2893. tokens.skip_whitespace();
  2894. auto& op_token = tokens.peek_token();
  2895. if (!op_token.is(Token::Type::Delim))
  2896. return nullptr;
  2897. auto op = op_token.token().delim();
  2898. if (op == "*"sv) {
  2899. tokens.next_token();
  2900. tokens.skip_whitespace();
  2901. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  2902. } else if (op == "/"sv) {
  2903. tokens.next_token();
  2904. tokens.skip_whitespace();
  2905. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  2906. } else {
  2907. return nullptr;
  2908. }
  2909. auto parsed_calc_value = parse_calc_number_value(context, tokens);
  2910. if (!parsed_calc_value.has_value())
  2911. return nullptr;
  2912. number_product_with_operator->value = parsed_calc_value.release_value();
  2913. return number_product_with_operator;
  2914. }
  2915. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2916. {
  2917. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  2918. CalculatedStyleValue::CalcNumberValue(0),
  2919. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  2920. auto first_calc_number_value_or_error = parse_calc_number_value(context, tokens);
  2921. if (!first_calc_number_value_or_error.has_value())
  2922. return nullptr;
  2923. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  2924. while (tokens.has_next_token()) {
  2925. auto number_product_with_operator = parse_calc_number_product_part_with_operator(context, tokens);
  2926. if (!number_product_with_operator)
  2927. break;
  2928. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  2929. }
  2930. return calc_number_product;
  2931. }
  2932. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2933. {
  2934. if (!(tokens.peek_token().is(Token::Type::Delim)
  2935. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2936. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2937. return nullptr;
  2938. auto& token = tokens.next_token();
  2939. tokens.skip_whitespace();
  2940. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  2941. auto delim = token.token().delim();
  2942. if (delim == "+"sv)
  2943. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  2944. else if (delim == "-"sv)
  2945. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  2946. else
  2947. return nullptr;
  2948. auto calc_number_product = parse_calc_number_product(context, tokens);
  2949. if (!calc_number_product)
  2950. return nullptr;
  2951. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  2952. }
  2953. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2954. {
  2955. auto first_calc_number_product_or_error = parse_calc_number_product(context, tokens);
  2956. if (!first_calc_number_product_or_error)
  2957. return nullptr;
  2958. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  2959. while (tokens.has_next_token()) {
  2960. auto calc_sum_part = parse_calc_number_sum_part_with_operator(context, tokens);
  2961. if (!calc_sum_part)
  2962. return nullptr;
  2963. additional.append(calc_sum_part.release_nonnull());
  2964. }
  2965. tokens.skip_whitespace();
  2966. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  2967. return calc_number_sum;
  2968. }
  2969. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2970. {
  2971. auto& first = tokens.peek_token();
  2972. if (first.is_block() && first.block().is_paren()) {
  2973. tokens.next_token();
  2974. auto block_values = TokenStream(first.block().values());
  2975. auto calc_number_sum = parse_calc_number_sum(context, block_values);
  2976. if (calc_number_sum)
  2977. return { calc_number_sum.release_nonnull() };
  2978. }
  2979. if (!first.is(Token::Type::Number))
  2980. return {};
  2981. tokens.next_token();
  2982. auto try_the_number = try_parse_float(first.token().number_string_value());
  2983. if (!try_the_number.has_value())
  2984. return {};
  2985. return try_the_number.value();
  2986. }
  2987. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2988. {
  2989. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  2990. CalculatedStyleValue::CalcValue(0),
  2991. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  2992. auto first_calc_value_or_error = parse_calc_value(context, tokens);
  2993. if (!first_calc_value_or_error.has_value())
  2994. return nullptr;
  2995. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  2996. while (tokens.has_next_token()) {
  2997. auto product_with_operator = parse_calc_product_part_with_operator(context, tokens);
  2998. if (!product_with_operator)
  2999. break;
  3000. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  3001. }
  3002. return calc_product;
  3003. }
  3004. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3005. {
  3006. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  3007. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  3008. if (!(tokens.peek_token().is(Token::Type::Delim)
  3009. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3010. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3011. return nullptr;
  3012. auto& token = tokens.next_token();
  3013. tokens.skip_whitespace();
  3014. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  3015. auto delim = token.token().delim();
  3016. if (delim == "+"sv)
  3017. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  3018. else if (delim == "-"sv)
  3019. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  3020. else
  3021. return nullptr;
  3022. auto calc_product = parse_calc_product(context, tokens);
  3023. if (!calc_product)
  3024. return nullptr;
  3025. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  3026. };
  3027. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3028. {
  3029. auto parsed_calc_product = parse_calc_product(context, tokens);
  3030. if (!parsed_calc_product)
  3031. return nullptr;
  3032. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  3033. while (tokens.has_next_token()) {
  3034. auto calc_sum_part = parse_calc_sum_part_with_operator(context, tokens);
  3035. if (!calc_sum_part)
  3036. return nullptr;
  3037. additional.append(calc_sum_part.release_nonnull());
  3038. }
  3039. tokens.skip_whitespace();
  3040. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  3041. }
  3042. bool Parser::has_ignored_vendor_prefix(StringView const& string)
  3043. {
  3044. if (!string.starts_with('-'))
  3045. return false;
  3046. if (string.starts_with("--"))
  3047. return false;
  3048. if (string.starts_with("-libweb-"))
  3049. return false;
  3050. return true;
  3051. }
  3052. }
  3053. namespace Web {
  3054. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView const& css)
  3055. {
  3056. if (css.is_empty())
  3057. return CSS::CSSStyleSheet::create({});
  3058. CSS::Parser parser(context, css);
  3059. return parser.parse_as_stylesheet();
  3060. }
  3061. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView const& css)
  3062. {
  3063. if (css.is_empty())
  3064. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  3065. CSS::Parser parser(context, css);
  3066. return parser.parse_as_list_of_declarations();
  3067. }
  3068. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView const& string, CSS::PropertyID property_id)
  3069. {
  3070. if (string.is_empty())
  3071. return {};
  3072. CSS::Parser parser(context, string);
  3073. return parser.parse_as_css_value(property_id);
  3074. }
  3075. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView const& selector_text)
  3076. {
  3077. CSS::Parser parser(context, selector_text);
  3078. return parser.parse_as_selector();
  3079. }
  3080. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView const& string)
  3081. {
  3082. auto integer = string.to_int();
  3083. if (integer.has_value())
  3084. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  3085. // FIXME: The const_cast is a hack.
  3086. return parse_css_value(CSS::ParsingContext(const_cast<DOM::Document&>(document)), string);
  3087. }
  3088. }