Parser.cpp 179 KB

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