Parser.cpp 158 KB

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