Parser.cpp 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238
  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 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_tokens = TokenStream { first_value.block().values() };
  323. attribute_tokens.skip_whitespace();
  324. if (!attribute_tokens.has_next_token()) {
  325. dbgln_if(CSS_PARSER_DEBUG, "CSS attribute selector is empty!");
  326. return ParsingResult::SyntaxError;
  327. }
  328. // FIXME: Handle namespace prefix for attribute name.
  329. auto& attribute_part = attribute_tokens.next_token();
  330. if (!attribute_part.is(Token::Type::Ident)) {
  331. dbgln_if(CSS_PARSER_DEBUG, "Expected ident for attribute name, got: '{}'", attribute_part.to_debug_string());
  332. return ParsingResult::SyntaxError;
  333. }
  334. Selector::SimpleSelector simple_selector {
  335. .type = Selector::SimpleSelector::Type::Attribute,
  336. .attribute = {
  337. .match_type = Selector::SimpleSelector::Attribute::MatchType::HasAttribute,
  338. // FIXME: Case-sensitivity is defined by the document language.
  339. // HTML is insensitive with attribute names, and our code generally assumes
  340. // they are converted to lowercase, so we do that here too. If we want to be
  341. // correct with XML later, we'll need to keep the original case and then do
  342. // a case-insensitive compare later.
  343. .name = attribute_part.token().ident().to_lowercase_string(),
  344. }
  345. };
  346. attribute_tokens.skip_whitespace();
  347. if (!attribute_tokens.has_next_token())
  348. return simple_selector;
  349. auto& delim_part = attribute_tokens.next_token();
  350. if (!delim_part.is(Token::Type::Delim)) {
  351. dbgln_if(CSS_PARSER_DEBUG, "Expected a delim for attribute comparison, got: '{}'", delim_part.to_debug_string());
  352. return ParsingResult::SyntaxError;
  353. }
  354. if (delim_part.token().delim() == "="sv) {
  355. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ExactValueMatch;
  356. } else {
  357. if (!attribute_tokens.has_next_token()) {
  358. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended part way through a match type.");
  359. return ParsingResult::SyntaxError;
  360. }
  361. auto& delim_second_part = attribute_tokens.next_token();
  362. if (!(delim_second_part.is(Token::Type::Delim) && delim_second_part.token().delim() == "=")) {
  363. dbgln_if(CSS_PARSER_DEBUG, "Expected a double delim for attribute comparison, got: '{}{}'", delim_part.to_debug_string(), delim_second_part.to_debug_string());
  364. return ParsingResult::SyntaxError;
  365. }
  366. if (delim_part.token().delim() == "~"sv) {
  367. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsWord;
  368. } else if (delim_part.token().delim() == "*"sv) {
  369. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::ContainsString;
  370. } else if (delim_part.token().delim() == "|"sv) {
  371. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithSegment;
  372. } else if (delim_part.token().delim() == "^"sv) {
  373. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::StartsWithString;
  374. } else if (delim_part.token().delim() == "$"sv) {
  375. simple_selector.attribute.match_type = Selector::SimpleSelector::Attribute::MatchType::EndsWithString;
  376. } else {
  377. attribute_tokens.reconsume_current_input_token();
  378. }
  379. }
  380. attribute_tokens.skip_whitespace();
  381. if (!attribute_tokens.has_next_token()) {
  382. dbgln_if(CSS_PARSER_DEBUG, "Attribute selector ended without a value to match.");
  383. return ParsingResult::SyntaxError;
  384. }
  385. auto& value_part = attribute_tokens.next_token();
  386. if (!value_part.is(Token::Type::Ident) && !value_part.is(Token::Type::String)) {
  387. dbgln_if(CSS_PARSER_DEBUG, "Expected a string or ident for the value to match attribute against, got: '{}'", value_part.to_debug_string());
  388. return ParsingResult::SyntaxError;
  389. }
  390. simple_selector.attribute.value = value_part.token().is(Token::Type::Ident) ? value_part.token().ident() : value_part.token().string();
  391. attribute_tokens.skip_whitespace();
  392. // FIXME: Handle case-sensitivity suffixes. https://www.w3.org/TR/selectors-4/#attribute-case
  393. return simple_selector;
  394. } else if (first_value.is(Token::Type::Colon)) {
  395. if (peek_token_ends_selector())
  396. return ParsingResult::SyntaxError;
  397. bool is_pseudo = false;
  398. if (tokens.peek_token().is(Token::Type::Colon)) {
  399. is_pseudo = true;
  400. tokens.next_token();
  401. if (peek_token_ends_selector())
  402. return ParsingResult::SyntaxError;
  403. }
  404. if (is_pseudo) {
  405. Selector::SimpleSelector simple_selector {
  406. .type = Selector::SimpleSelector::Type::PseudoElement
  407. };
  408. auto& name_token = tokens.next_token();
  409. if (!name_token.is(Token::Type::Ident)) {
  410. dbgln_if(CSS_PARSER_DEBUG, "Expected an ident for pseudo-element, got: '{}'", name_token.to_debug_string());
  411. return ParsingResult::SyntaxError;
  412. }
  413. auto pseudo_name = name_token.token().ident();
  414. if (has_ignored_vendor_prefix(pseudo_name))
  415. return ParsingResult::IncludesIgnoredVendorPrefix;
  416. if (pseudo_name.equals_ignoring_case("after")) {
  417. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  418. } else if (pseudo_name.equals_ignoring_case("before")) {
  419. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  420. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  421. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  422. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  423. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  424. } else {
  425. dbgln("Unrecognized pseudo-element: '::{}'", pseudo_name);
  426. return ParsingResult::SyntaxError;
  427. }
  428. return simple_selector;
  429. }
  430. if (peek_token_ends_selector())
  431. return ParsingResult::SyntaxError;
  432. auto& pseudo_class_token = tokens.next_token();
  433. Selector::SimpleSelector simple_selector {
  434. .type = Selector::SimpleSelector::Type::PseudoClass
  435. };
  436. if (pseudo_class_token.is(Token::Type::Ident)) {
  437. auto pseudo_name = pseudo_class_token.token().ident();
  438. if (has_ignored_vendor_prefix(pseudo_name))
  439. return ParsingResult::IncludesIgnoredVendorPrefix;
  440. if (pseudo_name.equals_ignoring_case("active")) {
  441. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Active;
  442. } else if (pseudo_name.equals_ignoring_case("checked")) {
  443. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Checked;
  444. } else if (pseudo_name.equals_ignoring_case("disabled")) {
  445. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Disabled;
  446. } else if (pseudo_name.equals_ignoring_case("empty")) {
  447. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Empty;
  448. } else if (pseudo_name.equals_ignoring_case("enabled")) {
  449. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Enabled;
  450. } else if (pseudo_name.equals_ignoring_case("first-child")) {
  451. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstChild;
  452. } else if (pseudo_name.equals_ignoring_case("first-of-type")) {
  453. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::FirstOfType;
  454. } else if (pseudo_name.equals_ignoring_case("focus")) {
  455. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Focus;
  456. } else if (pseudo_name.equals_ignoring_case("hover")) {
  457. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Hover;
  458. } else if (pseudo_name.equals_ignoring_case("last-child")) {
  459. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastChild;
  460. } else if (pseudo_name.equals_ignoring_case("last-of-type")) {
  461. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::LastOfType;
  462. } else if (pseudo_name.equals_ignoring_case("link")) {
  463. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Link;
  464. } else if (pseudo_name.equals_ignoring_case("only-child")) {
  465. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::OnlyChild;
  466. } else if (pseudo_name.equals_ignoring_case("root")) {
  467. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Root;
  468. } else if (pseudo_name.equals_ignoring_case("visited")) {
  469. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Visited;
  470. } else if (pseudo_name.equals_ignoring_case("after")) {
  471. // Single-colon syntax allowed for compatibility. https://www.w3.org/TR/selectors/#pseudo-element-syntax
  472. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  473. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::After;
  474. } else if (pseudo_name.equals_ignoring_case("before")) {
  475. // See :after
  476. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  477. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::Before;
  478. } else if (pseudo_name.equals_ignoring_case("first-letter")) {
  479. // See :after
  480. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  481. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLetter;
  482. } else if (pseudo_name.equals_ignoring_case("first-line")) {
  483. // See :after
  484. simple_selector.type = Selector::SimpleSelector::Type::PseudoElement;
  485. simple_selector.pseudo_element = Selector::SimpleSelector::PseudoElement::FirstLine;
  486. } else {
  487. dbgln("Unrecognized pseudo-class: ':{}'", pseudo_name);
  488. return ParsingResult::SyntaxError;
  489. }
  490. return simple_selector;
  491. } else if (pseudo_class_token.is_function()) {
  492. auto& pseudo_function = pseudo_class_token.function();
  493. if (pseudo_function.name().equals_ignoring_case("not")) {
  494. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::Not;
  495. auto function_token_stream = TokenStream(pseudo_function.values());
  496. auto not_selector = parse_a_selector(function_token_stream);
  497. if (not_selector.is_error()) {
  498. dbgln_if(CSS_PARSER_DEBUG, "Invalid selector in :not() clause");
  499. return ParsingResult::SyntaxError;
  500. }
  501. simple_selector.pseudo_class.not_selector = not_selector.release_value();
  502. } else if (pseudo_function.name().equals_ignoring_case("nth-child")) {
  503. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthChild;
  504. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  505. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  506. if (nth_child_pattern.has_value()) {
  507. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  508. } else {
  509. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  510. return ParsingResult::SyntaxError;
  511. }
  512. } else if (pseudo_function.name().equals_ignoring_case("nth-last-child")) {
  513. simple_selector.pseudo_class.type = Selector::SimpleSelector::PseudoClass::Type::NthLastChild;
  514. auto function_values = TokenStream<StyleComponentValueRule>(pseudo_function.values());
  515. auto nth_child_pattern = parse_a_n_plus_b_pattern(function_values);
  516. if (nth_child_pattern.has_value()) {
  517. simple_selector.pseudo_class.nth_child_pattern = nth_child_pattern.value();
  518. } else {
  519. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid nth-child format");
  520. return ParsingResult::SyntaxError;
  521. }
  522. } else {
  523. dbgln("Unrecognized pseudo-class function: ':{}'()", pseudo_function.name());
  524. return ParsingResult::SyntaxError;
  525. }
  526. return simple_selector;
  527. } else {
  528. dbgln_if(CSS_PARSER_DEBUG, "Unexpected Block in pseudo-class name, expected a function or identifier. '{}'", pseudo_class_token.to_debug_string());
  529. return ParsingResult::SyntaxError;
  530. }
  531. }
  532. // Whitespace is not required between the compound-selector and a combinator.
  533. // So, if we see a combinator, return that this compound-selector is done, instead of a syntax error.
  534. if (first_value.is(Token::Type::Delim)) {
  535. auto delim = first_value.token().delim();
  536. if ((delim == ">"sv) || (delim == "+"sv) || (delim == "~"sv) || (delim == "|"sv)) {
  537. tokens.reconsume_current_input_token();
  538. return ParsingResult::Done;
  539. }
  540. }
  541. dbgln_if(CSS_PARSER_DEBUG, "!!! Invalid simple selector!");
  542. return ParsingResult::SyntaxError;
  543. }
  544. NonnullRefPtrVector<MediaQuery> Parser::parse_as_media_query_list()
  545. {
  546. return parse_a_media_query_list(m_token_stream);
  547. }
  548. template<typename T>
  549. NonnullRefPtrVector<MediaQuery> Parser::parse_a_media_query_list(TokenStream<T>& tokens)
  550. {
  551. // https://www.w3.org/TR/mediaqueries-4/#mq-list
  552. auto comma_separated_lists = parse_a_comma_separated_list_of_component_values(tokens);
  553. AK::NonnullRefPtrVector<MediaQuery> media_queries;
  554. for (auto& media_query_parts : comma_separated_lists) {
  555. auto stream = TokenStream(media_query_parts);
  556. media_queries.append(parse_media_query(stream));
  557. }
  558. return media_queries;
  559. }
  560. RefPtr<MediaQuery> Parser::parse_as_media_query()
  561. {
  562. // https://www.w3.org/TR/cssom-1/#parse-a-media-query
  563. auto media_query_list = parse_as_media_query_list();
  564. if (media_query_list.is_empty())
  565. return MediaQuery::create_not_all();
  566. if (media_query_list.size() == 1)
  567. return media_query_list.first();
  568. return nullptr;
  569. }
  570. NonnullRefPtr<MediaQuery> Parser::parse_media_query(TokenStream<StyleComponentValueRule>& tokens)
  571. {
  572. // Returns whether to negate the query
  573. auto consume_initial_modifier = [](auto& tokens) -> Optional<bool> {
  574. auto& token = tokens.next_token();
  575. if (!token.is(Token::Type::Ident)) {
  576. tokens.reconsume_current_input_token();
  577. return {};
  578. }
  579. auto ident = token.token().ident();
  580. if (ident.equals_ignoring_case("not")) {
  581. return true;
  582. } else if (ident.equals_ignoring_case("only")) {
  583. return false;
  584. }
  585. tokens.reconsume_current_input_token();
  586. return {};
  587. };
  588. auto invalid_media_query = [&]() {
  589. // "A media query that does not match the grammar in the previous section must be replaced by `not all`
  590. // during parsing." - https://www.w3.org/TR/mediaqueries-5/#error-handling
  591. if constexpr (CSS_PARSER_DEBUG) {
  592. dbgln("Invalid media query:");
  593. tokens.dump_all_tokens();
  594. }
  595. return MediaQuery::create_not_all();
  596. };
  597. auto media_query = MediaQuery::create();
  598. tokens.skip_whitespace();
  599. // Only `<media-condition>`
  600. if (auto media_condition = consume_media_condition(tokens)) {
  601. tokens.skip_whitespace();
  602. if (tokens.has_next_token())
  603. return invalid_media_query();
  604. media_query->m_media_condition = move(media_condition);
  605. return media_query;
  606. }
  607. // Optional `"only" | "not"`
  608. if (auto modifier = consume_initial_modifier(tokens); modifier.has_value()) {
  609. media_query->m_negated = modifier.value();
  610. tokens.skip_whitespace();
  611. }
  612. // `<media-type>`
  613. if (auto media_type = consume_media_type(tokens); media_type.has_value()) {
  614. media_query->m_media_type = media_type.value();
  615. tokens.skip_whitespace();
  616. } else {
  617. return invalid_media_query();
  618. }
  619. if (!tokens.has_next_token())
  620. return media_query;
  621. // Optional "and <media-condition>"
  622. if (auto maybe_and = tokens.next_token(); maybe_and.is(Token::Type::Ident) && maybe_and.token().ident().equals_ignoring_case("and")) {
  623. if (auto media_condition = consume_media_condition(tokens)) {
  624. tokens.skip_whitespace();
  625. if (tokens.has_next_token())
  626. return invalid_media_query();
  627. media_query->m_media_condition = move(media_condition);
  628. return media_query;
  629. }
  630. return invalid_media_query();
  631. }
  632. return invalid_media_query();
  633. }
  634. OwnPtr<MediaQuery::MediaCondition> Parser::consume_media_condition(TokenStream<StyleComponentValueRule>& tokens)
  635. {
  636. // "not <media-condition>"
  637. // ( `<media-not>` in the grammar )
  638. auto position = tokens.position();
  639. auto& first_token = tokens.peek_token();
  640. if (first_token.is(Token::Type::Ident) && first_token.token().ident().equals_ignoring_case("not"sv)) {
  641. tokens.next_token();
  642. auto condition = new MediaQuery::MediaCondition;
  643. condition->type = MediaQuery::MediaCondition::Type::Not;
  644. if (auto child_condition = consume_media_condition(tokens)) {
  645. condition->conditions.append(child_condition.release_nonnull());
  646. return adopt_own(*condition);
  647. }
  648. tokens.rewind_to_position(position);
  649. return {};
  650. }
  651. // "<media-condition> ([and | or] <media-condition>)*"
  652. // ( `<media-in-parens> [ <media-and>* | <media-or>* ]` in the grammar )
  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. // `<general-enclosed>`
  721. tokens.rewind_to_position(position);
  722. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  723. auto condition = new MediaQuery::MediaCondition;
  724. condition->type = MediaQuery::MediaCondition::Type::GeneralEnclosed;
  725. condition->general_enclosed = general_enclosed.release_value();
  726. return adopt_own(*condition);
  727. }
  728. tokens.rewind_to_position(position);
  729. return {};
  730. }
  731. Optional<MediaQuery::MediaFeature> Parser::consume_media_feature(TokenStream<StyleComponentValueRule>& outer_tokens)
  732. {
  733. outer_tokens.skip_whitespace();
  734. auto invalid_feature = [&]() -> Optional<MediaQuery::MediaFeature> {
  735. outer_tokens.reconsume_current_input_token();
  736. return {};
  737. };
  738. auto& block_token = outer_tokens.next_token();
  739. if (block_token.is_block() && block_token.block().is_paren()) {
  740. TokenStream tokens { block_token.block().values() };
  741. tokens.skip_whitespace();
  742. auto& name_token = tokens.next_token();
  743. // FIXME: Range syntax allows a value to come before the name
  744. // https://www.w3.org/TR/mediaqueries-4/#mq-range-context
  745. if (!name_token.is(Token::Type::Ident))
  746. return invalid_feature();
  747. auto feature_name = name_token.token().ident();
  748. tokens.skip_whitespace();
  749. if (!tokens.has_next_token()) {
  750. return MediaQuery::MediaFeature {
  751. .type = MediaQuery::MediaFeature::Type::IsTrue,
  752. .name = feature_name,
  753. };
  754. }
  755. if (!tokens.next_token().is(Token::Type::Colon))
  756. return invalid_feature();
  757. tokens.skip_whitespace();
  758. auto value = parse_css_value(PropertyID::Custom, tokens);
  759. if (value.is_error())
  760. return invalid_feature();
  761. if (tokens.has_next_token())
  762. return invalid_feature();
  763. if (feature_name.starts_with("min-", CaseSensitivity::CaseInsensitive)) {
  764. return MediaQuery::MediaFeature {
  765. .type = MediaQuery::MediaFeature::Type::MinValue,
  766. .name = feature_name.substring_view(4),
  767. .value = value.release_value(),
  768. };
  769. } else if (feature_name.starts_with("max-", CaseSensitivity::CaseInsensitive)) {
  770. return MediaQuery::MediaFeature {
  771. .type = MediaQuery::MediaFeature::Type::MaxValue,
  772. .name = feature_name.substring_view(4),
  773. .value = value.release_value(),
  774. };
  775. }
  776. return MediaQuery::MediaFeature {
  777. .type = MediaQuery::MediaFeature::Type::ExactValue,
  778. .name = feature_name,
  779. .value = value.release_value(),
  780. };
  781. }
  782. return invalid_feature();
  783. }
  784. Optional<MediaQuery::MediaType> Parser::consume_media_type(TokenStream<StyleComponentValueRule>& tokens)
  785. {
  786. auto& token = tokens.next_token();
  787. if (!token.is(Token::Type::Ident)) {
  788. tokens.reconsume_current_input_token();
  789. return {};
  790. }
  791. auto ident = token.token().ident();
  792. if (ident.equals_ignoring_case("all")) {
  793. return MediaQuery::MediaType::All;
  794. } else if (ident.equals_ignoring_case("aural")) {
  795. return MediaQuery::MediaType::Aural;
  796. } else if (ident.equals_ignoring_case("braille")) {
  797. return MediaQuery::MediaType::Braille;
  798. } else if (ident.equals_ignoring_case("embossed")) {
  799. return MediaQuery::MediaType::Embossed;
  800. } else if (ident.equals_ignoring_case("handheld")) {
  801. return MediaQuery::MediaType::Handheld;
  802. } else if (ident.equals_ignoring_case("print")) {
  803. return MediaQuery::MediaType::Print;
  804. } else if (ident.equals_ignoring_case("projection")) {
  805. return MediaQuery::MediaType::Projection;
  806. } else if (ident.equals_ignoring_case("screen")) {
  807. return MediaQuery::MediaType::Screen;
  808. } else if (ident.equals_ignoring_case("speech")) {
  809. return MediaQuery::MediaType::Speech;
  810. } else if (ident.equals_ignoring_case("tty")) {
  811. return MediaQuery::MediaType::TTY;
  812. } else if (ident.equals_ignoring_case("tv")) {
  813. return MediaQuery::MediaType::TV;
  814. }
  815. tokens.reconsume_current_input_token();
  816. return {};
  817. }
  818. RefPtr<Supports> Parser::parse_as_supports()
  819. {
  820. return parse_a_supports(m_token_stream);
  821. }
  822. template<typename T>
  823. RefPtr<Supports> Parser::parse_a_supports(TokenStream<T>& tokens)
  824. {
  825. auto component_values = parse_a_list_of_component_values(tokens);
  826. TokenStream<StyleComponentValueRule> token_stream { component_values };
  827. auto maybe_condition = parse_supports_condition(token_stream);
  828. token_stream.skip_whitespace();
  829. if (maybe_condition && !token_stream.has_next_token())
  830. return Supports::create(maybe_condition.release_nonnull());
  831. return {};
  832. }
  833. OwnPtr<Supports::Condition> Parser::parse_supports_condition(TokenStream<StyleComponentValueRule>& tokens)
  834. {
  835. tokens.skip_whitespace();
  836. auto start_position = tokens.position();
  837. auto& peeked_token = tokens.peek_token();
  838. // `not <supports-in-parens>`
  839. if (peeked_token.is(Token::Type::Ident) && peeked_token.token().ident().equals_ignoring_case("not")) {
  840. tokens.next_token();
  841. tokens.skip_whitespace();
  842. auto child = parse_supports_in_parens(tokens);
  843. if (child.has_value()) {
  844. auto* condition = new Supports::Condition;
  845. condition->type = Supports::Condition::Type::Not;
  846. condition->children.append(child.release_value());
  847. return adopt_own(*condition);
  848. }
  849. tokens.rewind_to_position(start_position);
  850. return {};
  851. }
  852. // ` <supports-in-parens> [ and <supports-in-parens> ]*
  853. // | <supports-in-parens> [ or <supports-in-parens> ]*`
  854. Vector<Supports::InParens> children;
  855. Optional<Supports::Condition::Type> condition_type {};
  856. auto as_condition_type = [](auto& token) -> Optional<Supports::Condition::Type> {
  857. if (!token.is(Token::Type::Ident))
  858. return {};
  859. auto ident = token.token().ident();
  860. if (ident.equals_ignoring_case("and"))
  861. return Supports::Condition::Type::And;
  862. if (ident.equals_ignoring_case("or"))
  863. return Supports::Condition::Type::Or;
  864. return {};
  865. };
  866. bool is_invalid = false;
  867. while (tokens.has_next_token()) {
  868. if (!children.is_empty()) {
  869. // Expect `and` or `or` here
  870. auto maybe_combination = as_condition_type(tokens.next_token());
  871. if (!maybe_combination.has_value()) {
  872. is_invalid = true;
  873. break;
  874. }
  875. if (!condition_type.has_value()) {
  876. condition_type = maybe_combination.value();
  877. } else if (maybe_combination != condition_type) {
  878. is_invalid = true;
  879. break;
  880. }
  881. }
  882. tokens.skip_whitespace();
  883. if (auto in_parens = parse_supports_in_parens(tokens); in_parens.has_value()) {
  884. children.append(in_parens.release_value());
  885. } else {
  886. is_invalid = true;
  887. break;
  888. }
  889. tokens.skip_whitespace();
  890. }
  891. if (!is_invalid && !children.is_empty()) {
  892. auto* condition = new Supports::Condition;
  893. condition->type = condition_type.value_or(Supports::Condition::Type::Or);
  894. condition->children = move(children);
  895. return adopt_own(*condition);
  896. }
  897. tokens.rewind_to_position(start_position);
  898. return {};
  899. }
  900. Optional<Supports::InParens> Parser::parse_supports_in_parens(TokenStream<StyleComponentValueRule>& tokens)
  901. {
  902. tokens.skip_whitespace();
  903. auto start_position = tokens.position();
  904. auto& first_token = tokens.peek_token();
  905. // `( <supports-condition> )`
  906. if (first_token.is_block() && first_token.block().is_paren()) {
  907. tokens.next_token();
  908. tokens.skip_whitespace();
  909. TokenStream child_tokens { first_token.block().values() };
  910. if (auto condition = parse_supports_condition(child_tokens)) {
  911. if (child_tokens.has_next_token()) {
  912. tokens.rewind_to_position(start_position);
  913. return {};
  914. }
  915. return Supports::InParens {
  916. .value = { condition.release_nonnull() }
  917. };
  918. }
  919. tokens.rewind_to_position(start_position);
  920. }
  921. // `<supports-feature>`
  922. if (auto feature = parse_supports_feature(tokens); feature.has_value()) {
  923. return Supports::InParens {
  924. .value = { feature.release_value() }
  925. };
  926. }
  927. // `<general-enclosed>`
  928. if (auto general_enclosed = parse_general_enclosed(tokens); general_enclosed.has_value()) {
  929. return Supports::InParens {
  930. .value = general_enclosed.release_value()
  931. };
  932. }
  933. tokens.rewind_to_position(start_position);
  934. return {};
  935. }
  936. Optional<Supports::Feature> Parser::parse_supports_feature(TokenStream<StyleComponentValueRule>& tokens)
  937. {
  938. tokens.skip_whitespace();
  939. auto start_position = tokens.position();
  940. auto& first_token = tokens.next_token();
  941. // `<supports-decl>`
  942. if (first_token.is_block() && first_token.block().is_paren()) {
  943. TokenStream block_tokens { first_token.block().values() };
  944. if (auto declaration = consume_a_declaration(block_tokens); declaration.has_value()) {
  945. return Supports::Feature {
  946. .declaration = declaration->to_string()
  947. };
  948. }
  949. }
  950. tokens.rewind_to_position(start_position);
  951. return {};
  952. }
  953. // https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
  954. Optional<GeneralEnclosed> Parser::parse_general_enclosed(TokenStream<StyleComponentValueRule>& tokens)
  955. {
  956. tokens.skip_whitespace();
  957. auto start_position = tokens.position();
  958. auto& first_token = tokens.next_token();
  959. // `[ <function-token> <any-value> ) ]`
  960. if (first_token.is_function())
  961. return GeneralEnclosed { first_token.to_string() };
  962. // `( <ident> <any-value> )`
  963. if (first_token.is_block() && first_token.block().is_paren()) {
  964. auto& block = first_token.block();
  965. if (!block.values().is_empty() && block.values().first().is(Token::Type::Ident))
  966. return GeneralEnclosed { first_token.to_string() };
  967. }
  968. tokens.rewind_to_position(start_position);
  969. return {};
  970. }
  971. template<typename T>
  972. NonnullRefPtrVector<StyleRule> Parser::consume_a_list_of_rules(TokenStream<T>& tokens, bool top_level)
  973. {
  974. NonnullRefPtrVector<StyleRule> rules;
  975. for (;;) {
  976. auto& token = tokens.next_token();
  977. if (token.is(Token::Type::Whitespace)) {
  978. continue;
  979. }
  980. if (token.is(Token::Type::EndOfFile)) {
  981. break;
  982. }
  983. if (token.is(Token::Type::CDO) || token.is(Token::Type::CDC)) {
  984. if (top_level) {
  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. continue;
  993. }
  994. if (token.is(Token::Type::AtKeyword)) {
  995. tokens.reconsume_current_input_token();
  996. rules.append(consume_an_at_rule(tokens));
  997. continue;
  998. }
  999. tokens.reconsume_current_input_token();
  1000. auto maybe_qualified = consume_a_qualified_rule(tokens);
  1001. if (maybe_qualified) {
  1002. rules.append(maybe_qualified.release_nonnull());
  1003. }
  1004. }
  1005. return rules;
  1006. }
  1007. template<typename T>
  1008. NonnullRefPtr<StyleRule> Parser::consume_an_at_rule(TokenStream<T>& tokens)
  1009. {
  1010. auto& name_ident = tokens.next_token();
  1011. VERIFY(name_ident.is(Token::Type::AtKeyword));
  1012. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::At);
  1013. rule->m_name = ((Token)name_ident).at_keyword();
  1014. for (;;) {
  1015. auto& token = tokens.next_token();
  1016. if (token.is(Token::Type::Semicolon)) {
  1017. return rule;
  1018. }
  1019. if (token.is(Token::Type::EndOfFile)) {
  1020. log_parse_error();
  1021. return rule;
  1022. }
  1023. if (token.is(Token::Type::OpenCurly)) {
  1024. rule->m_block = consume_a_simple_block(tokens);
  1025. return rule;
  1026. }
  1027. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1028. StyleComponentValueRule const& component_value = token;
  1029. if (component_value.is_block() && component_value.block().is_curly()) {
  1030. rule->m_block = component_value.block();
  1031. return rule;
  1032. }
  1033. }
  1034. tokens.reconsume_current_input_token();
  1035. auto value = consume_a_component_value(tokens);
  1036. rule->m_prelude.append(value);
  1037. }
  1038. }
  1039. template<typename T>
  1040. RefPtr<StyleRule> Parser::consume_a_qualified_rule(TokenStream<T>& tokens)
  1041. {
  1042. auto rule = make_ref_counted<StyleRule>(StyleRule::Type::Qualified);
  1043. for (;;) {
  1044. auto& token = tokens.next_token();
  1045. if (token.is(Token::Type::EndOfFile)) {
  1046. log_parse_error();
  1047. return {};
  1048. }
  1049. if (token.is(Token::Type::OpenCurly)) {
  1050. rule->m_block = consume_a_simple_block(tokens);
  1051. return rule;
  1052. }
  1053. if constexpr (IsSame<T, StyleComponentValueRule>) {
  1054. StyleComponentValueRule const& component_value = token;
  1055. if (component_value.is_block() && component_value.block().is_curly()) {
  1056. rule->m_block = component_value.block();
  1057. return rule;
  1058. }
  1059. }
  1060. tokens.reconsume_current_input_token();
  1061. auto value = consume_a_component_value(tokens);
  1062. rule->m_prelude.append(value);
  1063. }
  1064. return rule;
  1065. }
  1066. template<>
  1067. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<StyleComponentValueRule>& tokens)
  1068. {
  1069. return tokens.next_token();
  1070. }
  1071. template<typename T>
  1072. StyleComponentValueRule Parser::consume_a_component_value(TokenStream<T>& tokens)
  1073. {
  1074. auto& token = tokens.next_token();
  1075. if (token.is(Token::Type::OpenCurly) || token.is(Token::Type::OpenSquare) || token.is(Token::Type::OpenParen))
  1076. return StyleComponentValueRule(consume_a_simple_block(tokens));
  1077. if (token.is(Token::Type::Function))
  1078. return StyleComponentValueRule(consume_a_function(tokens));
  1079. return StyleComponentValueRule(token);
  1080. }
  1081. template<typename T>
  1082. NonnullRefPtr<StyleBlockRule> Parser::consume_a_simple_block(TokenStream<T>& tokens)
  1083. {
  1084. auto ending_token = ((Token)tokens.current_token()).mirror_variant();
  1085. auto block = make_ref_counted<StyleBlockRule>();
  1086. block->m_token = tokens.current_token();
  1087. for (;;) {
  1088. auto& token = tokens.next_token();
  1089. if (token.is(ending_token)) {
  1090. return block;
  1091. }
  1092. if (token.is(Token::Type::EndOfFile)) {
  1093. log_parse_error();
  1094. return block;
  1095. }
  1096. tokens.reconsume_current_input_token();
  1097. auto value = consume_a_component_value(tokens);
  1098. block->m_values.append(value);
  1099. }
  1100. }
  1101. template<typename T>
  1102. NonnullRefPtr<StyleFunctionRule> Parser::consume_a_function(TokenStream<T>& tokens)
  1103. {
  1104. auto name_ident = tokens.current_token();
  1105. VERIFY(name_ident.is(Token::Type::Function));
  1106. auto function = make_ref_counted<StyleFunctionRule>(((Token)name_ident).function());
  1107. for (;;) {
  1108. auto& token = tokens.next_token();
  1109. if (token.is(Token::Type::CloseParen)) {
  1110. return function;
  1111. }
  1112. if (token.is(Token::Type::EndOfFile)) {
  1113. log_parse_error();
  1114. return function;
  1115. }
  1116. tokens.reconsume_current_input_token();
  1117. auto value = consume_a_component_value(tokens);
  1118. function->m_values.append(value);
  1119. }
  1120. return function;
  1121. }
  1122. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  1123. template<typename T>
  1124. Optional<StyleDeclarationRule> Parser::consume_a_declaration(TokenStream<T>& tokens)
  1125. {
  1126. // Note: This algorithm assumes that the next input token has already been checked to
  1127. // be an <ident-token>.
  1128. // To consume a declaration:
  1129. // Consume the next input token.
  1130. tokens.skip_whitespace();
  1131. auto start_position = tokens.position();
  1132. auto& token = tokens.next_token();
  1133. if (!token.is(Token::Type::Ident)) {
  1134. tokens.rewind_to_position(start_position);
  1135. return {};
  1136. }
  1137. // Create a new declaration with its name set to the value of the current input token
  1138. // and its value initially set to the empty list.
  1139. StyleDeclarationRule declaration;
  1140. declaration.m_name = ((Token)token).ident();
  1141. // 1. While the next input token is a <whitespace-token>, consume the next input token.
  1142. tokens.skip_whitespace();
  1143. // 2. If the next input token is anything other than a <colon-token>, this is a parse error.
  1144. // Return nothing.
  1145. auto& maybe_colon = tokens.peek_token();
  1146. if (!maybe_colon.is(Token::Type::Colon)) {
  1147. log_parse_error();
  1148. tokens.rewind_to_position(start_position);
  1149. return {};
  1150. }
  1151. // Otherwise, consume the next input token.
  1152. tokens.next_token();
  1153. // 3. While the next input token is a <whitespace-token>, consume the next input token.
  1154. tokens.skip_whitespace();
  1155. // 4. As long as the next input token is anything other than an <EOF-token>, consume a
  1156. // component value and append it to the declaration’s value.
  1157. for (;;) {
  1158. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1159. break;
  1160. }
  1161. declaration.m_values.append(consume_a_component_value(tokens));
  1162. }
  1163. // 5. If the last two non-<whitespace-token>s in the declaration’s value are a <delim-token>
  1164. // with the value "!" followed by an <ident-token> with a value that is an ASCII case-insensitive
  1165. // match for "important", remove them from the declaration’s value and set the declaration’s
  1166. // important flag to true.
  1167. if (declaration.m_values.size() >= 2) {
  1168. // Walk backwards from the end until we find "important"
  1169. Optional<size_t> important_index;
  1170. for (size_t i = declaration.m_values.size() - 1; i > 0; i--) {
  1171. auto value = declaration.m_values[i];
  1172. if (value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("important")) {
  1173. important_index = i;
  1174. break;
  1175. }
  1176. if (value.is(Token::Type::Whitespace))
  1177. continue;
  1178. break;
  1179. }
  1180. // Walk backwards from important until we find "!"
  1181. if (important_index.has_value()) {
  1182. Optional<size_t> bang_index;
  1183. for (size_t i = important_index.value() - 1; i > 0; i--) {
  1184. auto value = declaration.m_values[i];
  1185. if (value.is(Token::Type::Delim) && value.token().delim() == "!"sv) {
  1186. bang_index = i;
  1187. break;
  1188. }
  1189. if (value.is(Token::Type::Whitespace))
  1190. continue;
  1191. break;
  1192. }
  1193. if (bang_index.has_value()) {
  1194. declaration.m_values.remove(important_index.value());
  1195. declaration.m_values.remove(bang_index.value());
  1196. declaration.m_important = true;
  1197. }
  1198. }
  1199. }
  1200. // 6. While the last token in the declaration’s value is a <whitespace-token>, remove that token.
  1201. while (!declaration.m_values.is_empty()) {
  1202. auto maybe_whitespace = declaration.m_values.last();
  1203. if (!(maybe_whitespace.is(Token::Type::Whitespace))) {
  1204. break;
  1205. }
  1206. declaration.m_values.take_last();
  1207. }
  1208. // 7. Return the declaration.
  1209. return declaration;
  1210. }
  1211. template<typename T>
  1212. Vector<DeclarationOrAtRule> Parser::consume_a_list_of_declarations(TokenStream<T>& tokens)
  1213. {
  1214. Vector<DeclarationOrAtRule> list;
  1215. for (;;) {
  1216. auto& token = tokens.next_token();
  1217. if (token.is(Token::Type::Whitespace) || token.is(Token::Type::Semicolon)) {
  1218. continue;
  1219. }
  1220. if (token.is(Token::Type::EndOfFile)) {
  1221. return list;
  1222. }
  1223. if (token.is(Token::Type::AtKeyword)) {
  1224. tokens.reconsume_current_input_token();
  1225. list.append(DeclarationOrAtRule(consume_an_at_rule(tokens)));
  1226. continue;
  1227. }
  1228. if (token.is(Token::Type::Ident)) {
  1229. Vector<StyleComponentValueRule> temp;
  1230. temp.append(token);
  1231. for (;;) {
  1232. auto& peek = tokens.peek_token();
  1233. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile)) {
  1234. break;
  1235. }
  1236. temp.append(consume_a_component_value(tokens));
  1237. }
  1238. auto token_stream = TokenStream(temp);
  1239. auto maybe_declaration = consume_a_declaration(token_stream);
  1240. if (maybe_declaration.has_value()) {
  1241. list.append(DeclarationOrAtRule(maybe_declaration.value()));
  1242. }
  1243. continue;
  1244. }
  1245. log_parse_error();
  1246. tokens.reconsume_current_input_token();
  1247. for (;;) {
  1248. auto& peek = tokens.peek_token();
  1249. if (peek.is(Token::Type::Semicolon) || peek.is(Token::Type::EndOfFile))
  1250. break;
  1251. dbgln("Discarding token: '{}'", peek.to_debug_string());
  1252. (void)consume_a_component_value(tokens);
  1253. }
  1254. }
  1255. return list;
  1256. }
  1257. RefPtr<CSSRule> Parser::parse_as_rule()
  1258. {
  1259. return parse_a_rule(m_token_stream);
  1260. }
  1261. template<typename T>
  1262. RefPtr<CSSRule> Parser::parse_a_rule(TokenStream<T>& tokens)
  1263. {
  1264. RefPtr<CSSRule> rule;
  1265. tokens.skip_whitespace();
  1266. auto& token = tokens.peek_token();
  1267. if (token.is(Token::Type::EndOfFile)) {
  1268. return {};
  1269. } else if (token.is(Token::Type::AtKeyword)) {
  1270. auto at_rule = consume_an_at_rule(m_token_stream);
  1271. rule = convert_to_rule(at_rule);
  1272. } else {
  1273. auto qualified_rule = consume_a_qualified_rule(tokens);
  1274. if (!qualified_rule)
  1275. return {};
  1276. rule = convert_to_rule(*qualified_rule);
  1277. }
  1278. tokens.skip_whitespace();
  1279. auto& maybe_eof = tokens.peek_token();
  1280. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1281. return rule;
  1282. }
  1283. return {};
  1284. }
  1285. NonnullRefPtrVector<CSSRule> Parser::parse_as_list_of_rules()
  1286. {
  1287. return parse_a_list_of_rules(m_token_stream);
  1288. }
  1289. template<typename T>
  1290. NonnullRefPtrVector<CSSRule> Parser::parse_a_list_of_rules(TokenStream<T>& tokens)
  1291. {
  1292. auto parsed_rules = consume_a_list_of_rules(tokens, false);
  1293. NonnullRefPtrVector<CSSRule> rules;
  1294. for (auto& rule : parsed_rules) {
  1295. auto converted_rule = convert_to_rule(rule);
  1296. if (converted_rule)
  1297. rules.append(*converted_rule);
  1298. }
  1299. return rules;
  1300. }
  1301. Optional<StyleProperty> Parser::parse_as_declaration()
  1302. {
  1303. return parse_a_declaration(m_token_stream);
  1304. }
  1305. template<typename T>
  1306. Optional<StyleProperty> Parser::parse_a_declaration(TokenStream<T>& tokens)
  1307. {
  1308. tokens.skip_whitespace();
  1309. auto& token = tokens.peek_token();
  1310. if (!token.is(Token::Type::Ident)) {
  1311. return {};
  1312. }
  1313. auto declaration = consume_a_declaration(tokens);
  1314. if (declaration.has_value())
  1315. return convert_to_style_property(declaration.value());
  1316. return {};
  1317. }
  1318. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_as_list_of_declarations()
  1319. {
  1320. return parse_a_list_of_declarations(m_token_stream);
  1321. }
  1322. template<typename T>
  1323. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::parse_a_list_of_declarations(TokenStream<T>& tokens)
  1324. {
  1325. auto declarations_and_at_rules = consume_a_list_of_declarations(tokens);
  1326. Vector<StyleProperty> properties;
  1327. HashMap<String, StyleProperty> custom_properties;
  1328. for (auto& declaration_or_at_rule : declarations_and_at_rules) {
  1329. if (declaration_or_at_rule.is_at_rule()) {
  1330. dbgln_if(CSS_PARSER_DEBUG, "!!! CSS at-rule is not allowed here!");
  1331. continue;
  1332. }
  1333. auto& declaration = declaration_or_at_rule.m_declaration;
  1334. auto maybe_property = convert_to_style_property(declaration);
  1335. if (maybe_property.has_value()) {
  1336. auto property = maybe_property.value();
  1337. if (property.property_id == PropertyID::Custom) {
  1338. custom_properties.set(property.custom_name, property);
  1339. } else {
  1340. properties.append(property);
  1341. }
  1342. }
  1343. }
  1344. return PropertyOwningCSSStyleDeclaration::create(move(properties), move(custom_properties));
  1345. }
  1346. Optional<StyleComponentValueRule> Parser::parse_as_component_value()
  1347. {
  1348. return parse_a_component_value(m_token_stream);
  1349. }
  1350. template<typename T>
  1351. Optional<StyleComponentValueRule> Parser::parse_a_component_value(TokenStream<T>& tokens)
  1352. {
  1353. tokens.skip_whitespace();
  1354. auto& token = tokens.peek_token();
  1355. if (token.is(Token::Type::EndOfFile)) {
  1356. return {};
  1357. }
  1358. auto value = consume_a_component_value(tokens);
  1359. tokens.skip_whitespace();
  1360. auto& maybe_eof = tokens.peek_token();
  1361. if (maybe_eof.is(Token::Type::EndOfFile)) {
  1362. return value;
  1363. }
  1364. return {};
  1365. }
  1366. Vector<StyleComponentValueRule> Parser::parse_as_list_of_component_values()
  1367. {
  1368. return parse_a_list_of_component_values(m_token_stream);
  1369. }
  1370. template<typename T>
  1371. Vector<StyleComponentValueRule> Parser::parse_a_list_of_component_values(TokenStream<T>& tokens)
  1372. {
  1373. Vector<StyleComponentValueRule> rules;
  1374. for (;;) {
  1375. if (tokens.peek_token().is(Token::Type::EndOfFile)) {
  1376. break;
  1377. }
  1378. rules.append(consume_a_component_value(tokens));
  1379. }
  1380. return rules;
  1381. }
  1382. Vector<Vector<StyleComponentValueRule>> Parser::parse_as_comma_separated_list_of_component_values()
  1383. {
  1384. return parse_a_comma_separated_list_of_component_values(m_token_stream);
  1385. }
  1386. template<typename T>
  1387. Vector<Vector<StyleComponentValueRule>> Parser::parse_a_comma_separated_list_of_component_values(TokenStream<T>& tokens)
  1388. {
  1389. Vector<Vector<StyleComponentValueRule>> lists;
  1390. lists.append({});
  1391. for (;;) {
  1392. auto& next = tokens.next_token();
  1393. if (next.is(Token::Type::Comma)) {
  1394. lists.append({});
  1395. continue;
  1396. } else if (next.is(Token::Type::EndOfFile)) {
  1397. break;
  1398. }
  1399. tokens.reconsume_current_input_token();
  1400. auto component_value = consume_a_component_value(tokens);
  1401. lists.last().append(component_value);
  1402. }
  1403. return lists;
  1404. }
  1405. Optional<AK::URL> Parser::parse_url_function(StyleComponentValueRule const& component_value, AllowedDataUrlType allowed_data_url_type)
  1406. {
  1407. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1408. // FIXME: Handle data: urls (RFC2397)
  1409. auto convert_string_to_url = [&](StringView& url_string) -> Optional<AK::URL> {
  1410. if (url_string.starts_with("data:", CaseSensitivity::CaseInsensitive)) {
  1411. auto data_url = AK::URL(url_string);
  1412. switch (allowed_data_url_type) {
  1413. case AllowedDataUrlType::Image:
  1414. if (data_url.data_mime_type().starts_with("image"sv, CaseSensitivity::CaseInsensitive))
  1415. return data_url;
  1416. break;
  1417. default:
  1418. break;
  1419. }
  1420. return {};
  1421. }
  1422. return m_context.complete_url(url_string);
  1423. };
  1424. if (component_value.is(Token::Type::Url)) {
  1425. auto url_string = component_value.token().url();
  1426. return convert_string_to_url(url_string);
  1427. }
  1428. if (component_value.is_function() && component_value.function().name().equals_ignoring_case("url")) {
  1429. auto& function_values = component_value.function().values();
  1430. // FIXME: Handle url-modifiers. https://www.w3.org/TR/css-values-4/#url-modifiers
  1431. for (size_t i = 0; i < function_values.size(); ++i) {
  1432. auto& value = function_values[i];
  1433. if (value.is(Token::Type::Whitespace))
  1434. continue;
  1435. if (value.is(Token::Type::String)) {
  1436. auto url_string = value.token().string();
  1437. return convert_string_to_url(url_string);
  1438. }
  1439. break;
  1440. }
  1441. }
  1442. return {};
  1443. }
  1444. RefPtr<CSSRule> Parser::convert_to_rule(NonnullRefPtr<StyleRule> rule)
  1445. {
  1446. if (rule->m_type == StyleRule::Type::At) {
  1447. if (has_ignored_vendor_prefix(rule->m_name)) {
  1448. return {};
  1449. } else if (rule->m_name.equals_ignoring_case("media"sv)) {
  1450. auto media_query_tokens = TokenStream { rule->prelude() };
  1451. auto media_query_list = parse_a_media_query_list(media_query_tokens);
  1452. auto child_tokens = TokenStream { rule->block().values() };
  1453. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1454. NonnullRefPtrVector<CSSRule> child_rules;
  1455. for (auto& raw_rule : parser_rules) {
  1456. if (auto child_rule = convert_to_rule(raw_rule))
  1457. child_rules.append(*child_rule);
  1458. }
  1459. return CSSMediaRule::create(MediaList::create(move(media_query_list)), move(child_rules));
  1460. } else if (rule->m_name.equals_ignoring_case("import"sv) && !rule->prelude().is_empty()) {
  1461. Optional<AK::URL> url;
  1462. for (auto& token : rule->prelude()) {
  1463. if (token.is(Token::Type::Whitespace))
  1464. continue;
  1465. if (token.is(Token::Type::String)) {
  1466. url = m_context.complete_url(token.token().string());
  1467. } else {
  1468. url = parse_url_function(token);
  1469. }
  1470. // FIXME: Handle list of media queries. https://www.w3.org/TR/css-cascade-3/#conditional-import
  1471. if (url.has_value())
  1472. break;
  1473. }
  1474. if (url.has_value())
  1475. return CSSImportRule::create(url.value(), const_cast<DOM::Document&>(*m_context.document()));
  1476. else
  1477. dbgln("Unable to parse url from @import rule");
  1478. } else if (rule->m_name.equals_ignoring_case("supports"sv)) {
  1479. auto supports_tokens = TokenStream { rule->prelude() };
  1480. auto supports = parse_a_supports(supports_tokens);
  1481. if (!supports) {
  1482. if constexpr (CSS_PARSER_DEBUG) {
  1483. dbgln("CSSParser: @supports rule invalid; discarding.");
  1484. supports_tokens.dump_all_tokens();
  1485. }
  1486. return {};
  1487. }
  1488. auto child_tokens = TokenStream { rule->block().values() };
  1489. auto parser_rules = consume_a_list_of_rules(child_tokens, false);
  1490. NonnullRefPtrVector<CSSRule> child_rules;
  1491. for (auto& raw_rule : parser_rules) {
  1492. if (auto child_rule = convert_to_rule(raw_rule))
  1493. child_rules.append(*child_rule);
  1494. }
  1495. return CSSSupportsRule::create(supports.release_nonnull(), move(child_rules));
  1496. } else {
  1497. dbgln("Unrecognized CSS at-rule: @{}", rule->m_name);
  1498. }
  1499. // FIXME: More at rules!
  1500. } else {
  1501. auto prelude_stream = TokenStream(rule->m_prelude);
  1502. auto selectors = parse_a_selector(prelude_stream);
  1503. if (selectors.is_error()) {
  1504. if (selectors.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1505. dbgln("CSSParser: style rule selectors invalid; discarding.");
  1506. if constexpr (CSS_PARSER_DEBUG) {
  1507. prelude_stream.dump_all_tokens();
  1508. }
  1509. }
  1510. return {};
  1511. }
  1512. if (selectors.value().is_empty()) {
  1513. dbgln("CSSParser: empty selector; discarding.");
  1514. return {};
  1515. }
  1516. auto declaration = convert_to_declaration(*rule->m_block);
  1517. if (!declaration) {
  1518. dbgln("CSSParser: style rule declaration invalid; discarding.");
  1519. return {};
  1520. }
  1521. return CSSStyleRule::create(move(selectors.value()), move(*declaration));
  1522. }
  1523. return {};
  1524. }
  1525. RefPtr<PropertyOwningCSSStyleDeclaration> Parser::convert_to_declaration(NonnullRefPtr<StyleBlockRule> block)
  1526. {
  1527. if (!block->is_curly())
  1528. return {};
  1529. auto stream = TokenStream(block->m_values);
  1530. return parse_a_list_of_declarations(stream);
  1531. }
  1532. Optional<StyleProperty> Parser::convert_to_style_property(StyleDeclarationRule const& declaration)
  1533. {
  1534. auto& property_name = declaration.m_name;
  1535. auto property_id = property_id_from_string(property_name);
  1536. if (property_id == PropertyID::Invalid) {
  1537. if (property_name.starts_with("--")) {
  1538. property_id = PropertyID::Custom;
  1539. } else if (has_ignored_vendor_prefix(property_name)) {
  1540. return {};
  1541. } else if (!property_name.starts_with("-")) {
  1542. dbgln("Unrecognized CSS property '{}'", property_name);
  1543. return {};
  1544. }
  1545. }
  1546. auto value_token_stream = TokenStream(declaration.m_values);
  1547. auto value = parse_css_value(property_id, value_token_stream);
  1548. if (value.is_error()) {
  1549. if (value.error() != ParsingResult::IncludesIgnoredVendorPrefix) {
  1550. dbgln("Unable to parse value for CSS property '{}'.", property_name);
  1551. if constexpr (CSS_PARSER_DEBUG) {
  1552. value_token_stream.dump_all_tokens();
  1553. }
  1554. }
  1555. return {};
  1556. }
  1557. if (property_id == PropertyID::Custom) {
  1558. return StyleProperty { declaration.m_important, property_id, value.release_value(), declaration.m_name };
  1559. } else {
  1560. return StyleProperty { declaration.m_important, property_id, value.release_value(), {} };
  1561. }
  1562. }
  1563. RefPtr<StyleValue> Parser::parse_builtin_value(StyleComponentValueRule const& component_value)
  1564. {
  1565. if (component_value.is(Token::Type::Ident)) {
  1566. auto ident = component_value.token().ident();
  1567. if (ident.equals_ignoring_case("inherit"))
  1568. return InheritStyleValue::the();
  1569. if (ident.equals_ignoring_case("initial"))
  1570. return InitialStyleValue::the();
  1571. if (ident.equals_ignoring_case("unset"))
  1572. return UnsetStyleValue::the();
  1573. // FIXME: Implement `revert` and `revert-layer` keywords, from Cascade4 and Cascade5 respectively
  1574. }
  1575. return {};
  1576. }
  1577. RefPtr<StyleValue> Parser::parse_dynamic_value(StyleComponentValueRule const& component_value)
  1578. {
  1579. if (component_value.is_function()) {
  1580. auto& function = component_value.function();
  1581. if (function.name().equals_ignoring_case("calc")) {
  1582. auto calc_expression = parse_calc_expression(function.values());
  1583. // FIXME: Either produce a string value of calc() here, or do so in CalculatedStyleValue::to_string().
  1584. if (calc_expression)
  1585. return CalculatedStyleValue::create("(FIXME:calc to string)", calc_expression.release_nonnull());
  1586. } else if (function.name().equals_ignoring_case("var")) {
  1587. // FIXME: Handle fallback value as second parameter
  1588. // https://www.w3.org/TR/css-variables-1/#using-variables
  1589. if (!component_value.function().values().is_empty()) {
  1590. auto& property_name_token = component_value.function().values().first();
  1591. if (property_name_token.is(Token::Type::Ident))
  1592. return CustomStyleValue::create(property_name_token.token().ident());
  1593. else
  1594. dbgln("First argument to var() function was not an ident: '{}'", property_name_token.to_debug_string());
  1595. }
  1596. }
  1597. }
  1598. return {};
  1599. }
  1600. Optional<Length> Parser::parse_length(StyleComponentValueRule const& component_value)
  1601. {
  1602. Length::Type type = Length::Type::Undefined;
  1603. Optional<float> numeric_value;
  1604. if (component_value.is(Token::Type::Dimension)) {
  1605. numeric_value = component_value.token().dimension_value();
  1606. auto unit_string = component_value.token().dimension_unit();
  1607. if (unit_string.equals_ignoring_case("px")) {
  1608. type = Length::Type::Px;
  1609. } else if (unit_string.equals_ignoring_case("pt")) {
  1610. type = Length::Type::Pt;
  1611. } else if (unit_string.equals_ignoring_case("pc")) {
  1612. type = Length::Type::Pc;
  1613. } else if (unit_string.equals_ignoring_case("mm")) {
  1614. type = Length::Type::Mm;
  1615. } else if (unit_string.equals_ignoring_case("rem")) {
  1616. type = Length::Type::Rem;
  1617. } else if (unit_string.equals_ignoring_case("em")) {
  1618. type = Length::Type::Em;
  1619. } else if (unit_string.equals_ignoring_case("ex")) {
  1620. type = Length::Type::Ex;
  1621. } else if (unit_string.equals_ignoring_case("ch")) {
  1622. type = Length::Type::Ch;
  1623. } else if (unit_string.equals_ignoring_case("vw")) {
  1624. type = Length::Type::Vw;
  1625. } else if (unit_string.equals_ignoring_case("vh")) {
  1626. type = Length::Type::Vh;
  1627. } else if (unit_string.equals_ignoring_case("vmax")) {
  1628. type = Length::Type::Vmax;
  1629. } else if (unit_string.equals_ignoring_case("vmin")) {
  1630. type = Length::Type::Vmin;
  1631. } else if (unit_string.equals_ignoring_case("cm")) {
  1632. type = Length::Type::Cm;
  1633. } else if (unit_string.equals_ignoring_case("in")) {
  1634. type = Length::Type::In;
  1635. } else if (unit_string.equals_ignoring_case("Q")) {
  1636. type = Length::Type::Q;
  1637. } else if (unit_string.equals_ignoring_case("%")) {
  1638. // A number followed by `%` must always result in a Percentage token.
  1639. VERIFY_NOT_REACHED();
  1640. } else {
  1641. return {};
  1642. }
  1643. } else if (component_value.is(Token::Type::Percentage)) {
  1644. type = Length::Type::Percentage;
  1645. numeric_value = component_value.token().percentage();
  1646. } else if (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto")) {
  1647. return Length::make_auto();
  1648. } else if (component_value.is(Token::Type::Number)) {
  1649. numeric_value = component_value.token().number_value();
  1650. if (numeric_value == 0) {
  1651. type = Length::Type::Px;
  1652. } else if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength)) {
  1653. // https://quirks.spec.whatwg.org/#quirky-length-value
  1654. // FIXME: Disallow quirk when inside a CSS sub-expression (like `calc()`)
  1655. // "The <quirky-length> value must not be supported in arguments to CSS expressions other than the rect()
  1656. // expression, and must not be supported in the supports() static method of the CSS interface."
  1657. type = Length::Type::Px;
  1658. }
  1659. }
  1660. if (!numeric_value.has_value())
  1661. return {};
  1662. return Length(numeric_value.value(), type);
  1663. }
  1664. RefPtr<StyleValue> Parser::parse_length_value(StyleComponentValueRule const& component_value)
  1665. {
  1666. // Numbers with no units can be lengths, in two situations:
  1667. // 1) We're in quirks mode, and it's an integer.
  1668. // 2) It's a 0.
  1669. // We handle case 1 here. Case 2 is handled by NumericStyleValue pretending to be a LengthStyleValue if it is 0.
  1670. // FIXME: "auto" is also treated as a Length, and most of the time that is how it is used, but not always.
  1671. // Possibly it should always be an Identifier, and then quietly converted to a Length when needed, like 0 above.
  1672. // Right now, it instead is quietly converted to an Identifier when needed.
  1673. if (component_value.is(Token::Type::Dimension) || component_value.is(Token::Type::Percentage)
  1674. || (component_value.is(Token::Type::Ident) && component_value.token().ident().equals_ignoring_case("auto"sv))
  1675. || (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::UnitlessLength) && component_value.is(Token::Type::Number) && component_value.token().number_value() != 0)) {
  1676. auto length = parse_length(component_value);
  1677. if (length.has_value())
  1678. return LengthStyleValue::create(length.value());
  1679. }
  1680. return {};
  1681. }
  1682. RefPtr<StyleValue> Parser::parse_numeric_value(StyleComponentValueRule const& component_value)
  1683. {
  1684. if (component_value.is(Token::Type::Number)) {
  1685. auto number = component_value.token();
  1686. if (number.number_type() == Token::NumberType::Integer) {
  1687. return NumericStyleValue::create_integer(number.to_integer());
  1688. } else {
  1689. return NumericStyleValue::create_float(number.number_value());
  1690. }
  1691. }
  1692. return {};
  1693. }
  1694. RefPtr<StyleValue> Parser::parse_identifier_value(StyleComponentValueRule const& component_value)
  1695. {
  1696. if (component_value.is(Token::Type::Ident)) {
  1697. auto value_id = value_id_from_string(component_value.token().ident());
  1698. if (value_id != ValueID::Invalid)
  1699. return IdentifierStyleValue::create(value_id);
  1700. }
  1701. return {};
  1702. }
  1703. Optional<Color> Parser::parse_color(StyleComponentValueRule const& component_value)
  1704. {
  1705. // https://www.w3.org/TR/css-color-3/
  1706. if (component_value.is(Token::Type::Ident)) {
  1707. auto ident = component_value.token().ident();
  1708. auto color = Color::from_string(ident);
  1709. if (color.has_value())
  1710. return color;
  1711. } else if (component_value.is(Token::Type::Hash)) {
  1712. auto color = Color::from_string(String::formatted("#{}", component_value.token().hash_value()));
  1713. if (color.has_value())
  1714. return color;
  1715. return {};
  1716. } else if (component_value.is_function()) {
  1717. auto& function = component_value.function();
  1718. auto& values = function.values();
  1719. Vector<Token> params;
  1720. for (size_t i = 0; i < values.size(); ++i) {
  1721. auto& value = values.at(i);
  1722. if (value.is(Token::Type::Whitespace))
  1723. continue;
  1724. if (value.is(Token::Type::Percentage) || value.is(Token::Type::Number)) {
  1725. params.append(value.token());
  1726. // Eat following comma and whitespace
  1727. while ((i + 1) < values.size()) {
  1728. auto& next = values.at(i + 1);
  1729. if (next.is(Token::Type::Whitespace))
  1730. i++;
  1731. else if (next.is(Token::Type::Comma))
  1732. break;
  1733. return {};
  1734. }
  1735. }
  1736. }
  1737. if (function.name().equals_ignoring_case("rgb")) {
  1738. if (params.size() != 3)
  1739. return {};
  1740. auto r_val = params[0];
  1741. auto g_val = params[1];
  1742. auto b_val = params[2];
  1743. if (r_val.is(Token::NumberType::Integer)
  1744. && g_val.is(Token::NumberType::Integer)
  1745. && b_val.is(Token::NumberType::Integer)) {
  1746. auto r = r_val.to_integer();
  1747. auto g = g_val.to_integer();
  1748. auto b = b_val.to_integer();
  1749. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  1750. return Color(r, g, b);
  1751. } else if (r_val.is(Token::Type::Percentage)
  1752. && g_val.is(Token::Type::Percentage)
  1753. && b_val.is(Token::Type::Percentage)) {
  1754. u8 r = clamp(lroundf(r_val.percentage() * 2.55), 0, 255);
  1755. u8 g = clamp(lroundf(g_val.percentage() * 2.55), 0, 255);
  1756. u8 b = clamp(lroundf(b_val.percentage() * 2.55), 0, 255);
  1757. return Color(r, g, b);
  1758. }
  1759. } else if (function.name().equals_ignoring_case("rgba")) {
  1760. if (params.size() != 4)
  1761. return {};
  1762. auto r_val = params[0];
  1763. auto g_val = params[1];
  1764. auto b_val = params[2];
  1765. auto a_val = params[3];
  1766. if (r_val.is(Token::NumberType::Integer)
  1767. && g_val.is(Token::NumberType::Integer)
  1768. && b_val.is(Token::NumberType::Integer)
  1769. && a_val.is(Token::Type::Number)) {
  1770. auto r = r_val.to_integer();
  1771. auto g = g_val.to_integer();
  1772. auto b = b_val.to_integer();
  1773. auto a = clamp(lroundf(a_val.number_value() * 255.0), 0, 255);
  1774. if (AK::is_within_range<u8>(r) && AK::is_within_range<u8>(g) && AK::is_within_range<u8>(b))
  1775. return Color(r, g, b, a);
  1776. } else if (r_val.is(Token::Type::Percentage)
  1777. && g_val.is(Token::Type::Percentage)
  1778. && b_val.is(Token::Type::Percentage)
  1779. && a_val.is(Token::Type::Number)) {
  1780. auto r = r_val.percentage();
  1781. auto g = g_val.percentage();
  1782. auto b = b_val.percentage();
  1783. auto a = a_val.number_value();
  1784. u8 r_255 = clamp(lroundf(r * 2.55), 0, 255);
  1785. u8 g_255 = clamp(lroundf(g * 2.55), 0, 255);
  1786. u8 b_255 = clamp(lroundf(b * 2.55), 0, 255);
  1787. u8 a_255 = clamp(lroundf(a * 255.0), 0, 255);
  1788. return Color(r_255, g_255, b_255, a_255);
  1789. }
  1790. } else if (function.name().equals_ignoring_case("hsl")) {
  1791. if (params.size() != 3)
  1792. return {};
  1793. auto h_val = params[0];
  1794. auto s_val = params[1];
  1795. auto l_val = params[2];
  1796. if (h_val.is(Token::Type::Number)
  1797. && s_val.is(Token::Type::Percentage)
  1798. && l_val.is(Token::Type::Percentage)) {
  1799. auto h = h_val.number_value();
  1800. auto s = s_val.percentage() / 100.0;
  1801. auto l = l_val.percentage() / 100.0;
  1802. return Color::from_hsl(h, s, l);
  1803. }
  1804. } else if (function.name().equals_ignoring_case("hsla")) {
  1805. if (params.size() != 4)
  1806. return {};
  1807. auto h_val = params[0];
  1808. auto s_val = params[1];
  1809. auto l_val = params[2];
  1810. auto a_val = params[3];
  1811. if (h_val.is(Token::Type::Number)
  1812. && s_val.is(Token::Type::Percentage)
  1813. && l_val.is(Token::Type::Percentage)
  1814. && a_val.is(Token::Type::Number)) {
  1815. auto h = h_val.number_value();
  1816. auto s = s_val.percentage() / 100.0;
  1817. auto l = l_val.percentage() / 100.0;
  1818. auto a = a_val.number_value();
  1819. return Color::from_hsla(h, s, l, a);
  1820. }
  1821. }
  1822. return {};
  1823. }
  1824. // https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
  1825. if (m_context.in_quirks_mode() && property_has_quirk(m_context.current_property_id(), Quirk::HashlessHexColor)) {
  1826. // The value of a quirky color is obtained from the possible component values using the following algorithm,
  1827. // aborting on the first step that returns a value:
  1828. // 1. Let cv be the component value.
  1829. auto& cv = component_value;
  1830. String serialization;
  1831. // 2. If cv is a <number-token> or a <dimension-token>, follow these substeps:
  1832. if (cv.is(Token::Type::Number) || cv.is(Token::Type::Dimension)) {
  1833. // 1. If cv’s type flag is not "integer", return an error.
  1834. // This means that values that happen to use scientific notation, e.g., 5e5e5e, will fail to parse.
  1835. if (cv.token().number_type() != Token::NumberType::Integer)
  1836. return {};
  1837. // 2. If cv’s value is less than zero, return an error.
  1838. auto value = cv.is(Token::Type::Number) ? cv.token().to_integer() : cv.token().dimension_value_int();
  1839. if (value < 0)
  1840. return {};
  1841. // 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.
  1842. StringBuilder serialization_builder;
  1843. serialization_builder.appendff("{}", value);
  1844. // 4. If cv is a <dimension-token>, append the unit to serialization.
  1845. if (cv.is(Token::Type::Dimension))
  1846. serialization_builder.append(cv.token().dimension_unit());
  1847. // 5. If serialization consists of fewer than six characters, prepend zeros (U+0030) so that it becomes six characters.
  1848. serialization = serialization_builder.to_string();
  1849. if (serialization_builder.length() < 6) {
  1850. StringBuilder builder;
  1851. for (size_t i = 0; i < (6 - serialization_builder.length()); i++)
  1852. builder.append('0');
  1853. builder.append(serialization_builder.string_view());
  1854. serialization = builder.to_string();
  1855. }
  1856. }
  1857. // 3. Otherwise, cv is an <ident-token>; let serialization be cv’s value.
  1858. else {
  1859. if (!cv.is(Token::Type::Ident))
  1860. return {};
  1861. serialization = cv.token().ident();
  1862. }
  1863. // 4. If serialization does not consist of three or six characters, return an error.
  1864. if (serialization.length() != 3 && serialization.length() != 6)
  1865. return {};
  1866. // 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.
  1867. for (auto c : serialization) {
  1868. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
  1869. return {};
  1870. }
  1871. // 6. Return the concatenation of "#" (U+0023) and serialization.
  1872. String concatenation = String::formatted("#{}", serialization);
  1873. return Color::from_string(concatenation);
  1874. }
  1875. return {};
  1876. }
  1877. RefPtr<StyleValue> Parser::parse_color_value(StyleComponentValueRule const& component_value)
  1878. {
  1879. auto color = parse_color(component_value);
  1880. if (color.has_value())
  1881. return ColorStyleValue::create(color.value());
  1882. return {};
  1883. }
  1884. RefPtr<StyleValue> Parser::parse_string_value(StyleComponentValueRule const& component_value)
  1885. {
  1886. if (component_value.is(Token::Type::String))
  1887. return StringStyleValue::create(component_value.token().string());
  1888. return {};
  1889. }
  1890. RefPtr<StyleValue> Parser::parse_image_value(StyleComponentValueRule const& component_value)
  1891. {
  1892. auto url = parse_url_function(component_value, AllowedDataUrlType::Image);
  1893. if (url.has_value())
  1894. return ImageStyleValue::create(url.value());
  1895. // FIXME: Handle gradients.
  1896. return {};
  1897. }
  1898. template<typename ParseFunction>
  1899. RefPtr<StyleValue> Parser::parse_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values, ParseFunction parse_one_value)
  1900. {
  1901. auto tokens = TokenStream { component_values };
  1902. auto first = parse_one_value(tokens);
  1903. if (!first || !tokens.has_next_token())
  1904. return first;
  1905. NonnullRefPtrVector<StyleValue> values;
  1906. values.append(first.release_nonnull());
  1907. while (tokens.has_next_token()) {
  1908. if (!tokens.next_token().is(Token::Type::Comma))
  1909. return {};
  1910. if (auto maybe_value = parse_one_value(tokens)) {
  1911. values.append(maybe_value.release_nonnull());
  1912. continue;
  1913. }
  1914. return {};
  1915. }
  1916. return StyleValueList::create(move(values));
  1917. }
  1918. RefPtr<StyleValue> Parser::parse_simple_comma_separated_value_list(Vector<StyleComponentValueRule> const& component_values)
  1919. {
  1920. return parse_comma_separated_value_list(component_values, [=, this](auto& tokens) -> RefPtr<StyleValue> {
  1921. auto& token = tokens.next_token();
  1922. if (auto value = parse_css_value(token); value && property_accepts_value(m_context.current_property_id(), *value))
  1923. return value;
  1924. tokens.reconsume_current_input_token();
  1925. return nullptr;
  1926. });
  1927. }
  1928. RefPtr<StyleValue> Parser::parse_background_value(Vector<StyleComponentValueRule> const& component_values)
  1929. {
  1930. NonnullRefPtrVector<StyleValue> background_images;
  1931. NonnullRefPtrVector<StyleValue> background_positions;
  1932. NonnullRefPtrVector<StyleValue> background_sizes;
  1933. NonnullRefPtrVector<StyleValue> background_repeats;
  1934. NonnullRefPtrVector<StyleValue> background_attachments;
  1935. NonnullRefPtrVector<StyleValue> background_clips;
  1936. NonnullRefPtrVector<StyleValue> background_origins;
  1937. RefPtr<StyleValue> background_color;
  1938. // Per-layer values
  1939. RefPtr<StyleValue> background_image;
  1940. RefPtr<StyleValue> background_position;
  1941. RefPtr<StyleValue> background_size;
  1942. RefPtr<StyleValue> background_repeat;
  1943. RefPtr<StyleValue> background_attachment;
  1944. RefPtr<StyleValue> background_clip;
  1945. RefPtr<StyleValue> background_origin;
  1946. bool has_multiple_layers = false;
  1947. auto background_layer_is_valid = [&](bool allow_background_color) -> bool {
  1948. if (allow_background_color) {
  1949. if (background_color)
  1950. return true;
  1951. } else {
  1952. if (background_color)
  1953. return false;
  1954. }
  1955. return background_image || background_position || background_size || background_repeat || background_attachment || background_clip || background_origin;
  1956. };
  1957. auto complete_background_layer = [&]() {
  1958. background_images.append(background_image ? background_image.release_nonnull() : property_initial_value(PropertyID::BackgroundImage));
  1959. background_positions.append(background_position ? background_position.release_nonnull() : property_initial_value(PropertyID::BackgroundPosition));
  1960. background_sizes.append(background_size ? background_size.release_nonnull() : property_initial_value(PropertyID::BackgroundSize));
  1961. background_repeats.append(background_repeat ? background_repeat.release_nonnull() : property_initial_value(PropertyID::BackgroundRepeat));
  1962. background_attachments.append(background_attachment ? background_attachment.release_nonnull() : property_initial_value(PropertyID::BackgroundAttachment));
  1963. if (!background_origin && !background_clip) {
  1964. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  1965. background_clip = property_initial_value(PropertyID::BackgroundClip);
  1966. } else if (!background_clip) {
  1967. background_clip = background_origin;
  1968. }
  1969. background_origins.append(background_origin.release_nonnull());
  1970. background_clips.append(background_clip.release_nonnull());
  1971. background_image = nullptr;
  1972. background_position = nullptr;
  1973. background_size = nullptr;
  1974. background_repeat = nullptr;
  1975. background_attachment = nullptr;
  1976. background_clip = nullptr;
  1977. background_origin = nullptr;
  1978. };
  1979. auto tokens = TokenStream { component_values };
  1980. while (tokens.has_next_token()) {
  1981. auto& part = tokens.next_token();
  1982. if (part.is(Token::Type::Comma)) {
  1983. has_multiple_layers = true;
  1984. if (!background_layer_is_valid(false))
  1985. return nullptr;
  1986. complete_background_layer();
  1987. continue;
  1988. }
  1989. auto value = parse_css_value(part);
  1990. if (!value)
  1991. return nullptr;
  1992. if (property_accepts_value(PropertyID::BackgroundAttachment, *value)) {
  1993. if (background_attachment)
  1994. return nullptr;
  1995. background_attachment = value.release_nonnull();
  1996. continue;
  1997. }
  1998. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  1999. if (background_color)
  2000. return nullptr;
  2001. background_color = value.release_nonnull();
  2002. continue;
  2003. }
  2004. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  2005. if (background_image)
  2006. return nullptr;
  2007. background_image = value.release_nonnull();
  2008. continue;
  2009. }
  2010. if (property_accepts_value(PropertyID::BackgroundOrigin, *value)) {
  2011. // background-origin and background-clip accept the same values. From the spec:
  2012. // "If one <box> value is present then it sets both background-origin and background-clip to that value.
  2013. // If two values are present, then the first sets background-origin and the second background-clip."
  2014. // - https://www.w3.org/TR/css-backgrounds-3/#background
  2015. // So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
  2016. // If we only get one, we copy the value before creating the BackgroundStyleValue.
  2017. if (!background_origin) {
  2018. background_origin = value.release_nonnull();
  2019. continue;
  2020. }
  2021. if (!background_clip) {
  2022. background_clip = value.release_nonnull();
  2023. continue;
  2024. }
  2025. return nullptr;
  2026. }
  2027. if (property_accepts_value(PropertyID::BackgroundPosition, *value)) {
  2028. if (background_position)
  2029. return nullptr;
  2030. tokens.reconsume_current_input_token();
  2031. if (auto maybe_background_position = parse_single_background_position_value(tokens)) {
  2032. background_position = maybe_background_position.release_nonnull();
  2033. // Attempt to parse `/ <background-size>`
  2034. auto before_slash = tokens.position();
  2035. auto& maybe_slash = tokens.next_token();
  2036. if (maybe_slash.is(Token::Type::Delim) && maybe_slash.token().delim() == "/"sv) {
  2037. if (auto maybe_background_size = parse_single_background_size_value(tokens)) {
  2038. background_size = maybe_background_size.release_nonnull();
  2039. continue;
  2040. }
  2041. return nullptr;
  2042. }
  2043. tokens.rewind_to_position(before_slash);
  2044. continue;
  2045. }
  2046. return nullptr;
  2047. }
  2048. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  2049. if (background_repeat)
  2050. return nullptr;
  2051. tokens.reconsume_current_input_token();
  2052. if (auto maybe_repeat = parse_single_background_repeat_value(tokens)) {
  2053. background_repeat = maybe_repeat.release_nonnull();
  2054. continue;
  2055. }
  2056. return nullptr;
  2057. }
  2058. return nullptr;
  2059. }
  2060. if (!background_layer_is_valid(true))
  2061. return nullptr;
  2062. // We only need to create StyleValueLists if there are multiple layers.
  2063. // Otherwise, we can pass the single StyleValues directly.
  2064. if (has_multiple_layers) {
  2065. complete_background_layer();
  2066. if (!background_color)
  2067. background_color = property_initial_value(PropertyID::BackgroundColor);
  2068. return BackgroundStyleValue::create(
  2069. background_color.release_nonnull(),
  2070. StyleValueList::create(move(background_images)),
  2071. StyleValueList::create(move(background_positions)),
  2072. StyleValueList::create(move(background_sizes)),
  2073. StyleValueList::create(move(background_repeats)),
  2074. StyleValueList::create(move(background_attachments)),
  2075. StyleValueList::create(move(background_origins)),
  2076. StyleValueList::create(move(background_clips)));
  2077. }
  2078. if (!background_color)
  2079. background_color = property_initial_value(PropertyID::BackgroundColor);
  2080. if (!background_image)
  2081. background_image = property_initial_value(PropertyID::BackgroundImage);
  2082. if (!background_position)
  2083. background_position = property_initial_value(PropertyID::BackgroundPosition);
  2084. if (!background_size)
  2085. background_size = property_initial_value(PropertyID::BackgroundSize);
  2086. if (!background_repeat)
  2087. background_repeat = property_initial_value(PropertyID::BackgroundRepeat);
  2088. if (!background_attachment)
  2089. background_attachment = property_initial_value(PropertyID::BackgroundAttachment);
  2090. if (!background_origin && !background_clip) {
  2091. background_origin = property_initial_value(PropertyID::BackgroundOrigin);
  2092. background_clip = property_initial_value(PropertyID::BackgroundClip);
  2093. } else if (!background_clip) {
  2094. background_clip = background_origin;
  2095. }
  2096. return BackgroundStyleValue::create(
  2097. background_color.release_nonnull(),
  2098. background_image.release_nonnull(),
  2099. background_position.release_nonnull(),
  2100. background_size.release_nonnull(),
  2101. background_repeat.release_nonnull(),
  2102. background_attachment.release_nonnull(),
  2103. background_origin.release_nonnull(),
  2104. background_clip.release_nonnull());
  2105. }
  2106. RefPtr<StyleValue> Parser::parse_single_background_position_value(TokenStream<StyleComponentValueRule>& tokens)
  2107. {
  2108. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  2109. // "Note: The background-position property also accepts a three-value syntax.
  2110. // This has been disallowed generically because it creates parsing ambiguities
  2111. // when combined with other length or percentage components in a property value."
  2112. // - https://www.w3.org/TR/css-values-4/#typedef-position
  2113. // So, we'll need a separate function to parse <position> later.
  2114. auto start_position = tokens.position();
  2115. auto error = [&]() {
  2116. tokens.rewind_to_position(start_position);
  2117. return nullptr;
  2118. };
  2119. auto to_edge = [](ValueID identifier) -> Optional<PositionEdge> {
  2120. switch (identifier) {
  2121. case ValueID::Top:
  2122. return PositionEdge::Top;
  2123. case ValueID::Bottom:
  2124. return PositionEdge::Bottom;
  2125. case ValueID::Left:
  2126. return PositionEdge::Left;
  2127. case ValueID::Right:
  2128. return PositionEdge::Right;
  2129. default:
  2130. return {};
  2131. }
  2132. };
  2133. auto is_horizontal = [](ValueID identifier) -> bool {
  2134. switch (identifier) {
  2135. case ValueID::Left:
  2136. case ValueID::Right:
  2137. return true;
  2138. default:
  2139. return false;
  2140. }
  2141. };
  2142. auto is_vertical = [](ValueID identifier) -> bool {
  2143. switch (identifier) {
  2144. case ValueID::Top:
  2145. case ValueID::Bottom:
  2146. return true;
  2147. default:
  2148. return false;
  2149. }
  2150. };
  2151. auto zero_offset = Length::make_px(0);
  2152. auto center_offset = Length { 50, Length::Type::Percentage };
  2153. struct EdgeOffset {
  2154. PositionEdge edge;
  2155. Length offset;
  2156. bool edge_provided;
  2157. bool offset_provided;
  2158. };
  2159. Optional<EdgeOffset> horizontal;
  2160. Optional<EdgeOffset> vertical;
  2161. bool found_center = false;
  2162. while (tokens.has_next_token()) {
  2163. // Check if we're done
  2164. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  2165. if (seen_items == 2)
  2166. break;
  2167. auto& token = tokens.peek_token();
  2168. auto maybe_value = parse_css_value(token);
  2169. if (!maybe_value || !property_accepts_value(PropertyID::BackgroundPosition, *maybe_value))
  2170. break;
  2171. tokens.next_token();
  2172. auto value = maybe_value.release_nonnull();
  2173. if (value->has_length()) {
  2174. if (!horizontal.has_value()) {
  2175. horizontal = EdgeOffset { PositionEdge::Left, value->to_length(), false, true };
  2176. } else if (!vertical.has_value()) {
  2177. vertical = EdgeOffset { PositionEdge::Top, value->to_length(), false, true };
  2178. } else {
  2179. return error();
  2180. }
  2181. continue;
  2182. }
  2183. if (value->has_identifier()) {
  2184. auto identifier = value->to_identifier();
  2185. if (is_horizontal(identifier)) {
  2186. Length offset = zero_offset;
  2187. bool offset_provided = false;
  2188. if (tokens.has_next_token()) {
  2189. auto maybe_offset = parse_length(tokens.peek_token());
  2190. if (maybe_offset.has_value()) {
  2191. offset = maybe_offset.value();
  2192. offset_provided = true;
  2193. tokens.next_token();
  2194. }
  2195. }
  2196. horizontal = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2197. } else if (is_vertical(identifier)) {
  2198. Length offset = zero_offset;
  2199. bool offset_provided = false;
  2200. if (tokens.has_next_token()) {
  2201. auto maybe_offset = parse_length(tokens.peek_token());
  2202. if (maybe_offset.has_value()) {
  2203. offset = maybe_offset.value();
  2204. offset_provided = true;
  2205. tokens.next_token();
  2206. }
  2207. }
  2208. vertical = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2209. } else if (identifier == ValueID::Center) {
  2210. found_center = true;
  2211. } else {
  2212. return error();
  2213. }
  2214. continue;
  2215. }
  2216. tokens.reconsume_current_input_token();
  2217. break;
  2218. }
  2219. if (found_center) {
  2220. if (horizontal.has_value() && vertical.has_value())
  2221. return error();
  2222. if (!horizontal.has_value())
  2223. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  2224. if (!vertical.has_value())
  2225. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  2226. }
  2227. if (!horizontal.has_value() && !vertical.has_value())
  2228. return error();
  2229. // Unpack `<edge> <length>`:
  2230. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  2231. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  2232. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  2233. // Split into `x y`
  2234. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  2235. horizontal->offset = zero_offset;
  2236. horizontal->offset_provided = false;
  2237. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  2238. // `y`, reconsume
  2239. vertical->offset = zero_offset;
  2240. vertical->offset_provided = false;
  2241. tokens.reconsume_current_input_token();
  2242. }
  2243. // If only one value is specified, the second value is assumed to be center.
  2244. if (!horizontal.has_value())
  2245. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  2246. if (!vertical.has_value())
  2247. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  2248. return PositionStyleValue::create(
  2249. horizontal->edge, horizontal->offset,
  2250. vertical->edge, vertical->offset);
  2251. }
  2252. RefPtr<StyleValue> Parser::parse_single_background_repeat_value(TokenStream<StyleComponentValueRule>& tokens)
  2253. {
  2254. auto start_position = tokens.position();
  2255. auto error = [&]() {
  2256. tokens.rewind_to_position(start_position);
  2257. return nullptr;
  2258. };
  2259. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2260. auto value_id = value.to_identifier();
  2261. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2262. };
  2263. auto as_repeat = [](ValueID identifier) {
  2264. switch (identifier) {
  2265. case ValueID::NoRepeat:
  2266. return Repeat::NoRepeat;
  2267. case ValueID::Repeat:
  2268. return Repeat::Repeat;
  2269. case ValueID::Round:
  2270. return Repeat::Round;
  2271. case ValueID::Space:
  2272. return Repeat::Space;
  2273. default:
  2274. VERIFY_NOT_REACHED();
  2275. }
  2276. };
  2277. auto& token = tokens.next_token();
  2278. auto maybe_x_value = parse_css_value(token);
  2279. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_x_value))
  2280. return error();
  2281. auto x_value = maybe_x_value.release_nonnull();
  2282. if (is_directional_repeat(*x_value)) {
  2283. auto value_id = x_value->to_identifier();
  2284. return BackgroundRepeatStyleValue::create(
  2285. value_id == ValueID::RepeatX ? Repeat::Repeat : Repeat::NoRepeat,
  2286. value_id == ValueID::RepeatX ? Repeat::NoRepeat : Repeat::Repeat);
  2287. }
  2288. // See if we have a second value for Y
  2289. auto& second_token = tokens.peek_token();
  2290. auto maybe_y_value = parse_css_value(second_token);
  2291. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundRepeat, *maybe_y_value)) {
  2292. // We don't have a second value, so use x for both
  2293. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(x_value->to_identifier()));
  2294. }
  2295. tokens.next_token();
  2296. auto y_value = maybe_y_value.release_nonnull();
  2297. if (is_directional_repeat(*y_value))
  2298. return error();
  2299. return BackgroundRepeatStyleValue::create(as_repeat(x_value->to_identifier()), as_repeat(y_value->to_identifier()));
  2300. }
  2301. RefPtr<StyleValue> Parser::parse_single_background_size_value(TokenStream<StyleComponentValueRule>& tokens)
  2302. {
  2303. auto start_position = tokens.position();
  2304. auto error = [&]() {
  2305. tokens.rewind_to_position(start_position);
  2306. return nullptr;
  2307. };
  2308. auto maybe_x_value = parse_css_value(tokens.next_token());
  2309. if (!maybe_x_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_x_value))
  2310. return error();
  2311. auto x_value = maybe_x_value.release_nonnull();
  2312. if (x_value->to_identifier() == ValueID::Cover || x_value->to_identifier() == ValueID::Contain)
  2313. return x_value;
  2314. auto maybe_y_value = parse_css_value(tokens.peek_token());
  2315. if (!maybe_y_value || !property_accepts_value(PropertyID::BackgroundSize, *maybe_y_value))
  2316. return BackgroundSizeStyleValue::create(x_value->to_length(), x_value->to_length());
  2317. tokens.next_token();
  2318. auto y_value = maybe_y_value.release_nonnull();
  2319. if (x_value->has_length() && y_value->has_length())
  2320. return BackgroundSizeStyleValue::create(x_value->to_length(), y_value->to_length());
  2321. return error();
  2322. }
  2323. RefPtr<StyleValue> Parser::parse_border_value(Vector<StyleComponentValueRule> const& component_values)
  2324. {
  2325. if (component_values.size() > 3)
  2326. return nullptr;
  2327. RefPtr<StyleValue> border_width;
  2328. RefPtr<StyleValue> border_color;
  2329. RefPtr<StyleValue> border_style;
  2330. for (auto& part : component_values) {
  2331. auto value = parse_css_value(part);
  2332. if (!value)
  2333. return nullptr;
  2334. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  2335. if (border_width)
  2336. return nullptr;
  2337. border_width = value.release_nonnull();
  2338. continue;
  2339. }
  2340. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  2341. if (border_color)
  2342. return nullptr;
  2343. border_color = value.release_nonnull();
  2344. continue;
  2345. }
  2346. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  2347. if (border_style)
  2348. return nullptr;
  2349. border_style = value.release_nonnull();
  2350. continue;
  2351. }
  2352. return nullptr;
  2353. }
  2354. if (!border_width)
  2355. border_width = property_initial_value(PropertyID::BorderWidth);
  2356. if (!border_style)
  2357. border_style = property_initial_value(PropertyID::BorderStyle);
  2358. if (!border_color)
  2359. border_color = property_initial_value(PropertyID::BorderColor);
  2360. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  2361. }
  2362. RefPtr<StyleValue> Parser::parse_border_radius_value(Vector<StyleComponentValueRule> const& component_values)
  2363. {
  2364. if (component_values.size() == 2) {
  2365. auto horizontal = parse_length(component_values[0]);
  2366. auto vertical = parse_length(component_values[1]);
  2367. if (horizontal.has_value() && vertical.has_value())
  2368. return BorderRadiusStyleValue::create(horizontal.value(), vertical.value());
  2369. return nullptr;
  2370. }
  2371. if (component_values.size() == 1) {
  2372. auto radius = parse_length(component_values[0]);
  2373. if (radius.has_value())
  2374. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  2375. return nullptr;
  2376. }
  2377. return nullptr;
  2378. }
  2379. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(Vector<StyleComponentValueRule> const& component_values)
  2380. {
  2381. auto top_left = [&](Vector<Length>& radii) { return radii[0]; };
  2382. auto top_right = [&](Vector<Length>& radii) {
  2383. switch (radii.size()) {
  2384. case 4:
  2385. case 3:
  2386. case 2:
  2387. return radii[1];
  2388. case 1:
  2389. return radii[0];
  2390. default:
  2391. VERIFY_NOT_REACHED();
  2392. }
  2393. };
  2394. auto bottom_right = [&](Vector<Length>& radii) {
  2395. switch (radii.size()) {
  2396. case 4:
  2397. case 3:
  2398. return radii[2];
  2399. case 2:
  2400. case 1:
  2401. return radii[0];
  2402. default:
  2403. VERIFY_NOT_REACHED();
  2404. }
  2405. };
  2406. auto bottom_left = [&](Vector<Length>& radii) {
  2407. switch (radii.size()) {
  2408. case 4:
  2409. return radii[3];
  2410. case 3:
  2411. case 2:
  2412. return radii[1];
  2413. case 1:
  2414. return radii[0];
  2415. default:
  2416. VERIFY_NOT_REACHED();
  2417. }
  2418. };
  2419. Vector<Length> horizontal_radii;
  2420. Vector<Length> vertical_radii;
  2421. bool reading_vertical = false;
  2422. for (auto& value : component_values) {
  2423. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  2424. if (reading_vertical || horizontal_radii.is_empty())
  2425. return nullptr;
  2426. reading_vertical = true;
  2427. continue;
  2428. }
  2429. auto maybe_length = parse_length(value);
  2430. if (!maybe_length.has_value())
  2431. return nullptr;
  2432. if (reading_vertical) {
  2433. vertical_radii.append(maybe_length.value());
  2434. } else {
  2435. horizontal_radii.append(maybe_length.value());
  2436. }
  2437. }
  2438. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2439. || horizontal_radii.is_empty()
  2440. || (reading_vertical && vertical_radii.is_empty()))
  2441. return nullptr;
  2442. NonnullRefPtrVector<StyleValue> border_radii;
  2443. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2444. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  2445. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2446. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  2447. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2448. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  2449. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2450. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  2451. return StyleValueList::create(move(border_radii));
  2452. }
  2453. RefPtr<StyleValue> Parser::parse_box_shadow_value(Vector<StyleComponentValueRule> const& component_values)
  2454. {
  2455. // "none"
  2456. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  2457. auto ident = parse_identifier_value(component_values.first());
  2458. if (ident && ident->to_identifier() == ValueID::None)
  2459. return ident;
  2460. }
  2461. // FIXME: Also support inset, spread-radius and multiple comma-separated box-shadows
  2462. Length offset_x {};
  2463. Length offset_y {};
  2464. Length blur_radius {};
  2465. Color color {};
  2466. if (component_values.size() < 3 || component_values.size() > 4)
  2467. return nullptr;
  2468. auto maybe_x = parse_length(component_values[0]);
  2469. if (!maybe_x.has_value())
  2470. return nullptr;
  2471. offset_x = maybe_x.value();
  2472. auto maybe_y = parse_length(component_values[1]);
  2473. if (!maybe_y.has_value())
  2474. return nullptr;
  2475. offset_y = maybe_y.value();
  2476. if (component_values.size() == 3) {
  2477. auto parsed_color = parse_color(component_values[2]);
  2478. if (!parsed_color.has_value())
  2479. return nullptr;
  2480. color = parsed_color.value();
  2481. } else if (component_values.size() == 4) {
  2482. auto maybe_blur_radius = parse_length(component_values[2]);
  2483. if (!maybe_blur_radius.has_value())
  2484. return nullptr;
  2485. blur_radius = maybe_blur_radius.value();
  2486. auto parsed_color = parse_color(component_values[3]);
  2487. if (!parsed_color.has_value())
  2488. return nullptr;
  2489. color = parsed_color.value();
  2490. }
  2491. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  2492. }
  2493. RefPtr<StyleValue> Parser::parse_flex_value(Vector<StyleComponentValueRule> const& component_values)
  2494. {
  2495. if (component_values.size() == 1) {
  2496. auto value = parse_css_value(component_values[0]);
  2497. if (!value)
  2498. return nullptr;
  2499. switch (value->to_identifier()) {
  2500. case ValueID::Auto: {
  2501. auto one = NumericStyleValue::create_integer(1);
  2502. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  2503. }
  2504. case ValueID::None: {
  2505. auto zero = NumericStyleValue::create_integer(0);
  2506. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  2507. }
  2508. default:
  2509. break;
  2510. }
  2511. }
  2512. RefPtr<StyleValue> flex_grow;
  2513. RefPtr<StyleValue> flex_shrink;
  2514. RefPtr<StyleValue> flex_basis;
  2515. for (size_t i = 0; i < component_values.size(); ++i) {
  2516. auto value = parse_css_value(component_values[i]);
  2517. if (!value)
  2518. return nullptr;
  2519. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  2520. if (value->has_number() && value->to_number() == 0) {
  2521. if (flex_grow && flex_shrink && !flex_basis) {
  2522. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  2523. continue;
  2524. }
  2525. }
  2526. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  2527. if (flex_grow)
  2528. return nullptr;
  2529. flex_grow = value.release_nonnull();
  2530. // Flex-shrink may optionally follow directly after.
  2531. if (i + 1 < component_values.size()) {
  2532. auto second_value = parse_css_value(component_values[i + 1]);
  2533. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  2534. flex_shrink = second_value.release_nonnull();
  2535. i++;
  2536. }
  2537. }
  2538. continue;
  2539. }
  2540. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  2541. if (flex_basis)
  2542. return nullptr;
  2543. flex_basis = value.release_nonnull();
  2544. continue;
  2545. }
  2546. return nullptr;
  2547. }
  2548. if (!flex_grow)
  2549. flex_grow = property_initial_value(PropertyID::FlexGrow);
  2550. if (!flex_shrink)
  2551. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  2552. if (!flex_basis)
  2553. flex_basis = property_initial_value(PropertyID::FlexBasis);
  2554. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  2555. }
  2556. RefPtr<StyleValue> Parser::parse_flex_flow_value(Vector<StyleComponentValueRule> const& component_values)
  2557. {
  2558. if (component_values.size() > 2)
  2559. return nullptr;
  2560. RefPtr<StyleValue> flex_direction;
  2561. RefPtr<StyleValue> flex_wrap;
  2562. for (auto& part : component_values) {
  2563. auto value = parse_css_value(part);
  2564. if (!value)
  2565. return nullptr;
  2566. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  2567. if (flex_direction)
  2568. return nullptr;
  2569. flex_direction = value.release_nonnull();
  2570. continue;
  2571. }
  2572. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  2573. if (flex_wrap)
  2574. return nullptr;
  2575. flex_wrap = value.release_nonnull();
  2576. continue;
  2577. }
  2578. }
  2579. if (!flex_direction)
  2580. flex_direction = property_initial_value(PropertyID::FlexDirection);
  2581. if (!flex_wrap)
  2582. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  2583. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  2584. }
  2585. RefPtr<StyleValue> Parser::parse_font_value(Vector<StyleComponentValueRule> const& component_values)
  2586. {
  2587. RefPtr<StyleValue> font_style;
  2588. RefPtr<StyleValue> font_weight;
  2589. RefPtr<StyleValue> font_size;
  2590. RefPtr<StyleValue> line_height;
  2591. RefPtr<StyleValue> font_families;
  2592. // FIXME: Implement font-stretch and font-variant.
  2593. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  2594. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  2595. // So, we have to handle that separately.
  2596. int normal_count = 0;
  2597. for (size_t i = 0; i < component_values.size(); ++i) {
  2598. auto value = parse_css_value(component_values[i]);
  2599. if (!value)
  2600. return nullptr;
  2601. if (value->to_identifier() == ValueID::Normal) {
  2602. normal_count++;
  2603. continue;
  2604. }
  2605. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  2606. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  2607. if (font_style)
  2608. return nullptr;
  2609. font_style = value.release_nonnull();
  2610. continue;
  2611. }
  2612. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  2613. if (font_weight)
  2614. return nullptr;
  2615. font_weight = value.release_nonnull();
  2616. continue;
  2617. }
  2618. if (property_accepts_value(PropertyID::FontSize, *value)) {
  2619. if (font_size)
  2620. return nullptr;
  2621. font_size = value.release_nonnull();
  2622. // Consume `/ line-height` if present
  2623. if (i + 2 < component_values.size()) {
  2624. auto maybe_solidus = component_values[i + 1];
  2625. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  2626. auto maybe_line_height = parse_css_value(component_values[i + 2]);
  2627. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  2628. return nullptr;
  2629. line_height = maybe_line_height.release_nonnull();
  2630. i += 2;
  2631. }
  2632. }
  2633. // Consume font-families
  2634. auto maybe_font_families = parse_font_family_value(component_values, i + 1);
  2635. if (!maybe_font_families)
  2636. return nullptr;
  2637. font_families = maybe_font_families.release_nonnull();
  2638. break;
  2639. }
  2640. return nullptr;
  2641. }
  2642. // Since normal is the default value for all the properties that can have it, we don't have to actually
  2643. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  2644. // We just need to make sure we were not given more normals than will fit.
  2645. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  2646. if (unset_value_count < normal_count)
  2647. return nullptr;
  2648. if (!font_size || !font_families)
  2649. return nullptr;
  2650. if (!font_style)
  2651. font_style = property_initial_value(PropertyID::FontStyle);
  2652. if (!font_weight)
  2653. font_weight = property_initial_value(PropertyID::FontWeight);
  2654. if (!line_height)
  2655. line_height = property_initial_value(PropertyID::LineHeight);
  2656. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  2657. }
  2658. RefPtr<StyleValue> Parser::parse_font_family_value(Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  2659. {
  2660. auto is_generic_font_family = [](ValueID identifier) -> bool {
  2661. switch (identifier) {
  2662. case ValueID::Cursive:
  2663. case ValueID::Fantasy:
  2664. case ValueID::Monospace:
  2665. case ValueID::Serif:
  2666. case ValueID::SansSerif:
  2667. case ValueID::UiMonospace:
  2668. case ValueID::UiRounded:
  2669. case ValueID::UiSerif:
  2670. case ValueID::UiSansSerif:
  2671. return true;
  2672. default:
  2673. return false;
  2674. }
  2675. };
  2676. auto is_comma_or_eof = [&](size_t i) -> bool {
  2677. if (i < component_values.size()) {
  2678. auto& maybe_comma = component_values[i];
  2679. if (!maybe_comma.is(Token::Type::Comma))
  2680. return false;
  2681. }
  2682. return true;
  2683. };
  2684. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  2685. // eg, these are equivalent:
  2686. // font-family: my cool font\!, serif;
  2687. // font-family: "my cool font!", serif;
  2688. NonnullRefPtrVector<StyleValue> font_families;
  2689. Vector<String> current_name_parts;
  2690. for (size_t i = start_index; i < component_values.size(); ++i) {
  2691. auto& part = component_values[i];
  2692. if (part.is(Token::Type::String)) {
  2693. // `font-family: my cool "font";` is invalid.
  2694. if (!current_name_parts.is_empty())
  2695. return nullptr;
  2696. if (!is_comma_or_eof(i + 1))
  2697. return nullptr;
  2698. font_families.append(StringStyleValue::create(part.token().string()));
  2699. i++;
  2700. continue;
  2701. }
  2702. if (part.is(Token::Type::Ident)) {
  2703. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  2704. auto maybe_ident = parse_css_value(part);
  2705. if (maybe_ident) {
  2706. // CSS-wide keywords are not allowed
  2707. if (maybe_ident->is_builtin())
  2708. return nullptr;
  2709. if (is_generic_font_family(maybe_ident->to_identifier())) {
  2710. // Can't have a generic-font-name as a token in an unquoted font name.
  2711. if (!current_name_parts.is_empty())
  2712. return nullptr;
  2713. if (!is_comma_or_eof(i + 1))
  2714. return nullptr;
  2715. font_families.append(maybe_ident.release_nonnull());
  2716. i++;
  2717. continue;
  2718. }
  2719. }
  2720. current_name_parts.append(part.token().ident());
  2721. continue;
  2722. }
  2723. if (part.is(Token::Type::Comma)) {
  2724. if (current_name_parts.is_empty())
  2725. return nullptr;
  2726. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2727. current_name_parts.clear();
  2728. // Can't have a trailing comma
  2729. if (i + 1 == component_values.size())
  2730. return nullptr;
  2731. continue;
  2732. }
  2733. }
  2734. if (!current_name_parts.is_empty()) {
  2735. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2736. current_name_parts.clear();
  2737. }
  2738. if (font_families.is_empty())
  2739. return nullptr;
  2740. return StyleValueList::create(move(font_families));
  2741. }
  2742. RefPtr<StyleValue> Parser::parse_list_style_value(Vector<StyleComponentValueRule> const& component_values)
  2743. {
  2744. if (component_values.size() > 3)
  2745. return nullptr;
  2746. RefPtr<StyleValue> list_position;
  2747. RefPtr<StyleValue> list_image;
  2748. RefPtr<StyleValue> list_type;
  2749. int found_nones = 0;
  2750. for (auto& part : component_values) {
  2751. auto value = parse_css_value(part);
  2752. if (!value)
  2753. return nullptr;
  2754. if (value->to_identifier() == ValueID::None) {
  2755. found_nones++;
  2756. continue;
  2757. }
  2758. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  2759. if (list_position)
  2760. return nullptr;
  2761. list_position = value.release_nonnull();
  2762. continue;
  2763. }
  2764. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  2765. if (list_image)
  2766. return nullptr;
  2767. list_image = value.release_nonnull();
  2768. continue;
  2769. }
  2770. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  2771. if (list_type)
  2772. return nullptr;
  2773. list_type = value.release_nonnull();
  2774. continue;
  2775. }
  2776. }
  2777. if (found_nones > 2)
  2778. return nullptr;
  2779. if (found_nones == 2) {
  2780. if (list_image || list_type)
  2781. return nullptr;
  2782. auto none = IdentifierStyleValue::create(ValueID::None);
  2783. list_image = none;
  2784. list_type = none;
  2785. } else if (found_nones == 1) {
  2786. if (list_image && list_type)
  2787. return nullptr;
  2788. auto none = IdentifierStyleValue::create(ValueID::None);
  2789. if (!list_image)
  2790. list_image = none;
  2791. if (!list_type)
  2792. list_type = none;
  2793. }
  2794. if (!list_position)
  2795. list_position = property_initial_value(PropertyID::ListStylePosition);
  2796. if (!list_image)
  2797. list_image = property_initial_value(PropertyID::ListStyleImage);
  2798. if (!list_type)
  2799. list_type = property_initial_value(PropertyID::ListStyleType);
  2800. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  2801. }
  2802. RefPtr<StyleValue> Parser::parse_overflow_value(Vector<StyleComponentValueRule> const& component_values)
  2803. {
  2804. if (component_values.size() == 1) {
  2805. auto maybe_value = parse_css_value(component_values.first());
  2806. if (!maybe_value)
  2807. return nullptr;
  2808. auto value = maybe_value.release_nonnull();
  2809. if (property_accepts_value(PropertyID::Overflow, *value))
  2810. return OverflowStyleValue::create(value, value);
  2811. return nullptr;
  2812. }
  2813. if (component_values.size() == 2) {
  2814. auto maybe_x_value = parse_css_value(component_values[0]);
  2815. auto maybe_y_value = parse_css_value(component_values[1]);
  2816. if (!maybe_x_value || !maybe_y_value)
  2817. return nullptr;
  2818. auto x_value = maybe_x_value.release_nonnull();
  2819. auto y_value = maybe_y_value.release_nonnull();
  2820. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  2821. return nullptr;
  2822. }
  2823. return OverflowStyleValue::create(x_value, y_value);
  2824. }
  2825. return nullptr;
  2826. }
  2827. RefPtr<StyleValue> Parser::parse_text_decoration_value(Vector<StyleComponentValueRule> const& component_values)
  2828. {
  2829. if (component_values.size() > 3)
  2830. return nullptr;
  2831. RefPtr<StyleValue> decoration_line;
  2832. RefPtr<StyleValue> decoration_style;
  2833. RefPtr<StyleValue> decoration_color;
  2834. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  2835. for (auto& part : component_values) {
  2836. auto value = parse_css_value(part);
  2837. if (!value)
  2838. return nullptr;
  2839. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  2840. if (decoration_color)
  2841. return nullptr;
  2842. decoration_color = value.release_nonnull();
  2843. continue;
  2844. }
  2845. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  2846. if (decoration_line)
  2847. return nullptr;
  2848. decoration_line = value.release_nonnull();
  2849. continue;
  2850. }
  2851. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  2852. if (decoration_style)
  2853. return nullptr;
  2854. decoration_style = value.release_nonnull();
  2855. continue;
  2856. }
  2857. return nullptr;
  2858. }
  2859. if (!decoration_line)
  2860. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  2861. if (!decoration_style)
  2862. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  2863. if (!decoration_color)
  2864. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  2865. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  2866. }
  2867. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  2868. {
  2869. if (name == "translateY")
  2870. return CSS::TransformFunction::TranslateY;
  2871. return {};
  2872. }
  2873. RefPtr<StyleValue> Parser::parse_transform_value(Vector<StyleComponentValueRule> const& component_values)
  2874. {
  2875. NonnullRefPtrVector<StyleValue> transformations;
  2876. for (auto& part : component_values) {
  2877. if (part.is(Token::Type::Ident) && part.token().ident().equals_ignoring_case("none")) {
  2878. if (!transformations.is_empty())
  2879. return nullptr;
  2880. return IdentifierStyleValue::create(ValueID::None);
  2881. }
  2882. if (!part.is_function())
  2883. return nullptr;
  2884. auto maybe_function = parse_transform_function_name(part.function().name());
  2885. if (!maybe_function.has_value())
  2886. return nullptr;
  2887. NonnullRefPtrVector<StyleValue> values;
  2888. for (auto& value : part.function().values()) {
  2889. if (value.is(Token::Type::Dimension)) {
  2890. auto maybe_length = parse_length(value);
  2891. if (!maybe_length.has_value())
  2892. return nullptr;
  2893. values.append(LengthStyleValue::create(maybe_length.release_value()));
  2894. } else if (value.is(Token::Type::Number)) {
  2895. auto number = parse_numeric_value(value);
  2896. values.append(number.release_nonnull());
  2897. } else {
  2898. dbgln("FIXME: Unsupported value type for transformation!");
  2899. return nullptr;
  2900. }
  2901. }
  2902. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  2903. }
  2904. return StyleValueList::create(move(transformations));
  2905. }
  2906. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2907. {
  2908. auto component_values = parse_as_list_of_component_values();
  2909. auto tokens = TokenStream(component_values);
  2910. auto parsed_value = parse_css_value(property_id, tokens);
  2911. if (parsed_value.is_error())
  2912. return {};
  2913. return parsed_value.release_value();
  2914. }
  2915. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2916. {
  2917. m_context.set_current_property_id(property_id);
  2918. Vector<StyleComponentValueRule> component_values;
  2919. while (tokens.has_next_token()) {
  2920. auto& token = tokens.next_token();
  2921. if (token.is(Token::Type::Semicolon)) {
  2922. tokens.reconsume_current_input_token();
  2923. break;
  2924. }
  2925. if (token.is(Token::Type::Whitespace))
  2926. continue;
  2927. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2928. return ParsingResult::IncludesIgnoredVendorPrefix;
  2929. component_values.append(token);
  2930. }
  2931. if (component_values.is_empty())
  2932. return ParsingResult::SyntaxError;
  2933. if (component_values.size() == 1) {
  2934. if (auto parsed_value = parse_builtin_value(component_values.first()))
  2935. return parsed_value.release_nonnull();
  2936. }
  2937. // Special-case property handling
  2938. switch (property_id) {
  2939. case PropertyID::Background:
  2940. if (auto parsed_value = parse_background_value(component_values))
  2941. return parsed_value.release_nonnull();
  2942. return ParsingResult::SyntaxError;
  2943. case PropertyID::BackgroundAttachment:
  2944. case PropertyID::BackgroundClip:
  2945. case PropertyID::BackgroundImage:
  2946. case PropertyID::BackgroundOrigin:
  2947. if (auto parsed_value = parse_simple_comma_separated_value_list(component_values))
  2948. return parsed_value.release_nonnull();
  2949. return ParsingResult::SyntaxError;
  2950. case PropertyID::BackgroundPosition:
  2951. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_position_value(tokens); }))
  2952. return parsed_value.release_nonnull();
  2953. return ParsingResult::SyntaxError;
  2954. case PropertyID::BackgroundRepeat:
  2955. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_repeat_value(tokens); }))
  2956. return parsed_value.release_nonnull();
  2957. return ParsingResult::SyntaxError;
  2958. case PropertyID::BackgroundSize:
  2959. if (auto parsed_value = parse_comma_separated_value_list(component_values, [this](auto& tokens) { return parse_single_background_size_value(tokens); }))
  2960. return parsed_value.release_nonnull();
  2961. return ParsingResult::SyntaxError;
  2962. case PropertyID::Border:
  2963. case PropertyID::BorderBottom:
  2964. case PropertyID::BorderLeft:
  2965. case PropertyID::BorderRight:
  2966. case PropertyID::BorderTop:
  2967. if (auto parsed_value = parse_border_value(component_values))
  2968. return parsed_value.release_nonnull();
  2969. return ParsingResult::SyntaxError;
  2970. case PropertyID::BorderTopLeftRadius:
  2971. case PropertyID::BorderTopRightRadius:
  2972. case PropertyID::BorderBottomRightRadius:
  2973. case PropertyID::BorderBottomLeftRadius:
  2974. if (auto parsed_value = parse_border_radius_value(component_values))
  2975. return parsed_value.release_nonnull();
  2976. return ParsingResult::SyntaxError;
  2977. case PropertyID::BorderRadius:
  2978. if (auto parsed_value = parse_border_radius_shorthand_value(component_values))
  2979. return parsed_value.release_nonnull();
  2980. return ParsingResult::SyntaxError;
  2981. case PropertyID::BoxShadow:
  2982. if (auto parsed_value = parse_box_shadow_value(component_values))
  2983. return parsed_value.release_nonnull();
  2984. return ParsingResult::SyntaxError;
  2985. case PropertyID::Flex:
  2986. if (auto parsed_value = parse_flex_value(component_values))
  2987. return parsed_value.release_nonnull();
  2988. return ParsingResult::SyntaxError;
  2989. case PropertyID::FlexFlow:
  2990. if (auto parsed_value = parse_flex_flow_value(component_values))
  2991. return parsed_value.release_nonnull();
  2992. return ParsingResult::SyntaxError;
  2993. case PropertyID::Font:
  2994. if (auto parsed_value = parse_font_value(component_values))
  2995. return parsed_value.release_nonnull();
  2996. return ParsingResult::SyntaxError;
  2997. case PropertyID::FontFamily:
  2998. if (auto parsed_value = parse_font_family_value(component_values))
  2999. return parsed_value.release_nonnull();
  3000. return ParsingResult::SyntaxError;
  3001. case PropertyID::ListStyle:
  3002. if (auto parsed_value = parse_list_style_value(component_values))
  3003. return parsed_value.release_nonnull();
  3004. return ParsingResult::SyntaxError;
  3005. case PropertyID::Overflow:
  3006. if (auto parsed_value = parse_overflow_value(component_values))
  3007. return parsed_value.release_nonnull();
  3008. return ParsingResult::SyntaxError;
  3009. case PropertyID::TextDecoration:
  3010. if (auto parsed_value = parse_text_decoration_value(component_values))
  3011. return parsed_value.release_nonnull();
  3012. return ParsingResult::SyntaxError;
  3013. case PropertyID::Transform:
  3014. if (auto parsed_value = parse_transform_value(component_values))
  3015. return parsed_value.release_nonnull();
  3016. return ParsingResult::SyntaxError;
  3017. default:
  3018. break;
  3019. }
  3020. if (component_values.size() == 1) {
  3021. if (auto parsed_value = parse_css_value(component_values.first())) {
  3022. if (property_accepts_value(property_id, *parsed_value))
  3023. return parsed_value.release_nonnull();
  3024. }
  3025. return ParsingResult::SyntaxError;
  3026. }
  3027. // We have multiple values, so treat them as a StyleValueList.
  3028. if (property_maximum_value_count(property_id) > 1) {
  3029. NonnullRefPtrVector<StyleValue> parsed_values;
  3030. for (auto& component_value : component_values) {
  3031. auto parsed_value = parse_css_value(component_value);
  3032. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  3033. return ParsingResult::SyntaxError;
  3034. parsed_values.append(parsed_value.release_nonnull());
  3035. }
  3036. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  3037. return { StyleValueList::create(move(parsed_values)) };
  3038. }
  3039. return ParsingResult::SyntaxError;
  3040. }
  3041. RefPtr<StyleValue> Parser::parse_css_value(StyleComponentValueRule const& component_value)
  3042. {
  3043. if (auto builtin = parse_builtin_value(component_value))
  3044. return builtin;
  3045. if (auto dynamic = parse_dynamic_value(component_value))
  3046. return dynamic;
  3047. // We parse colors before numbers, to catch hashless hex colors.
  3048. if (auto color = parse_color_value(component_value))
  3049. return color;
  3050. if (auto length = parse_length_value(component_value))
  3051. return length;
  3052. if (auto numeric = parse_numeric_value(component_value))
  3053. return numeric;
  3054. if (auto identifier = parse_identifier_value(component_value))
  3055. return identifier;
  3056. if (auto string = parse_string_value(component_value))
  3057. return string;
  3058. if (auto image = parse_image_value(component_value))
  3059. return image;
  3060. return {};
  3061. }
  3062. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  3063. {
  3064. int a = 0;
  3065. int b = 0;
  3066. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3067. if constexpr (CSS_PARSER_DEBUG) {
  3068. dbgln("Invalid An+B value:");
  3069. values.dump_all_tokens();
  3070. }
  3071. return {};
  3072. };
  3073. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3074. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  3075. values.skip_whitespace();
  3076. if (values.has_next_token()) {
  3077. if constexpr (CSS_PARSER_DEBUG) {
  3078. dbgln("Extra tokens at end of An+B value:");
  3079. values.dump_all_tokens();
  3080. }
  3081. return syntax_error();
  3082. } else {
  3083. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  3084. }
  3085. };
  3086. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  3087. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  3088. };
  3089. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  3090. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  3091. };
  3092. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  3093. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  3094. };
  3095. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  3096. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  3097. };
  3098. auto is_delim = [](StyleComponentValueRule const& value, StringView delim) -> bool {
  3099. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  3100. };
  3101. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  3102. if (!value.is(Token::Type::Dimension))
  3103. return false;
  3104. if (value.token().number_type() != Token::NumberType::Integer)
  3105. return false;
  3106. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  3107. return false;
  3108. return true;
  3109. };
  3110. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  3111. if (!value.is(Token::Type::Dimension))
  3112. return false;
  3113. if (value.token().number_type() != Token::NumberType::Integer)
  3114. return false;
  3115. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  3116. return false;
  3117. return true;
  3118. };
  3119. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  3120. if (!value.is(Token::Type::Dimension))
  3121. return false;
  3122. if (value.token().number_type() != Token::NumberType::Integer)
  3123. return false;
  3124. auto dimension_unit = value.token().dimension_unit();
  3125. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3126. return false;
  3127. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  3128. if (!is_ascii_digit(dimension_unit[i]))
  3129. return false;
  3130. }
  3131. return true;
  3132. };
  3133. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3134. if (!value.is(Token::Type::Ident))
  3135. return false;
  3136. auto ident = value.token().ident();
  3137. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3138. return false;
  3139. for (size_t i = 2; i < ident.length(); ++i) {
  3140. if (!is_ascii_digit(ident[i]))
  3141. return false;
  3142. }
  3143. return true;
  3144. };
  3145. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3146. if (!value.is(Token::Type::Ident))
  3147. return false;
  3148. auto ident = value.token().ident();
  3149. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  3150. return false;
  3151. for (size_t i = 3; i < ident.length(); ++i) {
  3152. if (!is_ascii_digit(ident[i]))
  3153. return false;
  3154. }
  3155. return true;
  3156. };
  3157. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  3158. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  3159. };
  3160. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3161. return is_integer(value) && value.token().is_integer_value_signed();
  3162. };
  3163. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3164. return is_integer(value) && !value.token().is_integer_value_signed();
  3165. };
  3166. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  3167. // Unfortunately these can't be in the same order as in the spec.
  3168. values.skip_whitespace();
  3169. auto& first_value = values.next_token();
  3170. // odd | even
  3171. if (first_value.is(Token::Type::Ident)) {
  3172. auto ident = first_value.token().ident();
  3173. if (ident.equals_ignoring_case("odd")) {
  3174. a = 2;
  3175. b = 1;
  3176. return make_return_value();
  3177. } else if (ident.equals_ignoring_case("even")) {
  3178. a = 2;
  3179. return make_return_value();
  3180. }
  3181. }
  3182. // <integer>
  3183. if (is_integer(first_value)) {
  3184. b = first_value.token().to_integer();
  3185. return make_return_value();
  3186. }
  3187. // <n-dimension>
  3188. // <n-dimension> <signed-integer>
  3189. // <n-dimension> ['+' | '-'] <signless-integer>
  3190. if (is_n_dimension(first_value)) {
  3191. a = first_value.token().dimension_value_int();
  3192. values.skip_whitespace();
  3193. auto& second_value = values.next_token();
  3194. if (second_value.is(Token::Type::EndOfFile)) {
  3195. // <n-dimension>
  3196. return make_return_value();
  3197. } else if (is_signed_integer(second_value)) {
  3198. // <n-dimension> <signed-integer>
  3199. b = second_value.token().to_integer();
  3200. return make_return_value();
  3201. }
  3202. values.skip_whitespace();
  3203. auto& third_value = values.next_token();
  3204. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3205. // <n-dimension> ['+' | '-'] <signless-integer>
  3206. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3207. return make_return_value();
  3208. }
  3209. return syntax_error();
  3210. }
  3211. // <ndash-dimension> <signless-integer>
  3212. if (is_ndash_dimension(first_value)) {
  3213. values.skip_whitespace();
  3214. auto& second_value = values.next_token();
  3215. if (is_signless_integer(second_value)) {
  3216. a = first_value.token().dimension_value_int();
  3217. b = -second_value.token().to_integer();
  3218. return make_return_value();
  3219. }
  3220. return syntax_error();
  3221. }
  3222. // <ndashdigit-dimension>
  3223. if (is_ndashdigit_dimension(first_value)) {
  3224. auto& dimension = first_value.token();
  3225. a = dimension.dimension_value_int();
  3226. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  3227. if (maybe_b.has_value()) {
  3228. b = maybe_b.value();
  3229. return make_return_value();
  3230. }
  3231. return syntax_error();
  3232. }
  3233. // <dashndashdigit-ident>
  3234. if (is_dashndashdigit_ident(first_value)) {
  3235. a = -1;
  3236. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  3237. if (maybe_b.has_value()) {
  3238. b = maybe_b.value();
  3239. return make_return_value();
  3240. }
  3241. return syntax_error();
  3242. }
  3243. // -n
  3244. // -n <signed-integer>
  3245. // -n ['+' | '-'] <signless-integer>
  3246. if (is_dashn(first_value)) {
  3247. a = -1;
  3248. values.skip_whitespace();
  3249. auto& second_value = values.next_token();
  3250. if (second_value.is(Token::Type::EndOfFile)) {
  3251. // -n
  3252. return make_return_value();
  3253. } else if (is_signed_integer(second_value)) {
  3254. // -n <signed-integer>
  3255. b = second_value.token().to_integer();
  3256. return make_return_value();
  3257. }
  3258. values.skip_whitespace();
  3259. auto& third_value = values.next_token();
  3260. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3261. // -n ['+' | '-'] <signless-integer>
  3262. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3263. return make_return_value();
  3264. }
  3265. return syntax_error();
  3266. }
  3267. // -n- <signless-integer>
  3268. if (is_dashndash(first_value)) {
  3269. values.skip_whitespace();
  3270. auto& second_value = values.next_token();
  3271. if (is_signless_integer(second_value)) {
  3272. a = -1;
  3273. b = -second_value.token().to_integer();
  3274. return make_return_value();
  3275. }
  3276. return syntax_error();
  3277. }
  3278. // All that's left now are these:
  3279. // '+'?† n
  3280. // '+'?† n <signed-integer>
  3281. // '+'?† n ['+' | '-'] <signless-integer>
  3282. // '+'?† n- <signless-integer>
  3283. // '+'?† <ndashdigit-ident>
  3284. // In all of these cases, the + is optional, and has no effect.
  3285. // So, we just skip the +, and carry on.
  3286. if (!is_delim(first_value, "+"sv)) {
  3287. values.reconsume_current_input_token();
  3288. // We do *not* skip whitespace here.
  3289. }
  3290. auto& first_after_plus = values.next_token();
  3291. // '+'?† n
  3292. // '+'?† n <signed-integer>
  3293. // '+'?† n ['+' | '-'] <signless-integer>
  3294. if (is_n(first_after_plus)) {
  3295. a = 1;
  3296. values.skip_whitespace();
  3297. auto& second_value = values.next_token();
  3298. if (second_value.is(Token::Type::EndOfFile)) {
  3299. // '+'?† n
  3300. return make_return_value();
  3301. } else if (is_signed_integer(second_value)) {
  3302. // '+'?† n <signed-integer>
  3303. b = second_value.token().to_integer();
  3304. return make_return_value();
  3305. }
  3306. values.skip_whitespace();
  3307. auto& third_value = values.next_token();
  3308. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3309. // '+'?† n ['+' | '-'] <signless-integer>
  3310. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3311. return make_return_value();
  3312. }
  3313. return syntax_error();
  3314. }
  3315. // '+'?† n- <signless-integer>
  3316. if (is_ndash(first_after_plus)) {
  3317. values.skip_whitespace();
  3318. auto& second_value = values.next_token();
  3319. if (is_signless_integer(second_value)) {
  3320. a = 1;
  3321. b = -second_value.token().to_integer();
  3322. return make_return_value();
  3323. }
  3324. return syntax_error();
  3325. }
  3326. // '+'?† <ndashdigit-ident>
  3327. if (is_ndashdigit_ident(first_after_plus)) {
  3328. a = 1;
  3329. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  3330. if (maybe_b.has_value()) {
  3331. b = maybe_b.value();
  3332. return make_return_value();
  3333. }
  3334. return syntax_error();
  3335. }
  3336. return syntax_error();
  3337. }
  3338. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(Vector<StyleComponentValueRule> const& values)
  3339. {
  3340. auto tokens = TokenStream(values);
  3341. return parse_calc_sum(tokens);
  3342. }
  3343. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(TokenStream<StyleComponentValueRule>& tokens)
  3344. {
  3345. auto current_token = tokens.next_token();
  3346. if (current_token.is_block() && current_token.block().is_paren()) {
  3347. auto block_values = TokenStream(current_token.block().values());
  3348. auto parsed_calc_sum = parse_calc_sum(block_values);
  3349. if (!parsed_calc_sum)
  3350. return {};
  3351. return CalculatedStyleValue::CalcValue { parsed_calc_sum.release_nonnull() };
  3352. }
  3353. if (current_token.is(Token::Type::Number))
  3354. return CalculatedStyleValue::CalcValue { static_cast<float>(current_token.token().number_value()) };
  3355. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  3356. auto maybe_length = parse_length(current_token);
  3357. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  3358. return CalculatedStyleValue::CalcValue { maybe_length.value() };
  3359. return {};
  3360. }
  3361. return {};
  3362. }
  3363. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3364. {
  3365. // Note: The default value is not used or passed around.
  3366. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  3367. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  3368. CalculatedStyleValue::CalcNumberValue(0));
  3369. tokens.skip_whitespace();
  3370. auto& op_token = tokens.peek_token();
  3371. if (!op_token.is(Token::Type::Delim))
  3372. return nullptr;
  3373. auto op = op_token.token().delim();
  3374. if (op == "*"sv) {
  3375. tokens.next_token();
  3376. tokens.skip_whitespace();
  3377. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  3378. auto parsed_calc_value = parse_calc_value(tokens);
  3379. if (!parsed_calc_value.has_value())
  3380. return nullptr;
  3381. product_with_operator->value = { parsed_calc_value.release_value() };
  3382. } else if (op == "/"sv) {
  3383. tokens.next_token();
  3384. tokens.skip_whitespace();
  3385. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  3386. auto parsed_calc_number_value = parse_calc_number_value(tokens);
  3387. if (!parsed_calc_number_value.has_value())
  3388. return nullptr;
  3389. product_with_operator->value = { parsed_calc_number_value.release_value() };
  3390. } else {
  3391. return nullptr;
  3392. }
  3393. return product_with_operator;
  3394. }
  3395. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3396. {
  3397. // Note: The default value is not used or passed around.
  3398. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  3399. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  3400. CalculatedStyleValue::CalcNumberValue(0));
  3401. tokens.skip_whitespace();
  3402. auto& op_token = tokens.peek_token();
  3403. if (!op_token.is(Token::Type::Delim))
  3404. return nullptr;
  3405. auto op = op_token.token().delim();
  3406. if (op == "*"sv) {
  3407. tokens.next_token();
  3408. tokens.skip_whitespace();
  3409. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  3410. } else if (op == "/"sv) {
  3411. tokens.next_token();
  3412. tokens.skip_whitespace();
  3413. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  3414. } else {
  3415. return nullptr;
  3416. }
  3417. auto parsed_calc_value = parse_calc_number_value(tokens);
  3418. if (!parsed_calc_value.has_value())
  3419. return nullptr;
  3420. number_product_with_operator->value = parsed_calc_value.release_value();
  3421. return number_product_with_operator;
  3422. }
  3423. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(TokenStream<StyleComponentValueRule>& tokens)
  3424. {
  3425. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  3426. CalculatedStyleValue::CalcNumberValue(0),
  3427. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  3428. auto first_calc_number_value_or_error = parse_calc_number_value(tokens);
  3429. if (!first_calc_number_value_or_error.has_value())
  3430. return nullptr;
  3431. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  3432. while (tokens.has_next_token()) {
  3433. auto number_product_with_operator = parse_calc_number_product_part_with_operator(tokens);
  3434. if (!number_product_with_operator)
  3435. break;
  3436. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  3437. }
  3438. return calc_number_product;
  3439. }
  3440. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3441. {
  3442. if (!(tokens.peek_token().is(Token::Type::Delim)
  3443. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3444. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3445. return nullptr;
  3446. auto& token = tokens.next_token();
  3447. tokens.skip_whitespace();
  3448. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  3449. auto delim = token.token().delim();
  3450. if (delim == "+"sv)
  3451. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  3452. else if (delim == "-"sv)
  3453. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  3454. else
  3455. return nullptr;
  3456. auto calc_number_product = parse_calc_number_product(tokens);
  3457. if (!calc_number_product)
  3458. return nullptr;
  3459. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  3460. }
  3461. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(TokenStream<StyleComponentValueRule>& tokens)
  3462. {
  3463. auto first_calc_number_product_or_error = parse_calc_number_product(tokens);
  3464. if (!first_calc_number_product_or_error)
  3465. return nullptr;
  3466. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  3467. while (tokens.has_next_token()) {
  3468. auto calc_sum_part = parse_calc_number_sum_part_with_operator(tokens);
  3469. if (!calc_sum_part)
  3470. return nullptr;
  3471. additional.append(calc_sum_part.release_nonnull());
  3472. }
  3473. tokens.skip_whitespace();
  3474. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  3475. return calc_number_sum;
  3476. }
  3477. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(TokenStream<StyleComponentValueRule>& tokens)
  3478. {
  3479. auto& first = tokens.peek_token();
  3480. if (first.is_block() && first.block().is_paren()) {
  3481. tokens.next_token();
  3482. auto block_values = TokenStream(first.block().values());
  3483. auto calc_number_sum = parse_calc_number_sum(block_values);
  3484. if (calc_number_sum)
  3485. return { calc_number_sum.release_nonnull() };
  3486. }
  3487. if (!first.is(Token::Type::Number))
  3488. return {};
  3489. tokens.next_token();
  3490. return first.token().number_value();
  3491. }
  3492. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(TokenStream<StyleComponentValueRule>& tokens)
  3493. {
  3494. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  3495. CalculatedStyleValue::CalcValue(0),
  3496. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  3497. auto first_calc_value_or_error = parse_calc_value(tokens);
  3498. if (!first_calc_value_or_error.has_value())
  3499. return nullptr;
  3500. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  3501. while (tokens.has_next_token()) {
  3502. auto product_with_operator = parse_calc_product_part_with_operator(tokens);
  3503. if (!product_with_operator)
  3504. break;
  3505. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  3506. }
  3507. return calc_product;
  3508. }
  3509. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(TokenStream<StyleComponentValueRule>& tokens)
  3510. {
  3511. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  3512. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  3513. if (!(tokens.peek_token().is(Token::Type::Delim)
  3514. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3515. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3516. return nullptr;
  3517. auto& token = tokens.next_token();
  3518. tokens.skip_whitespace();
  3519. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  3520. auto delim = token.token().delim();
  3521. if (delim == "+"sv)
  3522. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  3523. else if (delim == "-"sv)
  3524. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  3525. else
  3526. return nullptr;
  3527. auto calc_product = parse_calc_product(tokens);
  3528. if (!calc_product)
  3529. return nullptr;
  3530. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  3531. };
  3532. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(TokenStream<StyleComponentValueRule>& tokens)
  3533. {
  3534. auto parsed_calc_product = parse_calc_product(tokens);
  3535. if (!parsed_calc_product)
  3536. return nullptr;
  3537. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  3538. while (tokens.has_next_token()) {
  3539. auto calc_sum_part = parse_calc_sum_part_with_operator(tokens);
  3540. if (!calc_sum_part)
  3541. return nullptr;
  3542. additional.append(calc_sum_part.release_nonnull());
  3543. }
  3544. tokens.skip_whitespace();
  3545. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  3546. }
  3547. bool Parser::has_ignored_vendor_prefix(StringView string)
  3548. {
  3549. if (!string.starts_with('-'))
  3550. return false;
  3551. if (string.starts_with("--"))
  3552. return false;
  3553. if (string.starts_with("-libweb-"))
  3554. return false;
  3555. return true;
  3556. }
  3557. }
  3558. namespace Web {
  3559. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView css)
  3560. {
  3561. if (css.is_empty())
  3562. return CSS::CSSStyleSheet::create({});
  3563. CSS::Parser parser(context, css);
  3564. return parser.parse_as_stylesheet();
  3565. }
  3566. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView css)
  3567. {
  3568. if (css.is_empty())
  3569. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  3570. CSS::Parser parser(context, css);
  3571. return parser.parse_as_list_of_declarations();
  3572. }
  3573. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView string, CSS::PropertyID property_id)
  3574. {
  3575. if (string.is_empty())
  3576. return {};
  3577. CSS::Parser parser(context, string);
  3578. return parser.parse_as_css_value(property_id);
  3579. }
  3580. RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
  3581. {
  3582. CSS::Parser parser(context, css_text);
  3583. return parser.parse_as_rule();
  3584. }
  3585. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView selector_text)
  3586. {
  3587. CSS::Parser parser(context, selector_text);
  3588. return parser.parse_as_selector();
  3589. }
  3590. RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView string)
  3591. {
  3592. CSS::Parser parser(context, string);
  3593. return parser.parse_as_media_query();
  3594. }
  3595. NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView string)
  3596. {
  3597. CSS::Parser parser(context, string);
  3598. return parser.parse_as_media_query_list();
  3599. }
  3600. RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const& context, StringView string)
  3601. {
  3602. if (string.is_empty())
  3603. return {};
  3604. CSS::Parser parser(context, string);
  3605. return parser.parse_as_supports();
  3606. }
  3607. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView string)
  3608. {
  3609. auto integer = string.to_int();
  3610. if (integer.has_value())
  3611. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  3612. return parse_css_value(CSS::ParsingContext(document), string);
  3613. }
  3614. }