Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
6 changes: 3 additions & 3 deletions src/css/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,9 @@ pub enum PrinterErrorKind {
/// the configured targets exceeded the expansion limit.
maximum_nesting_expansion,
/// Serializing a style rule once per vendor prefix re-serializes its whole
/// body in every pass, so nesting vendor-prefixed multi-selector rules
/// expands the output multiplicatively with depth. The total bytes emitted
/// by those duplicate passes exceeded the expansion limit.
/// body in every pass when nesting is preserved, so nesting vendor-prefixed
/// multi-selector rules expands the output multiplicatively with depth. The
/// total bytes emitted by the duplicate passes exceeded the expansion limit.
Comment thread
robobun marked this conversation as resolved.
Resolved
maximum_vendor_prefix_expansion,
no_import_records,
}
Expand Down
19 changes: 8 additions & 11 deletions src/css/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,6 @@ pub struct Printer<'a> {
pub(crate) minify: bool,
pub(crate) targets: Targets,
pub(crate) vendor_prefix: css::VendorPrefix,
/// True while nested rules are being re-serialized for a non-final vendor
/// prefix pass of an ancestor style rule (when nesting is compiled away).
/// Nested style rules that carry their own vendor prefixes override
/// `vendor_prefix`, so their output is identical in every ancestor pass;
/// they are skipped while this is set and emitted once in the final pass,
/// keeping the output linear in nesting depth instead of exponential.
pub(crate) skip_prefixed_nested_rules: bool,
pub(crate) in_calc: bool,
pub(crate) css_module: Option<css::CssModule<'a>>,
pub(crate) dependencies: Option<BumpVec<'a, css::Dependency>>,
Expand All @@ -152,8 +145,8 @@ pub struct Printer<'a> {
/// mixing `:-webkit-autofill` with an unprefixed pseudo-class, or a single
/// pseudo downleveled to several prefixes) is serialized once per prefix,
/// and every pass after the first re-serializes the rule's whole body —
/// declarations, nested rules, and everything under them. Nesting such
/// rules repeats that body once per prefix at every level, so the output
/// declarations and, when nesting is preserved, nested rules. Nesting such
/// rules then repeats that body once per prefix at every level, so it
Comment thread
robobun marked this conversation as resolved.
Resolved
/// grows by (prefix count)^depth. The bytes written by each such duplicate
/// pass are measured and accumulated here (across the whole stylesheet,
/// never reset) and bounded in `StyleRule::to_css`, so a few kilobytes of
Expand Down Expand Up @@ -305,7 +298,6 @@ impl<'a> Printer<'a> {
line: 0,
col: 0,
vendor_prefix: css::VendorPrefix::default(),
skip_prefixed_nested_rules: false,
in_calc: false,
css_module: None,
ctx: None,
Expand Down Expand Up @@ -798,6 +790,7 @@ impl<'a> Printer<'a> {
pub(crate) fn with_context<C, F>(
&mut self,
selectors: &css::SelectorList,
prefix_passes: css::VendorPrefix,
closure: C,
func: F,
) -> PrintResult<()>
Expand All @@ -811,7 +804,11 @@ impl<'a> Printer<'a> {
None
};

let ctx = css::StyleContext { selectors, parent };
let ctx = css::StyleContext {
selectors,
parent,
prefix_passes,
};

// `&ctx` is stack-local but the field type is `&'a StyleContext<'a>`;
// soundness relies on restoring `parent` before this frame returns.
Expand Down
27 changes: 3 additions & 24 deletions src/css/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,21 +401,6 @@ impl<R> media::MediaRule<R> {
}
}

impl<R> CssRule<R> {
/// Whether this rule is skipped while `Printer::skip_prefixed_nested_rules`
/// is set (a non-final vendor prefix pass of an ancestor style rule) and
/// emitted only in the ancestor's final pass: a style rule with its own
/// vendor prefixes overrides `Printer::vendor_prefix`, so its output is
/// identical in every ancestor pass.
fn is_deferred_to_final_prefix_pass(&self) -> bool {
match self {
CssRule::Style(style) => !style.vendor_prefix.is_empty(),
CssRule::Nesting(nesting) => !nesting.style.vendor_prefix.is_empty(),
_ => false,
}
}
}

// ─── CssRuleList::{to_css,minify,deep_clone} ──────────────────────────────

impl<R> CssRuleList<R> {
Expand All @@ -428,15 +413,6 @@ impl<R> CssRuleList<R> {
continue;
}

// While re-serializing nested rules for a non-final vendor prefix
// pass of an ancestor style rule, skip style rules that carry
// their own vendor prefixes: they override `dest.vendor_prefix`,
// so this pass would emit an exact duplicate of what the final
// pass emits.
if dest.skip_prefixed_nested_rules && rule.is_deferred_to_final_prefix_pass() {
continue;
}

// Skip @import rules if collecting dependencies.
if let CssRule::Import(import_rule) = rule
&& dest.remove_imports
Expand Down Expand Up @@ -1191,6 +1167,9 @@ pub use crate::Location;
pub struct StyleContext<'a> {
pub(crate) selectors: &'a crate::selectors::SelectorList,
pub(crate) parent: Option<&'a StyleContext<'a>>,
/// The vendor prefix passes `selectors` print in. A nested style rule
/// without passes of its own prints once per pass in this set.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) prefix_passes: crate::VendorPrefix,
}

/// Upper bound on the number of selectors that compiling nested rules away for
Expand Down
19 changes: 17 additions & 2 deletions src/css/rules/scope.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::css_rules::{CssRuleList, Location};
use crate::selectors::SelectorList;
use crate::{PrintErr, Printer};
use crate::{PrintErr, Printer, VendorPrefix};

/// A [@scope](https://drafts.csswg.org/css-cascade-6/#scope-atrule) rule.
///
Expand Down Expand Up @@ -30,6 +30,17 @@ impl<R> ScopeRule<R> {
// compiling nesting, like style rule preludes do (see
// `serialize::serialize_nesting`).
dest.nesting_expansions = 0;
// With nesting compiled away, `&` prints the parent selectors, which
// differ per vendor prefix pass. This rule prints once, so it takes the
// last pass: the unprefixed one if there is one (`FIELDS` ends with `NONE`).
Comment thread
robobun marked this conversation as resolved.
Resolved
let saved_prefix = dest.vendor_prefix;
if let Some(ctx) = dest.ctx
&& let Some(&last_pass) = VendorPrefix::FIELDS
.iter()
.rfind(|&&prefix| ctx.prefix_passes.contains(prefix))
{
dest.vendor_prefix = last_pass;
}
if let Some(scope_start) = &self.scope_start {
dest.write_char(b'(')?;
// scope_start.to_css(dest)?;
Expand All @@ -52,6 +63,7 @@ impl<R> ScopeRule<R> {
// first closure arg (no `&self` capture across `&mut dest`).
dest.with_context(
scope_start,
VendorPrefix::empty(),
scope_end,
|scope_end: &SelectorList, d: &mut Printer| -> Result<(), PrintErr> {
let ctx = d.ctx;
Expand All @@ -60,11 +72,14 @@ impl<R> ScopeRule<R> {
)?;
} else {
let ctx = dest.ctx;
return serialize_selector_list(scope_end.v.slice(), dest, ctx, false);
let result = serialize_selector_list(scope_end.v.slice(), dest, ctx, false);
dest.vendor_prefix = saved_prefix;
return result;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
dest.write_char(b')')?;
dest.whitespace()?;
}
dest.vendor_prefix = saved_prefix;
dest.write_char(b'{')?;
dest.indent();
dest.newline()?;
Expand Down
131 changes: 55 additions & 76 deletions src/css/rules/style.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate as css;
use crate::css_rules::{CssRule, CssRuleList, Location, MinifyContext};
use crate::css_rules::{CssRuleList, Location, MinifyContext};
use crate::declaration::DeclarationBlock;
use crate::error::MinifyErr;
use crate::selectors::selector;
Expand Down Expand Up @@ -79,9 +79,9 @@ impl<R> StyleRule<R> {
/// a list mixing `:-webkit-autofill` with an unprefixed pseudo-class, or a
/// single pseudo downleveled to several prefixes), `StyleRule::to_css`
/// serializes the rule once per prefix, and every pass after the first
/// re-serializes the rule's whole body — declarations, nested rules, and
/// everything under them. Nesting such rules repeats that body once per prefix
/// at every level, so the output grows by (prefix count)^depth. The bytes
/// re-serializes the rule's whole body — declarations and, when nesting is
/// preserved, nested rules. Nesting such rules then repeats that body once per
/// prefix at every level, so it grows by (prefix count)^depth. The bytes
Comment thread
robobun marked this conversation as resolved.
Resolved
/// emitted by each duplicate pass are measured and bounded, so a few kilobytes
/// of deeply nested input cannot expand into gigabytes — whatever the
/// duplicated payload is (nested rules, a large declaration block, etc.). Real
Expand All @@ -93,18 +93,29 @@ const MAX_PREFIX_EXPANSION_BYTES: usize = 64 << 20;

impl<R> StyleRule<R> {
pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> {
if self.vendor_prefix.is_empty() {
self.to_css_base(dest, true)?;
// If supported, or there are no targets, preserve nesting. Otherwise, write nested rules after parent.
let supports_nesting = self.rules.v.len() == 0
|| !css::targets::Targets::should_compile_same(&dest.targets, css::Feature::Nesting);

// With nesting compiled away, `&` prints differently in each pass of
// an ancestor, so a rule without passes of its own prints in those.
Comment thread
robobun marked this conversation as resolved.
Resolved
let passes = if self.vendor_prefix.is_empty() {
dest.ctx
.map_or(VendorPrefix::empty(), |ctx| ctx.prefix_passes)
} else {
self.vendor_prefix
};

if passes.is_empty() {
self.to_css_base(dest, supports_nesting)?;
} else {
let mut first_rule = true;
let mut emitted_first_pass = false;
let mut remaining_prefixes = self.vendor_prefix;
// `inline for (css.VendorPrefix.FIELDS) |field|` — iterate the bool fields of the
// packed struct in declared order. In Rust the bitflags type exposes the same
// ordered single-bit table directly.
for &prefix in VendorPrefix::FIELDS {
if self.vendor_prefix.contains(prefix) {
remaining_prefixes.remove(prefix);
if passes.contains(prefix) {
if !first_rule {
if !dest.minify {
dest.write_char(b'\n')?; // no indent
Expand All @@ -115,8 +126,9 @@ impl<R> StyleRule<R> {
dest.vendor_prefix = prefix;
let (line, col) = (dest.line, dest.col);
// The first prefix pass is the original; every later pass
// re-serializes the same body (declarations + nested rules),
// so its output is a duplicate produced by the fan-out.
// re-serializes the same body (declarations, and the nested
// rules when nesting is preserved), so its output is a
// duplicate produced by the fan-out.
Comment thread
robobun marked this conversation as resolved.
Resolved
// Measure how much it emits and charge it against the
// expansion-byte budget so nesting fanning-out rules can't
// expand a few kilobytes into gigabytes. The first pass
Expand All @@ -129,7 +141,7 @@ impl<R> StyleRule<R> {
} else {
0
};
self.to_css_base(dest, remaining_prefixes.is_empty())?;
self.to_css_base(dest, supports_nesting)?;
if is_duplicate_pass {
let emitted = dest.bytes_written().saturating_sub(bytes_before);
dest.prefix_expansion_bytes =
Expand All @@ -141,10 +153,9 @@ impl<R> StyleRule<R> {
);
}
}
// A non-final pass emits nothing when the rule has no
// declarations of its own and all of its nested rules are
// deferred to the final pass; don't write a separator
// after such a pass.
// A pass emits nothing when the rule has no declarations
// of its own and its nested rules print after the passes;
// don't write a separator after such a pass.
Comment thread
robobun marked this conversation as resolved.
Resolved
if dest.line != line || dest.col != col {
first_rule = false;
emitted_first_pass = true;
Expand All @@ -154,17 +165,30 @@ impl<R> StyleRule<R> {

dest.vendor_prefix = VendorPrefix::empty();
}

// Nested rules print once, after every pass. All variants of a rule
// then precede all variants of the rules after it, so a browser that
// parses only some of the variants still applies them in source order.
Comment thread
robobun marked this conversation as resolved.
Resolved
if !supports_nesting {
if !dest.minify && !self.declarations.is_empty() {
dest.write_char(b'\n')?;
dest.newline()?;
}
// `with_context` keeps the (closure-data, fn) split so the
// `Printer` reborrow lives only inside `func`.
Comment thread
robobun marked this conversation as resolved.
Resolved
dest.with_context(&self.selectors, passes, &self.rules, |rules, d| {
rules.to_css(d)
})?;
}
Ok(())
}

fn to_css_base(&self, dest: &mut Printer, is_final_prefix_pass: bool) -> Result<(), PrintErr> {
/// Prints the prelude and the declarations, and the nested rules when
/// nesting is preserved.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn to_css_base(&self, dest: &mut Printer, supports_nesting: bool) -> Result<(), PrintErr> {
use css::error::PrinterErrorKind;
use css::properties::Property;

// If supported, or there are no targets, preserve nesting. Otherwise, write nested rules after parent.
let supports_nesting = self.rules.v.len() == 0
|| !css::targets::Targets::should_compile_same(&dest.targets, css::Feature::Nesting);

let len =
self.declarations.declarations.len() + self.declarations.important_declarations.len();
let has_declarations = supports_nesting || len > 0 || self.rules.v.len() == 0;
Expand Down Expand Up @@ -246,64 +270,19 @@ impl<R> StyleRule<R> {
}
}

fn helpers_newline<R>(
self_: &StyleRule<R>,
d: &mut Printer,
supports_nesting2: bool,
len1: usize,
) -> Result<(), PrintErr> {
if !d.minify && (supports_nesting2 || len1 > 0) && self_.rules.v.len() > 0 {
if len1 > 0 {
d.write_char(b'\n')?;
if supports_nesting {
if !dest.minify && self.rules.v.len() > 0 {
if len > 0 {
dest.write_char(b'\n')?;
}
d.newline()?;
}
Ok(())
}

fn helpers_end(d: &mut Printer, has_decls: bool) -> Result<(), PrintErr> {
if has_decls {
d.dedent();
d.newline()?;
d.write_char(b'}')?;
dest.newline()?;
}
Ok(())
}

// Write nested rules after the parent.
if supports_nesting {
helpers_newline(self, dest, supports_nesting, len)?;
self.rules.to_css(dest)?;
helpers_end(dest, has_declarations)?;
} else {
// This rule is serialized once per vendor prefix, and each pass
// re-serializes the nested rules. Nested style rules that carry
// their own vendor prefixes override `dest.vendor_prefix`, so they
// produce identical output in every pass; mark non-final passes so
// they are skipped and emitted only in the final pass. Otherwise
// they would be duplicated once per ancestor prefix, which grows
// exponentially with nesting depth.
let saved_skip = dest.skip_prefixed_nested_rules;
let skip_prefixed_nested = saved_skip || !is_final_prefix_pass;
// Whether any nested rule is emitted in this pass; if not, don't
// write the separator between the declarations and the nested
// rules (nothing would follow it).
let has_nested_output = !skip_prefixed_nested
|| self.rules.v.iter().any(|rule| {
!matches!(rule, CssRule::Ignored) && !rule.is_deferred_to_final_prefix_pass()
});

helpers_end(dest, has_declarations)?;
if has_nested_output {
helpers_newline(self, dest, supports_nesting, len)?;
}
dest.skip_prefixed_nested_rules = skip_prefixed_nested;
// `with_context` keeps the (closure-data, fn) split so the
// `Printer` reborrow lives only inside `func`.
let result =
dest.with_context(&self.selectors, &self.rules, |rules, d| rules.to_css(d));
dest.skip_prefixed_nested_rules = saved_skip;
result?;
}
if has_declarations {
dest.dedent();
dest.newline()?;
dest.write_char(b'}')?;
}
Ok(())
}
Expand Down
Loading
Loading