Parser.cpp 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200
  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. RefPtr<StyleValue> background_position;
  2004. // FIXME: Implement background-size.
  2005. RefPtr<StyleValue> background_attachment;
  2006. // FIXME: Implement background-clip.
  2007. // FIXME: Implement background-origin.
  2008. auto tokens = TokenStream { component_values };
  2009. while (tokens.has_next_token()) {
  2010. auto& part = tokens.next_token();
  2011. // FIXME: Handle multiple backgrounds, by returning a List of BackgroundStyleValues.
  2012. if (part.is(Token::Type::Comma)) {
  2013. dbgln("CSS Parser does not yet support multiple comma-separated values for background.");
  2014. break;
  2015. }
  2016. auto value = parse_css_value(context, part);
  2017. if (!value)
  2018. return nullptr;
  2019. if (property_accepts_value(PropertyID::BackgroundAttachment, *value)) {
  2020. if (background_attachment)
  2021. return nullptr;
  2022. background_attachment = value.release_nonnull();
  2023. continue;
  2024. }
  2025. if (property_accepts_value(PropertyID::BackgroundColor, *value)) {
  2026. if (background_color)
  2027. return nullptr;
  2028. background_color = value.release_nonnull();
  2029. continue;
  2030. }
  2031. if (property_accepts_value(PropertyID::BackgroundImage, *value)) {
  2032. if (background_image)
  2033. return nullptr;
  2034. background_image = value.release_nonnull();
  2035. continue;
  2036. }
  2037. if (property_accepts_value(PropertyID::BackgroundPosition, *value)) {
  2038. if (background_position)
  2039. return nullptr;
  2040. tokens.reconsume_current_input_token();
  2041. if (auto maybe_background_position = parse_single_background_position_value(context, tokens)) {
  2042. background_position = maybe_background_position.release_nonnull();
  2043. // FIXME: background-size optionally goes here, after a '/'
  2044. continue;
  2045. }
  2046. return nullptr;
  2047. }
  2048. if (property_accepts_value(PropertyID::BackgroundRepeat, *value)) {
  2049. if (repeat_x)
  2050. return nullptr;
  2051. auto value_id = value->to_identifier();
  2052. if (value_id == ValueID::RepeatX || value_id == ValueID::RepeatY) {
  2053. repeat_x = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat);
  2054. repeat_y = IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat);
  2055. continue;
  2056. }
  2057. // Check following value, if it's also a repeat, set both.
  2058. if (tokens.has_next_token()) {
  2059. auto next_value = parse_css_value(context, tokens.peek_token());
  2060. if (next_value && property_accepts_value(PropertyID::BackgroundRepeat, *next_value)) {
  2061. tokens.next_token();
  2062. repeat_x = value.release_nonnull();
  2063. repeat_y = next_value.release_nonnull();
  2064. continue;
  2065. }
  2066. }
  2067. auto repeat = value.release_nonnull();
  2068. repeat_x = repeat;
  2069. repeat_y = repeat;
  2070. continue;
  2071. }
  2072. return nullptr;
  2073. }
  2074. if (!background_color)
  2075. background_color = property_initial_value(PropertyID::BackgroundColor);
  2076. if (!background_image)
  2077. background_image = property_initial_value(PropertyID::BackgroundImage);
  2078. if (!background_position)
  2079. background_position = property_initial_value(PropertyID::BackgroundPosition);
  2080. if (!repeat_x)
  2081. repeat_x = property_initial_value(PropertyID::BackgroundRepeatX);
  2082. if (!repeat_y)
  2083. repeat_y = property_initial_value(PropertyID::BackgroundRepeatY);
  2084. if (!background_attachment)
  2085. background_attachment = property_initial_value(PropertyID::BackgroundAttachment);
  2086. return BackgroundStyleValue::create(background_color.release_nonnull(), background_image.release_nonnull(), background_position.release_nonnull(), repeat_x.release_nonnull(), repeat_y.release_nonnull(), background_attachment.release_nonnull());
  2087. }
  2088. RefPtr<StyleValue> Parser::parse_background_image_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2089. {
  2090. if (component_values.size() == 1) {
  2091. auto maybe_value = parse_css_value(context, component_values.first());
  2092. if (!maybe_value)
  2093. return nullptr;
  2094. auto value = maybe_value.release_nonnull();
  2095. if (property_accepts_value(PropertyID::BackgroundImage, *value))
  2096. return value;
  2097. return nullptr;
  2098. }
  2099. // FIXME: Handle multiple sets of comma-separated values.
  2100. dbgln("CSS Parser does not yet support multiple comma-separated values for background-image.");
  2101. return nullptr;
  2102. }
  2103. RefPtr<StyleValue> Parser::parse_single_background_position_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  2104. {
  2105. // NOTE: This *looks* like it parses a <position>, but it doesn't. From the spec:
  2106. // "Note: The background-position property also accepts a three-value syntax.
  2107. // This has been disallowed generically because it creates parsing ambiguities
  2108. // when combined with other length or percentage components in a property value."
  2109. // - https://www.w3.org/TR/css-values-4/#typedef-position
  2110. // So, we'll need a separate function to parse <position> later.
  2111. auto start_position = tokens.position();
  2112. auto error = [&]() {
  2113. tokens.rewind_to_position(start_position);
  2114. return nullptr;
  2115. };
  2116. auto to_edge = [](ValueID identifier) -> Optional<PositionEdge> {
  2117. switch (identifier) {
  2118. case ValueID::Top:
  2119. return PositionEdge::Top;
  2120. case ValueID::Bottom:
  2121. return PositionEdge::Bottom;
  2122. case ValueID::Left:
  2123. return PositionEdge::Left;
  2124. case ValueID::Right:
  2125. return PositionEdge::Right;
  2126. default:
  2127. return {};
  2128. }
  2129. };
  2130. auto is_horizontal = [](ValueID identifier) -> bool {
  2131. switch (identifier) {
  2132. case ValueID::Left:
  2133. case ValueID::Right:
  2134. return true;
  2135. default:
  2136. return false;
  2137. }
  2138. };
  2139. auto is_vertical = [](ValueID identifier) -> bool {
  2140. switch (identifier) {
  2141. case ValueID::Top:
  2142. case ValueID::Bottom:
  2143. return true;
  2144. default:
  2145. return false;
  2146. }
  2147. };
  2148. auto zero_offset = Length::make_px(0);
  2149. auto center_offset = Length { 50, Length::Type::Percentage };
  2150. struct EdgeOffset {
  2151. PositionEdge edge;
  2152. Length offset;
  2153. bool edge_provided;
  2154. bool offset_provided;
  2155. };
  2156. Optional<EdgeOffset> horizontal;
  2157. Optional<EdgeOffset> vertical;
  2158. bool found_center = false;
  2159. while (tokens.has_next_token()) {
  2160. // Check if we're done
  2161. auto seen_items = (horizontal.has_value() ? 1 : 0) + (vertical.has_value() ? 1 : 0) + (found_center ? 1 : 0);
  2162. if (seen_items == 2)
  2163. break;
  2164. auto& token = tokens.peek_token();
  2165. auto maybe_value = parse_css_value(context, token);
  2166. if (!maybe_value || !property_accepts_value(PropertyID::BackgroundPosition, *maybe_value))
  2167. break;
  2168. tokens.next_token();
  2169. auto value = maybe_value.release_nonnull();
  2170. if (value->has_length()) {
  2171. if (!horizontal.has_value()) {
  2172. horizontal = EdgeOffset { PositionEdge::Left, value->to_length(), false, true };
  2173. } else if (!vertical.has_value()) {
  2174. vertical = EdgeOffset { PositionEdge::Top, value->to_length(), false, true };
  2175. } else {
  2176. return error();
  2177. }
  2178. continue;
  2179. }
  2180. if (value->has_identifier()) {
  2181. auto identifier = value->to_identifier();
  2182. if (is_horizontal(identifier)) {
  2183. Length offset = zero_offset;
  2184. bool offset_provided = false;
  2185. if (tokens.has_next_token()) {
  2186. auto maybe_offset = parse_length(context, tokens.peek_token());
  2187. if (maybe_offset.has_value()) {
  2188. offset = maybe_offset.value();
  2189. offset_provided = true;
  2190. tokens.next_token();
  2191. }
  2192. }
  2193. horizontal = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2194. } else if (is_vertical(identifier)) {
  2195. Length offset = zero_offset;
  2196. bool offset_provided = false;
  2197. if (tokens.has_next_token()) {
  2198. auto maybe_offset = parse_length(context, tokens.peek_token());
  2199. if (maybe_offset.has_value()) {
  2200. offset = maybe_offset.value();
  2201. offset_provided = true;
  2202. tokens.next_token();
  2203. }
  2204. }
  2205. vertical = EdgeOffset { *to_edge(identifier), offset, true, offset_provided };
  2206. } else if (identifier == ValueID::Center) {
  2207. found_center = true;
  2208. } else {
  2209. return error();
  2210. }
  2211. continue;
  2212. }
  2213. tokens.reconsume_current_input_token();
  2214. break;
  2215. }
  2216. if (found_center) {
  2217. if (horizontal.has_value() && vertical.has_value())
  2218. return error();
  2219. if (!horizontal.has_value())
  2220. horizontal = EdgeOffset { PositionEdge::Left, center_offset, true, false };
  2221. if (!vertical.has_value())
  2222. vertical = EdgeOffset { PositionEdge::Top, center_offset, true, false };
  2223. }
  2224. if (!horizontal.has_value() && !vertical.has_value())
  2225. return error();
  2226. // Unpack `<edge> <length>`:
  2227. // The loop above reads this pattern as a single EdgeOffset, when actually, it should be treated
  2228. // as `x y` if the edge is horizontal, and `y` (with the second token reconsumed) otherwise.
  2229. if (!vertical.has_value() && horizontal->edge_provided && horizontal->offset_provided) {
  2230. // Split into `x y`
  2231. vertical = EdgeOffset { PositionEdge::Top, horizontal->offset, false, true };
  2232. horizontal->offset = zero_offset;
  2233. horizontal->offset_provided = false;
  2234. } else if (!horizontal.has_value() && vertical->edge_provided && vertical->offset_provided) {
  2235. // `y`, reconsume
  2236. vertical->offset = zero_offset;
  2237. vertical->offset_provided = false;
  2238. tokens.reconsume_current_input_token();
  2239. }
  2240. // If only one value is specified, the second value is assumed to be center.
  2241. if (!horizontal.has_value())
  2242. horizontal = EdgeOffset { PositionEdge::Left, center_offset, false, false };
  2243. if (!vertical.has_value())
  2244. vertical = EdgeOffset { PositionEdge::Top, center_offset, false, false };
  2245. return PositionStyleValue::create(
  2246. horizontal->edge, horizontal->offset,
  2247. vertical->edge, vertical->offset);
  2248. }
  2249. RefPtr<StyleValue> Parser::parse_background_position_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2250. {
  2251. auto tokens = TokenStream { component_values };
  2252. // FIXME: Handle multiple sets of comma-separated values.
  2253. return parse_single_background_position_value(context, tokens);
  2254. }
  2255. RefPtr<StyleValue> Parser::parse_background_repeat_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2256. {
  2257. auto is_directional_repeat = [](StyleValue const& value) -> bool {
  2258. auto value_id = value.to_identifier();
  2259. return value_id == ValueID::RepeatX || value_id == ValueID::RepeatY;
  2260. };
  2261. if (component_values.size() == 1) {
  2262. auto maybe_value = parse_css_value(context, component_values.first());
  2263. if (!maybe_value)
  2264. return nullptr;
  2265. auto value = maybe_value.release_nonnull();
  2266. if (!property_accepts_value(PropertyID::BackgroundRepeat, *value))
  2267. return nullptr;
  2268. if (is_directional_repeat(value)) {
  2269. auto value_id = value->to_identifier();
  2270. return BackgroundRepeatStyleValue::create(
  2271. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::Repeat : ValueID::NoRepeat),
  2272. IdentifierStyleValue::create(value_id == ValueID::RepeatX ? ValueID::NoRepeat : ValueID::Repeat));
  2273. }
  2274. return BackgroundRepeatStyleValue::create(value, value);
  2275. }
  2276. if (component_values.size() == 2) {
  2277. auto maybe_x_value = parse_css_value(context, component_values[0]);
  2278. auto maybe_y_value = parse_css_value(context, component_values[1]);
  2279. if (!maybe_x_value || !maybe_y_value)
  2280. return nullptr;
  2281. auto x_value = maybe_x_value.release_nonnull();
  2282. auto y_value = maybe_y_value.release_nonnull();
  2283. if (!property_accepts_value(PropertyID::BackgroundRepeat, x_value) || !property_accepts_value(PropertyID::BackgroundRepeat, y_value))
  2284. return nullptr;
  2285. if (is_directional_repeat(x_value) || is_directional_repeat(y_value))
  2286. return nullptr;
  2287. return BackgroundRepeatStyleValue::create(x_value, y_value);
  2288. }
  2289. // FIXME: Handle multiple sets of comma-separated values.
  2290. dbgln("CSS Parser does not yet support multiple comma-separated values for background-repeat.");
  2291. return nullptr;
  2292. }
  2293. RefPtr<StyleValue> Parser::parse_border_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2294. {
  2295. if (component_values.size() > 3)
  2296. return nullptr;
  2297. RefPtr<StyleValue> border_width;
  2298. RefPtr<StyleValue> border_color;
  2299. RefPtr<StyleValue> border_style;
  2300. for (auto& part : component_values) {
  2301. auto value = parse_css_value(context, part);
  2302. if (!value)
  2303. return nullptr;
  2304. if (property_accepts_value(PropertyID::BorderWidth, *value)) {
  2305. if (border_width)
  2306. return nullptr;
  2307. border_width = value.release_nonnull();
  2308. continue;
  2309. }
  2310. if (property_accepts_value(PropertyID::BorderColor, *value)) {
  2311. if (border_color)
  2312. return nullptr;
  2313. border_color = value.release_nonnull();
  2314. continue;
  2315. }
  2316. if (property_accepts_value(PropertyID::BorderStyle, *value)) {
  2317. if (border_style)
  2318. return nullptr;
  2319. border_style = value.release_nonnull();
  2320. continue;
  2321. }
  2322. return nullptr;
  2323. }
  2324. if (!border_width)
  2325. border_width = property_initial_value(PropertyID::BorderWidth);
  2326. if (!border_style)
  2327. border_style = property_initial_value(PropertyID::BorderStyle);
  2328. if (!border_color)
  2329. border_color = property_initial_value(PropertyID::BorderColor);
  2330. return BorderStyleValue::create(border_width.release_nonnull(), border_style.release_nonnull(), border_color.release_nonnull());
  2331. }
  2332. RefPtr<StyleValue> Parser::parse_border_radius_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2333. {
  2334. if (component_values.size() == 2) {
  2335. auto horizontal = parse_length(context, component_values[0]);
  2336. auto vertical = parse_length(context, component_values[1]);
  2337. if (horizontal.has_value() && vertical.has_value())
  2338. return BorderRadiusStyleValue::create(horizontal.value(), vertical.value());
  2339. return nullptr;
  2340. }
  2341. if (component_values.size() == 1) {
  2342. auto radius = parse_length(context, component_values[0]);
  2343. if (radius.has_value())
  2344. return BorderRadiusStyleValue::create(radius.value(), radius.value());
  2345. return nullptr;
  2346. }
  2347. return nullptr;
  2348. }
  2349. RefPtr<StyleValue> Parser::parse_border_radius_shorthand_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2350. {
  2351. auto top_left = [&](Vector<Length>& radii) { return radii[0]; };
  2352. auto top_right = [&](Vector<Length>& radii) {
  2353. switch (radii.size()) {
  2354. case 4:
  2355. case 3:
  2356. case 2:
  2357. return radii[1];
  2358. case 1:
  2359. return radii[0];
  2360. default:
  2361. VERIFY_NOT_REACHED();
  2362. }
  2363. };
  2364. auto bottom_right = [&](Vector<Length>& radii) {
  2365. switch (radii.size()) {
  2366. case 4:
  2367. case 3:
  2368. return radii[2];
  2369. case 2:
  2370. case 1:
  2371. return radii[0];
  2372. default:
  2373. VERIFY_NOT_REACHED();
  2374. }
  2375. };
  2376. auto bottom_left = [&](Vector<Length>& radii) {
  2377. switch (radii.size()) {
  2378. case 4:
  2379. return radii[3];
  2380. case 3:
  2381. case 2:
  2382. return radii[1];
  2383. case 1:
  2384. return radii[0];
  2385. default:
  2386. VERIFY_NOT_REACHED();
  2387. }
  2388. };
  2389. Vector<Length> horizontal_radii;
  2390. Vector<Length> vertical_radii;
  2391. bool reading_vertical = false;
  2392. for (auto& value : component_values) {
  2393. if (value.is(Token::Type::Delim) && value.token().delim() == "/"sv) {
  2394. if (reading_vertical || horizontal_radii.is_empty())
  2395. return nullptr;
  2396. reading_vertical = true;
  2397. continue;
  2398. }
  2399. auto maybe_length = parse_length(context, value);
  2400. if (!maybe_length.has_value())
  2401. return nullptr;
  2402. if (reading_vertical) {
  2403. vertical_radii.append(maybe_length.value());
  2404. } else {
  2405. horizontal_radii.append(maybe_length.value());
  2406. }
  2407. }
  2408. if (horizontal_radii.size() > 4 || vertical_radii.size() > 4
  2409. || horizontal_radii.is_empty()
  2410. || (reading_vertical && vertical_radii.is_empty()))
  2411. return nullptr;
  2412. NonnullRefPtrVector<StyleValue> border_radii;
  2413. border_radii.append(BorderRadiusStyleValue::create(top_left(horizontal_radii),
  2414. vertical_radii.is_empty() ? top_left(horizontal_radii) : top_left(vertical_radii)));
  2415. border_radii.append(BorderRadiusStyleValue::create(top_right(horizontal_radii),
  2416. vertical_radii.is_empty() ? top_right(horizontal_radii) : top_right(vertical_radii)));
  2417. border_radii.append(BorderRadiusStyleValue::create(bottom_right(horizontal_radii),
  2418. vertical_radii.is_empty() ? bottom_right(horizontal_radii) : bottom_right(vertical_radii)));
  2419. border_radii.append(BorderRadiusStyleValue::create(bottom_left(horizontal_radii),
  2420. vertical_radii.is_empty() ? bottom_left(horizontal_radii) : bottom_left(vertical_radii)));
  2421. return StyleValueList::create(move(border_radii));
  2422. }
  2423. RefPtr<StyleValue> Parser::parse_box_shadow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2424. {
  2425. // "none"
  2426. if (component_values.size() == 1 && component_values.first().is(Token::Type::Ident)) {
  2427. auto ident = parse_identifier_value(context, component_values.first());
  2428. if (ident && ident->to_identifier() == ValueID::None)
  2429. return ident;
  2430. }
  2431. // FIXME: Also support inset, spread-radius and multiple comma-separated box-shadows
  2432. Length offset_x {};
  2433. Length offset_y {};
  2434. Length blur_radius {};
  2435. Color color {};
  2436. if (component_values.size() < 3 || component_values.size() > 4)
  2437. return nullptr;
  2438. auto maybe_x = parse_length(context, component_values[0]);
  2439. if (!maybe_x.has_value())
  2440. return nullptr;
  2441. offset_x = maybe_x.value();
  2442. auto maybe_y = parse_length(context, component_values[1]);
  2443. if (!maybe_y.has_value())
  2444. return nullptr;
  2445. offset_y = maybe_y.value();
  2446. if (component_values.size() == 3) {
  2447. auto parsed_color = parse_color(context, component_values[2]);
  2448. if (!parsed_color.has_value())
  2449. return nullptr;
  2450. color = parsed_color.value();
  2451. } else if (component_values.size() == 4) {
  2452. auto maybe_blur_radius = parse_length(context, component_values[2]);
  2453. if (!maybe_blur_radius.has_value())
  2454. return nullptr;
  2455. blur_radius = maybe_blur_radius.value();
  2456. auto parsed_color = parse_color(context, component_values[3]);
  2457. if (!parsed_color.has_value())
  2458. return nullptr;
  2459. color = parsed_color.value();
  2460. }
  2461. return BoxShadowStyleValue::create(offset_x, offset_y, blur_radius, color);
  2462. }
  2463. RefPtr<StyleValue> Parser::parse_flex_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2464. {
  2465. if (component_values.size() == 1) {
  2466. auto value = parse_css_value(context, component_values[0]);
  2467. if (!value)
  2468. return nullptr;
  2469. switch (value->to_identifier()) {
  2470. case ValueID::Auto: {
  2471. auto one = NumericStyleValue::create_integer(1);
  2472. return FlexStyleValue::create(one, one, IdentifierStyleValue::create(ValueID::Auto));
  2473. }
  2474. case ValueID::None: {
  2475. auto zero = NumericStyleValue::create_integer(0);
  2476. return FlexStyleValue::create(zero, zero, IdentifierStyleValue::create(ValueID::Auto));
  2477. }
  2478. default:
  2479. break;
  2480. }
  2481. }
  2482. RefPtr<StyleValue> flex_grow;
  2483. RefPtr<StyleValue> flex_shrink;
  2484. RefPtr<StyleValue> flex_basis;
  2485. for (size_t i = 0; i < component_values.size(); ++i) {
  2486. auto value = parse_css_value(context, component_values[i]);
  2487. if (!value)
  2488. return nullptr;
  2489. // Zero is a valid value for basis, but only if grow and shrink are already specified.
  2490. if (value->has_number() && value->to_number() == 0) {
  2491. if (flex_grow && flex_shrink && !flex_basis) {
  2492. flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
  2493. continue;
  2494. }
  2495. }
  2496. if (property_accepts_value(PropertyID::FlexGrow, *value)) {
  2497. if (flex_grow)
  2498. return nullptr;
  2499. flex_grow = value.release_nonnull();
  2500. // Flex-shrink may optionally follow directly after.
  2501. if (i + 1 < component_values.size()) {
  2502. auto second_value = parse_css_value(context, component_values[i + 1]);
  2503. if (second_value && property_accepts_value(PropertyID::FlexShrink, *second_value)) {
  2504. flex_shrink = second_value.release_nonnull();
  2505. i++;
  2506. }
  2507. }
  2508. continue;
  2509. }
  2510. if (property_accepts_value(PropertyID::FlexBasis, *value)) {
  2511. if (flex_basis)
  2512. return nullptr;
  2513. flex_basis = value.release_nonnull();
  2514. continue;
  2515. }
  2516. return nullptr;
  2517. }
  2518. if (!flex_grow)
  2519. flex_grow = property_initial_value(PropertyID::FlexGrow);
  2520. if (!flex_shrink)
  2521. flex_shrink = property_initial_value(PropertyID::FlexShrink);
  2522. if (!flex_basis)
  2523. flex_basis = property_initial_value(PropertyID::FlexBasis);
  2524. return FlexStyleValue::create(flex_grow.release_nonnull(), flex_shrink.release_nonnull(), flex_basis.release_nonnull());
  2525. }
  2526. RefPtr<StyleValue> Parser::parse_flex_flow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2527. {
  2528. if (component_values.size() > 2)
  2529. return nullptr;
  2530. RefPtr<StyleValue> flex_direction;
  2531. RefPtr<StyleValue> flex_wrap;
  2532. for (auto& part : component_values) {
  2533. auto value = parse_css_value(context, part);
  2534. if (!value)
  2535. return nullptr;
  2536. if (property_accepts_value(PropertyID::FlexDirection, *value)) {
  2537. if (flex_direction)
  2538. return nullptr;
  2539. flex_direction = value.release_nonnull();
  2540. continue;
  2541. }
  2542. if (property_accepts_value(PropertyID::FlexWrap, *value)) {
  2543. if (flex_wrap)
  2544. return nullptr;
  2545. flex_wrap = value.release_nonnull();
  2546. continue;
  2547. }
  2548. }
  2549. if (!flex_direction)
  2550. flex_direction = property_initial_value(PropertyID::FlexDirection);
  2551. if (!flex_wrap)
  2552. flex_wrap = property_initial_value(PropertyID::FlexWrap);
  2553. return FlexFlowStyleValue::create(flex_direction.release_nonnull(), flex_wrap.release_nonnull());
  2554. }
  2555. RefPtr<StyleValue> Parser::parse_font_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2556. {
  2557. RefPtr<StyleValue> font_style;
  2558. RefPtr<StyleValue> font_weight;
  2559. RefPtr<StyleValue> font_size;
  2560. RefPtr<StyleValue> line_height;
  2561. RefPtr<StyleValue> font_families;
  2562. // FIXME: Implement font-stretch and font-variant.
  2563. // FIXME: Handle system fonts. (caption, icon, menu, message-box, small-caption, status-bar)
  2564. // Several sub-properties can be "normal", and appear in any order: style, variant, weight, stretch
  2565. // So, we have to handle that separately.
  2566. int normal_count = 0;
  2567. for (size_t i = 0; i < component_values.size(); ++i) {
  2568. auto value = parse_css_value(context, component_values[i]);
  2569. if (!value)
  2570. return nullptr;
  2571. if (value->to_identifier() == ValueID::Normal) {
  2572. normal_count++;
  2573. continue;
  2574. }
  2575. // FIXME: Handle angle parameter to `oblique`: https://www.w3.org/TR/css-fonts-4/#font-style-prop
  2576. if (property_accepts_value(PropertyID::FontStyle, *value)) {
  2577. if (font_style)
  2578. return nullptr;
  2579. font_style = value.release_nonnull();
  2580. continue;
  2581. }
  2582. if (property_accepts_value(PropertyID::FontWeight, *value)) {
  2583. if (font_weight)
  2584. return nullptr;
  2585. font_weight = value.release_nonnull();
  2586. continue;
  2587. }
  2588. if (property_accepts_value(PropertyID::FontSize, *value)) {
  2589. if (font_size)
  2590. return nullptr;
  2591. font_size = value.release_nonnull();
  2592. // Consume `/ line-height` if present
  2593. if (i + 2 < component_values.size()) {
  2594. auto maybe_solidus = component_values[i + 1];
  2595. if (maybe_solidus.is(Token::Type::Delim) && maybe_solidus.token().delim() == "/"sv) {
  2596. auto maybe_line_height = parse_css_value(context, component_values[i + 2]);
  2597. if (!(maybe_line_height && property_accepts_value(PropertyID::LineHeight, *maybe_line_height)))
  2598. return nullptr;
  2599. line_height = maybe_line_height.release_nonnull();
  2600. i += 2;
  2601. }
  2602. }
  2603. // Consume font-families
  2604. auto maybe_font_families = parse_font_family_value(context, component_values, i + 1);
  2605. if (!maybe_font_families)
  2606. return nullptr;
  2607. font_families = maybe_font_families.release_nonnull();
  2608. break;
  2609. }
  2610. return nullptr;
  2611. }
  2612. // Since normal is the default value for all the properties that can have it, we don't have to actually
  2613. // set anything to normal here. It'll be set when we create the FontStyleValue below.
  2614. // We just need to make sure we were not given more normals than will fit.
  2615. int unset_value_count = (font_style ? 0 : 1) + (font_weight ? 0 : 1);
  2616. if (unset_value_count < normal_count)
  2617. return nullptr;
  2618. if (!font_size || !font_families)
  2619. return nullptr;
  2620. if (!font_style)
  2621. font_style = property_initial_value(PropertyID::FontStyle);
  2622. if (!font_weight)
  2623. font_weight = property_initial_value(PropertyID::FontWeight);
  2624. if (!line_height)
  2625. line_height = property_initial_value(PropertyID::LineHeight);
  2626. return FontStyleValue::create(font_style.release_nonnull(), font_weight.release_nonnull(), font_size.release_nonnull(), line_height.release_nonnull(), font_families.release_nonnull());
  2627. }
  2628. RefPtr<StyleValue> Parser::parse_font_family_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values, size_t start_index)
  2629. {
  2630. auto is_generic_font_family = [](ValueID identifier) -> bool {
  2631. switch (identifier) {
  2632. case ValueID::Cursive:
  2633. case ValueID::Fantasy:
  2634. case ValueID::Monospace:
  2635. case ValueID::Serif:
  2636. case ValueID::SansSerif:
  2637. case ValueID::UiMonospace:
  2638. case ValueID::UiRounded:
  2639. case ValueID::UiSerif:
  2640. case ValueID::UiSansSerif:
  2641. return true;
  2642. default:
  2643. return false;
  2644. }
  2645. };
  2646. auto is_comma_or_eof = [&](size_t i) -> bool {
  2647. if (i < component_values.size()) {
  2648. auto& maybe_comma = component_values[i];
  2649. if (!maybe_comma.is(Token::Type::Comma))
  2650. return false;
  2651. }
  2652. return true;
  2653. };
  2654. // Note: Font-family names can either be a quoted string, or a keyword, or a series of custom-idents.
  2655. // eg, these are equivalent:
  2656. // font-family: my cool font\!, serif;
  2657. // font-family: "my cool font!", serif;
  2658. NonnullRefPtrVector<StyleValue> font_families;
  2659. Vector<String> current_name_parts;
  2660. for (size_t i = start_index; i < component_values.size(); ++i) {
  2661. auto& part = component_values[i];
  2662. if (part.is(Token::Type::String)) {
  2663. // `font-family: my cool "font";` is invalid.
  2664. if (!current_name_parts.is_empty())
  2665. return nullptr;
  2666. if (!is_comma_or_eof(i + 1))
  2667. return nullptr;
  2668. font_families.append(StringStyleValue::create(part.token().string()));
  2669. i++;
  2670. continue;
  2671. }
  2672. if (part.is(Token::Type::Ident)) {
  2673. // If this is a valid identifier, it's NOT a custom-ident and can't be part of a larger name.
  2674. auto maybe_ident = parse_css_value(context, part);
  2675. if (maybe_ident) {
  2676. // CSS-wide keywords are not allowed
  2677. if (maybe_ident->is_builtin())
  2678. return nullptr;
  2679. if (is_generic_font_family(maybe_ident->to_identifier())) {
  2680. // Can't have a generic-font-name as a token in an unquoted font name.
  2681. if (!current_name_parts.is_empty())
  2682. return nullptr;
  2683. if (!is_comma_or_eof(i + 1))
  2684. return nullptr;
  2685. font_families.append(maybe_ident.release_nonnull());
  2686. i++;
  2687. continue;
  2688. }
  2689. }
  2690. current_name_parts.append(part.token().ident());
  2691. continue;
  2692. }
  2693. if (part.is(Token::Type::Comma)) {
  2694. if (current_name_parts.is_empty())
  2695. return nullptr;
  2696. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2697. current_name_parts.clear();
  2698. // Can't have a trailing comma
  2699. if (i + 1 == component_values.size())
  2700. return nullptr;
  2701. continue;
  2702. }
  2703. }
  2704. if (!current_name_parts.is_empty()) {
  2705. font_families.append(StringStyleValue::create(String::join(' ', current_name_parts)));
  2706. current_name_parts.clear();
  2707. }
  2708. if (font_families.is_empty())
  2709. return nullptr;
  2710. return StyleValueList::create(move(font_families));
  2711. }
  2712. RefPtr<StyleValue> Parser::parse_list_style_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2713. {
  2714. if (component_values.size() > 3)
  2715. return nullptr;
  2716. RefPtr<StyleValue> list_position;
  2717. RefPtr<StyleValue> list_image;
  2718. RefPtr<StyleValue> list_type;
  2719. int found_nones = 0;
  2720. for (auto& part : component_values) {
  2721. auto value = parse_css_value(context, part);
  2722. if (!value)
  2723. return nullptr;
  2724. if (value->to_identifier() == ValueID::None) {
  2725. found_nones++;
  2726. continue;
  2727. }
  2728. if (property_accepts_value(PropertyID::ListStylePosition, *value)) {
  2729. if (list_position)
  2730. return nullptr;
  2731. list_position = value.release_nonnull();
  2732. continue;
  2733. }
  2734. if (property_accepts_value(PropertyID::ListStyleImage, *value)) {
  2735. if (list_image)
  2736. return nullptr;
  2737. list_image = value.release_nonnull();
  2738. continue;
  2739. }
  2740. if (property_accepts_value(PropertyID::ListStyleType, *value)) {
  2741. if (list_type)
  2742. return nullptr;
  2743. list_type = value.release_nonnull();
  2744. continue;
  2745. }
  2746. }
  2747. if (found_nones > 2)
  2748. return nullptr;
  2749. if (found_nones == 2) {
  2750. if (list_image || list_type)
  2751. return nullptr;
  2752. auto none = IdentifierStyleValue::create(ValueID::None);
  2753. list_image = none;
  2754. list_type = none;
  2755. } else if (found_nones == 1) {
  2756. if (list_image && list_type)
  2757. return nullptr;
  2758. auto none = IdentifierStyleValue::create(ValueID::None);
  2759. if (!list_image)
  2760. list_image = none;
  2761. if (!list_type)
  2762. list_type = none;
  2763. }
  2764. if (!list_position)
  2765. list_position = property_initial_value(PropertyID::ListStylePosition);
  2766. if (!list_image)
  2767. list_image = property_initial_value(PropertyID::ListStyleImage);
  2768. if (!list_type)
  2769. list_type = property_initial_value(PropertyID::ListStyleType);
  2770. return ListStyleStyleValue::create(list_position.release_nonnull(), list_image.release_nonnull(), list_type.release_nonnull());
  2771. }
  2772. RefPtr<StyleValue> Parser::parse_overflow_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2773. {
  2774. if (component_values.size() == 1) {
  2775. auto maybe_value = parse_css_value(context, component_values.first());
  2776. if (!maybe_value)
  2777. return nullptr;
  2778. auto value = maybe_value.release_nonnull();
  2779. if (property_accepts_value(PropertyID::Overflow, *value))
  2780. return OverflowStyleValue::create(value, value);
  2781. return nullptr;
  2782. }
  2783. if (component_values.size() == 2) {
  2784. auto maybe_x_value = parse_css_value(context, component_values[0]);
  2785. auto maybe_y_value = parse_css_value(context, component_values[1]);
  2786. if (!maybe_x_value || !maybe_y_value)
  2787. return nullptr;
  2788. auto x_value = maybe_x_value.release_nonnull();
  2789. auto y_value = maybe_y_value.release_nonnull();
  2790. if (!property_accepts_value(PropertyID::OverflowX, x_value) || !property_accepts_value(PropertyID::OverflowY, y_value)) {
  2791. return nullptr;
  2792. }
  2793. return OverflowStyleValue::create(x_value, y_value);
  2794. }
  2795. return nullptr;
  2796. }
  2797. RefPtr<StyleValue> Parser::parse_text_decoration_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2798. {
  2799. if (component_values.size() > 3)
  2800. return nullptr;
  2801. RefPtr<StyleValue> decoration_line;
  2802. RefPtr<StyleValue> decoration_style;
  2803. RefPtr<StyleValue> decoration_color;
  2804. // FIXME: Implement 'text-decoration-thickness' parameter. https://www.w3.org/TR/css-text-decor-4/#text-decoration-width-property
  2805. for (auto& part : component_values) {
  2806. auto value = parse_css_value(context, part);
  2807. if (!value)
  2808. return nullptr;
  2809. if (property_accepts_value(PropertyID::TextDecorationColor, *value)) {
  2810. if (decoration_color)
  2811. return nullptr;
  2812. decoration_color = value.release_nonnull();
  2813. continue;
  2814. }
  2815. if (property_accepts_value(PropertyID::TextDecorationLine, *value)) {
  2816. if (decoration_line)
  2817. return nullptr;
  2818. decoration_line = value.release_nonnull();
  2819. continue;
  2820. }
  2821. if (property_accepts_value(PropertyID::TextDecorationStyle, *value)) {
  2822. if (decoration_style)
  2823. return nullptr;
  2824. decoration_style = value.release_nonnull();
  2825. continue;
  2826. }
  2827. return nullptr;
  2828. }
  2829. if (!decoration_line)
  2830. decoration_line = property_initial_value(PropertyID::TextDecorationLine);
  2831. if (!decoration_style)
  2832. decoration_style = property_initial_value(PropertyID::TextDecorationStyle);
  2833. if (!decoration_color)
  2834. decoration_color = property_initial_value(PropertyID::TextDecorationColor);
  2835. return TextDecorationStyleValue::create(decoration_line.release_nonnull(), decoration_style.release_nonnull(), decoration_color.release_nonnull());
  2836. }
  2837. static Optional<CSS::TransformFunction> parse_transform_function_name(StringView name)
  2838. {
  2839. if (name == "translateY")
  2840. return CSS::TransformFunction::TranslateY;
  2841. return {};
  2842. }
  2843. RefPtr<StyleValue> Parser::parse_transform_value(ParsingContext const& context, Vector<StyleComponentValueRule> const& component_values)
  2844. {
  2845. NonnullRefPtrVector<StyleValue> transformations;
  2846. for (auto& part : component_values) {
  2847. if (!part.is_function())
  2848. return nullptr;
  2849. auto maybe_function = parse_transform_function_name(part.function().name());
  2850. if (!maybe_function.has_value())
  2851. return nullptr;
  2852. NonnullRefPtrVector<StyleValue> values;
  2853. for (auto& value : part.function().values()) {
  2854. if (value.is(Token::Type::Dimension)) {
  2855. auto maybe_length = parse_length(context, value);
  2856. if (!maybe_length.has_value())
  2857. return nullptr;
  2858. values.append(LengthStyleValue::create(maybe_length.release_value()));
  2859. } else if (value.is(Token::Type::Number)) {
  2860. auto number = parse_numeric_value(context, value);
  2861. values.append(number.release_nonnull());
  2862. } else {
  2863. dbgln("FIXME: Unsupported value type for transformation!");
  2864. return nullptr;
  2865. }
  2866. }
  2867. transformations.append(TransformationStyleValue::create(maybe_function.value(), move(values)));
  2868. }
  2869. return StyleValueList::create(move(transformations));
  2870. }
  2871. RefPtr<StyleValue> Parser::parse_as_css_value(PropertyID property_id)
  2872. {
  2873. auto component_values = parse_as_list_of_component_values();
  2874. auto tokens = TokenStream(component_values);
  2875. auto parsed_value = parse_css_value(property_id, tokens);
  2876. if (parsed_value.is_error())
  2877. return {};
  2878. return parsed_value.release_value();
  2879. }
  2880. Result<NonnullRefPtr<StyleValue>, Parser::ParsingResult> Parser::parse_css_value(PropertyID property_id, TokenStream<StyleComponentValueRule>& tokens)
  2881. {
  2882. m_context.set_current_property_id(property_id);
  2883. Vector<StyleComponentValueRule> component_values;
  2884. while (tokens.has_next_token()) {
  2885. auto& token = tokens.next_token();
  2886. if (token.is(Token::Type::Semicolon)) {
  2887. tokens.reconsume_current_input_token();
  2888. break;
  2889. }
  2890. if (token.is(Token::Type::Whitespace))
  2891. continue;
  2892. if (token.is(Token::Type::Ident) && has_ignored_vendor_prefix(token.token().ident()))
  2893. return ParsingResult::IncludesIgnoredVendorPrefix;
  2894. component_values.append(token);
  2895. }
  2896. if (component_values.is_empty())
  2897. return ParsingResult::SyntaxError;
  2898. if (component_values.size() == 1) {
  2899. if (auto parsed_value = parse_builtin_value(m_context, component_values.first()))
  2900. return parsed_value.release_nonnull();
  2901. }
  2902. // Special-case property handling
  2903. switch (property_id) {
  2904. case PropertyID::Background:
  2905. if (auto parsed_value = parse_background_value(m_context, component_values))
  2906. return parsed_value.release_nonnull();
  2907. return ParsingResult::SyntaxError;
  2908. case PropertyID::BackgroundImage:
  2909. if (auto parsed_value = parse_background_image_value(m_context, component_values))
  2910. return parsed_value.release_nonnull();
  2911. return ParsingResult::SyntaxError;
  2912. case PropertyID::BackgroundPosition:
  2913. if (auto parsed_value = parse_background_position_value(m_context, component_values))
  2914. return parsed_value.release_nonnull();
  2915. return ParsingResult::SyntaxError;
  2916. case PropertyID::BackgroundRepeat:
  2917. if (auto parsed_value = parse_background_repeat_value(m_context, component_values))
  2918. return parsed_value.release_nonnull();
  2919. return ParsingResult::SyntaxError;
  2920. case PropertyID::Border:
  2921. case PropertyID::BorderBottom:
  2922. case PropertyID::BorderLeft:
  2923. case PropertyID::BorderRight:
  2924. case PropertyID::BorderTop:
  2925. if (auto parsed_value = parse_border_value(m_context, component_values))
  2926. return parsed_value.release_nonnull();
  2927. return ParsingResult::SyntaxError;
  2928. case PropertyID::BorderTopLeftRadius:
  2929. case PropertyID::BorderTopRightRadius:
  2930. case PropertyID::BorderBottomRightRadius:
  2931. case PropertyID::BorderBottomLeftRadius:
  2932. if (auto parsed_value = parse_border_radius_value(m_context, component_values))
  2933. return parsed_value.release_nonnull();
  2934. return ParsingResult::SyntaxError;
  2935. case PropertyID::BorderRadius:
  2936. if (auto parsed_value = parse_border_radius_shorthand_value(m_context, component_values))
  2937. return parsed_value.release_nonnull();
  2938. return ParsingResult::SyntaxError;
  2939. case PropertyID::BoxShadow:
  2940. if (auto parsed_value = parse_box_shadow_value(m_context, component_values))
  2941. return parsed_value.release_nonnull();
  2942. return ParsingResult::SyntaxError;
  2943. case PropertyID::Flex:
  2944. if (auto parsed_value = parse_flex_value(m_context, component_values))
  2945. return parsed_value.release_nonnull();
  2946. return ParsingResult::SyntaxError;
  2947. case PropertyID::FlexFlow:
  2948. if (auto parsed_value = parse_flex_flow_value(m_context, component_values))
  2949. return parsed_value.release_nonnull();
  2950. return ParsingResult::SyntaxError;
  2951. case PropertyID::Font:
  2952. if (auto parsed_value = parse_font_value(m_context, component_values))
  2953. return parsed_value.release_nonnull();
  2954. return ParsingResult::SyntaxError;
  2955. case PropertyID::FontFamily:
  2956. if (auto parsed_value = parse_font_family_value(m_context, component_values))
  2957. return parsed_value.release_nonnull();
  2958. return ParsingResult::SyntaxError;
  2959. case PropertyID::ListStyle:
  2960. if (auto parsed_value = parse_list_style_value(m_context, component_values))
  2961. return parsed_value.release_nonnull();
  2962. return ParsingResult::SyntaxError;
  2963. case PropertyID::Overflow:
  2964. if (auto parsed_value = parse_overflow_value(m_context, component_values))
  2965. return parsed_value.release_nonnull();
  2966. return ParsingResult::SyntaxError;
  2967. case PropertyID::TextDecoration:
  2968. if (auto parsed_value = parse_text_decoration_value(m_context, component_values))
  2969. return parsed_value.release_nonnull();
  2970. return ParsingResult::SyntaxError;
  2971. case PropertyID::Transform:
  2972. if (auto parsed_value = parse_transform_value(m_context, component_values))
  2973. return parsed_value.release_nonnull();
  2974. return ParsingResult::SyntaxError;
  2975. default:
  2976. break;
  2977. }
  2978. if (component_values.size() == 1) {
  2979. if (auto parsed_value = parse_css_value(m_context, component_values.first())) {
  2980. if (property_accepts_value(property_id, *parsed_value))
  2981. return parsed_value.release_nonnull();
  2982. }
  2983. return ParsingResult::SyntaxError;
  2984. }
  2985. // We have multiple values, so treat them as a StyleValueList.
  2986. if (property_maximum_value_count(property_id) > 1) {
  2987. NonnullRefPtrVector<StyleValue> parsed_values;
  2988. for (auto& component_value : component_values) {
  2989. auto parsed_value = parse_css_value(m_context, component_value);
  2990. if (!parsed_value || !property_accepts_value(property_id, *parsed_value))
  2991. return ParsingResult::SyntaxError;
  2992. parsed_values.append(parsed_value.release_nonnull());
  2993. }
  2994. if (!parsed_values.is_empty() && parsed_values.size() <= property_maximum_value_count(property_id))
  2995. return { StyleValueList::create(move(parsed_values)) };
  2996. }
  2997. return ParsingResult::SyntaxError;
  2998. }
  2999. RefPtr<StyleValue> Parser::parse_css_value(ParsingContext const& context, StyleComponentValueRule const& component_value)
  3000. {
  3001. if (auto builtin = parse_builtin_value(context, component_value))
  3002. return builtin;
  3003. if (auto dynamic = parse_dynamic_value(context, component_value))
  3004. return dynamic;
  3005. // We parse colors before numbers, to catch hashless hex colors.
  3006. if (auto color = parse_color_value(context, component_value))
  3007. return color;
  3008. if (auto length = parse_length_value(context, component_value))
  3009. return length;
  3010. if (auto numeric = parse_numeric_value(context, component_value))
  3011. return numeric;
  3012. if (auto identifier = parse_identifier_value(context, component_value))
  3013. return identifier;
  3014. if (auto string = parse_string_value(context, component_value))
  3015. return string;
  3016. if (auto image = parse_image_value(context, component_value))
  3017. return image;
  3018. return {};
  3019. }
  3020. Optional<Selector::SimpleSelector::ANPlusBPattern> Parser::parse_a_n_plus_b_pattern(TokenStream<StyleComponentValueRule>& values)
  3021. {
  3022. int a = 0;
  3023. int b = 0;
  3024. auto syntax_error = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3025. if constexpr (CSS_PARSER_DEBUG) {
  3026. dbgln("Invalid An+B value:");
  3027. values.dump_all_tokens();
  3028. }
  3029. return {};
  3030. };
  3031. auto make_return_value = [&]() -> Optional<Selector::SimpleSelector::ANPlusBPattern> {
  3032. // When we think we are done, but there are more non-whitespace tokens, then it's a parse error.
  3033. values.skip_whitespace();
  3034. if (values.has_next_token()) {
  3035. if constexpr (CSS_PARSER_DEBUG) {
  3036. dbgln("Extra tokens at end of An+B value:");
  3037. values.dump_all_tokens();
  3038. }
  3039. return syntax_error();
  3040. } else {
  3041. return Selector::SimpleSelector::ANPlusBPattern { a, b };
  3042. }
  3043. };
  3044. auto is_n = [](StyleComponentValueRule const& value) -> bool {
  3045. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n"sv);
  3046. };
  3047. auto is_ndash = [](StyleComponentValueRule const& value) -> bool {
  3048. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("n-"sv);
  3049. };
  3050. auto is_dashn = [](StyleComponentValueRule const& value) -> bool {
  3051. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n"sv);
  3052. };
  3053. auto is_dashndash = [](StyleComponentValueRule const& value) -> bool {
  3054. return value.is(Token::Type::Ident) && value.token().ident().equals_ignoring_case("-n-"sv);
  3055. };
  3056. auto is_delim = [](StyleComponentValueRule const& value, StringView const& delim) -> bool {
  3057. return value.is(Token::Type::Delim) && value.token().delim().equals_ignoring_case(delim);
  3058. };
  3059. auto is_n_dimension = [](StyleComponentValueRule const& value) -> bool {
  3060. if (!value.is(Token::Type::Dimension))
  3061. return false;
  3062. if (value.token().number_type() != Token::NumberType::Integer)
  3063. return false;
  3064. if (!value.token().dimension_unit().equals_ignoring_case("n"sv))
  3065. return false;
  3066. return true;
  3067. };
  3068. auto is_ndash_dimension = [](StyleComponentValueRule const& value) -> bool {
  3069. if (!value.is(Token::Type::Dimension))
  3070. return false;
  3071. if (value.token().number_type() != Token::NumberType::Integer)
  3072. return false;
  3073. if (!value.token().dimension_unit().equals_ignoring_case("n-"sv))
  3074. return false;
  3075. return true;
  3076. };
  3077. auto is_ndashdigit_dimension = [](StyleComponentValueRule const& value) -> bool {
  3078. if (!value.is(Token::Type::Dimension))
  3079. return false;
  3080. if (value.token().number_type() != Token::NumberType::Integer)
  3081. return false;
  3082. auto dimension_unit = value.token().dimension_unit();
  3083. if (!dimension_unit.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3084. return false;
  3085. for (size_t i = 2; i < dimension_unit.length(); ++i) {
  3086. if (!is_ascii_digit(dimension_unit[i]))
  3087. return false;
  3088. }
  3089. return true;
  3090. };
  3091. auto is_ndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3092. if (!value.is(Token::Type::Ident))
  3093. return false;
  3094. auto ident = value.token().ident();
  3095. if (!ident.starts_with("n-"sv, CaseSensitivity::CaseInsensitive))
  3096. return false;
  3097. for (size_t i = 2; i < ident.length(); ++i) {
  3098. if (!is_ascii_digit(ident[i]))
  3099. return false;
  3100. }
  3101. return true;
  3102. };
  3103. auto is_dashndashdigit_ident = [](StyleComponentValueRule const& value) -> bool {
  3104. if (!value.is(Token::Type::Ident))
  3105. return false;
  3106. auto ident = value.token().ident();
  3107. if (!ident.starts_with("-n-"sv, CaseSensitivity::CaseInsensitive))
  3108. return false;
  3109. for (size_t i = 3; i < ident.length(); ++i) {
  3110. if (!is_ascii_digit(ident[i]))
  3111. return false;
  3112. }
  3113. return true;
  3114. };
  3115. auto is_integer = [](StyleComponentValueRule const& value) -> bool {
  3116. return value.is(Token::Type::Number) && value.token().is(Token::NumberType::Integer);
  3117. };
  3118. auto is_signed_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3119. return is_integer(value) && value.token().is_integer_value_signed();
  3120. };
  3121. auto is_signless_integer = [is_integer](StyleComponentValueRule const& value) -> bool {
  3122. return is_integer(value) && !value.token().is_integer_value_signed();
  3123. };
  3124. // https://www.w3.org/TR/css-syntax-3/#the-anb-type
  3125. // Unfortunately these can't be in the same order as in the spec.
  3126. values.skip_whitespace();
  3127. auto& first_value = values.next_token();
  3128. // odd | even
  3129. if (first_value.is(Token::Type::Ident)) {
  3130. auto ident = first_value.token().ident();
  3131. if (ident.equals_ignoring_case("odd")) {
  3132. a = 2;
  3133. b = 1;
  3134. return make_return_value();
  3135. } else if (ident.equals_ignoring_case("even")) {
  3136. a = 2;
  3137. return make_return_value();
  3138. }
  3139. }
  3140. // <integer>
  3141. if (is_integer(first_value)) {
  3142. b = first_value.token().to_integer();
  3143. return make_return_value();
  3144. }
  3145. // <n-dimension>
  3146. // <n-dimension> <signed-integer>
  3147. // <n-dimension> ['+' | '-'] <signless-integer>
  3148. if (is_n_dimension(first_value)) {
  3149. a = first_value.token().dimension_value_int();
  3150. values.skip_whitespace();
  3151. auto& second_value = values.next_token();
  3152. if (second_value.is(Token::Type::EndOfFile)) {
  3153. // <n-dimension>
  3154. return make_return_value();
  3155. } else if (is_signed_integer(second_value)) {
  3156. // <n-dimension> <signed-integer>
  3157. b = second_value.token().to_integer();
  3158. return make_return_value();
  3159. }
  3160. values.skip_whitespace();
  3161. auto& third_value = values.next_token();
  3162. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3163. // <n-dimension> ['+' | '-'] <signless-integer>
  3164. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3165. return make_return_value();
  3166. }
  3167. return syntax_error();
  3168. }
  3169. // <ndash-dimension> <signless-integer>
  3170. if (is_ndash_dimension(first_value)) {
  3171. values.skip_whitespace();
  3172. auto& second_value = values.next_token();
  3173. if (is_signless_integer(second_value)) {
  3174. a = first_value.token().dimension_value_int();
  3175. b = -second_value.token().to_integer();
  3176. return make_return_value();
  3177. }
  3178. return syntax_error();
  3179. }
  3180. // <ndashdigit-dimension>
  3181. if (is_ndashdigit_dimension(first_value)) {
  3182. auto& dimension = first_value.token();
  3183. a = dimension.dimension_value_int();
  3184. auto maybe_b = dimension.dimension_unit().substring_view(1).to_int();
  3185. if (maybe_b.has_value()) {
  3186. b = maybe_b.value();
  3187. return make_return_value();
  3188. }
  3189. return syntax_error();
  3190. }
  3191. // <dashndashdigit-ident>
  3192. if (is_dashndashdigit_ident(first_value)) {
  3193. a = -1;
  3194. auto maybe_b = first_value.token().ident().substring_view(2).to_int();
  3195. if (maybe_b.has_value()) {
  3196. b = maybe_b.value();
  3197. return make_return_value();
  3198. }
  3199. return syntax_error();
  3200. }
  3201. // -n
  3202. // -n <signed-integer>
  3203. // -n ['+' | '-'] <signless-integer>
  3204. if (is_dashn(first_value)) {
  3205. a = -1;
  3206. values.skip_whitespace();
  3207. auto& second_value = values.next_token();
  3208. if (second_value.is(Token::Type::EndOfFile)) {
  3209. // -n
  3210. return make_return_value();
  3211. } else if (is_signed_integer(second_value)) {
  3212. // -n <signed-integer>
  3213. b = second_value.token().to_integer();
  3214. return make_return_value();
  3215. }
  3216. values.skip_whitespace();
  3217. auto& third_value = values.next_token();
  3218. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3219. // -n ['+' | '-'] <signless-integer>
  3220. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3221. return make_return_value();
  3222. }
  3223. return syntax_error();
  3224. }
  3225. // -n- <signless-integer>
  3226. if (is_dashndash(first_value)) {
  3227. values.skip_whitespace();
  3228. auto& second_value = values.next_token();
  3229. if (is_signless_integer(second_value)) {
  3230. a = -1;
  3231. b = -second_value.token().to_integer();
  3232. return make_return_value();
  3233. }
  3234. return syntax_error();
  3235. }
  3236. // All that's left now are these:
  3237. // '+'?† n
  3238. // '+'?† n <signed-integer>
  3239. // '+'?† n ['+' | '-'] <signless-integer>
  3240. // '+'?† n- <signless-integer>
  3241. // '+'?† <ndashdigit-ident>
  3242. // In all of these cases, the + is optional, and has no effect.
  3243. // So, we just skip the +, and carry on.
  3244. if (!is_delim(first_value, "+"sv)) {
  3245. values.reconsume_current_input_token();
  3246. // We do *not* skip whitespace here.
  3247. }
  3248. auto& first_after_plus = values.next_token();
  3249. // '+'?† n
  3250. // '+'?† n <signed-integer>
  3251. // '+'?† n ['+' | '-'] <signless-integer>
  3252. if (is_n(first_after_plus)) {
  3253. a = 1;
  3254. values.skip_whitespace();
  3255. auto& second_value = values.next_token();
  3256. if (second_value.is(Token::Type::EndOfFile)) {
  3257. // '+'?† n
  3258. return make_return_value();
  3259. } else if (is_signed_integer(second_value)) {
  3260. // '+'?† n <signed-integer>
  3261. b = second_value.token().to_integer();
  3262. return make_return_value();
  3263. }
  3264. values.skip_whitespace();
  3265. auto& third_value = values.next_token();
  3266. if ((is_delim(second_value, "+"sv) || is_delim(second_value, "-"sv)) && is_signless_integer(third_value)) {
  3267. // '+'?† n ['+' | '-'] <signless-integer>
  3268. b = third_value.token().to_integer() * (is_delim(second_value, "+"sv) ? 1 : -1);
  3269. return make_return_value();
  3270. }
  3271. return syntax_error();
  3272. }
  3273. // '+'?† n- <signless-integer>
  3274. if (is_ndash(first_after_plus)) {
  3275. values.skip_whitespace();
  3276. auto& second_value = values.next_token();
  3277. if (is_signless_integer(second_value)) {
  3278. a = 1;
  3279. b = -second_value.token().to_integer();
  3280. return make_return_value();
  3281. }
  3282. return syntax_error();
  3283. }
  3284. // '+'?† <ndashdigit-ident>
  3285. if (is_ndashdigit_ident(first_after_plus)) {
  3286. a = 1;
  3287. auto maybe_b = first_after_plus.token().ident().substring_view(1).to_int();
  3288. if (maybe_b.has_value()) {
  3289. b = maybe_b.value();
  3290. return make_return_value();
  3291. }
  3292. return syntax_error();
  3293. }
  3294. return syntax_error();
  3295. }
  3296. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_expression(ParsingContext const& context, Vector<StyleComponentValueRule> const& values)
  3297. {
  3298. auto tokens = TokenStream(values);
  3299. return parse_calc_sum(context, tokens);
  3300. }
  3301. Optional<CalculatedStyleValue::CalcValue> Parser::parse_calc_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3302. {
  3303. auto current_token = tokens.next_token();
  3304. if (current_token.is_block() && current_token.block().is_paren()) {
  3305. auto block_values = TokenStream(current_token.block().values());
  3306. auto parsed_calc_sum = parse_calc_sum(context, block_values);
  3307. if (!parsed_calc_sum)
  3308. return {};
  3309. return (CalculatedStyleValue::CalcValue) { parsed_calc_sum.release_nonnull() };
  3310. }
  3311. if (current_token.is(Token::Type::Number)) {
  3312. auto try_the_number = try_parse_float(current_token.token().number_string_value());
  3313. if (try_the_number.has_value())
  3314. return (CalculatedStyleValue::CalcValue) { try_the_number.value() };
  3315. return {};
  3316. }
  3317. if (current_token.is(Token::Type::Dimension) || current_token.is(Token::Type::Percentage)) {
  3318. auto maybe_length = parse_length(context, current_token);
  3319. if (maybe_length.has_value() && !maybe_length.value().is_undefined())
  3320. return (CalculatedStyleValue::CalcValue) { maybe_length.value() };
  3321. return {};
  3322. }
  3323. return {};
  3324. }
  3325. OwnPtr<CalculatedStyleValue::CalcProductPartWithOperator> Parser::parse_calc_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3326. {
  3327. // Note: The default value is not used or passed around.
  3328. auto product_with_operator = make<CalculatedStyleValue::CalcProductPartWithOperator>(
  3329. CalculatedStyleValue::CalcProductPartWithOperator::Multiply,
  3330. CalculatedStyleValue::CalcNumberValue(0));
  3331. tokens.skip_whitespace();
  3332. auto& op_token = tokens.peek_token();
  3333. if (!op_token.is(Token::Type::Delim))
  3334. return nullptr;
  3335. auto op = op_token.token().delim();
  3336. if (op == "*"sv) {
  3337. tokens.next_token();
  3338. tokens.skip_whitespace();
  3339. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Multiply;
  3340. auto parsed_calc_value = parse_calc_value(context, tokens);
  3341. if (!parsed_calc_value.has_value())
  3342. return nullptr;
  3343. product_with_operator->value = { parsed_calc_value.release_value() };
  3344. } else if (op == "/"sv) {
  3345. tokens.next_token();
  3346. tokens.skip_whitespace();
  3347. product_with_operator->op = CalculatedStyleValue::CalcProductPartWithOperator::Divide;
  3348. auto parsed_calc_number_value = parse_calc_number_value(context, tokens);
  3349. if (!parsed_calc_number_value.has_value())
  3350. return nullptr;
  3351. product_with_operator->value = { parsed_calc_number_value.release_value() };
  3352. } else {
  3353. return nullptr;
  3354. }
  3355. return product_with_operator;
  3356. }
  3357. OwnPtr<CalculatedStyleValue::CalcNumberProductPartWithOperator> Parser::parse_calc_number_product_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3358. {
  3359. // Note: The default value is not used or passed around.
  3360. auto number_product_with_operator = make<CalculatedStyleValue::CalcNumberProductPartWithOperator>(
  3361. CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply,
  3362. CalculatedStyleValue::CalcNumberValue(0));
  3363. tokens.skip_whitespace();
  3364. auto& op_token = tokens.peek_token();
  3365. if (!op_token.is(Token::Type::Delim))
  3366. return nullptr;
  3367. auto op = op_token.token().delim();
  3368. if (op == "*"sv) {
  3369. tokens.next_token();
  3370. tokens.skip_whitespace();
  3371. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply;
  3372. } else if (op == "/"sv) {
  3373. tokens.next_token();
  3374. tokens.skip_whitespace();
  3375. number_product_with_operator->op = CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide;
  3376. } else {
  3377. return nullptr;
  3378. }
  3379. auto parsed_calc_value = parse_calc_number_value(context, tokens);
  3380. if (!parsed_calc_value.has_value())
  3381. return nullptr;
  3382. number_product_with_operator->value = parsed_calc_value.release_value();
  3383. return number_product_with_operator;
  3384. }
  3385. OwnPtr<CalculatedStyleValue::CalcNumberProduct> Parser::parse_calc_number_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3386. {
  3387. auto calc_number_product = make<CalculatedStyleValue::CalcNumberProduct>(
  3388. CalculatedStyleValue::CalcNumberValue(0),
  3389. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberProductPartWithOperator> {});
  3390. auto first_calc_number_value_or_error = parse_calc_number_value(context, tokens);
  3391. if (!first_calc_number_value_or_error.has_value())
  3392. return nullptr;
  3393. calc_number_product->first_calc_number_value = first_calc_number_value_or_error.release_value();
  3394. while (tokens.has_next_token()) {
  3395. auto number_product_with_operator = parse_calc_number_product_part_with_operator(context, tokens);
  3396. if (!number_product_with_operator)
  3397. break;
  3398. calc_number_product->zero_or_more_additional_calc_number_values.append(number_product_with_operator.release_nonnull());
  3399. }
  3400. return calc_number_product;
  3401. }
  3402. OwnPtr<CalculatedStyleValue::CalcNumberSumPartWithOperator> Parser::parse_calc_number_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3403. {
  3404. if (!(tokens.peek_token().is(Token::Type::Delim)
  3405. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3406. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3407. return nullptr;
  3408. auto& token = tokens.next_token();
  3409. tokens.skip_whitespace();
  3410. CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation op;
  3411. auto delim = token.token().delim();
  3412. if (delim == "+"sv)
  3413. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Add;
  3414. else if (delim == "-"sv)
  3415. op = CalculatedStyleValue::CalcNumberSumPartWithOperator::Operation::Subtract;
  3416. else
  3417. return nullptr;
  3418. auto calc_number_product = parse_calc_number_product(context, tokens);
  3419. if (!calc_number_product)
  3420. return nullptr;
  3421. return make<CalculatedStyleValue::CalcNumberSumPartWithOperator>(op, calc_number_product.release_nonnull());
  3422. }
  3423. OwnPtr<CalculatedStyleValue::CalcNumberSum> Parser::parse_calc_number_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3424. {
  3425. auto first_calc_number_product_or_error = parse_calc_number_product(context, tokens);
  3426. if (!first_calc_number_product_or_error)
  3427. return nullptr;
  3428. NonnullOwnPtrVector<CalculatedStyleValue::CalcNumberSumPartWithOperator> additional {};
  3429. while (tokens.has_next_token()) {
  3430. auto calc_sum_part = parse_calc_number_sum_part_with_operator(context, tokens);
  3431. if (!calc_sum_part)
  3432. return nullptr;
  3433. additional.append(calc_sum_part.release_nonnull());
  3434. }
  3435. tokens.skip_whitespace();
  3436. auto calc_number_sum = make<CalculatedStyleValue::CalcNumberSum>(first_calc_number_product_or_error.release_nonnull(), move(additional));
  3437. return calc_number_sum;
  3438. }
  3439. Optional<CalculatedStyleValue::CalcNumberValue> Parser::parse_calc_number_value(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3440. {
  3441. auto& first = tokens.peek_token();
  3442. if (first.is_block() && first.block().is_paren()) {
  3443. tokens.next_token();
  3444. auto block_values = TokenStream(first.block().values());
  3445. auto calc_number_sum = parse_calc_number_sum(context, block_values);
  3446. if (calc_number_sum)
  3447. return { calc_number_sum.release_nonnull() };
  3448. }
  3449. if (!first.is(Token::Type::Number))
  3450. return {};
  3451. tokens.next_token();
  3452. auto try_the_number = try_parse_float(first.token().number_string_value());
  3453. if (!try_the_number.has_value())
  3454. return {};
  3455. return try_the_number.value();
  3456. }
  3457. OwnPtr<CalculatedStyleValue::CalcProduct> Parser::parse_calc_product(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3458. {
  3459. auto calc_product = make<CalculatedStyleValue::CalcProduct>(
  3460. CalculatedStyleValue::CalcValue(0),
  3461. NonnullOwnPtrVector<CalculatedStyleValue::CalcProductPartWithOperator> {});
  3462. auto first_calc_value_or_error = parse_calc_value(context, tokens);
  3463. if (!first_calc_value_or_error.has_value())
  3464. return nullptr;
  3465. calc_product->first_calc_value = first_calc_value_or_error.release_value();
  3466. while (tokens.has_next_token()) {
  3467. auto product_with_operator = parse_calc_product_part_with_operator(context, tokens);
  3468. if (!product_with_operator)
  3469. break;
  3470. calc_product->zero_or_more_additional_calc_values.append(product_with_operator.release_nonnull());
  3471. }
  3472. return calc_product;
  3473. }
  3474. OwnPtr<CalculatedStyleValue::CalcSumPartWithOperator> Parser::parse_calc_sum_part_with_operator(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3475. {
  3476. // The following has to have the shape of <Whitespace><+ or -><Whitespace>
  3477. // But the first whitespace gets eaten in parse_calc_product_part_with_operator().
  3478. if (!(tokens.peek_token().is(Token::Type::Delim)
  3479. && tokens.peek_token().token().delim().is_one_of("+"sv, "-"sv)
  3480. && tokens.peek_token(1).is(Token::Type::Whitespace)))
  3481. return nullptr;
  3482. auto& token = tokens.next_token();
  3483. tokens.skip_whitespace();
  3484. CalculatedStyleValue::CalcSumPartWithOperator::Operation op;
  3485. auto delim = token.token().delim();
  3486. if (delim == "+"sv)
  3487. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add;
  3488. else if (delim == "-"sv)
  3489. op = CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract;
  3490. else
  3491. return nullptr;
  3492. auto calc_product = parse_calc_product(context, tokens);
  3493. if (!calc_product)
  3494. return nullptr;
  3495. return make<CalculatedStyleValue::CalcSumPartWithOperator>(op, calc_product.release_nonnull());
  3496. };
  3497. OwnPtr<CalculatedStyleValue::CalcSum> Parser::parse_calc_sum(ParsingContext const& context, TokenStream<StyleComponentValueRule>& tokens)
  3498. {
  3499. auto parsed_calc_product = parse_calc_product(context, tokens);
  3500. if (!parsed_calc_product)
  3501. return nullptr;
  3502. NonnullOwnPtrVector<CalculatedStyleValue::CalcSumPartWithOperator> additional {};
  3503. while (tokens.has_next_token()) {
  3504. auto calc_sum_part = parse_calc_sum_part_with_operator(context, tokens);
  3505. if (!calc_sum_part)
  3506. return nullptr;
  3507. additional.append(calc_sum_part.release_nonnull());
  3508. }
  3509. tokens.skip_whitespace();
  3510. return make<CalculatedStyleValue::CalcSum>(parsed_calc_product.release_nonnull(), move(additional));
  3511. }
  3512. bool Parser::has_ignored_vendor_prefix(StringView const& string)
  3513. {
  3514. if (!string.starts_with('-'))
  3515. return false;
  3516. if (string.starts_with("--"))
  3517. return false;
  3518. if (string.starts_with("-libweb-"))
  3519. return false;
  3520. return true;
  3521. }
  3522. }
  3523. namespace Web {
  3524. RefPtr<CSS::CSSStyleSheet> parse_css(CSS::ParsingContext const& context, StringView const& css)
  3525. {
  3526. if (css.is_empty())
  3527. return CSS::CSSStyleSheet::create({});
  3528. CSS::Parser parser(context, css);
  3529. return parser.parse_as_stylesheet();
  3530. }
  3531. RefPtr<CSS::PropertyOwningCSSStyleDeclaration> parse_css_declaration(CSS::ParsingContext const& context, StringView const& css)
  3532. {
  3533. if (css.is_empty())
  3534. return CSS::PropertyOwningCSSStyleDeclaration::create({}, {});
  3535. CSS::Parser parser(context, css);
  3536. return parser.parse_as_list_of_declarations();
  3537. }
  3538. RefPtr<CSS::StyleValue> parse_css_value(CSS::ParsingContext const& context, StringView const& string, CSS::PropertyID property_id)
  3539. {
  3540. if (string.is_empty())
  3541. return {};
  3542. CSS::Parser parser(context, string);
  3543. return parser.parse_as_css_value(property_id);
  3544. }
  3545. RefPtr<CSS::CSSRule> parse_css_rule(CSS::ParsingContext const& context, StringView css_text)
  3546. {
  3547. CSS::Parser parser(context, css_text);
  3548. return parser.parse_as_rule();
  3549. }
  3550. Optional<CSS::SelectorList> parse_selector(CSS::ParsingContext const& context, StringView const& selector_text)
  3551. {
  3552. CSS::Parser parser(context, selector_text);
  3553. return parser.parse_as_selector();
  3554. }
  3555. RefPtr<CSS::MediaQuery> parse_media_query(CSS::ParsingContext const& context, StringView const& string)
  3556. {
  3557. CSS::Parser parser(context, string);
  3558. return parser.parse_as_media_query();
  3559. }
  3560. NonnullRefPtrVector<CSS::MediaQuery> parse_media_query_list(CSS::ParsingContext const& context, StringView const& string)
  3561. {
  3562. CSS::Parser parser(context, string);
  3563. return parser.parse_as_media_query_list();
  3564. }
  3565. RefPtr<CSS::Supports> parse_css_supports(CSS::ParsingContext const& context, StringView const& string)
  3566. {
  3567. if (string.is_empty())
  3568. return {};
  3569. CSS::Parser parser(context, string);
  3570. return parser.parse_as_supports();
  3571. }
  3572. RefPtr<CSS::StyleValue> parse_html_length(DOM::Document const& document, StringView const& string)
  3573. {
  3574. auto integer = string.to_int();
  3575. if (integer.has_value())
  3576. return CSS::LengthStyleValue::create(CSS::Length::make_px(integer.value()));
  3577. return parse_css_value(CSS::ParsingContext(document), string);
  3578. }
  3579. }