Parser.cpp 182 KB

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