Parser.cpp 197 KB

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