Parser.cpp 141 KB

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