Parser.cpp 182 KB

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