Parser.cpp 173 KB

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