Parser.cpp 170 KB

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