Parser.cpp 182 KB

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