Parser.cpp 185 KB

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