Parser.cpp 182 KB

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