diff --git a/src/css/rules/mod.rs b/src/css/rules/mod.rs index 0a89042a286e..4bd39565b398 100644 --- a/src/css/rules/mod.rs +++ b/src/css/rules/mod.rs @@ -592,7 +592,13 @@ 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)?; + // The wrapped rule prints its selector list as written, so only compiled nesting multiplies it. + let split_rule_count = 1; + nst.style.minify_nested_rules( + context, + parent_is_unused, + split_rule_count, + )?; } CssRule::StartingStyle(rl) => { // See `Container` above: recurse so nested style rules @@ -653,56 +659,37 @@ fn minify_style_arm css::generics::DeepClone<'b>>( parent_is_unused: bool, ) -> Result<(), MinifyErr> { use css::SmallList; - use css::selector::{self, Component, Selector, SelectorList}; + use css::selector::{self, Selector, SelectorList}; let CssRule::Style(sty) = rule else { unreachable!() }; - if parent_is_unused || sty.minify(context, parent_is_unused)? { + if parent_is_unused { + return Ok(()); + } + + 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 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 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 { - // 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)); - } + // we need to split them into multiple rules. + let mut incompatible = SmallList::::default(); + 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() { + 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 } - } else { - SmallList::default() - }; + } sty.update_prefix(context); diff --git a/src/css/rules/style.rs b/src/css/rules/style.rs index bfc3551a87da..343c739e7570 100644 --- a/src/css/rules/style.rs +++ b/src/css/rules/style.rs @@ -68,6 +68,22 @@ impl StyleRule { pub(crate) fn is_compatible(&self, targets: &css::targets::Targets) -> bool { selector::is_compatible(self.selectors.v.slice(), 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 + } } // ─── to_css ─────────────────────────────────────────────────────────────── @@ -314,6 +330,7 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: bool, + split_rule_count: u32, ) -> Result where R: for<'b> css::generics::DeepClone<'b>, @@ -368,7 +385,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, split_rule_count)?; if unused && self.rules.v.len() == 0 { return Ok(true); } @@ -413,37 +430,22 @@ impl StyleRule { &mut self, context: &mut MinifyContext<'_, '_>, parent_is_unused: 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. - // - // Mirrors the selector-compatibility branch in `minify_style_arm` - // (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. + // 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; - 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 { - 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/src/css/selectors/parser.rs b/src/css/selectors/parser.rs index 5e8df3665529..958266176040 100644 --- a/src/css/selectors/parser.rs +++ b/src/css/selectors/parser.rs @@ -1597,31 +1597,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, @@ -1845,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() @@ -2692,9 +2663,6 @@ pub struct SpecificityAndFlags { } impl SpecificityAndFlags { - pub(crate) fn has_pseudo_element(self) -> bool { - self.flags.contains(SelectorFlags::HAS_PSEUDO) - } pub(crate) fn hash(self, hasher: &mut Wyhash) { hasher.update(&self.specificity.to_ne_bytes()); hasher.update(&[self.flags.bits()]); diff --git a/test/js/bun/css/css.test.ts b/test/js/bun/css/css.test.ts index 890ffa4dcd95..74e2d17c67bd 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,103 @@ 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. 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 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 split = (targets: Browsers, list: string, ...rules: string[]) => + minify_test(`${list} { color: red }`, rules.map(rule => `${rule}{color:red}`).join(""), targets); + + 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", + ); + + // 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"); + + // 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 { & .a:has(.x), & .b:has(.x) { color: red } }", + ".p .a:has(.x){color:red}.p .b:has(.x){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: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( + ".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( + ".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:user-valid, .b:user-valid { color: red } }", + ".p{& .a:user-valid{color:red}& .b:user-valid{color:red}}", + nativeNesting, + ); + 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( + ".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}"); 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..c23d89da85f5 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,27 +94,47 @@ 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("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. + 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 4978530ce5d2..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,9 +160,24 @@ 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, 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", + ); + expect(minifyTest(nestedMixedPrefix(1), "", { chrome: 130 << 16 })).toBe( + ".a:placeholder-shown .x{color:red}.b:-webkit-autofill .y{color:red}", + ); +}); + +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", () => { 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); }); }