Parser.cpp 177 KB

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