Parser.cpp 124 KB

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