Parser.cpp 180 KB

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