Parser.cpp 154 KB

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