Parser.cpp 153 KB

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