Parser.cpp 140 KB

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