Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 28 additions & 41 deletions src/css/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,13 @@ impl<R> CssRuleList<R> {
// 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 splits_selectors = false;
nst.style.minify_nested_rules(
context,
parent_is_unused,
splits_selectors,
)?;
}
CssRule::StartingStyle(rl) => {
// See `Container` above: recurse so nested style rules
Expand Down Expand Up @@ -653,56 +659,37 @@ fn minify_style_arm<R: for<'b> 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 splits_selectors = sty.splits_selectors(context.targets);
if sty.minify(context, parent_is_unused, splits_selectors)? {
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<Selector, 1> = 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::<Selector, 1>::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::<Selector, 1>::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::<Selector, 1>::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
}
} else {
SmallList::default()
};
}

sty.update_prefix(context);
Comment thread
robobun marked this conversation as resolved.
Resolved

Expand Down
27 changes: 10 additions & 17 deletions src/css/rules/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ impl<R> StyleRule<R> {
pub(crate) fn is_compatible(&self, targets: &css::targets::Targets) -> bool {
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)
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}

// ─── to_css ───────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -314,6 +321,7 @@ impl<R> StyleRule<R> {
&mut self,
context: &mut MinifyContext<'_, '_>,
parent_is_unused: bool,
splits_selectors: bool,
) -> Result<bool, MinifyErr>
where
R: for<'b> css::generics::DeepClone<'b>,
Expand Down Expand Up @@ -368,7 +376,7 @@ impl<R> StyleRule<R> {
context.handler_context.context = DeclarationContext::None;

if self.rules.v.len() > 0 {
self.minify_nested_rules(context, unused)?;
self.minify_nested_rules(context, unused, splits_selectors)?;
if unused && self.rules.v.len() == 0 {
return Ok(true);
}
Expand Down Expand Up @@ -413,6 +421,7 @@ impl<R> StyleRule<R> {
&mut self,
context: &mut MinifyContext<'_, '_>,
parent_is_unused: bool,
splits_selectors: bool,
) -> Result<(), MinifyErr>
where
R: for<'b> css::generics::DeepClone<'b>,
Expand All @@ -422,23 +431,7 @@ impl<R> StyleRule<R> {
// 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.
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
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand Down
32 changes: 0 additions & 32 deletions src/css/selectors/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1597,31 +1597,6 @@ impl<Impl: SelectorImpl> GenericSelectorList<Impl> {
}

impl<Impl: BunSelectorImpl> GenericSelectorList<Impl> {
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,
Expand Down Expand Up @@ -1845,10 +1820,6 @@ impl<Impl: BunSelectorImpl> GenericSelector<Impl> {
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()
Expand Down Expand Up @@ -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()]);
Expand Down
98 changes: 98 additions & 0 deletions test/js/bun/css/css.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 [
Expand Down
42 changes: 25 additions & 17 deletions test/js/bun/css/nested-selector-list-expansion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand All @@ -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);
});
Expand Down Expand Up @@ -94,27 +94,35 @@ 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("@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),
Expand Down
Loading
Loading