Parser.cpp 177 KB

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