Parser.cpp 155 KB

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