Parser.cpp 168 KB

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