Parser.cpp 144 KB

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