Parser.cpp 156 KB

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