From 546d75a520a746fbb2ce319642c59f4ecd058e3d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 24 Oct 2026 04:54:44 +0000 Subject: [PATCH 1/5] css: wrap a selector list in :is() only when every selector keeps its match and specificity When the browser targets cannot parse every selector of a list, the minifier replaces the list with one `:is(list)` selector or moves each unsupported selector to its own rule. The `:is()` form is valid only if it matches the same elements with the same specificity. The check read two values that are stored when a selector is parsed, and both were wrong for some selectors: - `has_pseudo_element()` read only `HAS_PSEUDO`. `::part()` and `::slotted()` set `HAS_PART` and `HAS_SLOTTED`. A pseudo-element inside `:is()` matches nothing, so `x-el::part(a), y-el z-el:has(q-el)` lost the `::part()` rule in every browser. - `:has()` had no weight. `:is()` takes the specificity of its most specific argument, so `:is(.a,.b:has(.x))` gave `.a` the specificity (0,2,0). `StyleRule::selector_list_lowering` now makes the decision once. The selector-expansion budget in `minify_nested_rules` reads the same verdict, so the two cannot disagree. A list becomes one `:is()` only if all of these hold: - The targets cannot parse any selector of the list on its own. A selector that every target can parse stays outside `:is()`. - The rule is not inside `@scope`, where each selector of a list is relative to the scoping root. - `selector::can_wrap_in_is` accepts the list: no pseudo-element, equal stored specificity, and no component that matches, weighs or prints differently inside `:is()`. `can_wrap_in_is` walks the components for what the stored values cannot describe. `&` weighs the parent rule's selector list and an unknown functional pseudo-class weighs its argument, so all selectors must have the same ones. A shadow host as the subject, `:visited`, `:link`, `:-webkit-any()`, a pseudo-class with a vendor prefix pass, an explicit namespace, and CSS modules `:local()` / `:global()` never go inside `:is()`. --- src/css/css_parser.rs | 1 + src/css/rules/mod.rs | 45 ++-- src/css/rules/style.rs | 56 ++++- src/css/selectors/parser.rs | 35 +--- src/css/selectors/selector.rs | 191 +++++++++++++++++ test/bundler/css/css-modules.test.ts | 45 +++- test/js/bun/css/css.test.ts | 194 ++++++++++++++++++ .../nested-selector-list-expansion.test.ts | 8 + .../nested-vendor-prefix-duplication.test.ts | 13 +- test/js/bun/css/util.ts | 5 +- 10 files changed, 529 insertions(+), 64 deletions(-) diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index 54f041ba317d..f8971bfc91ec 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2407,6 +2407,7 @@ mod stylesheet_impl { err: None, selector_expansion_multiplier: 1, selector_expansion_total: 0, + in_scope_rule: false, }; if self.rules.minify(&mut minify_ctx, false).is_err() { diff --git a/src/css/rules/mod.rs b/src/css/rules/mod.rs index 0a89042a286e..04ab500b2fbe 100644 --- a/src/css/rules/mod.rs +++ b/src/css/rules/mod.rs @@ -575,7 +575,11 @@ impl CssRuleList { CssRule::Scope(scpe) => { // See `Container` above: recurse so nested style rules // count against the selector-expansion cap. - scpe.rules.minify(context, parent_is_unused)?; + let was_in_scope_rule = + core::mem::replace(&mut context.in_scope_rule, true); + let result = scpe.rules.minify(context, parent_is_unused); + context.in_scope_rule = was_in_scope_rule; + result?; } CssRule::Nesting(nst) => { // See `Container` above. `@nest` wraps a single style @@ -592,7 +596,11 @@ impl CssRuleList { // untouched preserves them verbatim, matching the // pre-port behavior. nst.style.charge_selector_expansion(context)?; - nst.style.minify_nested_rules(context, parent_is_unused)?; + let lowering = nst + .style + .selector_list_lowering(context.targets, context.in_scope_rule); + nst.style + .minify_nested_rules(context, parent_is_unused, lowering)?; } CssRule::StartingStyle(rl) => { // See `Container` above: recurse so nested style rules @@ -654,36 +662,33 @@ fn minify_style_arm css::generics::DeepClone<'b>>( ) -> Result<(), MinifyErr> { use css::SmallList; use css::selector::{self, Component, Selector, SelectorList}; + use style::SelectorListLowering; let CssRule::Style(sty) = rule else { unreachable!() }; - if parent_is_unused || sty.minify(context, parent_is_unused)? { + if parent_is_unused { return Ok(()); } // If some of the selectors in this rule are not compatible with the targets, // we need to either wrap in :is() or split them into multiple rules. - let mut incompatible: SmallList = if sty.selectors.v.len() > 1 - && context.targets.should_compile_selectors() - && !sty.is_compatible(context.targets) - { - // The :is() selector accepts a forgiving selector list, so use that if possible. - // Note that :is() does not allow pseudo elements, so we need to check for that. - // In addition, :is() takes the highest specificity of its arguments, so if the selectors - // have different weights, we need to split them into separate rules as well. - if context - .targets - .is_compatible(css::compat::Feature::IsSelector) - && !sty.selectors.any_has_pseudo_element() - && sty.selectors.specifities_all_equal() - { + let lowering = sty.selector_list_lowering(context.targets, context.in_scope_rule); + if sty.minify(context, parent_is_unused, lowering)? { + return Ok(()); + } + + let mut incompatible: SmallList = match lowering { + SelectorListLowering::AsWritten => SmallList::default(), + SelectorListLowering::WrapInIs => { + debug_assert!(selector::can_wrap_in_is(sty.selectors.v.slice())); let component = Component::Is(core::mem::take(&mut sty.selectors.v).to_owned_slice()); let mut list = SmallList::::default(); list.append(Selector::from_component(component)); sty.selectors = SelectorList { v: list }; SmallList::default() - } else { + } + SelectorListLowering::Partition => { // Otherwise, partition the selectors and keep the compatible ones in this rule. // We will generate additional rules for incompatible selectors later. let mut incompatible = SmallList::::default(); @@ -700,8 +705,6 @@ fn minify_style_arm css::generics::DeepClone<'b>>( } incompatible } - } else { - SmallList::default() }; sty.update_prefix(context); @@ -1254,4 +1257,6 @@ pub struct MinifyContext<'a, 'bump> { /// Running total of selectors that compiling nested rules for the targets /// will expand to, checked against [`MAX_SELECTOR_EXPANSION`]. pub(crate) selector_expansion_total: u32, + /// Whether the rules being minified are inside an `@scope` rule. + pub(crate) in_scope_rule: bool, } diff --git a/src/css/rules/style.rs b/src/css/rules/style.rs index bfc3551a87da..475b653f152f 100644 --- a/src/css/rules/style.rs +++ b/src/css/rules/style.rs @@ -31,6 +31,17 @@ impl StyleRule { } } +/// How a selector list is printed for targets that may not parse all of its selectors. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum SelectorListLowering { + /// The targets can parse every selector, so the list stays as written. + AsWritten, + /// The list becomes the single selector `:is(list)`, which ignores what a browser cannot parse. + WrapInIs, + /// Each selector that the targets cannot parse moves to its own copy of the rule. + Partition, +} + // ─── behavior bodies ────────────────────────────────────────────────────── impl StyleRule { /// Returns a hash of this rule for use when deduplicating. @@ -68,6 +79,34 @@ impl StyleRule { pub(crate) fn is_compatible(&self, targets: &css::targets::Targets) -> bool { selector::is_compatible(self.selectors.v.slice(), targets) } + + /// `minify_style_arm` acts on this verdict, and `minify_nested_rules` budgets for the same one. + pub(crate) fn selector_list_lowering( + &self, + targets: &css::targets::Targets, + in_scope_rule: bool, + ) -> SelectorListLowering { + let selectors = self.selectors.v.slice(); + if selectors.len() <= 1 + || !targets.should_compile_selectors() + || selector::is_compatible(selectors, targets) + { + return SelectorListLowering::AsWritten; + } + // In `@scope`, each selector of a list is relative to the scoping root. An `:is()` argument is not. + if in_scope_rule || !targets.is_compatible(css::Feature::IsSelector) { + return SelectorListLowering::Partition; + } + // A selector that every target can parse stays outside `:is()`. + let all_need_lowering = selectors + .iter() + .all(|one| !selector::is_compatible(core::slice::from_ref(one), targets)); + if all_need_lowering && selector::can_wrap_in_is(selectors) { + SelectorListLowering::WrapInIs + } else { + SelectorListLowering::Partition + } + } } // ─── to_css ─────────────────────────────────────────────────────────────── @@ -314,6 +353,7 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, + lowering: SelectorListLowering, ) -> Result where R: for<'b> css::generics::DeepClone<'b>, @@ -368,7 +408,7 @@ impl StyleRule { context.handler_context.context = DeclarationContext::None; if self.rules.v.len() > 0 { - self.minify_nested_rules(context, unused)?; + self.minify_nested_rules(context, unused, lowering)?; if unused && self.rules.v.len() == 0 { return Ok(true); } @@ -413,6 +453,7 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, + lowering: SelectorListLowering, ) -> Result<(), MinifyErr> where R: for<'b> css::generics::DeepClone<'b>, @@ -423,7 +464,7 @@ impl StyleRule { // rule's selectors for compatibility), each of this rule's selectors // multiplies the expansion of every nested rule. // - // Mirrors the selector-compatibility branch in `minify_style_arm` + // `lowering` is the verdict that `minify_style_arm` acts on // (rules/mod.rs): an incompatible selector list is either collapsed // into a single `:is()` selector (nothing cloned) or partitioned // into one cloned rule per selector (fan-out = selector count). @@ -432,14 +473,9 @@ impl StyleRule { // nesting is compiled away the printed output still fans out per // selector, which is why the nesting branch bumps unconditionally. let saved_expansion_multiplier = context.selector_expansion_multiplier; - let selectors_incompatible = self.selectors.v.len() > 1 - && context.targets.should_compile_selectors() - && !self.is_compatible(context.targets); - let splits_selectors = selectors_incompatible - && !(context.targets.is_compatible(css::Feature::IsSelector) - && !self.selectors.any_has_pseudo_element() - && self.selectors.specifities_all_equal()); - if context.targets.should_compile_same(css::Feature::Nesting) || splits_selectors { + if context.targets.should_compile_same(css::Feature::Nesting) + || lowering == SelectorListLowering::Partition + { context.selector_expansion_multiplier = context .selector_expansion_multiplier .saturating_mul(self.selectors.v.len().max(1)); diff --git a/src/css/selectors/parser.rs b/src/css/selectors/parser.rs index 5e8df3665529..a3bed0036185 100644 --- a/src/css/selectors/parser.rs +++ b/src/css/selectors/parser.rs @@ -498,7 +498,7 @@ fn compute_simple_selector_specificity( } specificity.add(Specificity::from_u32(max)); } - C::Negation(_) | C::Is(_) | C::Any { .. } => { + C::Negation(_) | C::Is(_) | C::Has(_) | C::Any { .. } => { // https://drafts.csswg.org/selectors/#specificity-rules: // // The specificity of an :is() pseudo-class is replaced by the @@ -507,6 +507,8 @@ fn compute_simple_selector_specificity( let list: &[GenericSelector] = match simple_selector { C::Negation(list) => list, C::Is(list) => list, + // Selectors 4 weighs :has() like :is(). lightningcss does not: parcel-bundler/lightningcss#1324 + C::Has(list) => list, C::Any { selectors, .. } => selectors, _ => unreachable!(), }; @@ -517,7 +519,6 @@ fn compute_simple_selector_specificity( specificity.add(Specificity::from_u32(max)); } C::Where(_) - | C::Has(_) | C::ExplicitUniversalType | C::ExplicitAnyNamespace | C::ExplicitNoNamespace @@ -1597,31 +1598,6 @@ impl GenericSelectorList { } impl GenericSelectorList { - pub(crate) fn any_has_pseudo_element(&self) -> bool { - for sel in self.v.slice() { - if sel.has_pseudo_element() { - return true; - } - } - false - } - - pub(crate) fn specifities_all_equal(&self) -> bool { - if self.v.len() == 0 { - return true; - } - if self.v.len() == 1 { - return true; - } - let value = self.v.at(0).specificity(); - for sel in &self.v.slice()[1..] { - if sel.specificity() != value { - return false; - } - } - true - } - pub fn parse( parser: &mut SelectorParser, input: &mut CssParser, @@ -2692,8 +2668,11 @@ pub struct SpecificityAndFlags { } impl SpecificityAndFlags { + /// `::part()` and `::slotted()` are pseudo-elements too, and the parser gives each its own flag. pub(crate) fn has_pseudo_element(self) -> bool { - self.flags.contains(SelectorFlags::HAS_PSEUDO) + self.flags.intersects( + SelectorFlags::HAS_PSEUDO | SelectorFlags::HAS_SLOTTED | SelectorFlags::HAS_PART, + ) } pub(crate) fn hash(self, hasher: &mut Wyhash) { hasher.update(&self.specificity.to_ne_bytes()); diff --git a/src/css/selectors/selector.rs b/src/css/selectors/selector.rs index f4900a75e939..006a38a8d608 100644 --- a/src/css/selectors/selector.rs +++ b/src/css/selectors/selector.rs @@ -492,6 +492,197 @@ pub(crate) fn is_compatible(selectors: &[parser::Selector], targets: &Targets) - true } +/// Whether `:is(selectors)` matches the same elements with the same specificity as the selector list. +pub(crate) fn can_wrap_in_is(selectors: &[parser::Selector]) -> bool { + let Some(first) = selectors.first() else { + return true; + }; + // `:is()` cannot hold a pseudo-element, and it takes the specificity of its most specific argument. + selectors.iter().all(|selector| { + !selector.has_pseudo_element() && selector.specificity() == first.specificity() + }) && components_allow_is(selectors) +} + +/// What the specificity and flags stored at parse time do not say about a component inside `:is()`. +enum InsideIs { + /// It matches inside `:is()`, and the stored specificity counts it as it prints. + Allowed, + /// Its weight is not known at parse time, so every selector of the list must have the same one. + IfShared, + /// It does not match, weigh or print inside `:is()` as it does outside. + Never, +} + +fn inside_is(component: &Component) -> InsideIs { + match component { + Component::NonTsPseudoClass(pseudo_class) => match pseudo_class { + // WebKit never matches `:visited` inside `:is()`, and there `:link` matches visited links too. + PseudoClass::Visited | PseudoClass::Link => InsideIs::Never, + + // A vendor prefix pass prints the `:is()` around them as `:-webkit-any()` or `:-moz-any()`. + PseudoClass::Fullscreen(_) + | PseudoClass::AnyLink(_) + | PseudoClass::ReadOnly(_) + | PseudoClass::ReadWrite(_) + | PseudoClass::PlaceholderShown(_) + | PseudoClass::Autofill(_) => InsideIs::Never, + + // CSS modules `:local()` and `:global()` print as their argument, which can end in a pseudo-element. + PseudoClass::Local { .. } | PseudoClass::Global { .. } => InsideIs::Never, + + // An unknown function weighs what its argument means. + PseudoClass::CustomFunction { .. } => InsideIs::IfShared, + + PseudoClass::Lang { .. } + | PseudoClass::Dir { .. } + | PseudoClass::Hover + | PseudoClass::Active + | PseudoClass::Focus + | PseudoClass::FocusVisible + | PseudoClass::FocusWithin + | PseudoClass::Current + | PseudoClass::Past + | PseudoClass::Future + | PseudoClass::Playing + | PseudoClass::Paused + | PseudoClass::Seeking + | PseudoClass::Buffering + | PseudoClass::Stalled + | PseudoClass::Muted + | PseudoClass::VolumeLocked + | PseudoClass::Open + | PseudoClass::Closed + | PseudoClass::Modal + | PseudoClass::PictureInPicture + | PseudoClass::PopoverOpen + | PseudoClass::Defined + | PseudoClass::LocalLink + | PseudoClass::Target + | PseudoClass::TargetWithin + | PseudoClass::Enabled + | PseudoClass::Disabled + | PseudoClass::Default + | PseudoClass::Checked + | PseudoClass::Indeterminate + | PseudoClass::Blank + | PseudoClass::Valid + | PseudoClass::Invalid + | PseudoClass::InRange + | PseudoClass::OutOfRange + | PseudoClass::Required + | PseudoClass::Optional + | PseudoClass::UserValid + | PseudoClass::UserInvalid + | PseudoClass::WebkitScrollbar(_) + | PseudoClass::Custom { .. } => InsideIs::Allowed, + }, + + // `&` weighs the selector list of the parent rule. + Component::Nesting => InsideIs::IfShared, + + // A hand-written `:-webkit-any()` prints as `:is()` here, and browsers do not weigh the two alike. + Component::Any { .. } + | Component::Slotted(_) + | Component::Part(_) + | Component::PseudoElement(_) => InsideIs::Never, + + // Under a default `@namespace`, the `:is()` itself matches only elements of that namespace. + Component::Namespace { .. } + | Component::ExplicitAnyNamespace + | Component::ExplicitNoNamespace => InsideIs::Never, + + Component::Negation(selectors) | Component::Is(selectors) | Component::Has(selectors) => { + arguments_inside_is(selectors) + } + Component::NthOf(nth) => arguments_inside_is(&nth.selectors), + Component::Host(Some(selector)) => arguments_inside_is(core::slice::from_ref(selector)), + + // `:where()` weighs nothing, whatever its arguments are. + Component::Where(_) + | Component::Host(None) + | Component::Combinator(_) + | Component::DefaultNamespace(_) + | Component::ExplicitUniversalType + | Component::LocalName(_) + | Component::Id(_) + | Component::Class(_) + | Component::AttributeInNoNamespaceExists { .. } + | Component::AttributeInNoNamespace { .. } + | Component::AttributeOther(_) + | Component::Root + | Component::Empty + | Component::Scope + | Component::Nth(_) => InsideIs::Allowed, + } +} + +// The most specific argument is not known if one of them has a component of unknown weight. +fn arguments_inside_is(selectors: &[parser::Selector]) -> InsideIs { + let mut verdict = InsideIs::Allowed; + for component in selectors + .iter() + .flat_map(|selector| selector.components.iter()) + { + match inside_is(component) { + InsideIs::Allowed => {} + InsideIs::IfShared => verdict = InsideIs::IfShared, + InsideIs::Never => return InsideIs::Never, + } + } + verdict +} + +// Chrome 124 and Firefox 128 do not match a shadow host that is the subject of one of several `:is()` arguments. +fn subject_is_shadow_host(selector: &parser::Selector) -> bool { + selector + .components + .iter() + .take_while(|component| !component.is_combinator()) + .any(|component| match component { + Component::Host(_) => true, + Component::NonTsPseudoClass(PseudoClass::CustomFunction { name, .. }) => { + bun_core::strings::eql_case_insensitive_ascii_check_length(name, b"host-context") + } + _ => false, + }) +} + +/// Whether no selector has a `Never` component and all of them have the same `IfShared` components. +#[cold] +#[inline(never)] +fn components_allow_is(selectors: &[parser::Selector]) -> bool { + fn next<'a>( + components: &mut core::slice::Iter<'a, Component>, + ) -> Option<(&'a Component, InsideIs)> { + components + .map(|component| (component, inside_is(component))) + .find(|(_, verdict)| !matches!(verdict, InsideIs::Allowed)) + } + + fn alike(a: &parser::Selector, b: &parser::Selector) -> bool { + let (mut a, mut b) = (a.components.iter(), b.components.iter()); + loop { + match (next(&mut a), next(&mut b)) { + (None, None) => return true, + (Some((x, InsideIs::IfShared)), Some((y, InsideIs::IfShared))) if x.eql(y) => {} + _ => return false, + } + } + } + + // Each selector is compared with the one before it, and the first with the last. + let Some(mut previous) = selectors.last() else { + return true; + }; + for selector in selectors { + if subject_is_shadow_host(selector) || !alike(previous, selector) { + return false; + } + previous = selector; + } + true +} + /// Determines whether a selector list contains only unused selectors. /// A selector is considered unused if it contains a class or id component that exists in the set of unused symbols. pub(crate) fn is_unused( diff --git a/test/bundler/css/css-modules.test.ts b/test/bundler/css/css-modules.test.ts index 849065706a6c..9d631446b3b8 100644 --- a/test/bundler/css/css-modules.test.ts +++ b/test/bundler/css/css-modules.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, tempDir } from "harness"; +import { bunEnv, bunExe, isASAN, isDebug, tempDir } from "harness"; import { join } from "node:path"; import { itBundled } from "../expectBundled"; @@ -656,6 +656,49 @@ test("css-module/NoBundleHashesByRelativePath", async () => { expect(hashA).not.toBe(hashB); }); +// `:global()` and `:local()` print as their argument, which can end in a +// pseudo-element and has a specificity of its own. So a selector list with one +// of them must not become one `:is(list)` selector for targets that have +// `:is()` and lack `:has()`. The first rule has neither and must become one: it +// shows that the targets apply. Browser targets reach a CSS module only through +// the `BUN_DEBUG_CSS_TARGET_*` variables, which debug and ASAN builds read. +test.skipIf(!isDebug && !isASAN)("css-module/GlobalSelectorListIsNotWrappedInIs", async () => { + using dir = tempDir("css-module-global-list", { + "styles.module.css": ` + .a:has(.k), .b:has(.k) { color: pink } + .x :global(.y::before), .x:has(.z) { color: red } + :global(x-el::part(a)), .y:has(.q) { color: green } + :global(.dark) .c:has(.k), :global(.dark) .d:has(.k) { color: teal } + :local(.e::after), :local(.f) { color: navy } + `, + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "build", "styles.module.css", "--minify", "--outdir", "out"], + env: { ...bunEnv, BUN_DEBUG_CSS_TARGET_chrome: "100 << 16" }, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + const css = await Bun.file(`${dir}/out/styles.module.css`).text(); + const hash = css.match(/\.x_([A-Za-z0-9_-]+) /)?.[1]; + expect(css.trim()).toBe( + [ + `:is(.a_${hash}:has(.k_${hash}),.b_${hash}:has(.k_${hash})){color:pink}`, + `.x_${hash} .y:before{color:red}`, + `.x_${hash}:has(.z_${hash}){color:red}`, + `x-el::part(a){color:green}`, + `.y_${hash}:has(.q_${hash}){color:green}`, + `.dark .c_${hash}:has(.k_${hash}){color:teal}`, + `.dark .d_${hash}:has(.k_${hash}){color:teal}`, + `.e_${hash}:after{color:navy}`, + `.f_${hash}{color:navy}`, + ].join(""), + ); + expect(exitCode).toBe(0); +}); + test("a resolve error in CSS covers the whole url() and composes path", async () => { using dir = tempDir("css-resolve-error-range", { "a.module.css": [ diff --git a/test/js/bun/css/css.test.ts b/test/js/bun/css/css.test.ts index 890ffa4dcd95..8e47cc6d0099 100644 --- a/test/js/bun/css/css.test.ts +++ b/test/js/bun/css/css.test.ts @@ -6,6 +6,7 @@ import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe } from "harness"; import { join } from "path"; import { + type Browsers, cssTest, cssTestTodo, indoc, @@ -5751,6 +5752,199 @@ describe("css tests", () => { minify_test(":host(:hover) {color: red}", ":host(:hover){color:red}"); minify_test("::slotted(:hover) {color: red}", "::slotted(:hover){color:red}"); + // A browser drops a rule when it cannot parse one selector of the list. For targets that + // cannot parse every selector, the minifier prints one `:is(list)` selector or moves each + // unsupported selector to its own rule. `lowered` takes the list and the selectors of the + // rules that it must print. + const noHas = { chrome: 100 << 16 }; + const noFocusVisible = { safari: 15 << 16 }; + const noHasInFirefox = { + chrome: 111 << 16, + edge: 111 << 16, + firefox: 114 << 16, + safari: (16 << 16) | (4 << 8), + ios_saf: (16 << 16) | (4 << 8), + }; + const nativeNesting = { chrome: 130 << 16 }; + const nativeNestingNoHas = { firefox: 118 << 16 }; + const lowered = (targets: Browsers, list: string, ...rules: string[]) => + minify_test(`${list} { color: red }`, rules.map(rule => `${rule}{color:red}`).join(""), targets); + + // Every selector needs the lowering, and all of them weigh the same. + lowered(noHas, "a:has(.x), b:has(.x)", ":is(a:has(.x),b:has(.x))"); + lowered(noHas, ".b:has(.x), .c:has(.x), .d:has(.x)", ":is(.b:has(.x),.c:has(.x),.d:has(.x))"); + lowered(noHas, ".a:has(> .x), .b:has(.x)", ":is(.a:has(>.x),.b:has(.x))"); + lowered(noHas, ".a:has(.x.y), .b.c:has(.z)", ":is(.a:has(.x.y),.b.c:has(.z))"); + lowered(noHas, ":state(a) .x:has(i), :state(a) .y:has(i)", ":is(:state(a) .x:has(i),:state(a) .y:has(i))"); + lowered( + noHas, + ":host(.dark) .a:has(.k), :host(.dark) .b:has(.x)", + ":is(:host(.dark) .a:has(.k),:host(.dark) .b:has(.x))", + ); + + // A selector that every target can parse stays outside `:is()`. + lowered(noFocusVisible, ".a:hover, .b:focus-visible", ".a:hover", ".b:focus-visible"); + lowered(noHas, ".a.b, .c:has(.x)", ".a.b", ".c:has(.x)"); + lowered(noHas, ".a, .b:has(.x), .c:has(.x)", ".a", ".b:has(.x)", ".c:has(.x)"); + lowered(noHas, ".b:has(.x), .a, .c:has(.x)", ".a", ".b:has(.x)", ".c:has(.x)"); + lowered(noHas, ".b:has(.x), .c:has(.x), .a", ".a", ".b:has(.x)", ".c:has(.x)"); + lowered( + noHasInFirefox, + ":root, :root:has(input.theme-controller[value=light]:checked), [data-theme=light]", + ":root,[data-theme=light]", + ":root:has(input.theme-controller[value=light]:checked)", + ); + + // `:is()` cannot hold a pseudo-element. + lowered(noHas, "a::before, b:has(.x)", "a:before", "b:has(.x)"); + lowered(noHas, "x-el::part(a), y-el z-el:has(q-el)", "x-el::part(a)", "y-el z-el:has(q-el)"); + lowered(noHas, "::slotted(.x), i.c:has(.q)", "::slotted(.x)", "i.c:has(.q)"); + lowered( + nativeNesting, + "x-el::part(a):user-valid, y-el z-el:user-valid", + "x-el::part(a):user-valid", + "y-el z-el:user-valid", + ); + lowered( + nativeNesting, + "y-el z-el:user-valid, x-el::part(a):user-valid, w-el v-el:user-valid", + "y-el z-el:user-valid", + "x-el::part(a):user-valid", + "w-el v-el:user-valid", + ); + + // `:is()` takes the specificity of its most specific argument, and so does `:has()`. + lowered(noHas, ".a:has(.x), .a:has(#y)", ".a:has(.x)", ".a:has(#y)"); + lowered(noHas, ".a:has(.x), .a:has(.x.y.z)", ".a:has(.x)", ".a:has(.x.y.z)"); + lowered(noHas, ".a:not(:has(.x)), .b:not(:has(#y))", ".a:not(:has(.x))", ".b:not(:has(#y))"); + lowered(noHas, "li:has(> hr), li:has(> .divider)", "li:has(>hr)", "li:has(>.divider)"); + lowered(noHas, ".a:has(#y), .b:has(.x), .c:has(.x)", ".a:has(#y)", ".b:has(.x)", ".c:has(.x)"); + lowered(noHas, ".b:has(.x), .a:has(#y), .c:has(.x)", ".b:has(.x)", ".a:has(#y)", ".c:has(.x)"); + lowered(noHas, ".b:has(.x), .c:has(.x), .a:has(#y)", ".b:has(.x)", ".c:has(.x)", ".a:has(#y)"); + + // An unknown functional pseudo-class weighs what its argument means. All selectors of the + // list must have the same ones. + lowered(noHas, ":state(a) .x:has(i), :state(b) .y:has(i)", ":state(a) .x:has(i)", ":state(b) .y:has(i)"); + lowered( + noHas, + ":state(b) .z:has(i), :state(a) .x:has(i), :state(a) .y:has(i)", + ":state(b) .z:has(i)", + ":state(a) .x:has(i)", + ":state(a) .y:has(i)", + ); + lowered( + noHas, + ":state(a) .x:has(i), :state(b) .z:has(i), :state(a) .y:has(i)", + ":state(a) .x:has(i)", + ":state(b) .z:has(i)", + ":state(a) .y:has(i)", + ); + lowered( + noHas, + ":state(a) .x:has(i), :state(a) .y:has(i), :state(b) .z:has(i)", + ":state(a) .x:has(i)", + ":state(a) .y:has(i)", + ":state(b) .z:has(i)", + ); + lowered(noHas, ".a:not(:state(x)):has(i), .b.k:has(i)", ".a:not(:state(x)):has(i)", ".b.k:has(i)"); + lowered( + noHas, + ".a:nth-child(2 of :state(x)):has(i), .b.k.m:has(i)", + ".a:nth-child(2 of :state(x)):has(i)", + ".b.k.m:has(i)", + ); + + // These do not match, weigh or print inside `:is()` as they do outside: a shadow host that + // is the subject, `:visited` and `:link`, `:-webkit-any()`, a pseudo-class with a vendor + // prefix pass, and a namespace. + lowered(noHas, ":host(.a):has(.x), :host(.b):has(.y)", ":host(.a):has(.x)", ":host(.b):has(.y)"); + lowered( + noHas, + ".k.b:has(.c), :host(.a):has(.x), .k.d:has(.c)", + ".k.b:has(.c)", + ":host(.a):has(.x)", + ".k.d:has(.c)", + ); + lowered(noHas, ":host-context(.dark):has(.x), .b:has(.y)", ":host-context(.dark):has(.x)", ".b:has(.y)"); + lowered(noHas, "a:visited:has(.x), a:hover:has(.y)", "a:visited:has(.x)", "a:hover:has(.y)"); + lowered(noHas, "a:link:has(.x), a:hover:has(.y)", "a:link:has(.x)", "a:hover:has(.y)"); + lowered(noHas, "a:not(:visited):has(.x), a:hover:has(.y)", "a:not(:visited):has(.x)", "a:hover:has(.y)"); + lowered(noHas, ":-webkit-any(h1, h2) c:has(i), d e:has(i)", ":-webkit-any(h1,h2) c:has(i)", "d e:has(i)"); + lowered( + noFocusVisible, + ".a:fullscreen:hover, .b:fullscreen:focus", + ".a:-webkit-full-screen:hover", + ".a:fullscreen:hover", + ".b:-webkit-full-screen:focus", + ".b:fullscreen:focus", + ); + minify_test( + "@namespace svg url(http://www.w3.org/2000/svg); svg|a:has(.y), a:has(.x) { color: red }", + '@namespace svg "http://www.w3.org/2000/svg";svg|a:has(.y){color:red}a:has(.x){color:red}', + noHas, + ); + + // `&` weighs as much as the selector list of the parent rule. Two selectors weigh the same + // only if both use `&` the same way. + minify_test( + ".p { & .a:has(.x), & .b:has(.x) { color: red } }", + ":is(.p .a:has(.x),.p .b:has(.x)){color:red}", + noHas, + ); + minify_test(".p { .a:has(&), .b:has(&) { color: red } }", ":is(.a:has(.p),.b:has(.p)){color:red}", noHas); + minify_test( + ".p { :where(&) .a:has(.x), :where(&) .b:has(.x) { color: red } }", + ":is(:where(.p) .a:has(.x),:where(.p) .b:has(.x)){color:red}", + noHas, + ); + minify_test(".p { &:has(.x), &:has(#y) { color: red } }", ".p:has(.x){color:red}.p:has(#y){color:red}", noHas); + minify_test(".p { & &:has(.x), &:has(.x) { color: red } }", ".p .p:has(.x){color:red}.p:has(.x){color:red}", noHas); + minify_test( + ".item { & + &:has(.x), &:has(.y) { color: red } }", + ".item+.item:has(.x){color:red}.item:has(.y){color:red}", + noHas, + ); + minify_test( + ".p { :is(&) .k a:has(.x), :is(&, .x) a:has(.x) { color: red } }", + ".p .k a:has(.x){color:red}:is(.p,.x) a:has(.x){color:red}", + noHas, + ); + + // The same decisions where the browser resolves `&`. + minify_test( + ".p { .a:user-valid, .b:user-valid { color: red } }", + ".p{:is(& .a:user-valid,& .b:user-valid){color:red}}", + nativeNesting, + ); + minify_test( + ".p { & &:user-valid, &:user-valid { color: red } }", + ".p{& &:user-valid{color:red}&:user-valid{color:red}}", + nativeNesting, + ); + minify_test( + ".p { & .a:has(.x), & .b:has(.x) { color: red } }", + ".p{:is(& .a:has(.x),& .b:has(.x)){color:red}}", + nativeNestingNoHas, + ); + minify_test( + ".p { &:has(.x), &:has(#y) { color: red } }", + ".p{&:has(.x){color:red}&:has(#y){color:red}}", + nativeNestingNoHas, + ); + + // In `@scope`, each selector of a list is relative to the scoping root. An `:is()` argument + // is not. + minify_test( + "@scope (.card) { .a .x:has(i), .b .y:has(i) { color: red } }", + "@scope(.card){.a .x:has(i){color:red}.b .y:has(i){color:red}}", + noHas, + ); + minify_test( + "@scope (.card) { .p { .a:has(i), .b:has(i) { color: red } } }", + "@scope(.card){.p .a:has(i){color:red}.p .b:has(i){color:red}}", + noHas, + ); + minify_test(":root::view-transition {position: fixed}", ":root::view-transition{position:fixed}"); for (const name of [ diff --git a/test/js/bun/css/nested-selector-list-expansion.test.ts b/test/js/bun/css/nested-selector-list-expansion.test.ts index d4faa3c18a61..fa03d11fe825 100644 --- a/test/js/bun/css/nested-selector-list-expansion.test.ts +++ b/test/js/bun/css/nested-selector-list-expansion.test.ts @@ -115,6 +115,14 @@ test("collapsed :is() lists still hit the limit when nesting has to be compiled expect(() => minifyTest(src, "", { chrome: 100 << 16 })).toThrow(LIMIT_ERROR); }); +test("incompatible selector lists that cannot collapse into :is() hit the limit when nesting is preserved", () => { + // `:is()` cannot hold `::part()`, so each list is split into one rule per + // selector, each with a clone of every nested rule. The limit has to count + // that split even though nesting stays native. + const src = nestedRules("x::part(a):user-valid, y z:user-valid", 17); + expect(() => minifyTest(src, "", MODERN_TARGETS)).toThrow(LIMIT_ERROR); +}); + test("bun build reports an error instead of exploding on deeply nested multi-selector css", async () => { using dir = tempDir("css-nested-selector-expansion", { "input.css": nestedRules("co :is(.bar), .bar :is(.baz)", 17), diff --git a/test/js/bun/css/nested-vendor-prefix-duplication.test.ts b/test/js/bun/css/nested-vendor-prefix-duplication.test.ts index 4978530ce5d2..636cf9f6b31d 100644 --- a/test/js/bun/css/nested-vendor-prefix-duplication.test.ts +++ b/test/js/bun/css/nested-vendor-prefix-duplication.test.ts @@ -160,9 +160,16 @@ test("the fuzzer reproduction shape errors instead of amplifying", () => { }); test("nesting-capable targets also bound the mixed vendor-prefix expansion", () => { - // Modern targets preserve nesting (no de-nesting), so the same per-prefix - // re-serialization of the body applies and must be bounded too. - expect(() => minifyTest(nestedMixedPrefix(20), "", { chrome: 130 << 16 })).toThrow(VENDOR_PREFIX_LIMIT_ERROR); + // Modern targets preserve nesting (no de-nesting). With browser targets, a + // selector with a prefixed pseudo-class never shares an `:is()` with another + // selector, so each level splits the list into one rule per selector, each + // with a copy of the nested rules. The selector-expansion limit bounds that. + expect(() => minifyTest(nestedMixedPrefix(20), "", { chrome: 130 << 16 })).toThrow( + "Nested CSS rules expand to more than", + ); + expect(minifyTest(nestedMixedPrefix(1), "", { chrome: 130 << 16 })).toBe( + ".a:placeholder-shown .x{color:red}.b:-webkit-autofill .y{color:red}", + ); }); test("shallow mixed vendor-prefix nesting still minifies with both prefix variants", () => { diff --git a/test/js/bun/css/util.ts b/test/js/bun/css/util.ts index 69694f0adcef..50b8f32e36da 100644 --- a/test/js/bun/css/util.ts +++ b/test/js/bun/css/util.ts @@ -47,9 +47,10 @@ export function minify_error_test_with_options(source: string, expectedError: st }); } -export function minify_test(source: string, expected: string) { +export function minify_test(source: string, expected: string, targets?: Browsers) { test(source, () => { - expect(minifyTestWithOptions(source, expected)).toEqual(expected); + const output = targets ? minifyTest(source, expected, targets) : minifyTestWithOptions(source, expected); + expect(output).toEqual(expected); }); } From 5e07d79f092ba7db4461f37a35a85e8f3fd69a31 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:33:21 +0000 Subject: [PATCH 2/5] css: keep split selector lists and nested lists correct around the :is() wrap - A rule whose selectors all move to their own rules prints nothing, so it no longer gets `@supports` and logical-property rules with an empty selector. The rule of each selector already gets its own copies. - The `@nest` arm budgets its selector list as written. That list is never wrapped or split, so with nesting preserved nothing multiplies. - `:where()` arguments count for the wrap decision, except for their weight. A host inside `:is()` or `:where()` is still a host subject. - With nesting compiled away, the printer writes the parent selector in place of `&`. A nested list is now wrapped only if the parent selectors can go inside `:is()` too: no pseudo-element, no component that `inside_is` refuses, and no `&` subject under a shadow host parent. The minifier passes a `ListPlacement` down with each rule list: whether the list is inside `@scope`, and the chain of parent selector lists that the printer writes in place of `&` (the printer's own `StyleContext`). `can_wrap_in_is` reads the chain only for a list that is otherwise a wrap candidate. It replaces the `in_scope_rule` field of `MinifyContext`. --- src/css/css_parser.rs | 7 +- src/css/rules/mod.rs | 65 ++++++++------- src/css/rules/style.rs | 34 +++++--- src/css/rules/supports.rs | 3 +- src/css/selectors/selector.rs | 61 +++++++++++--- test/js/bun/css/css.test.ts | 81 +++++++++++++++++++ .../nested-selector-list-expansion.test.ts | 9 +++ .../nested-vendor-prefix-duplication.test.ts | 8 ++ 8 files changed, 218 insertions(+), 50 deletions(-) diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index f8971bfc91ec..2528e96361ff 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2407,10 +2407,13 @@ mod stylesheet_impl { err: None, selector_expansion_multiplier: 1, selector_expansion_total: 0, - in_scope_rule: false, }; - if self.rules.minify(&mut minify_ctx, false).is_err() { + if self + .rules + .minify(&mut minify_ctx, false, Default::default()) + .is_err() + { // Rule-level minify signals failure with the unit `MinifyErr` // and records the diagnostic out-of-band on the context. debug_assert!(minify_ctx.err.is_some()); diff --git a/src/css/rules/mod.rs b/src/css/rules/mod.rs index 04ab500b2fbe..cfa59784aebb 100644 --- a/src/css/rules/mod.rs +++ b/src/css/rules/mod.rs @@ -392,11 +392,12 @@ impl media::MediaRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, + placement: css::selector::ListPlacement<'_>, ) -> Result where R: for<'b> css::generics::DeepClone<'b>, { - self.rules.minify(context, parent_is_unused)?; + self.rules.minify(context, parent_is_unused, placement)?; Ok(self.rules.v.is_empty() || self.query.never_matches()) } } @@ -488,6 +489,7 @@ impl CssRuleList { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, + placement: css::selector::ListPlacement<'_>, ) -> Result<(), MinifyErr> where R: for<'b> css::generics::DeepClone<'b>, @@ -518,10 +520,10 @@ impl CssRuleList { && last_rule.query.eql(&med.query) { last_rule.rules.v.append(&mut med.rules.v); - let _ = last_rule.minify(context, parent_is_unused)?; + let _ = last_rule.minify(context, parent_is_unused, placement)?; break 'arm; } - if med.minify(context, parent_is_unused)? { + if med.minify(context, parent_is_unused, placement)? { break 'arm; } } @@ -532,7 +534,7 @@ impl CssRuleList { // Drop the duplicate-condition rule outright. break 'arm; } - supp.minify(context, parent_is_unused)?; + supp.minify(context, parent_is_unused, placement)?; if supp.rules.v.is_empty() { break 'arm; } @@ -544,10 +546,10 @@ impl CssRuleList { // `MAX_SELECTOR_EXPANSION` — otherwise an at-rule between // two nesting levels hides the inner levels from the cap // and the printer expands them exponentially. - cont.rules.minify(context, parent_is_unused)?; + cont.rules.minify(context, parent_is_unused, placement)?; } CssRule::LayerBlock(lay) => { - lay.rules.minify(context, parent_is_unused)?; + lay.rules.minify(context, parent_is_unused, placement)?; if lay.rules.v.is_empty() { break 'arm; } @@ -558,7 +560,7 @@ impl CssRuleList { CssRule::MozDocument(doc) => { // See `Container` above: recurse so nested style rules // count against the selector-expansion cap. - doc.rules.minify(context, parent_is_unused)?; + doc.rules.minify(context, parent_is_unused, placement)?; } CssRule::Style(_sty) => { minify_style_arm( @@ -568,6 +570,7 @@ impl CssRuleList { &mut merge_state, context, parent_is_unused, + placement, )?; break 'arm; } @@ -575,11 +578,11 @@ impl CssRuleList { CssRule::Scope(scpe) => { // See `Container` above: recurse so nested style rules // count against the selector-expansion cap. - let was_in_scope_rule = - core::mem::replace(&mut context.in_scope_rule, true); - let result = scpe.rules.minify(context, parent_is_unused); - context.in_scope_rule = was_in_scope_rule; - result?; + let in_scope = css::selector::ListPlacement { + in_scope_rule: true, + ..placement + }; + scpe.rules.minify(context, parent_is_unused, in_scope)?; } CssRule::Nesting(nst) => { // See `Container` above. `@nest` wraps a single style @@ -596,16 +599,18 @@ impl CssRuleList { // untouched preserves them verbatim, matching the // pre-port behavior. nst.style.charge_selector_expansion(context)?; - let lowering = nst - .style - .selector_list_lowering(context.targets, context.in_scope_rule); - nst.style - .minify_nested_rules(context, parent_is_unused, lowering)?; + // The wrapped rule prints its selector list as written, so only compiled nesting multiplies it. + nst.style.minify_nested_rules( + context, + parent_is_unused, + style::SelectorListLowering::AsWritten, + placement, + )?; } CssRule::StartingStyle(rl) => { // See `Container` above: recurse so nested style rules // count against the selector-expansion cap. - rl.rules.minify(context, parent_is_unused)?; + rl.rules.minify(context, parent_is_unused, placement)?; } CssRule::FontPaletteValues(_) => {} CssRule::Property(_) => {} @@ -659,6 +664,7 @@ fn minify_style_arm css::generics::DeepClone<'b>>( merge_state: &mut StyleRuleMergeState, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, + placement: css::selector::ListPlacement<'_>, ) -> Result<(), MinifyErr> { use css::SmallList; use css::selector::{self, Component, Selector, SelectorList}; @@ -673,15 +679,15 @@ fn minify_style_arm css::generics::DeepClone<'b>>( // If some of the selectors in this rule are not compatible with the targets, // we need to either wrap in :is() or split them into multiple rules. - let lowering = sty.selector_list_lowering(context.targets, context.in_scope_rule); - if sty.minify(context, parent_is_unused, lowering)? { + let lowering = sty.selector_list_lowering(context.targets, placement); + if sty.minify(context, parent_is_unused, lowering, placement)? { return Ok(()); } let mut incompatible: SmallList = match lowering { SelectorListLowering::AsWritten => SmallList::default(), SelectorListLowering::WrapInIs => { - debug_assert!(selector::can_wrap_in_is(sty.selectors.v.slice())); + debug_assert!(selector::can_wrap_in_is(sty.selectors.v.slice(), placement)); let component = Component::Is(core::mem::take(&mut sty.selectors.v).to_owned_slice()); let mut list = SmallList::::default(); list.append(Selector::from_component(component)); @@ -774,8 +780,15 @@ fn minify_style_arm css::generics::DeepClone<'b>>( } // Create additional rules for logical properties, @supports overrides, and incompatible selectors. - let supps = context.handler_context.get_supports_rules::(sty); - let logical = context.handler_context.get_additional_rules::(sty); + let (supps, logical) = if sty.selectors.v.is_empty() { + // The partition left this rule no selector. The rule of each selector gets its own copies below. + (Vec::new(), Vec::new()) + } else { + ( + context.handler_context.get_supports_rules::(sty), + context.handler_context.get_additional_rules::(sty), + ) + }; struct IncompatibleRuleEntry { rule: style::StyleRule, @@ -877,7 +890,7 @@ fn minify_style_arm css::generics::DeepClone<'b>>( if !logical.is_empty() { let mut log = CssRuleList { v: logical }; - log.minify(context, parent_is_unused)?; + log.minify(context, parent_is_unused, placement)?; rules.append(&mut log.v); } rules.extend(supps); @@ -888,7 +901,7 @@ fn minify_style_arm css::generics::DeepClone<'b>>( } if !entry.logical.is_empty() { let mut log = CssRuleList { v: entry.logical }; - log.minify(context, parent_is_unused)?; + log.minify(context, parent_is_unused, placement)?; rules.append(&mut log.v); } rules.extend(entry.supports); @@ -1257,6 +1270,4 @@ pub struct MinifyContext<'a, 'bump> { /// Running total of selectors that compiling nested rules for the targets /// will expand to, checked against [`MAX_SELECTOR_EXPANSION`]. pub(crate) selector_expansion_total: u32, - /// Whether the rules being minified are inside an `@scope` rule. - pub(crate) in_scope_rule: bool, } diff --git a/src/css/rules/style.rs b/src/css/rules/style.rs index 475b653f152f..d6ae4671660c 100644 --- a/src/css/rules/style.rs +++ b/src/css/rules/style.rs @@ -1,5 +1,5 @@ use crate as css; -use crate::css_rules::{CssRule, CssRuleList, Location, MinifyContext}; +use crate::css_rules::{CssRule, CssRuleList, Location, MinifyContext, StyleContext}; use crate::declaration::DeclarationBlock; use crate::error::MinifyErr; use crate::selectors::selector; @@ -84,7 +84,7 @@ impl StyleRule { pub(crate) fn selector_list_lowering( &self, targets: &css::targets::Targets, - in_scope_rule: bool, + placement: selector::ListPlacement<'_>, ) -> SelectorListLowering { let selectors = self.selectors.v.slice(); if selectors.len() <= 1 @@ -93,15 +93,14 @@ impl StyleRule { { return SelectorListLowering::AsWritten; } - // In `@scope`, each selector of a list is relative to the scoping root. An `:is()` argument is not. - if in_scope_rule || !targets.is_compatible(css::Feature::IsSelector) { + if !targets.is_compatible(css::Feature::IsSelector) { return SelectorListLowering::Partition; } // A selector that every target can parse stays outside `:is()`. let all_need_lowering = selectors .iter() .all(|one| !selector::is_compatible(core::slice::from_ref(one), targets)); - if all_need_lowering && selector::can_wrap_in_is(selectors) { + if all_need_lowering && selector::can_wrap_in_is(selectors, placement) { SelectorListLowering::WrapInIs } else { SelectorListLowering::Partition @@ -354,6 +353,7 @@ impl StyleRule { context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, lowering: SelectorListLowering, + placement: selector::ListPlacement<'_>, ) -> Result where R: for<'b> css::generics::DeepClone<'b>, @@ -408,7 +408,7 @@ impl StyleRule { context.handler_context.context = DeclarationContext::None; if self.rules.v.len() > 0 { - self.minify_nested_rules(context, unused, lowering)?; + self.minify_nested_rules(context, unused, lowering, placement)?; if unused && self.rules.v.len() == 0 { return Ok(true); } @@ -454,6 +454,7 @@ impl StyleRule { context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, lowering: SelectorListLowering, + placement: selector::ListPlacement<'_>, ) -> Result<(), MinifyErr> where R: for<'b> css::generics::DeepClone<'b>, @@ -473,20 +474,33 @@ impl StyleRule { // nesting is compiled away the printed output still fans out per // selector, which is why the nesting branch bumps unconditionally. let saved_expansion_multiplier = context.selector_expansion_multiplier; - if context.targets.should_compile_same(css::Feature::Nesting) - || lowering == SelectorListLowering::Partition - { + let compiles_nesting = context.targets.should_compile_same(css::Feature::Nesting); + if compiles_nesting || lowering == SelectorListLowering::Partition { context.selector_expansion_multiplier = context .selector_expansion_multiplier .saturating_mul(self.selectors.v.len().max(1)); } + // The printer then writes these selectors in place of `&` in the nested rules. + let nesting = StyleContext { + selectors: &self.selectors, + parent: placement.nesting, + }; + let placement = selector::ListPlacement { + nesting: if compiles_nesting { + Some(&nesting) + } else { + placement.nesting + }, + ..placement + }; + let mut handler_context = context.handler_context.child(DeclarationContext::StyleRule); core::mem::swap::>( &mut context.handler_context, &mut handler_context, ); - let result = self.rules.minify(context, parent_is_unused); + let result = self.rules.minify(context, parent_is_unused, placement); core::mem::swap::>( &mut context.handler_context, &mut handler_context, diff --git a/src/css/rules/supports.rs b/src/css/rules/supports.rs index 04c1d052d5e2..aa47e1e9a7cf 100644 --- a/src/css/rules/supports.rs +++ b/src/css/rules/supports.rs @@ -398,6 +398,7 @@ impl SupportsRule { &mut self, context: &mut MinifyContext, parent_is_unused: bool, + placement: crate::selector::ListPlacement<'_>, ) -> core::result::Result<(), MinifyErr> where R: for<'b> crate::generics::DeepClone<'b>, @@ -410,7 +411,7 @@ impl SupportsRule { // behind it multiply against the enclosing nesting levels exactly like // plain nested rules — leaving them unvisited here lets the printer // expand them exponentially. - self.rules.minify(context, parent_is_unused) + self.rules.minify(context, parent_is_unused, placement) } } diff --git a/src/css/selectors/selector.rs b/src/css/selectors/selector.rs index 006a38a8d608..6ab009b51aaa 100644 --- a/src/css/selectors/selector.rs +++ b/src/css/selectors/selector.rs @@ -492,15 +492,26 @@ pub(crate) fn is_compatible(selectors: &[parser::Selector], targets: &Targets) - true } +/// Where a selector list is in the style sheet, as far as an `:is()` around the list is concerned. +#[derive(Clone, Copy, Default)] +pub(crate) struct ListPlacement<'a> { + /// The list is inside `@scope`. There each selector of a list is relative to the scoping root, and an `:is()` argument is not. + pub(crate) in_scope_rule: bool, + /// The selector lists that the printer writes in place of `&`, innermost first. + pub(crate) nesting: Option<&'a StyleContext<'a>>, +} + /// Whether `:is(selectors)` matches the same elements with the same specificity as the selector list. -pub(crate) fn can_wrap_in_is(selectors: &[parser::Selector]) -> bool { +pub(crate) fn can_wrap_in_is(selectors: &[parser::Selector], placement: ListPlacement<'_>) -> bool { let Some(first) = selectors.first() else { return true; }; // `:is()` cannot hold a pseudo-element, and it takes the specificity of its most specific argument. - selectors.iter().all(|selector| { - !selector.has_pseudo_element() && selector.specificity() == first.specificity() - }) && components_allow_is(selectors) + !placement.in_scope_rule + && selectors.iter().all(|selector| { + !selector.has_pseudo_element() && selector.specificity() == first.specificity() + }) + && components_allow_is(selectors, placement.nesting) } /// What the specificity and flags stored at parse time do not say about a component inside `:is()`. @@ -597,9 +608,13 @@ fn inside_is(component: &Component) -> InsideIs { Component::NthOf(nth) => arguments_inside_is(&nth.selectors), Component::Host(Some(selector)) => arguments_inside_is(core::slice::from_ref(selector)), - // `:where()` weighs nothing, whatever its arguments are. - Component::Where(_) - | Component::Host(None) + // `:where()` weighs nothing, so an argument of unknown weight does not count. + Component::Where(selectors) => match arguments_inside_is(selectors) { + InsideIs::Never => InsideIs::Never, + InsideIs::Allowed | InsideIs::IfShared => InsideIs::Allowed, + }, + + Component::Host(None) | Component::Combinator(_) | Component::DefaultNamespace(_) | Component::ExplicitUniversalType @@ -633,7 +648,7 @@ fn arguments_inside_is(selectors: &[parser::Selector]) -> InsideIs { } // Chrome 124 and Firefox 128 do not match a shadow host that is the subject of one of several `:is()` arguments. -fn subject_is_shadow_host(selector: &parser::Selector) -> bool { +fn subject_is_shadow_host(selector: &parser::Selector, nesting_is_shadow_host: bool) -> bool { selector .components .iter() @@ -643,14 +658,40 @@ fn subject_is_shadow_host(selector: &parser::Selector) -> bool { Component::NonTsPseudoClass(PseudoClass::CustomFunction { name, .. }) => { bun_core::strings::eql_case_insensitive_ascii_check_length(name, b"host-context") } + Component::Nesting => nesting_is_shadow_host, + // The printer writes an `:is()` of one argument as that argument, so its subject is the subject here. + Component::Is(selectors) | Component::Where(selectors) => selectors + .iter() + .any(|selector| subject_is_shadow_host(selector, nesting_is_shadow_host)), _ => false, }) } +// `None` if a selector that the printer writes in place of `&` cannot go inside `:is()`, else whether its subject is a shadow host. +fn nesting_inside_is(nesting: Option<&StyleContext<'_>>) -> Option { + let Some(context) = nesting else { + return Some(false); + }; + let outer_is_shadow_host = nesting_inside_is(context.parent)?; + let selectors = context.selectors.v.slice(); + if matches!(arguments_inside_is(selectors), InsideIs::Never) { + return None; + } + Some( + selectors + .iter() + .any(|selector| subject_is_shadow_host(selector, outer_is_shadow_host)), + ) +} + /// Whether no selector has a `Never` component and all of them have the same `IfShared` components. #[cold] #[inline(never)] -fn components_allow_is(selectors: &[parser::Selector]) -> bool { +fn components_allow_is(selectors: &[parser::Selector], nesting: Option<&StyleContext<'_>>) -> bool { + let Some(nesting_is_shadow_host) = nesting_inside_is(nesting) else { + return false; + }; + fn next<'a>( components: &mut core::slice::Iter<'a, Component>, ) -> Option<(&'a Component, InsideIs)> { @@ -675,7 +716,7 @@ fn components_allow_is(selectors: &[parser::Selector]) -> bool { return true; }; for selector in selectors { - if subject_is_shadow_host(selector) || !alike(previous, selector) { + if subject_is_shadow_host(selector, nesting_is_shadow_host) || !alike(previous, selector) { return false; } previous = selector; diff --git a/test/js/bun/css/css.test.ts b/test/js/bun/css/css.test.ts index 8e47cc6d0099..8f1e0f7e366f 100644 --- a/test/js/bun/css/css.test.ts +++ b/test/js/bun/css/css.test.ts @@ -5781,6 +5781,7 @@ describe("css tests", () => { ":host(.dark) .a:has(.k), :host(.dark) .b:has(.x)", ":is(:host(.dark) .a:has(.k),:host(.dark) .b:has(.x))", ); + lowered(noHas, ":where(:state(x)) .a:has(.x), .b:has(.x)", ":is(:where(:state(x)) .a:has(.x),.b:has(.x))"); // A selector that every target can parse stays outside `:is()`. lowered(noFocusVisible, ".a:hover, .b:focus-visible", ".a:hover", ".b:focus-visible"); @@ -5866,6 +5867,13 @@ describe("css tests", () => { ".k.d:has(.c)", ); lowered(noHas, ":host-context(.dark):has(.x), .b:has(.y)", ":host-context(.dark):has(.x)", ".b:has(.y)"); + lowered(noHas, ":is(:host(.a)):has(.x), :is(:host(.b)):has(.y)", ":host(.a):has(.x)", ":host(.b):has(.y)"); + lowered( + noHas, + ":where(:host(.a)):has(.x), :where(:host(.b)):has(.y)", + ":where(:host(.a)):has(.x)", + ":where(:host(.b)):has(.y)", + ); lowered(noHas, "a:visited:has(.x), a:hover:has(.y)", "a:visited:has(.x)", "a:hover:has(.y)"); lowered(noHas, "a:link:has(.x), a:hover:has(.y)", "a:link:has(.x)", "a:hover:has(.y)"); lowered(noHas, "a:not(:visited):has(.x), a:hover:has(.y)", "a:not(:visited):has(.x)", "a:hover:has(.y)"); @@ -5878,12 +5886,31 @@ describe("css tests", () => { ".b:-webkit-full-screen:focus", ".b:fullscreen:focus", ); + lowered( + noFocusVisible, + ":where(:fullscreen) .a:focus-visible, :where(:fullscreen) .b:focus-visible", + ":where(:-webkit-full-screen) .a:focus-visible", + ":where(:fullscreen) .a:focus-visible", + ":where(:-webkit-full-screen) .b:focus-visible", + ":where(:fullscreen) .b:focus-visible", + ); minify_test( "@namespace svg url(http://www.w3.org/2000/svg); svg|a:has(.y), a:has(.x) { color: red }", '@namespace svg "http://www.w3.org/2000/svg";svg|a:has(.y){color:red}a:has(.x){color:red}', noHas, ); + // A rule whose selectors all move to their own rules prints nothing itself, so it gets no + // `@supports` rule for the color fallback either. + minify_test( + ".a:has(.x), .b.c:has(.y) { box-shadow: var(--w) 12px lab(40% 56.6 39) }", + ".a:has(.x){box-shadow:var(--w)12px #b32323}" + + "@supports (color:lab(0% 0 0)){.a:has(.x){box-shadow:var(--w)12px lab(40% 56.6 39)}}" + + ".b.c:has(.y){box-shadow:var(--w)12px #b32323}" + + "@supports (color:lab(0% 0 0)){.b.c:has(.y){box-shadow:var(--w)12px lab(40% 56.6 39)}}", + noHas, + ); + // `&` weighs as much as the selector list of the parent rule. Two selectors weigh the same // only if both use `&` the same way. minify_test( @@ -5910,6 +5937,55 @@ describe("css tests", () => { noHas, ); + // With nesting compiled away, the printer writes the parent selector in place of `&`. The + // nested list then goes inside `:is()` only if the parent selector can. + minify_test(".p { &:has(.x), &:has(.y) { color: red } }", ":is(.p:has(.x),.p:has(.y)){color:red}", noHas); + minify_test( + "x-el::part(input) { &:user-valid, &:user-invalid { color: red } }", + "x-el::part(input):user-valid{color:red}x-el::part(input):user-invalid{color:red}", + noHasInFirefox, + ); + minify_test( + "a:visited { &:has(.x), &:has(.y) { color: red } }", + "a:visited:has(.x){color:red}a:visited:has(.y){color:red}", + noHas, + ); + minify_test( + "a:visited { .k { @media (min-width: 1px) { &:has(.x), &:has(.y) { color: red } } } }", + "@media (min-width:1px){a:visited .k:has(.x){color:red}a:visited .k:has(.y){color:red}}", + noHas, + ); + minify_test( + ".a:fullscreen { .x:has(i), .y:has(i) { color: red } }", + ".a:fullscreen .x:has(i){color:red}.a:fullscreen .y:has(i){color:red}", + noHas, + ); + minify_test( + ".p { @nest a:visited & { &:has(.x), &:has(.y) { color: red } } }", + "a:visited .p:has(.x){color:red}a:visited .p:has(.y){color:red}", + noHas, + ); + minify_test( + ":host(.a) { &:has(.x), &:has(.y) { color: red } }", + ":host(.a):has(.x){color:red}:host(.a):has(.y){color:red}", + noHas, + ); + minify_test( + ":host { &:hover { &:has(.x), &:has(.y) { color: red } } }", + ":host:hover:has(.x){color:red}:host:hover:has(.y){color:red}", + noHas, + ); + minify_test( + ":host(.a) { .x:has(i), .y:has(i) { color: red } }", + ":is(:host(.a) .x:has(i),:host(.a) .y:has(i)){color:red}", + noHas, + ); + minify_test( + ":host { .k { &:has(.x), &:has(.y) { color: red } } }", + ":is(:host .k:has(.x),:host .k:has(.y)){color:red}", + noHas, + ); + // The same decisions where the browser resolves `&`. minify_test( ".p { .a:user-valid, .b:user-valid { color: red } }", @@ -5931,6 +6007,11 @@ describe("css tests", () => { ".p{&:has(.x){color:red}&:has(#y){color:red}}", nativeNestingNoHas, ); + minify_test( + "x-el::part(a) { &:user-valid, &:user-invalid { color: red } }", + "x-el::part(a){:is(&:user-valid,&:user-invalid){color:red}}", + nativeNesting, + ); // In `@scope`, each selector of a list is relative to the scoping root. An `:is()` argument // is not. diff --git a/test/js/bun/css/nested-selector-list-expansion.test.ts b/test/js/bun/css/nested-selector-list-expansion.test.ts index fa03d11fe825..43fc9e32eab6 100644 --- a/test/js/bun/css/nested-selector-list-expansion.test.ts +++ b/test/js/bun/css/nested-selector-list-expansion.test.ts @@ -123,6 +123,15 @@ test("incompatible selector lists that cannot collapse into :is() hit the limit expect(() => minifyTest(src, "", MODERN_TARGETS)).toThrow(LIMIT_ERROR); }); +test("@nest selector lists are not charged for a split when nesting is preserved", () => { + // An `@nest` rule prints its selector list as written. With native nesting + // nothing multiplies, so 20 levels stay linear and no limit applies. + const src = ".p {\n" + "@nest & .a, & .b:user-valid {\n".repeat(20) + "color: red;\n" + "}\n".repeat(21); + const out = minifyTest(src, "", MODERN_TARGETS); + expect(out).toContain("color:red"); + expect(out.length).toBeLessThan(10_000); +}); + test("bun build reports an error instead of exploding on deeply nested multi-selector css", async () => { using dir = tempDir("css-nested-selector-expansion", { "input.css": nestedRules("co :is(.bar), .bar :is(.baz)", 17), diff --git a/test/js/bun/css/nested-vendor-prefix-duplication.test.ts b/test/js/bun/css/nested-vendor-prefix-duplication.test.ts index 636cf9f6b31d..14dbc84c107e 100644 --- a/test/js/bun/css/nested-vendor-prefix-duplication.test.ts +++ b/test/js/bun/css/nested-vendor-prefix-duplication.test.ts @@ -172,6 +172,14 @@ test("nesting-capable targets also bound the mixed vendor-prefix expansion", () ); }); +test("nesting-capable targets bound the vendor-prefix expansion of a single selector", () => { + // One selector with both an unprefixed and a `-webkit-` pseudo-class is + // printed once per prefix, and no selector list is involved. With nesting + // preserved, every level doubles the copies of the body. + const src = ".a:placeholder-shown:-webkit-autofill {\n".repeat(20) + "color: red;\n" + "}\n".repeat(20); + expect(() => minifyTest(src, "", { chrome: 130 << 16 })).toThrow(VENDOR_PREFIX_LIMIT_ERROR); +}); + test("shallow mixed vendor-prefix nesting still minifies with both prefix variants", () => { // Below the limit, the rule is still emitted once per prefix variant — the // expansion is correct and necessary, just bounded. From 86b1f7e49cb6191c5292af8120ccb2c4e910cfd6 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 25 Oct 2026 05:26:45 +0000 Subject: [PATCH 3/5] css: never wrap a selector list in :is() When a target cannot parse one selector of a list, the minifier no longer prints the whole list as one `:is(list)` selector. Each such selector moves to its own copy of the rule, as it already does for targets that have no `:is()`. One `:is(list)` is not the same rule as the list. A pseudo-element inside `:is()` matches nothing, and every selector takes the specificity of the most specific one. The earlier commits of this branch kept the wrap behind a classifier of these cases, which kept growing in review (`:visited` in WebKit, shadow host subjects, vendor prefix passes, parent selectors of nested rules, `@scope`). On a corpus of 490 stylesheets the guarded wrap still applied to 40 of about 12,700 selector lists at the targets of #40369. - `StyleRule::splits_selectors` is computed once per rule. `minify_style_arm` acts on it and the nested-rule budget reads the same value, so the second `is_compatible` walk is gone. - The `@nest` arm passes `false`. That rule prints its selector list as written, so with nesting preserved nothing multiplies. - `any_has_pseudo_element`, `specifities_all_equal` and the two `has_pseudo_element` accessors have no reader left. --- src/css/css_parser.rs | 6 +- src/css/rules/mod.rs | 95 +++--- src/css/rules/style.rs | 79 +---- src/css/rules/supports.rs | 3 +- src/css/selectors/parser.rs | 15 +- src/css/selectors/selector.rs | 232 --------------- test/bundler/css/css-modules.test.ts | 45 +-- test/js/bun/css/css.test.ts | 275 ++++-------------- .../nested-selector-list-expansion.test.ts | 41 +-- .../nested-vendor-prefix-duplication.test.ts | 8 +- 10 files changed, 118 insertions(+), 681 deletions(-) diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index 2528e96361ff..54f041ba317d 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2409,11 +2409,7 @@ mod stylesheet_impl { selector_expansion_total: 0, }; - if self - .rules - .minify(&mut minify_ctx, false, Default::default()) - .is_err() - { + if self.rules.minify(&mut minify_ctx, false).is_err() { // Rule-level minify signals failure with the unit `MinifyErr` // and records the diagnostic out-of-band on the context. debug_assert!(minify_ctx.err.is_some()); diff --git a/src/css/rules/mod.rs b/src/css/rules/mod.rs index cfa59784aebb..33b62a483c1f 100644 --- a/src/css/rules/mod.rs +++ b/src/css/rules/mod.rs @@ -392,12 +392,11 @@ impl media::MediaRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, - placement: css::selector::ListPlacement<'_>, ) -> Result where R: for<'b> css::generics::DeepClone<'b>, { - self.rules.minify(context, parent_is_unused, placement)?; + self.rules.minify(context, parent_is_unused)?; Ok(self.rules.v.is_empty() || self.query.never_matches()) } } @@ -489,7 +488,6 @@ impl CssRuleList { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, - placement: css::selector::ListPlacement<'_>, ) -> Result<(), MinifyErr> where R: for<'b> css::generics::DeepClone<'b>, @@ -520,10 +518,10 @@ impl CssRuleList { && last_rule.query.eql(&med.query) { last_rule.rules.v.append(&mut med.rules.v); - let _ = last_rule.minify(context, parent_is_unused, placement)?; + let _ = last_rule.minify(context, parent_is_unused)?; break 'arm; } - if med.minify(context, parent_is_unused, placement)? { + if med.minify(context, parent_is_unused)? { break 'arm; } } @@ -534,7 +532,7 @@ impl CssRuleList { // Drop the duplicate-condition rule outright. break 'arm; } - supp.minify(context, parent_is_unused, placement)?; + supp.minify(context, parent_is_unused)?; if supp.rules.v.is_empty() { break 'arm; } @@ -546,10 +544,10 @@ impl CssRuleList { // `MAX_SELECTOR_EXPANSION` — otherwise an at-rule between // two nesting levels hides the inner levels from the cap // and the printer expands them exponentially. - cont.rules.minify(context, parent_is_unused, placement)?; + cont.rules.minify(context, parent_is_unused)?; } CssRule::LayerBlock(lay) => { - lay.rules.minify(context, parent_is_unused, placement)?; + lay.rules.minify(context, parent_is_unused)?; if lay.rules.v.is_empty() { break 'arm; } @@ -560,7 +558,7 @@ impl CssRuleList { CssRule::MozDocument(doc) => { // See `Container` above: recurse so nested style rules // count against the selector-expansion cap. - doc.rules.minify(context, parent_is_unused, placement)?; + doc.rules.minify(context, parent_is_unused)?; } CssRule::Style(_sty) => { minify_style_arm( @@ -570,7 +568,6 @@ impl CssRuleList { &mut merge_state, context, parent_is_unused, - placement, )?; break 'arm; } @@ -578,11 +575,7 @@ impl CssRuleList { CssRule::Scope(scpe) => { // See `Container` above: recurse so nested style rules // count against the selector-expansion cap. - let in_scope = css::selector::ListPlacement { - in_scope_rule: true, - ..placement - }; - scpe.rules.minify(context, parent_is_unused, in_scope)?; + scpe.rules.minify(context, parent_is_unused)?; } CssRule::Nesting(nst) => { // See `Container` above. `@nest` wraps a single style @@ -600,17 +593,17 @@ impl CssRuleList { // pre-port behavior. nst.style.charge_selector_expansion(context)?; // The wrapped rule prints its selector list as written, so only compiled nesting multiplies it. + let splits_selectors = false; nst.style.minify_nested_rules( context, parent_is_unused, - style::SelectorListLowering::AsWritten, - placement, + splits_selectors, )?; } CssRule::StartingStyle(rl) => { // See `Container` above: recurse so nested style rules // count against the selector-expansion cap. - rl.rules.minify(context, parent_is_unused, placement)?; + rl.rules.minify(context, parent_is_unused)?; } CssRule::FontPaletteValues(_) => {} CssRule::Property(_) => {} @@ -664,11 +657,9 @@ fn minify_style_arm css::generics::DeepClone<'b>>( merge_state: &mut StyleRuleMergeState, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, - placement: css::selector::ListPlacement<'_>, ) -> Result<(), MinifyErr> { use css::SmallList; - use css::selector::{self, Component, Selector, SelectorList}; - use style::SelectorListLowering; + use css::selector::{self, Selector, SelectorList}; let CssRule::Style(sty) = rule else { unreachable!() }; @@ -677,41 +668,28 @@ fn minify_style_arm css::generics::DeepClone<'b>>( return Ok(()); } - // If some of the selectors in this rule are not compatible with the targets, - // we need to either wrap in :is() or split them into multiple rules. - let lowering = sty.selector_list_lowering(context.targets, placement); - if sty.minify(context, parent_is_unused, lowering, placement)? { + let splits_selectors = sty.splits_selectors(context.targets); + if sty.minify(context, parent_is_unused, splits_selectors)? { return Ok(()); } - let mut incompatible: SmallList = match lowering { - SelectorListLowering::AsWritten => SmallList::default(), - SelectorListLowering::WrapInIs => { - debug_assert!(selector::can_wrap_in_is(sty.selectors.v.slice(), placement)); - let component = Component::Is(core::mem::take(&mut sty.selectors.v).to_owned_slice()); - let mut list = SmallList::::default(); - list.append(Selector::from_component(component)); - sty.selectors = SelectorList { v: list }; - SmallList::default() - } - SelectorListLowering::Partition => { - // Otherwise, partition the selectors and keep the compatible ones in this rule. - // We will generate additional rules for incompatible selectors later. - let mut incompatible = SmallList::::default(); - let mut i: u32 = 0; - while i < sty.selectors.v.len() { - if selector::is_compatible( - &sty.selectors.v.slice()[i as usize..i as usize + 1], - context.targets, - ) { - i += 1; - } else { - incompatible.append(sty.selectors.v.ordered_remove(i)); - } + // If some of the selectors in this rule are not compatible with the targets, + // we need to split them into multiple rules. + let mut incompatible = SmallList::::default(); + if splits_selectors { + // The compatible selectors stay in this rule. The rules for the incompatible ones are generated later. + let mut i: u32 = 0; + while i < sty.selectors.v.len() { + if selector::is_compatible( + &sty.selectors.v.slice()[i as usize..i as usize + 1], + context.targets, + ) { + i += 1; + } else { + incompatible.append(sty.selectors.v.ordered_remove(i)); } - incompatible } - }; + } sty.update_prefix(context); @@ -780,15 +758,8 @@ fn minify_style_arm css::generics::DeepClone<'b>>( } // Create additional rules for logical properties, @supports overrides, and incompatible selectors. - let (supps, logical) = if sty.selectors.v.is_empty() { - // The partition left this rule no selector. The rule of each selector gets its own copies below. - (Vec::new(), Vec::new()) - } else { - ( - context.handler_context.get_supports_rules::(sty), - context.handler_context.get_additional_rules::(sty), - ) - }; + let supps = context.handler_context.get_supports_rules::(sty); + let logical = context.handler_context.get_additional_rules::(sty); struct IncompatibleRuleEntry { rule: style::StyleRule, @@ -890,7 +861,7 @@ fn minify_style_arm css::generics::DeepClone<'b>>( if !logical.is_empty() { let mut log = CssRuleList { v: logical }; - log.minify(context, parent_is_unused, placement)?; + log.minify(context, parent_is_unused)?; rules.append(&mut log.v); } rules.extend(supps); @@ -901,7 +872,7 @@ fn minify_style_arm css::generics::DeepClone<'b>>( } if !entry.logical.is_empty() { let mut log = CssRuleList { v: entry.logical }; - log.minify(context, parent_is_unused, placement)?; + log.minify(context, parent_is_unused)?; rules.append(&mut log.v); } rules.extend(entry.supports); diff --git a/src/css/rules/style.rs b/src/css/rules/style.rs index d6ae4671660c..660412c7dc24 100644 --- a/src/css/rules/style.rs +++ b/src/css/rules/style.rs @@ -1,5 +1,5 @@ use crate as css; -use crate::css_rules::{CssRule, CssRuleList, Location, MinifyContext, StyleContext}; +use crate::css_rules::{CssRule, CssRuleList, Location, MinifyContext}; use crate::declaration::DeclarationBlock; use crate::error::MinifyErr; use crate::selectors::selector; @@ -31,17 +31,6 @@ impl StyleRule { } } -/// How a selector list is printed for targets that may not parse all of its selectors. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum SelectorListLowering { - /// The targets can parse every selector, so the list stays as written. - AsWritten, - /// The list becomes the single selector `:is(list)`, which ignores what a browser cannot parse. - WrapInIs, - /// Each selector that the targets cannot parse moves to its own copy of the rule. - Partition, -} - // ─── behavior bodies ────────────────────────────────────────────────────── impl StyleRule { /// Returns a hash of this rule for use when deduplicating. @@ -80,31 +69,11 @@ impl StyleRule { selector::is_compatible(self.selectors.v.slice(), targets) } - /// `minify_style_arm` acts on this verdict, and `minify_nested_rules` budgets for the same one. - pub(crate) fn selector_list_lowering( - &self, - targets: &css::targets::Targets, - placement: selector::ListPlacement<'_>, - ) -> SelectorListLowering { - let selectors = self.selectors.v.slice(); - if selectors.len() <= 1 - || !targets.should_compile_selectors() - || selector::is_compatible(selectors, targets) - { - return SelectorListLowering::AsWritten; - } - if !targets.is_compatible(css::Feature::IsSelector) { - return SelectorListLowering::Partition; - } - // A selector that every target can parse stays outside `:is()`. - let all_need_lowering = selectors - .iter() - .all(|one| !selector::is_compatible(core::slice::from_ref(one), targets)); - if all_need_lowering && selector::can_wrap_in_is(selectors, placement) { - SelectorListLowering::WrapInIs - } else { - SelectorListLowering::Partition - } + /// Whether each selector that a target cannot parse moves to its own copy of the rule. One `:is(list)` instead would change what the selectors match and weigh. + pub(crate) fn splits_selectors(&self, targets: &css::targets::Targets) -> bool { + self.selectors.v.len() > 1 + && targets.should_compile_selectors() + && !self.is_compatible(targets) } } @@ -352,8 +321,7 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, - lowering: SelectorListLowering, - placement: selector::ListPlacement<'_>, + splits_selectors: bool, ) -> Result where R: for<'b> css::generics::DeepClone<'b>, @@ -408,7 +376,7 @@ impl StyleRule { context.handler_context.context = DeclarationContext::None; if self.rules.v.len() > 0 { - self.minify_nested_rules(context, unused, lowering, placement)?; + self.minify_nested_rules(context, unused, splits_selectors)?; if unused && self.rules.v.len() == 0 { return Ok(true); } @@ -453,8 +421,7 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, - lowering: SelectorListLowering, - placement: selector::ListPlacement<'_>, + splits_selectors: bool, ) -> Result<(), MinifyErr> where R: for<'b> css::generics::DeepClone<'b>, @@ -464,43 +431,19 @@ impl StyleRule { // When the targets require compiling nesting away (or splitting this // rule's selectors for compatibility), each of this rule's selectors // multiplies the expansion of every nested rule. - // - // `lowering` is the verdict that `minify_style_arm` acts on - // (rules/mod.rs): an incompatible selector list is either collapsed - // into a single `:is()` selector (nothing cloned) or partitioned - // into one cloned rule per selector (fan-out = selector count). - // Only the partition case multiplies on its own — but the `:is()` - // wrap keeps one `&` reference per original selector, so when - // nesting is compiled away the printed output still fans out per - // selector, which is why the nesting branch bumps unconditionally. let saved_expansion_multiplier = context.selector_expansion_multiplier; - let compiles_nesting = context.targets.should_compile_same(css::Feature::Nesting); - if compiles_nesting || lowering == SelectorListLowering::Partition { + if context.targets.should_compile_same(css::Feature::Nesting) || splits_selectors { context.selector_expansion_multiplier = context .selector_expansion_multiplier .saturating_mul(self.selectors.v.len().max(1)); } - // The printer then writes these selectors in place of `&` in the nested rules. - let nesting = StyleContext { - selectors: &self.selectors, - parent: placement.nesting, - }; - let placement = selector::ListPlacement { - nesting: if compiles_nesting { - Some(&nesting) - } else { - placement.nesting - }, - ..placement - }; - let mut handler_context = context.handler_context.child(DeclarationContext::StyleRule); core::mem::swap::>( &mut context.handler_context, &mut handler_context, ); - let result = self.rules.minify(context, parent_is_unused, placement); + let result = self.rules.minify(context, parent_is_unused); core::mem::swap::>( &mut context.handler_context, &mut handler_context, diff --git a/src/css/rules/supports.rs b/src/css/rules/supports.rs index aa47e1e9a7cf..04c1d052d5e2 100644 --- a/src/css/rules/supports.rs +++ b/src/css/rules/supports.rs @@ -398,7 +398,6 @@ impl SupportsRule { &mut self, context: &mut MinifyContext, parent_is_unused: bool, - placement: crate::selector::ListPlacement<'_>, ) -> core::result::Result<(), MinifyErr> where R: for<'b> crate::generics::DeepClone<'b>, @@ -411,7 +410,7 @@ impl SupportsRule { // behind it multiply against the enclosing nesting levels exactly like // plain nested rules — leaving them unvisited here lets the printer // expand them exponentially. - self.rules.minify(context, parent_is_unused, placement) + self.rules.minify(context, parent_is_unused) } } diff --git a/src/css/selectors/parser.rs b/src/css/selectors/parser.rs index a3bed0036185..958266176040 100644 --- a/src/css/selectors/parser.rs +++ b/src/css/selectors/parser.rs @@ -498,7 +498,7 @@ fn compute_simple_selector_specificity( } specificity.add(Specificity::from_u32(max)); } - C::Negation(_) | C::Is(_) | C::Has(_) | C::Any { .. } => { + C::Negation(_) | C::Is(_) | C::Any { .. } => { // https://drafts.csswg.org/selectors/#specificity-rules: // // The specificity of an :is() pseudo-class is replaced by the @@ -507,8 +507,6 @@ fn compute_simple_selector_specificity( let list: &[GenericSelector] = match simple_selector { C::Negation(list) => list, C::Is(list) => list, - // Selectors 4 weighs :has() like :is(). lightningcss does not: parcel-bundler/lightningcss#1324 - C::Has(list) => list, C::Any { selectors, .. } => selectors, _ => unreachable!(), }; @@ -519,6 +517,7 @@ fn compute_simple_selector_specificity( specificity.add(Specificity::from_u32(max)); } C::Where(_) + | C::Has(_) | C::ExplicitUniversalType | C::ExplicitAnyNamespace | C::ExplicitNoNamespace @@ -1821,10 +1820,6 @@ impl GenericSelector { false } - pub(crate) fn has_pseudo_element(&self) -> bool { - self.specificity_and_flags.has_pseudo_element() - } - /// Returns count of simple selectors and combinators in the Selector. pub(crate) fn len(&self) -> usize { self.components.len() @@ -2668,12 +2663,6 @@ pub struct SpecificityAndFlags { } impl SpecificityAndFlags { - /// `::part()` and `::slotted()` are pseudo-elements too, and the parser gives each its own flag. - pub(crate) fn has_pseudo_element(self) -> bool { - self.flags.intersects( - SelectorFlags::HAS_PSEUDO | SelectorFlags::HAS_SLOTTED | SelectorFlags::HAS_PART, - ) - } pub(crate) fn hash(self, hasher: &mut Wyhash) { hasher.update(&self.specificity.to_ne_bytes()); hasher.update(&[self.flags.bits()]); diff --git a/src/css/selectors/selector.rs b/src/css/selectors/selector.rs index 6ab009b51aaa..f4900a75e939 100644 --- a/src/css/selectors/selector.rs +++ b/src/css/selectors/selector.rs @@ -492,238 +492,6 @@ pub(crate) fn is_compatible(selectors: &[parser::Selector], targets: &Targets) - true } -/// Where a selector list is in the style sheet, as far as an `:is()` around the list is concerned. -#[derive(Clone, Copy, Default)] -pub(crate) struct ListPlacement<'a> { - /// The list is inside `@scope`. There each selector of a list is relative to the scoping root, and an `:is()` argument is not. - pub(crate) in_scope_rule: bool, - /// The selector lists that the printer writes in place of `&`, innermost first. - pub(crate) nesting: Option<&'a StyleContext<'a>>, -} - -/// Whether `:is(selectors)` matches the same elements with the same specificity as the selector list. -pub(crate) fn can_wrap_in_is(selectors: &[parser::Selector], placement: ListPlacement<'_>) -> bool { - let Some(first) = selectors.first() else { - return true; - }; - // `:is()` cannot hold a pseudo-element, and it takes the specificity of its most specific argument. - !placement.in_scope_rule - && selectors.iter().all(|selector| { - !selector.has_pseudo_element() && selector.specificity() == first.specificity() - }) - && components_allow_is(selectors, placement.nesting) -} - -/// What the specificity and flags stored at parse time do not say about a component inside `:is()`. -enum InsideIs { - /// It matches inside `:is()`, and the stored specificity counts it as it prints. - Allowed, - /// Its weight is not known at parse time, so every selector of the list must have the same one. - IfShared, - /// It does not match, weigh or print inside `:is()` as it does outside. - Never, -} - -fn inside_is(component: &Component) -> InsideIs { - match component { - Component::NonTsPseudoClass(pseudo_class) => match pseudo_class { - // WebKit never matches `:visited` inside `:is()`, and there `:link` matches visited links too. - PseudoClass::Visited | PseudoClass::Link => InsideIs::Never, - - // A vendor prefix pass prints the `:is()` around them as `:-webkit-any()` or `:-moz-any()`. - PseudoClass::Fullscreen(_) - | PseudoClass::AnyLink(_) - | PseudoClass::ReadOnly(_) - | PseudoClass::ReadWrite(_) - | PseudoClass::PlaceholderShown(_) - | PseudoClass::Autofill(_) => InsideIs::Never, - - // CSS modules `:local()` and `:global()` print as their argument, which can end in a pseudo-element. - PseudoClass::Local { .. } | PseudoClass::Global { .. } => InsideIs::Never, - - // An unknown function weighs what its argument means. - PseudoClass::CustomFunction { .. } => InsideIs::IfShared, - - PseudoClass::Lang { .. } - | PseudoClass::Dir { .. } - | PseudoClass::Hover - | PseudoClass::Active - | PseudoClass::Focus - | PseudoClass::FocusVisible - | PseudoClass::FocusWithin - | PseudoClass::Current - | PseudoClass::Past - | PseudoClass::Future - | PseudoClass::Playing - | PseudoClass::Paused - | PseudoClass::Seeking - | PseudoClass::Buffering - | PseudoClass::Stalled - | PseudoClass::Muted - | PseudoClass::VolumeLocked - | PseudoClass::Open - | PseudoClass::Closed - | PseudoClass::Modal - | PseudoClass::PictureInPicture - | PseudoClass::PopoverOpen - | PseudoClass::Defined - | PseudoClass::LocalLink - | PseudoClass::Target - | PseudoClass::TargetWithin - | PseudoClass::Enabled - | PseudoClass::Disabled - | PseudoClass::Default - | PseudoClass::Checked - | PseudoClass::Indeterminate - | PseudoClass::Blank - | PseudoClass::Valid - | PseudoClass::Invalid - | PseudoClass::InRange - | PseudoClass::OutOfRange - | PseudoClass::Required - | PseudoClass::Optional - | PseudoClass::UserValid - | PseudoClass::UserInvalid - | PseudoClass::WebkitScrollbar(_) - | PseudoClass::Custom { .. } => InsideIs::Allowed, - }, - - // `&` weighs the selector list of the parent rule. - Component::Nesting => InsideIs::IfShared, - - // A hand-written `:-webkit-any()` prints as `:is()` here, and browsers do not weigh the two alike. - Component::Any { .. } - | Component::Slotted(_) - | Component::Part(_) - | Component::PseudoElement(_) => InsideIs::Never, - - // Under a default `@namespace`, the `:is()` itself matches only elements of that namespace. - Component::Namespace { .. } - | Component::ExplicitAnyNamespace - | Component::ExplicitNoNamespace => InsideIs::Never, - - Component::Negation(selectors) | Component::Is(selectors) | Component::Has(selectors) => { - arguments_inside_is(selectors) - } - Component::NthOf(nth) => arguments_inside_is(&nth.selectors), - Component::Host(Some(selector)) => arguments_inside_is(core::slice::from_ref(selector)), - - // `:where()` weighs nothing, so an argument of unknown weight does not count. - Component::Where(selectors) => match arguments_inside_is(selectors) { - InsideIs::Never => InsideIs::Never, - InsideIs::Allowed | InsideIs::IfShared => InsideIs::Allowed, - }, - - Component::Host(None) - | Component::Combinator(_) - | Component::DefaultNamespace(_) - | Component::ExplicitUniversalType - | Component::LocalName(_) - | Component::Id(_) - | Component::Class(_) - | Component::AttributeInNoNamespaceExists { .. } - | Component::AttributeInNoNamespace { .. } - | Component::AttributeOther(_) - | Component::Root - | Component::Empty - | Component::Scope - | Component::Nth(_) => InsideIs::Allowed, - } -} - -// The most specific argument is not known if one of them has a component of unknown weight. -fn arguments_inside_is(selectors: &[parser::Selector]) -> InsideIs { - let mut verdict = InsideIs::Allowed; - for component in selectors - .iter() - .flat_map(|selector| selector.components.iter()) - { - match inside_is(component) { - InsideIs::Allowed => {} - InsideIs::IfShared => verdict = InsideIs::IfShared, - InsideIs::Never => return InsideIs::Never, - } - } - verdict -} - -// Chrome 124 and Firefox 128 do not match a shadow host that is the subject of one of several `:is()` arguments. -fn subject_is_shadow_host(selector: &parser::Selector, nesting_is_shadow_host: bool) -> bool { - selector - .components - .iter() - .take_while(|component| !component.is_combinator()) - .any(|component| match component { - Component::Host(_) => true, - Component::NonTsPseudoClass(PseudoClass::CustomFunction { name, .. }) => { - bun_core::strings::eql_case_insensitive_ascii_check_length(name, b"host-context") - } - Component::Nesting => nesting_is_shadow_host, - // The printer writes an `:is()` of one argument as that argument, so its subject is the subject here. - Component::Is(selectors) | Component::Where(selectors) => selectors - .iter() - .any(|selector| subject_is_shadow_host(selector, nesting_is_shadow_host)), - _ => false, - }) -} - -// `None` if a selector that the printer writes in place of `&` cannot go inside `:is()`, else whether its subject is a shadow host. -fn nesting_inside_is(nesting: Option<&StyleContext<'_>>) -> Option { - let Some(context) = nesting else { - return Some(false); - }; - let outer_is_shadow_host = nesting_inside_is(context.parent)?; - let selectors = context.selectors.v.slice(); - if matches!(arguments_inside_is(selectors), InsideIs::Never) { - return None; - } - Some( - selectors - .iter() - .any(|selector| subject_is_shadow_host(selector, outer_is_shadow_host)), - ) -} - -/// Whether no selector has a `Never` component and all of them have the same `IfShared` components. -#[cold] -#[inline(never)] -fn components_allow_is(selectors: &[parser::Selector], nesting: Option<&StyleContext<'_>>) -> bool { - let Some(nesting_is_shadow_host) = nesting_inside_is(nesting) else { - return false; - }; - - fn next<'a>( - components: &mut core::slice::Iter<'a, Component>, - ) -> Option<(&'a Component, InsideIs)> { - components - .map(|component| (component, inside_is(component))) - .find(|(_, verdict)| !matches!(verdict, InsideIs::Allowed)) - } - - fn alike(a: &parser::Selector, b: &parser::Selector) -> bool { - let (mut a, mut b) = (a.components.iter(), b.components.iter()); - loop { - match (next(&mut a), next(&mut b)) { - (None, None) => return true, - (Some((x, InsideIs::IfShared)), Some((y, InsideIs::IfShared))) if x.eql(y) => {} - _ => return false, - } - } - } - - // Each selector is compared with the one before it, and the first with the last. - let Some(mut previous) = selectors.last() else { - return true; - }; - for selector in selectors { - if subject_is_shadow_host(selector, nesting_is_shadow_host) || !alike(previous, selector) { - return false; - } - previous = selector; - } - true -} - /// Determines whether a selector list contains only unused selectors. /// A selector is considered unused if it contains a class or id component that exists in the set of unused symbols. pub(crate) fn is_unused( diff --git a/test/bundler/css/css-modules.test.ts b/test/bundler/css/css-modules.test.ts index 9d631446b3b8..849065706a6c 100644 --- a/test/bundler/css/css-modules.test.ts +++ b/test/bundler/css/css-modules.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, isASAN, isDebug, tempDir } from "harness"; +import { bunEnv, bunExe, tempDir } from "harness"; import { join } from "node:path"; import { itBundled } from "../expectBundled"; @@ -656,49 +656,6 @@ test("css-module/NoBundleHashesByRelativePath", async () => { expect(hashA).not.toBe(hashB); }); -// `:global()` and `:local()` print as their argument, which can end in a -// pseudo-element and has a specificity of its own. So a selector list with one -// of them must not become one `:is(list)` selector for targets that have -// `:is()` and lack `:has()`. The first rule has neither and must become one: it -// shows that the targets apply. Browser targets reach a CSS module only through -// the `BUN_DEBUG_CSS_TARGET_*` variables, which debug and ASAN builds read. -test.skipIf(!isDebug && !isASAN)("css-module/GlobalSelectorListIsNotWrappedInIs", async () => { - using dir = tempDir("css-module-global-list", { - "styles.module.css": ` - .a:has(.k), .b:has(.k) { color: pink } - .x :global(.y::before), .x:has(.z) { color: red } - :global(x-el::part(a)), .y:has(.q) { color: green } - :global(.dark) .c:has(.k), :global(.dark) .d:has(.k) { color: teal } - :local(.e::after), :local(.f) { color: navy } - `, - }); - await using proc = Bun.spawn({ - cmd: [bunExe(), "build", "styles.module.css", "--minify", "--outdir", "out"], - env: { ...bunEnv, BUN_DEBUG_CSS_TARGET_chrome: "100 << 16" }, - cwd: String(dir), - stdout: "pipe", - stderr: "pipe", - }); - const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stderr).toBe(""); - const css = await Bun.file(`${dir}/out/styles.module.css`).text(); - const hash = css.match(/\.x_([A-Za-z0-9_-]+) /)?.[1]; - expect(css.trim()).toBe( - [ - `:is(.a_${hash}:has(.k_${hash}),.b_${hash}:has(.k_${hash})){color:pink}`, - `.x_${hash} .y:before{color:red}`, - `.x_${hash}:has(.z_${hash}){color:red}`, - `x-el::part(a){color:green}`, - `.y_${hash}:has(.q_${hash}){color:green}`, - `.dark .c_${hash}:has(.k_${hash}){color:teal}`, - `.dark .d_${hash}:has(.k_${hash}){color:teal}`, - `.e_${hash}:after{color:navy}`, - `.f_${hash}{color:navy}`, - ].join(""), - ); - expect(exitCode).toBe(0); -}); - test("a resolve error in CSS covers the whole url() and composes path", async () => { using dir = tempDir("css-resolve-error-range", { "a.module.css": [ diff --git a/test/js/bun/css/css.test.ts b/test/js/bun/css/css.test.ts index 8f1e0f7e366f..74e2d17c67bd 100644 --- a/test/js/bun/css/css.test.ts +++ b/test/js/bun/css/css.test.ts @@ -5752,12 +5752,11 @@ describe("css tests", () => { minify_test(":host(:hover) {color: red}", ":host(:hover){color:red}"); minify_test("::slotted(:hover) {color: red}", "::slotted(:hover){color:red}"); - // A browser drops a rule when it cannot parse one selector of the list. For targets that - // cannot parse every selector, the minifier prints one `:is(list)` selector or moves each - // unsupported selector to its own rule. `lowered` takes the list and the selectors of the - // rules that it must print. + // A browser drops a rule when it cannot parse one selector of the list. So each selector + // that a target cannot parse moves to its own rule. The minifier does not print one + // `:is(list)` for such a list: a pseudo-element inside `:is()` matches nothing, and every + // selector would weigh as much as the most specific one. const noHas = { chrome: 100 << 16 }; - const noFocusVisible = { safari: 15 << 16 }; const noHasInFirefox = { chrome: 111 << 16, edge: 111 << 16, @@ -5766,264 +5765,88 @@ describe("css tests", () => { ios_saf: (16 << 16) | (4 << 8), }; const nativeNesting = { chrome: 130 << 16 }; - const nativeNestingNoHas = { firefox: 118 << 16 }; - const lowered = (targets: Browsers, list: string, ...rules: string[]) => + const split = (targets: Browsers, list: string, ...rules: string[]) => minify_test(`${list} { color: red }`, rules.map(rule => `${rule}{color:red}`).join(""), targets); - // Every selector needs the lowering, and all of them weigh the same. - lowered(noHas, "a:has(.x), b:has(.x)", ":is(a:has(.x),b:has(.x))"); - lowered(noHas, ".b:has(.x), .c:has(.x), .d:has(.x)", ":is(.b:has(.x),.c:has(.x),.d:has(.x))"); - lowered(noHas, ".a:has(> .x), .b:has(.x)", ":is(.a:has(>.x),.b:has(.x))"); - lowered(noHas, ".a:has(.x.y), .b.c:has(.z)", ":is(.a:has(.x.y),.b.c:has(.z))"); - lowered(noHas, ":state(a) .x:has(i), :state(a) .y:has(i)", ":is(:state(a) .x:has(i),:state(a) .y:has(i))"); - lowered( - noHas, - ":host(.dark) .a:has(.k), :host(.dark) .b:has(.x)", - ":is(:host(.dark) .a:has(.k),:host(.dark) .b:has(.x))", - ); - lowered(noHas, ":where(:state(x)) .a:has(.x), .b:has(.x)", ":is(:where(:state(x)) .a:has(.x),.b:has(.x))"); - - // A selector that every target can parse stays outside `:is()`. - lowered(noFocusVisible, ".a:hover, .b:focus-visible", ".a:hover", ".b:focus-visible"); - lowered(noHas, ".a.b, .c:has(.x)", ".a.b", ".c:has(.x)"); - lowered(noHas, ".a, .b:has(.x), .c:has(.x)", ".a", ".b:has(.x)", ".c:has(.x)"); - lowered(noHas, ".b:has(.x), .a, .c:has(.x)", ".a", ".b:has(.x)", ".c:has(.x)"); - lowered(noHas, ".b:has(.x), .c:has(.x), .a", ".a", ".b:has(.x)", ".c:has(.x)"); - lowered( - noHasInFirefox, - ":root, :root:has(input.theme-controller[value=light]:checked), [data-theme=light]", - ":root,[data-theme=light]", - ":root:has(input.theme-controller[value=light]:checked)", - ); - - // `:is()` cannot hold a pseudo-element. - lowered(noHas, "a::before, b:has(.x)", "a:before", "b:has(.x)"); - lowered(noHas, "x-el::part(a), y-el z-el:has(q-el)", "x-el::part(a)", "y-el z-el:has(q-el)"); - lowered(noHas, "::slotted(.x), i.c:has(.q)", "::slotted(.x)", "i.c:has(.q)"); - lowered( + split(noHas, "x-el::part(a), y-el z-el:has(q-el)", "x-el::part(a)", "y-el z-el:has(q-el)"); + split(noHas, "::slotted(.x), i.c:has(.q)", "::slotted(.x)", "i.c:has(.q)"); + split(noHas, ".a, .b:has(.x)", ".a", ".b:has(.x)"); + split(noHas, ".a:has(.x), .a:has(#y)", ".a:has(.x)", ".a:has(#y)"); + split(noHas, ".a:has(.x), .a:has(.x.y.z)", ".a:has(.x)", ".a:has(.x.y.z)"); + split(noHas, "a:has(.x), b:has(.x)", "a:has(.x)", "b:has(.x)"); + split(noHas, ":host(.a):has(.x), :host(.b):has(.y)", ":host(.a):has(.x)", ":host(.b):has(.y)"); + split(noHas, "a:visited:has(.x), a:hover:has(.y)", "a:visited:has(.x)", "a:hover:has(.y)"); + split(noHasInFirefox, ":has(.a), :has(.c)", ":has(.a)", ":has(.c)"); + split( nativeNesting, "x-el::part(a):user-valid, y-el z-el:user-valid", "x-el::part(a):user-valid", "y-el z-el:user-valid", ); - lowered( - nativeNesting, - "y-el z-el:user-valid, x-el::part(a):user-valid, w-el v-el:user-valid", - "y-el z-el:user-valid", - "x-el::part(a):user-valid", - "w-el v-el:user-valid", - ); - - // `:is()` takes the specificity of its most specific argument, and so does `:has()`. - lowered(noHas, ".a:has(.x), .a:has(#y)", ".a:has(.x)", ".a:has(#y)"); - lowered(noHas, ".a:has(.x), .a:has(.x.y.z)", ".a:has(.x)", ".a:has(.x.y.z)"); - lowered(noHas, ".a:not(:has(.x)), .b:not(:has(#y))", ".a:not(:has(.x))", ".b:not(:has(#y))"); - lowered(noHas, "li:has(> hr), li:has(> .divider)", "li:has(>hr)", "li:has(>.divider)"); - lowered(noHas, ".a:has(#y), .b:has(.x), .c:has(.x)", ".a:has(#y)", ".b:has(.x)", ".c:has(.x)"); - lowered(noHas, ".b:has(.x), .a:has(#y), .c:has(.x)", ".b:has(.x)", ".a:has(#y)", ".c:has(.x)"); - lowered(noHas, ".b:has(.x), .c:has(.x), .a:has(#y)", ".b:has(.x)", ".c:has(.x)", ".a:has(#y)"); - - // An unknown functional pseudo-class weighs what its argument means. All selectors of the - // list must have the same ones. - lowered(noHas, ":state(a) .x:has(i), :state(b) .y:has(i)", ":state(a) .x:has(i)", ":state(b) .y:has(i)"); - lowered( - noHas, - ":state(b) .z:has(i), :state(a) .x:has(i), :state(a) .y:has(i)", - ":state(b) .z:has(i)", - ":state(a) .x:has(i)", - ":state(a) .y:has(i)", - ); - lowered( - noHas, - ":state(a) .x:has(i), :state(b) .z:has(i), :state(a) .y:has(i)", - ":state(a) .x:has(i)", - ":state(b) .z:has(i)", - ":state(a) .y:has(i)", - ); - lowered( - noHas, - ":state(a) .x:has(i), :state(a) .y:has(i), :state(b) .z:has(i)", - ":state(a) .x:has(i)", - ":state(a) .y:has(i)", - ":state(b) .z:has(i)", - ); - lowered(noHas, ".a:not(:state(x)):has(i), .b.k:has(i)", ".a:not(:state(x)):has(i)", ".b.k:has(i)"); - lowered( - noHas, - ".a:nth-child(2 of :state(x)):has(i), .b.k.m:has(i)", - ".a:nth-child(2 of :state(x)):has(i)", - ".b.k.m:has(i)", - ); - // These do not match, weigh or print inside `:is()` as they do outside: a shadow host that - // is the subject, `:visited` and `:link`, `:-webkit-any()`, a pseudo-class with a vendor - // prefix pass, and a namespace. - lowered(noHas, ":host(.a):has(.x), :host(.b):has(.y)", ":host(.a):has(.x)", ":host(.b):has(.y)"); - lowered( - noHas, - ".k.b:has(.c), :host(.a):has(.x), .k.d:has(.c)", - ".k.b:has(.c)", - ":host(.a):has(.x)", - ".k.d:has(.c)", - ); - lowered(noHas, ":host-context(.dark):has(.x), .b:has(.y)", ":host-context(.dark):has(.x)", ".b:has(.y)"); - lowered(noHas, ":is(:host(.a)):has(.x), :is(:host(.b)):has(.y)", ":host(.a):has(.x)", ":host(.b):has(.y)"); - lowered( - noHas, - ":where(:host(.a)):has(.x), :where(:host(.b)):has(.y)", - ":where(:host(.a)):has(.x)", - ":where(:host(.b)):has(.y)", - ); - lowered(noHas, "a:visited:has(.x), a:hover:has(.y)", "a:visited:has(.x)", "a:hover:has(.y)"); - lowered(noHas, "a:link:has(.x), a:hover:has(.y)", "a:link:has(.x)", "a:hover:has(.y)"); - lowered(noHas, "a:not(:visited):has(.x), a:hover:has(.y)", "a:not(:visited):has(.x)", "a:hover:has(.y)"); - lowered(noHas, ":-webkit-any(h1, h2) c:has(i), d e:has(i)", ":-webkit-any(h1,h2) c:has(i)", "d e:has(i)"); - lowered( - noFocusVisible, - ".a:fullscreen:hover, .b:fullscreen:focus", - ".a:-webkit-full-screen:hover", - ".a:fullscreen:hover", - ".b:-webkit-full-screen:focus", - ".b:fullscreen:focus", - ); - lowered( - noFocusVisible, - ":where(:fullscreen) .a:focus-visible, :where(:fullscreen) .b:focus-visible", - ":where(:-webkit-full-screen) .a:focus-visible", - ":where(:fullscreen) .a:focus-visible", - ":where(:-webkit-full-screen) .b:focus-visible", - ":where(:fullscreen) .b:focus-visible", - ); - minify_test( - "@namespace svg url(http://www.w3.org/2000/svg); svg|a:has(.y), a:has(.x) { color: red }", - '@namespace svg "http://www.w3.org/2000/svg";svg|a:has(.y){color:red}a:has(.x){color:red}', - noHas, - ); - - // A rule whose selectors all move to their own rules prints nothing itself, so it gets no - // `@supports` rule for the color fallback either. - minify_test( - ".a:has(.x), .b.c:has(.y) { box-shadow: var(--w) 12px lab(40% 56.6 39) }", - ".a:has(.x){box-shadow:var(--w)12px #b32323}" + - "@supports (color:lab(0% 0 0)){.a:has(.x){box-shadow:var(--w)12px lab(40% 56.6 39)}}" + - ".b.c:has(.y){box-shadow:var(--w)12px #b32323}" + - "@supports (color:lab(0% 0 0)){.b.c:has(.y){box-shadow:var(--w)12px lab(40% 56.6 39)}}", - noHas, + // The selectors that every target can parse stay in one rule. + split(noHas, ".b:has(.x), .a, .c:has(.y), .d", ".a,.d", ".b:has(.x)", ".c:has(.y)"); + split( + noHasInFirefox, + ":root, :root:has(input.theme-controller[value=light]:checked), [data-theme=light]", + ":root,[data-theme=light]", + ":root:has(input.theme-controller[value=light]:checked)", ); + split(noHas, ".a, .b:hover", ".a,.b:hover"); + split(noHas, ":is(.a, .b:has(.x)) .c, .d", ":is(.a,.b:has(.x)) .c,.d"); - // `&` weighs as much as the selector list of the parent rule. Two selectors weigh the same - // only if both use `&` the same way. - minify_test( - ".p { & .a:has(.x), & .b:has(.x) { color: red } }", - ":is(.p .a:has(.x),.p .b:has(.x)){color:red}", - noHas, - ); - minify_test(".p { .a:has(&), .b:has(&) { color: red } }", ":is(.a:has(.p),.b:has(.p)){color:red}", noHas); - minify_test( - ".p { :where(&) .a:has(.x), :where(&) .b:has(.x) { color: red } }", - ":is(:where(.p) .a:has(.x),:where(.p) .b:has(.x)){color:red}", - noHas, - ); + // The same in nested rules, with nesting compiled away and with native nesting. minify_test(".p { &:has(.x), &:has(#y) { color: red } }", ".p:has(.x){color:red}.p:has(#y){color:red}", noHas); - minify_test(".p { & &:has(.x), &:has(.x) { color: red } }", ".p .p:has(.x){color:red}.p:has(.x){color:red}", noHas); minify_test( - ".item { & + &:has(.x), &:has(.y) { color: red } }", - ".item+.item:has(.x){color:red}.item:has(.y){color:red}", - noHas, - ); - minify_test( - ".p { :is(&) .k a:has(.x), :is(&, .x) a:has(.x) { color: red } }", - ".p .k a:has(.x){color:red}:is(.p,.x) a:has(.x){color:red}", + ".p { & .a:has(.x), & .b:has(.x) { color: red } }", + ".p .a:has(.x){color:red}.p .b:has(.x){color:red}", noHas, ); - - // With nesting compiled away, the printer writes the parent selector in place of `&`. The - // nested list then goes inside `:is()` only if the parent selector can. - minify_test(".p { &:has(.x), &:has(.y) { color: red } }", ":is(.p:has(.x),.p:has(.y)){color:red}", noHas); minify_test( "x-el::part(input) { &:user-valid, &:user-invalid { color: red } }", "x-el::part(input):user-valid{color:red}x-el::part(input):user-invalid{color:red}", noHasInFirefox, ); minify_test( - "a:visited { &:has(.x), &:has(.y) { color: red } }", - "a:visited:has(.x){color:red}a:visited:has(.y){color:red}", - noHas, - ); - minify_test( - "a:visited { .k { @media (min-width: 1px) { &:has(.x), &:has(.y) { color: red } } } }", - "@media (min-width:1px){a:visited .k:has(.x){color:red}a:visited .k:has(.y){color:red}}", - noHas, - ); - minify_test( - ".a:fullscreen { .x:has(i), .y:has(i) { color: red } }", - ".a:fullscreen .x:has(i){color:red}.a:fullscreen .y:has(i){color:red}", - noHas, - ); - minify_test( - ".p { @nest a:visited & { &:has(.x), &:has(.y) { color: red } } }", - "a:visited .p:has(.x){color:red}a:visited .p:has(.y){color:red}", - noHas, - ); - minify_test( - ":host(.a) { &:has(.x), &:has(.y) { color: red } }", - ":host(.a):has(.x){color:red}:host(.a):has(.y){color:red}", - noHas, - ); - minify_test( - ":host { &:hover { &:has(.x), &:has(.y) { color: red } } }", - ":host:hover:has(.x){color:red}:host:hover:has(.y){color:red}", + ".a:has(.x), .b:has(.y) { color: red; .c { color: blue } }", + ".a:has(.x){color:red}.a:has(.x) .c{color:#00f}.b:has(.y){color:red}.b:has(.y) .c{color:#00f}", noHas, ); + // The nested rules of the selectors that stay come after every split rule, so the + // declarations of a split rule cannot override them. minify_test( - ":host(.a) { .x:has(i), .y:has(i) { color: red } }", - ":is(:host(.a) .x:has(i),:host(.a) .y:has(i)){color:red}", + ".a, .b:has(.x) { color: red; .c { color: blue } }", + ".a{color:red}.b:has(.x){color:red}.b:has(.x) .c{color:#00f}.a .c{color:#00f}", noHas, ); + minify_test(".a, .b:has(.x) { .c { color: blue } }", ".b:has(.x) .c{color:#00f}.a .c{color:#00f}", noHas); minify_test( - ":host { .k { &:has(.x), &:has(.y) { color: red } } }", - ":is(:host .k:has(.x),:host .k:has(.y)){color:red}", - noHas, - ); - - // The same decisions where the browser resolves `&`. - minify_test( - ".p { .a:user-valid, .b:user-valid { color: red } }", - ".p{:is(& .a:user-valid,& .b:user-valid){color:red}}", - nativeNesting, - ); - minify_test( - ".p { & &:user-valid, &:user-valid { color: red } }", - ".p{& &:user-valid{color:red}&:user-valid{color:red}}", + ".a, .b:user-valid { color: red; .c { color: blue } }", + ".a{color:red}.b:user-valid{color:red;& .c{color:#00f}}.a{& .c{color:#00f}}", nativeNesting, ); minify_test( - ".p { & .a:has(.x), & .b:has(.x) { color: red } }", - ".p{:is(& .a:has(.x),& .b:has(.x)){color:red}}", - nativeNestingNoHas, - ); - minify_test( - ".p { &:has(.x), &:has(#y) { color: red } }", - ".p{&:has(.x){color:red}&:has(#y){color:red}}", - nativeNestingNoHas, - ); - minify_test( - "x-el::part(a) { &:user-valid, &:user-invalid { color: red } }", - "x-el::part(a){:is(&:user-valid,&:user-invalid){color:red}}", + ".p { .a:user-valid, .b:user-valid { color: red } }", + ".p{& .a:user-valid{color:red}& .b:user-valid{color:red}}", nativeNesting, ); - - // In `@scope`, each selector of a list is relative to the scoping root. An `:is()` argument - // is not. minify_test( "@scope (.card) { .a .x:has(i), .b .y:has(i) { color: red } }", "@scope(.card){.a .x:has(i){color:red}.b .y:has(i){color:red}}", noHas, ); + + // The rules that a logical property adds for each direction are minified again, and their + // selector lists split the same way. + const rtl = "ae ar arc bcc bqi ckb dv fa glk he ku mzn nqo pnb ps sd ug ur yi" + .split(" ") + .map(language => `:lang(${language})`) + .join(","); minify_test( - "@scope (.card) { .p { .a:has(i), .b:has(i) { color: red } } }", - "@scope(.card){.p .a:has(i){color:red}.p .b:has(i){color:red}}", - noHas, + ".a, .b { border-start-start-radius: 1px }", + `.a:not(${rtl}){border-top-left-radius:1px}.b:not(${rtl}){border-top-left-radius:1px}` + + `.a:is(${rtl}){border-top-right-radius:1px}.b:is(${rtl}){border-top-right-radius:1px}`, + { chrome: 88 << 16 }, ); minify_test(":root::view-transition {position: fixed}", ":root::view-transition{position:fixed}"); diff --git a/test/js/bun/css/nested-selector-list-expansion.test.ts b/test/js/bun/css/nested-selector-list-expansion.test.ts index 43fc9e32eab6..fec54e163fdf 100644 --- a/test/js/bun/css/nested-selector-list-expansion.test.ts +++ b/test/js/bun/css/nested-selector-list-expansion.test.ts @@ -55,7 +55,7 @@ function nestedRules(selectors: string, depth: number): string { // Targets that support neither `:is()` nor CSS nesting. const OLD_TARGETS = { chrome: 80 << 16 }; -// Targets that support CSS nesting natively, so nothing needs to be expanded. +// Targets that support CSS nesting natively, so nesting is not compiled away. const MODERN_TARGETS = { chrome: 130 << 16 }; test("deeply nested multi-selector rules error instead of exploding when compiled for old targets", () => { @@ -64,9 +64,9 @@ test("deeply nested multi-selector rules error instead of exploding when compile }); test("deeply nested ::part() selector lists error instead of exploding when compiled for old targets", () => { - // ::part() can never be wrapped in :is(), so each selector is split into its - // own rule with a clone of every nested rule — the other shape of the same - // exponential blowup. + // Chrome 80 cannot parse the :is() that a compiled `&` needs, so each nested + // selector is split into its own rule with a clone of every nested rule. That + // is the other shape of the same exponential blowup. const src = nestedRules("x::part(a), y::part(b)", 17); expect(() => minifyTest(src, "", OLD_TARGETS)).toThrow(LIMIT_ERROR); }); @@ -94,35 +94,26 @@ test("deep nesting is preserved as-is for targets that support CSS nesting", () expect(out.length).toBeLessThan(10_000); }); -// `:user-valid` is treated as unsupported for every target, but the lists below -// have no pseudo-elements and equal specificity, so the minifier collapses each -// list into a single `:is(& .a:user-valid, & .b:user-valid)` selector instead -// of splitting it into cloned rules. +// `:user-valid` is treated as unsupported for every target, so each list below +// is split into one rule per selector, and each of those rules gets a clone of +// every nested rule. The minifier does not collapse such a list into a single +// `:is(& .a:user-valid, & .b:user-valid)` selector. -test("incompatible selector lists that collapse into :is() don't hit the limit when nesting is preserved", () => { - // Nothing is cloned and nesting stays native, so the output is linear and no - // limit applies — even though a per-level multiplier would naively reach 2^20. +test("incompatible selector lists hit the limit when nesting is preserved", () => { + // Nesting stays native, but the split doubles the nested rules at every level. + expect(minifyTest(nestedRules(".a:user-valid, .b:user-valid", 2), "", MODERN_TARGETS)).toBe( + ".a:user-valid{& .a:user-valid{color:red}& .b:user-valid{color:red}}" + + ".b:user-valid{& .a:user-valid{color:red}& .b:user-valid{color:red}}", + ); const src = nestedRules(".a:user-valid, .b:user-valid", 20); - const out = minifyTest(src, "", MODERN_TARGETS); - expect(out).toContain("color:red"); - expect(out.length).toBeLessThan(100_000); + expect(() => minifyTest(src, "", MODERN_TARGETS)).toThrow(LIMIT_ERROR); }); -test("collapsed :is() lists still hit the limit when nesting has to be compiled away", () => { - // The :is() wrap keeps one `&` per original selector, so compiling nesting - // away still doubles the printed selector per level (~34 MB at this depth). +test("incompatible selector lists hit the limit when nesting has to be compiled away", () => { const src = nestedRules(".a:user-valid, .b:user-valid", 20); expect(() => minifyTest(src, "", { chrome: 100 << 16 })).toThrow(LIMIT_ERROR); }); -test("incompatible selector lists that cannot collapse into :is() hit the limit when nesting is preserved", () => { - // `:is()` cannot hold `::part()`, so each list is split into one rule per - // selector, each with a clone of every nested rule. The limit has to count - // that split even though nesting stays native. - const src = nestedRules("x::part(a):user-valid, y z:user-valid", 17); - expect(() => minifyTest(src, "", MODERN_TARGETS)).toThrow(LIMIT_ERROR); -}); - test("@nest selector lists are not charged for a split when nesting is preserved", () => { // An `@nest` rule prints its selector list as written. With native nesting // nothing multiplies, so 20 levels stay linear and no limit applies. diff --git a/test/js/bun/css/nested-vendor-prefix-duplication.test.ts b/test/js/bun/css/nested-vendor-prefix-duplication.test.ts index 14dbc84c107e..a3e88dbdc55e 100644 --- a/test/js/bun/css/nested-vendor-prefix-duplication.test.ts +++ b/test/js/bun/css/nested-vendor-prefix-duplication.test.ts @@ -160,10 +160,10 @@ test("the fuzzer reproduction shape errors instead of amplifying", () => { }); test("nesting-capable targets also bound the mixed vendor-prefix expansion", () => { - // Modern targets preserve nesting (no de-nesting). With browser targets, a - // selector with a prefixed pseudo-class never shares an `:is()` with another - // selector, so each level splits the list into one rule per selector, each - // with a copy of the nested rules. The selector-expansion limit bounds that. + // Modern targets preserve nesting (no de-nesting). With browser targets, the + // `:-webkit-autofill` selector moves to its own rule at every level, and each + // rule gets a copy of the nested rules. The selector-expansion limit bounds + // that. expect(() => minifyTest(nestedMixedPrefix(20), "", { chrome: 130 << 16 })).toThrow( "Nested CSS rules expand to more than", ); From 647e5d8d1fdae323f7d543f0237d3c05583f3d60 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:57:08 +0000 Subject: [PATCH 4/5] ci: retrigger From 5105baf57a041695c217e56cb448550f5b4951bd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:17:28 +0000 Subject: [PATCH 5/5] css: charge a split selector list for the rules it prints With native nesting, a selector list that is split prints one rule for the selectors that every target can parse and one rule for each other selector. Each of those rules gets a copy of the nested rules. The selector-expansion budget multiplied by the number of selectors instead, so `.a.b, .c.d, .e.f, .g.h, .i:user-valid` nested 7 deep at chrome 130 reported the limit for 6,984 bytes of output. `StyleRule::split_rule_count` replaces `splits_selectors`. It returns the number of rules, and `minify_nested_rules` multiplies by it when nesting is preserved. With nesting compiled away the factor stays the number of selectors, because the printer repeats every nested selector for each of them. --- src/css/rules/mod.rs | 10 ++--- src/css/rules/style.rs | 41 +++++++++++-------- .../nested-selector-list-expansion.test.ts | 12 ++++++ 3 files changed, 42 insertions(+), 21 deletions(-) diff --git a/src/css/rules/mod.rs b/src/css/rules/mod.rs index 33b62a483c1f..4bd39565b398 100644 --- a/src/css/rules/mod.rs +++ b/src/css/rules/mod.rs @@ -593,11 +593,11 @@ impl CssRuleList { // pre-port behavior. nst.style.charge_selector_expansion(context)?; // The wrapped rule prints its selector list as written, so only compiled nesting multiplies it. - let splits_selectors = false; + let split_rule_count = 1; nst.style.minify_nested_rules( context, parent_is_unused, - splits_selectors, + split_rule_count, )?; } CssRule::StartingStyle(rl) => { @@ -668,15 +668,15 @@ fn minify_style_arm css::generics::DeepClone<'b>>( return Ok(()); } - let splits_selectors = sty.splits_selectors(context.targets); - if sty.minify(context, parent_is_unused, splits_selectors)? { + let split_rule_count = sty.split_rule_count(context.targets); + if sty.minify(context, parent_is_unused, split_rule_count)? { return Ok(()); } // If some of the selectors in this rule are not compatible with the targets, // we need to split them into multiple rules. let mut incompatible = SmallList::::default(); - if splits_selectors { + if split_rule_count > 1 { // The compatible selectors stay in this rule. The rules for the incompatible ones are generated later. let mut i: u32 = 0; while i < sty.selectors.v.len() { diff --git a/src/css/rules/style.rs b/src/css/rules/style.rs index 660412c7dc24..343c739e7570 100644 --- a/src/css/rules/style.rs +++ b/src/css/rules/style.rs @@ -69,11 +69,20 @@ impl StyleRule { selector::is_compatible(self.selectors.v.slice(), targets) } - /// Whether each selector that a target cannot parse moves to its own copy of the rule. One `:is(list)` instead would change what the selectors match and weigh. - pub(crate) fn splits_selectors(&self, targets: &css::targets::Targets) -> bool { - self.selectors.v.len() > 1 - && targets.should_compile_selectors() - && !self.is_compatible(targets) + /// How many rules this rule prints as. Each selector that a target cannot parse moves to its own copy of the rule, because one `:is(list)` would change what the selectors match and weigh. + pub(crate) fn split_rule_count(&self, targets: &css::targets::Targets) -> u32 { + let selectors = self.selectors.v.slice(); + if selectors.len() <= 1 + || !targets.should_compile_selectors() + || self.is_compatible(targets) + { + return 1; + } + let moved = selectors + .iter() + .filter(|one| !selector::is_compatible(core::slice::from_ref(*one), targets)) + .count(); + (moved + usize::from(moved < selectors.len())) as u32 } } @@ -321,7 +330,7 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, - splits_selectors: bool, + split_rule_count: u32, ) -> Result where R: for<'b> css::generics::DeepClone<'b>, @@ -376,7 +385,7 @@ impl StyleRule { context.handler_context.context = DeclarationContext::None; if self.rules.v.len() > 0 { - self.minify_nested_rules(context, unused, splits_selectors)?; + self.minify_nested_rules(context, unused, split_rule_count)?; if unused && self.rules.v.len() == 0 { return Ok(true); } @@ -421,22 +430,22 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, - splits_selectors: bool, + split_rule_count: u32, ) -> Result<(), MinifyErr> where R: for<'b> css::generics::DeepClone<'b>, { use css::context::{DeclarationContext, PropertyHandlerContext}; - // When the targets require compiling nesting away (or splitting this - // rule's selectors for compatibility), each of this rule's selectors - // multiplies the expansion of every nested rule. + // Compiled nesting repeats every nested rule for each selector of this rule. Native nesting repeats it for each rule that the selector list is split into. let saved_expansion_multiplier = context.selector_expansion_multiplier; - if context.targets.should_compile_same(css::Feature::Nesting) || splits_selectors { - context.selector_expansion_multiplier = context - .selector_expansion_multiplier - .saturating_mul(self.selectors.v.len().max(1)); - } + let copies = if context.targets.should_compile_same(css::Feature::Nesting) { + self.selectors.v.len().max(1) + } else { + split_rule_count + }; + context.selector_expansion_multiplier = + context.selector_expansion_multiplier.saturating_mul(copies); let mut handler_context = context.handler_context.child(DeclarationContext::StyleRule); core::mem::swap::>( diff --git a/test/js/bun/css/nested-selector-list-expansion.test.ts b/test/js/bun/css/nested-selector-list-expansion.test.ts index fec54e163fdf..c23d89da85f5 100644 --- a/test/js/bun/css/nested-selector-list-expansion.test.ts +++ b/test/js/bun/css/nested-selector-list-expansion.test.ts @@ -114,6 +114,18 @@ test("incompatible selector lists hit the limit when nesting has to be compiled expect(() => minifyTest(src, "", { chrome: 100 << 16 })).toThrow(LIMIT_ERROR); }); +test("a split list is charged for the rules it prints when nesting is preserved", () => { + // The four selectors that chrome 130 can parse stay in one rule and + // `.i:user-valid` gets its own, so every level doubles the nested rules. It + // does not multiply them by five. + expect(minifyTest(nestedRules(".a.b, .c.d, .e.f, .g.h, .i:user-valid", 1), "", MODERN_TARGETS)).toBe( + ".a.b,.c.d,.e.f,.g.h{color:red}.i:user-valid{color:red}", + ); + const out = minifyTest(nestedRules(".a.b, .c.d, .e.f, .g.h, .i:user-valid", 7), "", MODERN_TARGETS); + expect(out).toContain("color:red"); + expect(out.length).toBeLessThan(10_000); +}); + test("@nest selector lists are not charged for a split when nesting is preserved", () => { // An `@nest` rule prints its selector list as written. With native nesting // nothing multiplies, so 20 levels stay linear and no limit applies.