Parser.cpp 172 KB

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