Parser.cpp 156 KB

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