Parser.cpp 154 KB

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