Parser.cpp 169 KB

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