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
94 changes: 94 additions & 0 deletions src/css/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::css_parser as css;

use css::css_rules::media::MediaRule;

use css::css_properties::PropertyId;
use css::css_properties::custom::UnparsedProperty;
use css::media_query::{MediaCondition, MediaFeature, MediaFeatureId, MediaList, MediaQuery};

Expand All @@ -16,6 +17,14 @@ pub struct SupportsEntry {

// No explicit deinit — all fields own their storage and drop automatically.

/// A property that has a copy in `PropertyHandlerContext::supports`, per importance.
struct Copied {
property_id: PropertyId,
important: bool,
/// The value of `staged` before the first of those copies.
since: u32,
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum DeclarationContext {
None,
Expand All @@ -30,6 +39,11 @@ pub struct PropertyHandlerContext<'a> {
pub(crate) targets: css::targets::Targets,
pub(crate) is_important: bool,
pub(crate) supports: Vec<SupportsEntry>,
copied: Vec<Copied>,
/// The count of declarations of the rule in hand that staged a copy in `supports`.
staged: u32,
/// Whether a later declaration dropped a copy from `supports` in the rule in hand.
pub(crate) retracted: bool,
pub(crate) ltr: Vec<css::Property>,
pub(crate) rtl: Vec<css::Property>,
pub(crate) dark: Vec<css::Property>,
Expand All @@ -48,6 +62,9 @@ impl<'a> PropertyHandlerContext<'a> {
targets: *targets,
is_important: false,
supports: Vec::new(),
copied: Vec::new(),
staged: 0,
retracted: false,
ltr: Vec::new(),
rtl: Vec::new(),
dark: Vec::new(),
Expand All @@ -62,6 +79,9 @@ impl<'a> PropertyHandlerContext<'a> {
targets: self.targets,
is_important: false,
supports: Vec::new(),
copied: Vec::new(),
staged: 0,
retracted: false,
ltr: Vec::new(),
rtl: Vec::new(),
dark: Vec::new(),
Expand Down Expand Up @@ -127,6 +147,10 @@ impl<'a> PropertyHandlerContext<'a> {
let mut dest: Vec<css::CssRule<T>> = Vec::with_capacity(self.supports.len());

for entry in &self.supports {
// An entry that lost each copy stays in place, so that the order of the rules does not change.
if entry.declarations.is_empty() && entry.important_declarations.is_empty() {
continue;
}
dest.push(css::CssRule::Supports(css::SupportsRule {
condition: entry.condition.deep_clone(self.arena),
rules: css::CssRuleList {
Expand Down Expand Up @@ -260,6 +284,9 @@ impl<'a> PropertyHandlerContext<'a> {
// Per-element `deinit()` calls dropped — Vec::clear drops each element,
// and SupportsEntry / Property own their resources via Drop.
self.supports.clear();
self.copied.clear();
self.staged = 0;
self.retracted = false;
self.ltr.clear();
self.rtl.clear();
self.dark.clear();
Expand Down Expand Up @@ -318,9 +345,13 @@ impl<'a> PropertyHandlerContext<'a> {
return;
}

if !self.supports.is_empty() {
self.retract_replaced(unparsed);
}
let fallbacks = unparsed.value.get_fallbacks(bump, &self.targets);
// `SmallList`
// has no `IntoIterator`, so spill to a Vec to preserve P3-before-LAB order.
let mut staged = false;
for condition_and_fallback in fallbacks.to_owned_slice().into_vec() {
self.add_conditional_property(
condition_and_fallback.0,
Expand All @@ -330,6 +361,69 @@ impl<'a> PropertyHandlerContext<'a> {
value: condition_and_fallback.1,
}),
);
staged = true;
}
if staged && self.context == DeclarationContext::StyleRule {
if self.copied_at(unparsed.property_id).is_none() {
self.copied.push(Copied {
property_id: unparsed.property_id,
important: self.is_important,
since: self.staged,
});
}
self.staged += 1;
}
}

fn copied_at(&self, property_id: PropertyId) -> Option<usize> {
self.copied.iter().position(|copied| {
copied.property_id == property_id && copied.important == self.is_important
})
}

/// Drops the staged copies that `unparsed` replaces in each browser that reads one. Runs before `unparsed` stages its own copies.
#[cold]
#[inline(never)]
fn retract_replaced(&mut self, unparsed: &UnparsedProperty) {
if let Some(at) = self.copied_at(unparsed.property_id)
&& unparsed.value.is_valid_at_parse_time()
{
self.retract_at(at);
}
}

/// Drops the staged copies of `property_id` that have the importance in hand.
#[cold]
#[inline(never)]
pub(crate) fn retract_conditional(&mut self, property_id: PropertyId) {
// The handlers also run over a merged rule, with no context, while the copies of the next rule are staged.
if self.context == DeclarationContext::StyleRule
&& let Some(at) = self.copied_at(property_id)
{
self.retract_at(at);
}
}

fn retract_at(&mut self, at: usize) {
// Departs from lightningcss on purpose: it prints these copies behind the rule, where they beat a later declaration that wins in the source.
let Copied {
property_id,
important,
since,
} = self.copied.swap_remove(at);
// A declaration adds at most one copy to a list, so the copies to drop are among the last `recent` of each list.
let recent = (self.staged - since) as usize;
for entry in &mut self.supports {
let copies = if important {
&mut entry.important_declarations
} else {
&mut entry.declarations
};
let from = copies.len().saturating_sub(recent);
copies
.extract_if(from.., |copy| copy.property_id() == property_id)
.for_each(drop);
}
self.retracted = true;
}
}
54 changes: 54 additions & 0 deletions src/css/properties/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,60 @@ impl TokenList {
fallbacks
}

/// Whether each browser that reads `color()` or `lab()` keeps a declaration with this value at parse time: it holds a `var()`, or is `inherit`, `initial`, `unset` or `revert`.
pub(crate) fn is_valid_at_parse_time(&self) -> bool {
if let [TokenOrValue::Token(Token::Ident(keyword))] = self.v.as_slice() {
return crate::match_ignore_ascii_case! { *keyword, {
b"inherit" | b"initial" | b"unset" | b"revert" => true,
_ => false,
}};
}
let mut has_var = false;
self.is_older_than_color(&mut has_var) && has_var
}

/// Whether the list has no `env()` and no empty `var()` fallback: Safari read `color()` before it read either.
fn is_older_than_color(&self, has_var: &mut bool) -> bool {
self.v.iter().all(|token_or_value| match token_or_value {
TokenOrValue::Var(var) => {
*has_var = true;
// The name `--` is reserved.
var.name.ident.v().len() > 2
&& var.fallback.as_ref().is_none_or(|fallback| {
fallback.is_declaration_value() && fallback.is_older_than_color(has_var)
})
}
TokenOrValue::Env(_) => false,
// `VAR()` and `ENV()` are plain functions to the parser.
TokenOrValue::Function(f) => crate::match_ignore_ascii_case! { f.name.v(), {
b"var" | b"env" => false,
_ => f.arguments.is_older_than_color(has_var),
}},
TokenOrValue::UnresolvedColor(
UnresolvedColor::RGB { alpha, .. } | UnresolvedColor::HSL { alpha, .. },
) => alpha.is_older_than_color(has_var),
TokenOrValue::UnresolvedColor(UnresolvedColor::LightDark { light, dark }) => {
light.is_older_than_color(has_var) && dark.is_older_than_color(has_var)
}
_ => true,
})
}

/// Whether the list is a `<declaration-value>`: it has a token that is not whitespace, and no `;` or `!`.
fn is_declaration_value(&self) -> bool {
let mut empty = true;
for token_or_value in &self.v {
match token_or_value {
TokenOrValue::Token(Token::Semicolon) => return false,
TokenOrValue::Token(Token::Delim(delim)) if *delim == u32::from(b'!') => {
return false;
}
_ => empty &= token_or_value.is_whitespace(),
}
}
!empty
}

// eql / hash / deep_clone — provided by `#[derive(CssEql, CssHash, DeepClone)]`.
}

Expand Down
3 changes: 3 additions & 0 deletions src/css/properties/prefix_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ impl FallbackHandler {
*$self_field = Some(dest.len());
dest.push(Property::$Variant(val));
Comment thread
robobun marked this conversation as resolved.
Resolved
} else if let Some(index) = *$self_field {
if !context.supports.is_empty() {
context.retract_conditional(property.property_id());
}
Comment thread
robobun marked this conversation as resolved.
Resolved
dest[index] = Property::$Variant(val);
} else {
// val dropped — Drop handles cleanup
Expand Down
8 changes: 8 additions & 0 deletions src/css/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,7 @@ fn minify_style_arm<R: for<'b> css::generics::DeepClone<'b>>(
});
}

let retracted = context.handler_context.retracted;
context.handler_context.reset();

// If the rule has nested rules, and we have extra rules to insert such as for logical properties,
Expand Down Expand Up @@ -894,6 +895,13 @@ fn minify_style_arm<R: for<'b> css::generics::DeepClone<'b>>(
rules.push(CssRule::Style(nested));
}

// The `@supports` rules of the dropped copies kept the next rule apart: merged into this one, its `all` and unparsed declarations move to the front (#42042, #42101).
if retracted && matches!(rules.last(), Some(CssRule::Style(_))) {
flush_pending_style_merge(rules, style_rules, merge_state, context);
merge_state.last_compat = None;
rules.push(CssRule::Ignored);
}

Ok(())
}

Expand Down
Loading
Loading