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