Parser.cpp 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566
  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. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2376. {
  2377. auto component_values = parse_as_list_of_component_values();
  2378. auto tokens = TokenStream(component_values);
  2379. auto parsed_value = parse_css_value(property_id, tokens);
  2380. if (parsed_value.is_error())
  2381. return {};
  2382. return parsed_value.release_value();
  2383. }
  2384. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2385. {
  2386. m_context.set_current_property_id(property_id);
  2387. Vector<StyleComponentValueRule> component_values;
  2388. while (tokens.has_next_token()) {
  2389. auto& token = tokens.next_token();
  2390. if (token.is(Token::Type::Semicolon)) {
  2391. tokens.reconsume_current_input_token();
  2392. break;
  2393. }
  2394. if (token.is(Token::Type::Whitespace))
  2395. continue;
  2396. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2397. return ParsingResult::IncludesIgnoredVendorPrefix;
  2398. component_values.append(token);
  2399. }
  2400. if (component_values.is_empty())
  2401. return ParsingResult::SyntaxError;
  2402. if (component_values.size() == 1) {
  2403. if (auto parsed_value = parse_builtin_value(m_context, component_values.first()))
  2404. return parsed_value.release_nonnull();
  2405. }
  2406. // Special-case property handling
  2407. switch (property_id) {
  2408. case PropertyID::Background:
  2409. if (auto parsed_value = parse_background_value(m_context, component_values))
  2410. return parsed_value.release_nonnull();
  2411. break;
  2412. case PropertyID::BackgroundImage:
  2413. if (auto parsed_value = parse_background_image_value(m_context, component_values))
  2414. return parsed_value.release_nonnull();
  2415. break;
  2416. case PropertyID::BackgroundRepeat:
  2417. if (auto parsed_value = parse_background_repeat_value(m_context, component_values))
  2418. return parsed_value.release_nonnull();
  2419. break;
  2420. case PropertyID::Border:
  2421. case PropertyID::BorderBottom:
  2422. case PropertyID::BorderLeft:
  2423. case PropertyID::BorderRight:
  2424. case PropertyID::BorderTop:
  2425. if (auto parsed_value = parse_border_value(m_context, component_values))
  2426. return parsed_value.release_nonnull();
  2427. break;
  2428. case PropertyID::BorderTopLeftRadius:
  2429. case PropertyID::BorderTopRightRadius:
  2430. case PropertyID::BorderBottomRightRadius:
  2431. case PropertyID::BorderBottomLeftRadius:
  2432. if (auto parsed_value = parse_border_radius_value(m_context, component_values))
  2433. return parsed_value.release_nonnull();
  2434. break;
  2435. case PropertyID::BorderRadius:
  2436. if (auto parsed_value = parse_border_radius_shorthand_value(m_context, component_values))
  2437. return parsed_value.release_nonnull();
  2438. break;
  2439. case PropertyID::BoxShadow:
  2440. if (auto parsed_value = parse_box_shadow_value(m_context, component_values))
  2441. return parsed_value.release_nonnull();
  2442. break;
  2443. case PropertyID::Flex:
  2444. if (auto parsed_value = parse_flex_value(m_context, component_values))
  2445. return parsed_value.release_nonnull();
  2446. break;
  2447. case PropertyID::FlexFlow:
  2448. if (auto parsed_value = parse_flex_flow_value(m_context, component_values))
  2449. return parsed_value.release_nonnull();
  2450. break;
  2451. case PropertyID::Font:
  2452. if (auto parsed_value = parse_font_value(m_context, component_values))
  2453. return parsed_value.release_nonnull();
  2454. break;
  2455. case PropertyID::FontFamily:
  2456. if (auto parsed_value = parse_font_family_value(m_context, component_values))
  2457. return parsed_value.release_nonnull();
  2458. break;
  2459. case PropertyID::ListStyle:
  2460. if (auto parsed_value = parse_list_style_value(m_context, component_values))
  2461. return parsed_value.release_nonnull();
  2462. break;
  2463. case PropertyID::Overflow:
  2464. if (auto parsed_value = parse_overflow_value(m_context, component_values))
  2465. return parsed_value.release_nonnull();
  2466. break;
  2467. case PropertyID::TextDecoration:
  2468. if (auto parsed_value = parse_text_decoration_value(m_context, component_values))
  2469. return parsed_value.release_nonnull();
  2470. break;
  2471. default:
  2472. break;
  2473. }
  2474. if (component_values.size() == 1) {
  2475. if (auto parsed_value = parse_css_value(m_context, component_values.first()))
  2476. return parsed_value.release_nonnull();
  2477. return ParsingResult::SyntaxError;
  2478. }
  2479. // We have multiple values, so treat them as a StyleValueList.
  2480. // FIXME: Specify in Properties.json whether to permit this for each property.
  2481. NonnullRefPtrVector<StyleValue> parsed_values;
  2482. for (auto& component_value : component_values) {
  2483. auto parsed = parse_css_value(m_context, component_value);
  2484. if (!parsed)
  2485. return ParsingResult::SyntaxError;
  2486. parsed_values.append(parsed.release_nonnull());
  2487. }
  2488. if (!parsed_values.is_empty())
  2489. return { StyleValueList::create(move(parsed_values)) };
  2490. return ParsingResult::SyntaxError;
  2491. }
  2492. RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  2493. {
  2494. if (auto builtin = parse_builtin_value(context, component_value))
  2495. return builtin;
  2496. if (auto dynamic = parse_dynamic_value(context, component_value))
  2497. return dynamic;
  2498. if (auto length = parse_length_value(context, component_value))
  2499. return length;
  2500. if (auto numeric = parse_numeric_value(context, component_value))
  2501. return numeric;
  2502. if (auto identifier = parse_identifier_value(context, component_value))
  2503. return identifier;
  2504. if (auto color = parse_color_value(context, component_value))
  2505. return color;
  2506. if (auto string = parse_string_value(context, component_value))
  2507. return string;
  2508. if (auto image = parse_image_value(context, component_value))
  2509. return image;
  2510. return {};
  2511. }
  2512. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  2513. {
  2514. int a = 0;
  2515. int b = 0;
  2516. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2517. if constexpr (CSS_PARSER_DEBUG) {
  2518. dbgln("Invalid An+B value:");
  2519. values.dump_all_tokens();
  2520. }
  2521. return {};
  2522. };
  2523. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  2524. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  2525. values.skip_whitespace();
  2526. if (values.has_next_token()) {
  2527. if constexpr (CSS_PARSER_DEBUG) {
  2528. dbgln("Extra tokens at end of An+B value:");
  2529. values.dump_all_tokens();
  2530. }
  2531. return syntax_error();
  2532. } else {
  2533. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  2534. }
  2535. };
  2536. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  2537. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  2538. };
  2539. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  2540. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  2541. };
  2542. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  2543. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  2544. };
  2545. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  2546. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  2547. };
  2548. auto is_delim = [](StyleComponentValueRule const& value, StringView const& delim) -> bool {
  2549. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  2550. };
  2551. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  2552. if (!value.is(Token::Type::Dimension))
  2553. return false;
  2554. if (value.token().number_type() != Token::NumberType::Integer)
  2555. return false;
  2556. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  2557. return false;
  2558. return true;
  2559. };
  2560. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  2561. if (!value.is(Token::Type::Dimension))
  2562. return false;
  2563. if (value.token().number_type() != Token::NumberType::Integer)
  2564. return false;
  2565. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  2566. return false;
  2567. return true;
  2568. };
  2569. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  2570. if (!value.is(Token::Type::Dimension))
  2571. return false;
  2572. if (value.token().number_type() != Token::NumberType::Integer)
  2573. return false;
  2574. auto dimension_unit = value.token().dimension_unit();
  2575. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2576. return false;
  2577. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  2578. if (!is_ascii_digit(dimension_unit[i]))
  2579. return false;
  2580. }
  2581. return true;
  2582. };
  2583. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2584. if (!value.is(Token::Type::Ident))
  2585. return false;
  2586. auto ident = value.token().ident();
  2587. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  2588. return false;
  2589. for (size_t i = 2; i < ident.length(); ++i) {
  2590. if (!is_ascii_digit(ident[i]))
  2591. return false;
  2592. }
  2593. return true;
  2594. };
  2595. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  2596. if (!value.is(Token::Type::Ident))
  2597. return false;
  2598. auto ident = value.token().ident();
  2599. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  2600. return false;
  2601. for (size_t i = 3; i < ident.length(); ++i) {
  2602. if (!is_ascii_digit(ident[i]))
  2603. return false;
  2604. }
  2605. return true;
  2606. };
  2607. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  2608. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  2609. };
  2610. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2611. return is_integer(value) && value.token().is_integer_value_signed();
  2612. };
  2613. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  2614. return is_integer(value) && !value.token().is_integer_value_signed();
  2615. };
  2616. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  2617. // Unfortunately these can't be in the same order as in the spec.
  2618. values.skip_whitespace();
  2619. auto& first_value = values.next_token();
  2620. // odd | even
  2621. if (first_value.is(Token::Type::Ident)) {
  2622. auto ident = first_value.token().ident();
  2623. if (ident.equals_ignoring_case("odd")) {
  2624. a = 2;
  2625. b = 1;
  2626. return make_return_value();
  2627. } else if (ident.equals_ignoring_case("even")) {
  2628. a = 2;
  2629. return make_return_value();
  2630. }
  2631. }
  2632. // <integer>
  2633. if (is_integer(first_value)) {
  2634. b = first_value.token().to_integer();
  2635. return make_return_value();
  2636. }
  2637. // <n-dimension>
  2638. // <n-dimension> <signed-integer>
  2639. // <n-dimension> ['+' | '-'] <signless-integer>
  2640. if (is_n_dimension(first_value)) {
  2641. a = first_value.token().dimension_value_int();
  2642. values.skip_whitespace();
  2643. auto& second_value = values.next_token();
  2644. if (second_value.is(Token::Type::EndOfFile)) {
  2645. // <n-dimension>
  2646. return make_return_value();
  2647. } else if (is_signed_integer(second_value)) {
  2648. // <n-dimension> <signed-integer>
  2649. b = second_value.token().to_integer();
  2650. return make_return_value();
  2651. }
  2652. values.skip_whitespace();
  2653. auto& third_value = values.next_token();
  2654. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2655. // <n-dimension> ['+' | '-'] <signless-integer>
  2656. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2657. return make_return_value();
  2658. }
  2659. return syntax_error();
  2660. }
  2661. // <ndash-dimension> <signless-integer>
  2662. if (is_ndash_dimension(first_value)) {
  2663. values.skip_whitespace();
  2664. auto& second_value = values.next_token();
  2665. if (is_signless_integer(second_value)) {
  2666. a = first_value.token().dimension_value_int();
  2667. b = -second_value.token().to_integer();
  2668. return make_return_value();
  2669. }
  2670. return syntax_error();
  2671. }
  2672. // <ndashdigit-dimension>
  2673. if (is_ndashdigit_dimension(first_value)) {
  2674. auto& dimension = first_value.token();
  2675. a = dimension.dimension_value_int();
  2676. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  2677. if (maybe_b.has_value()) {
  2678. b = maybe_b.value();
  2679. return make_return_value();
  2680. }
  2681. return syntax_error();
  2682. }
  2683. // <dashndashdigit-ident>
  2684. if (is_dashndashdigit_ident(first_value)) {
  2685. a = -1;
  2686. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  2687. if (maybe_b.has_value()) {
  2688. b = maybe_b.value();
  2689. return make_return_value();
  2690. }
  2691. return syntax_error();
  2692. }
  2693. // -n
  2694. // -n <signed-integer>
  2695. // -n ['+' | '-'] <signless-integer>
  2696. if (is_dashn(first_value)) {
  2697. a = -1;
  2698. values.skip_whitespace();
  2699. auto& second_value = values.next_token();
  2700. if (second_value.is(Token::Type::EndOfFile)) {
  2701. // -n
  2702. return make_return_value();
  2703. } else if (is_signed_integer(second_value)) {
  2704. // -n <signed-integer>
  2705. b = second_value.token().to_integer();
  2706. return make_return_value();
  2707. }
  2708. values.skip_whitespace();
  2709. auto& third_value = values.next_token();
  2710. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2711. // -n ['+' | '-'] <signless-integer>
  2712. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2713. return make_return_value();
  2714. }
  2715. return syntax_error();
  2716. }
  2717. // -n- <signless-integer>
  2718. if (is_dashndash(first_value)) {
  2719. values.skip_whitespace();
  2720. auto& second_value = values.next_token();
  2721. if (is_signless_integer(second_value)) {
  2722. a = -1;
  2723. b = -second_value.token().to_integer();
  2724. return make_return_value();
  2725. }
  2726. return syntax_error();
  2727. }
  2728. // All that's left now are these:
  2729. // '+'?† n
  2730. // '+'?† n <signed-integer>
  2731. // '+'?† n ['+' | '-'] <signless-integer>
  2732. // '+'?† n- <signless-integer>
  2733. // '+'?† <ndashdigit-ident>
  2734. // In all of these cases, the + is optional, and has no effect.
  2735. // So, we just skip the +, and carry on.
  2736. if (!is_delim(first_value, "+"sv)) {
  2737. values.reconsume_current_input_token();
  2738. // We do *not* skip whitespace here.
  2739. }
  2740. auto& first_after_plus = values.next_token();
  2741. // '+'?† n
  2742. // '+'?† n <signed-integer>
  2743. // '+'?† n ['+' | '-'] <signless-integer>
  2744. if (is_n(first_after_plus)) {
  2745. a = 1;
  2746. values.skip_whitespace();
  2747. auto& second_value = values.next_token();
  2748. if (second_value.is(Token::Type::EndOfFile)) {
  2749. // '+'?† n
  2750. return make_return_value();
  2751. } else if (is_signed_integer(second_value)) {
  2752. // '+'?† n <signed-integer>
  2753. b = second_value.token().to_integer();
  2754. return make_return_value();
  2755. }
  2756. values.skip_whitespace();
  2757. auto& third_value = values.next_token();
  2758. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  2759. // '+'?† n ['+' | '-'] <signless-integer>
  2760. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  2761. return make_return_value();
  2762. }
  2763. return syntax_error();
  2764. }
  2765. // '+'?† n- <signless-integer>
  2766. if (is_ndash(first_after_plus)) {
  2767. values.skip_whitespace();
  2768. auto& second_value = values.next_token();
  2769. if (is_signless_integer(second_value)) {
  2770. a = 1;
  2771. b = -second_value.token().to_integer();
  2772. return make_return_value();
  2773. }
  2774. return syntax_error();
  2775. }
  2776. // '+'?† <ndashdigit-ident>
  2777. if (is_ndashdigit_ident(first_after_plus)) {
  2778. a = 1;
  2779. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  2780. if (maybe_b.has_value()) {
  2781. b = maybe_b.value();
  2782. return make_return_value();
  2783. }
  2784. return syntax_error();
  2785. }
  2786. return syntax_error();
  2787. }
  2788. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(ParsingContext const& context, Vector<StyleComponentValueRule> const& values)
  2789. {
  2790. auto tokens = TokenStream(values);
  2791. return parse_calc_sum(context, tokens);
  2792. }
  2793. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2794. {
  2795. auto current_token = tokens.next_token();
  2796. if (current_token.is_block() && current_token.block().is_paren()) {
  2797. auto block_values = TokenStream(current_token.block().values());
  2798. auto parsed_calc_sum = parse_calc_sum(context, block_values);
  2799. if (!parsed_calc_sum)
  2800. return {};
  2801. return (CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() };
  2802. }
  2803. if (current_token.is(Token::Type::Number)) {
  2804. auto try_the_number = try_parse_float(current_token.token().number_string_value());
  2805. if (try_the_number.has_value())
  2806. return (CalculatedStyleValue::CalcValue) { try_the_number.value() };
  2807. return {};
  2808. }
  2809. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  2810. auto maybe_length = parse_length(context, current_token);
  2811. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  2812. return (CalculatedStyleValue::CalcValue) { maybe_length.value() };
  2813. return {};
  2814. }
  2815. return {};
  2816. }
  2817. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2818. {
  2819. // Note: The default value is not used or passed around.
  2820. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  2821. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  2822. CalculatedStyleValue::CalcNumberValue(0));
  2823. tokens.skip_whitespace();
  2824. auto& op_token = tokens.peek_token();
  2825. if (!op_token.is(Token::Type::Delim))
  2826. return nullptr;
  2827. auto op = op_token.token().delim();
  2828. if (op == "*"sv) {
  2829. tokens.next_token();
  2830. tokens.skip_whitespace();
  2831. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  2832. auto parsed_calc_value = parse_calc_value(context, tokens);
  2833. if (!parsed_calc_value.has_value())
  2834. return nullptr;
  2835. product_with_operator->value = { parsed_calc_value.release_value() };
  2836. } else if (op == "/"sv) {
  2837. tokens.next_token();
  2838. tokens.skip_whitespace();
  2839. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  2840. auto parsed_calc_number_value = parse_calc_number_value(context, tokens);
  2841. if (!parsed_calc_number_value.has_value())
  2842. return nullptr;
  2843. product_with_operator->value = { parsed_calc_number_value.release_value() };
  2844. } else {
  2845. return nullptr;
  2846. }
  2847. return product_with_operator;
  2848. }
  2849. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2850. {
  2851. // Note: The default value is not used or passed around.
  2852. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  2853. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  2854. CalculatedStyleValue::CalcNumberValue(0));
  2855. tokens.skip_whitespace();
  2856. auto& op_token = tokens.peek_token();
  2857. if (!op_token.is(Token::Type::Delim))
  2858. return nullptr;
  2859. auto op = op_token.token().delim();
  2860. if (op == "*"sv) {
  2861. tokens.next_token();
  2862. tokens.skip_whitespace();
  2863. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  2864. } else if (op == "/"sv) {
  2865. tokens.next_token();
  2866. tokens.skip_whitespace();
  2867. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  2868. } else {
  2869. return nullptr;
  2870. }
  2871. auto parsed_calc_value = parse_calc_number_value(context, tokens);
  2872. if (!parsed_calc_value.has_value())
  2873. return nullptr;
  2874. number_product_with_operator->value = parsed_calc_value.release_value();
  2875. return number_product_with_operator;
  2876. }
  2877. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2878. {
  2879. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  2880. CalculatedStyleValue::CalcNumberValue(0),
  2881. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  2882. auto first_calc_number_value_or_error = parse_calc_number_value(context, tokens);
  2883. if (!first_calc_number_value_or_error.has_value())
  2884. return nullptr;
  2885. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  2886. while (tokens.has_next_token()) {
  2887. auto number_product_with_operator = parse_calc_number_product_part_with_operator(context, tokens);
  2888. if (!number_product_with_operator)
  2889. break;
  2890. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  2891. }
  2892. return calc_number_product;
  2893. }
  2894. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2895. {
  2896. if (!(tokens.peek_token().is(Token::Type::Delim)
  2897. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2898. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2899. return nullptr;
  2900. auto& token = tokens.next_token();
  2901. tokens.skip_whitespace();
  2902. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  2903. auto delim = token.token().delim();
  2904. if (delim == "+"sv)
  2905. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  2906. else if (delim == "-"sv)
  2907. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  2908. else
  2909. return nullptr;
  2910. auto calc_number_product = parse_calc_number_product(context, tokens);
  2911. if (!calc_number_product)
  2912. return nullptr;
  2913. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  2914. }
  2915. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2916. {
  2917. auto first_calc_number_product_or_error = parse_calc_number_product(context, tokens);
  2918. if (!first_calc_number_product_or_error)
  2919. return nullptr;
  2920. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  2921. while (tokens.has_next_token()) {
  2922. auto calc_sum_part = parse_calc_number_sum_part_with_operator(context, tokens);
  2923. if (!calc_sum_part)
  2924. return nullptr;
  2925. additional.append(calc_sum_part.release_nonnull());
  2926. }
  2927. tokens.skip_whitespace();
  2928. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  2929. return calc_number_sum;
  2930. }
  2931. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2932. {
  2933. auto& first = tokens.peek_token();
  2934. if (first.is_block() && first.block().is_paren()) {
  2935. tokens.next_token();
  2936. auto block_values = TokenStream(first.block().values());
  2937. auto calc_number_sum = parse_calc_number_sum(context, block_values);
  2938. if (calc_number_sum)
  2939. return { calc_number_sum.release_nonnull() };
  2940. }
  2941. if (!first.is(Token::Type::Number))
  2942. return {};
  2943. tokens.next_token();
  2944. auto try_the_number = try_parse_float(first.token().number_string_value());
  2945. if (!try_the_number.has_value())
  2946. return {};
  2947. return try_the_number.value();
  2948. }
  2949. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2950. {
  2951. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  2952. CalculatedStyleValue::CalcValue(0),
  2953. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  2954. auto first_calc_value_or_error = parse_calc_value(context, tokens);
  2955. if (!first_calc_value_or_error.has_value())
  2956. return nullptr;
  2957. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  2958. while (tokens.has_next_token()) {
  2959. auto product_with_operator = parse_calc_product_part_with_operator(context, tokens);
  2960. if (!product_with_operator)
  2961. break;
  2962. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  2963. }
  2964. return calc_product;
  2965. }
  2966. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2967. {
  2968. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  2969. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  2970. if (!(tokens.peek_token().is(Token::Type::Delim)
  2971. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  2972. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  2973. return nullptr;
  2974. auto& token = tokens.next_token();
  2975. tokens.skip_whitespace();
  2976. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  2977. auto delim = token.token().delim();
  2978. if (delim == "+"sv)
  2979. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  2980. else if (delim == "-"sv)
  2981. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  2982. else
  2983. return nullptr;
  2984. auto calc_product = parse_calc_product(context, tokens);
  2985. if (!calc_product)
  2986. return nullptr;
  2987. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  2988. };
  2989. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2990. {
  2991. auto parsed_calc_product = parse_calc_product(context, tokens);
  2992. if (!parsed_calc_product)
  2993. return nullptr;
  2994. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  2995. while (tokens.has_next_token()) {
  2996. auto calc_sum_part = parse_calc_sum_part_with_operator(context, tokens);
  2997. if (!calc_sum_part)
  2998. return nullptr;
  2999. additional.append(calc_sum_part.release_nonnull());
  3000. }
  3001. tokens.skip_whitespace();
  3002. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  3003. }
  3004. bool Parser::has_ignored_vendor_prefix(StringView const& string)
  3005. {
  3006. if (!string.starts_with('-'))
  3007. return false;
  3008. if (string.starts_with("--"))
  3009. return false;
  3010. if (string.starts_with("-libweb-"))
  3011. return false;
  3012. return true;
  3013. }
  3014. }
  3015. namespace Web {
  3016. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView const& css)
  3017. {
  3018. if (css.is_empty())
  3019. return CSS::CSSStyleSheet::create({});
  3020. CSS::Parser parser(context, css);
  3021. return parser.parse_as_stylesheet();
  3022. }
  3023. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView const& css)
  3024. {
  3025. if (css.is_empty())
  3026. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  3027. CSS::Parser parser(context, css);
  3028. return parser.parse_as_list_of_declarations();
  3029. }
  3030. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView const& string, CSS::PropertyID property_id)
  3031. {
  3032. if (string.is_empty())
  3033. return {};
  3034. CSS::Parser parser(context, string);
  3035. return parser.parse_as_css_value(property_id);
  3036. }
  3037. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView const& selector_text)
  3038. {
  3039. CSS::Parser parser(context, selector_text);
  3040. return parser.parse_as_selector();
  3041. }
  3042. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView const& string)
  3043. {
  3044. auto integer = string.to_int();
  3045. if (integer.has_value())
  3046. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  3047. // FIXME: The const_cast is a hack.
  3048. return parse_css_value(CSS::ParsingContext(const_cast<DOM::Document&>(document)), string);
  3049. }
  3050. }