Parser.cpp 186 KB

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