Parser.cpp 173 KB

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