Skip to main content

fallow_extract/
css_metrics.rs

1//! Structural CSS analytics computed from the parsed CSS syntax tree.
2//!
3//! `fallow health` consumes these on demand to surface specificity hotspots,
4//! `!important` density, over-complex selectors, and deep nesting: the kind of
5//! codebase-scale structural CSS slop that per-rule linters do not aggregate.
6//! The metrics come from the same lightningcss parse used for CSS Module class
7//! extraction. Callers gate by file extension: lightningcss parses standard CSS,
8//! not Sass, so `.scss` sources are NOT passed here (with error recovery on,
9//! Sass syntax recovers into a partial, inaccurate result rather than failing).
10//! A hard parse failure yields `None`.
11
12use cssparser::{Delimiter, Parser, ParserInput, parse_important};
13use lightningcss::declaration::DeclarationBlock;
14use lightningcss::printer::PrinterOptions;
15use lightningcss::properties::animation::AnimationName;
16use lightningcss::properties::box_shadow::BoxShadow;
17use lightningcss::properties::custom::{
18    CustomProperty, CustomPropertyName, Token, TokenOrValue, UnparsedProperty, Variable,
19};
20use lightningcss::properties::font::FontFamily;
21use lightningcss::properties::grid::GridTemplateAreas;
22use lightningcss::properties::{Property, PropertyId};
23use lightningcss::rules::CssRule;
24use lightningcss::rules::font_face::FontFaceProperty;
25use lightningcss::rules::keyframes::KeyframesName;
26use lightningcss::rules::nesting::NestedDeclarationsRule;
27use lightningcss::rules::style::StyleRule;
28use lightningcss::selector::{Component, Selector};
29use lightningcss::stylesheet::{ParserOptions, StyleSheet};
30use lightningcss::traits::{Parse, ToCss};
31use lightningcss::values::color::CssColor;
32use lightningcss::visitor::{VisitTypes, Visitor};
33use rustc_hash::{FxHashMap, FxHashSet};
34
35use fallow_types::extract::{
36    CssAnalytics, CssCustomPropertyDefinition, CssDeclarationBlock, CssRawStyleValue, CssRuleMetric,
37};
38
39/// Selector component count above which a rule is considered over-complex.
40const MAX_PLAIN_COMPLEXITY: u16 = 4;
41
42/// Style-rule nesting depth at or above which a rule is recorded.
43const NOTABLE_NESTING_DEPTH: u8 = 3;
44
45/// Upper bound on per-file recorded rules. Compiled utility frameworks can emit
46/// thousands of `!important` rules; the scalar aggregates stay accurate while
47/// the per-rule finding list is capped to keep output and storage bounded.
48pub const MAX_NOTABLE_RULES: usize = 500;
49
50/// Minimum declaration count for a rule to be fingerprinted as a duplicate-block
51/// candidate. Small blocks (e.g. `display: flex; align-items: center`) repeat
52/// legitimately, so the floor keeps the signal a strong copy-paste indicator.
53const MIN_BLOCK_DECLARATIONS: usize = 4;
54
55/// Upper bound on per-file declaration-block fingerprints. The `MIN_BLOCK`
56/// floor already bounds compiled utility CSS (whose rules are tiny), so this
57/// only guards a pathological hand-written stylesheet.
58pub const MAX_DECLARATION_BLOCKS: usize = 2000;
59
60/// Upper bound on per-file located raw values. One noisy compiled stylesheet
61/// should not dominate health or audit output.
62pub const MAX_RAW_STYLE_VALUES: usize = 200;
63
64/// Mask for a single 10-bit CSS specificity component.
65const SPECIFICITY_COMPONENT_MASK: u32 = 0x3FF;
66
67/// Compute structural CSS analytics for a standard-CSS stylesheet source.
68///
69/// Returns `None` on a hard parse failure and on a stylesheet that nests
70/// brackets too deep for the parser stack; with error recovery on,
71/// individual malformed rules are skipped and the rest of the sheet still
72/// contributes. Callers must gate by extension and NOT pass `.scss` sources:
73/// Sass syntax is not standard CSS and recovers into an inaccurate partial
74/// rather than `None`. Parsing runs in CSS Modules mode so `:local()` /
75/// `:global()` selectors are understood.
76#[must_use]
77pub fn compute_css_analytics(source: &str) -> Option<CssAnalytics> {
78    crate::parse_style_bounded(source, || css_analytics_unbounded(source)).flatten()
79}
80
81fn css_analytics_unbounded(source: &str) -> Option<CssAnalytics> {
82    let options = ParserOptions {
83        error_recovery: true,
84        css_modules: Some(lightningcss::css_modules::Config::default()),
85        ..ParserOptions::default()
86    };
87    let mut stylesheet = StyleSheet::parse(source, options).ok()?;
88
89    // Pass 1: walk the rule tree for structural metrics + font-size / z-index
90    // design tokens (these are top-level declaration properties).
91    let mut acc = Accumulator::default();
92    walk_rules(&stylesheet.rules.0, 0, &mut acc);
93
94    // Pass 2: visit every color value (including colors nested inside shorthands
95    // and gradients) for the design-token-sprawl signal. The visitor needs `&mut`,
96    // so it runs after the immutable rule walk above.
97    let mut collector = ValueCollector::default();
98    let _ = collector.visit_stylesheet(&mut stylesheet);
99
100    let mut analytics = acc.analytics;
101    analytics.colors = sorted_vec(collector.colors);
102    analytics.referenced_custom_properties = sorted_vec(collector.referenced_custom_properties);
103    analytics.font_sizes = sorted_vec(acc.font_sizes);
104    analytics.z_indexes = sorted_vec(acc.z_indexes);
105    analytics.box_shadows = sorted_vec(acc.box_shadows);
106    analytics.border_radii = sorted_vec(acc.border_radii);
107    analytics.line_heights = sorted_vec(acc.line_heights);
108    analytics.defined_custom_properties = sorted_vec(acc.defined_custom_properties);
109    analytics.defined_keyframes = sorted_vec(acc.defined_keyframes);
110    analytics.referenced_keyframes = sorted_vec(acc.referenced_keyframes);
111    let mut keyframe_reference_lines: Vec<(String, u32)> =
112        acc.keyframe_reference_lines.into_iter().collect();
113    keyframe_reference_lines.sort_unstable();
114    analytics.keyframe_reference_lines = keyframe_reference_lines;
115    analytics.registered_custom_properties = sorted_vec(acc.registered_custom_properties);
116    analytics.declared_layers = sorted_vec(acc.declared_layers);
117    analytics.populated_layers = sorted_vec(acc.populated_layers);
118    analytics.defined_font_faces = sorted_vec(acc.defined_font_faces);
119    analytics.referenced_font_families = sorted_vec(acc.referenced_font_families);
120    Some(analytics)
121}
122
123/// Working accumulator threaded through the rule walk: the structural analytics
124/// plus the per-stylesheet sets of distinct `font-size` / `z-index` values.
125#[derive(Default)]
126struct Accumulator {
127    analytics: CssAnalytics,
128    font_sizes: FxHashSet<String>,
129    z_indexes: FxHashSet<String>,
130    box_shadows: FxHashSet<String>,
131    border_radii: FxHashSet<String>,
132    line_heights: FxHashSet<String>,
133    defined_custom_properties: FxHashSet<String>,
134    defined_keyframes: FxHashSet<String>,
135    referenced_keyframes: FxHashSet<String>,
136    keyframe_reference_lines: FxHashMap<String, u32>,
137    registered_custom_properties: FxHashSet<String>,
138    declared_layers: FxHashSet<String>,
139    populated_layers: FxHashSet<String>,
140    defined_font_faces: FxHashSet<String>,
141    referenced_font_families: FxHashSet<String>,
142    raw_style_value_keys: FxHashSet<String>,
143}
144
145/// The concrete family name of a `font-family` value, or `None` for a generic
146/// keyword (`serif`, `sans-serif`, `monospace`, ...), which is never an authored
147/// `@font-face`.
148fn font_family_name(family: &FontFamily<'_>) -> Option<String> {
149    match family {
150        // Render the family via ToCss and strip surrounding quotes so a declared
151        // `font-family: "Inter"` and a referenced `font-family: Inter` normalize
152        // to the same key.
153        FontFamily::FamilyName(_) => family
154            .to_css_string(PrinterOptions::default())
155            .ok()
156            .map(|s| s.trim_matches(['"', '\'']).to_string()),
157        FontFamily::Generic(_) => None,
158    }
159}
160
161/// Collects value-level design tokens via the lightningcss visitor: every
162/// distinct color (including colors nested in shorthands like `border` /
163/// `background` and gradients, not just standalone `color:` values) and every
164/// `var()` custom-property reference.
165#[derive(Default)]
166struct ValueCollector {
167    colors: FxHashSet<String>,
168    referenced_custom_properties: FxHashSet<String>,
169}
170
171impl Visitor<'_> for ValueCollector {
172    type Error = std::convert::Infallible;
173
174    fn visit_types(&self) -> VisitTypes {
175        VisitTypes::COLORS | VisitTypes::VARIABLES
176    }
177
178    fn visit_color(&mut self, color: &mut CssColor) -> Result<(), Self::Error> {
179        if let Ok(rendered) = color.to_css_string(PrinterOptions::default()) {
180            self.colors.insert(rendered);
181        }
182        Ok(())
183    }
184
185    fn visit_variable(&mut self, var: &mut Variable<'_>) -> Result<(), Self::Error> {
186        self.referenced_custom_properties
187            .insert(var.name.ident.0.to_string());
188        Ok(())
189    }
190}
191
192#[derive(Default)]
193struct FirstRgbColorCollector {
194    rgb: Option<(f64, f64, f64)>,
195}
196
197impl Visitor<'_> for FirstRgbColorCollector {
198    type Error = std::convert::Infallible;
199
200    fn visit_types(&self) -> VisitTypes {
201        VisitTypes::COLORS
202    }
203
204    fn visit_color(&mut self, color: &mut CssColor) -> Result<(), Self::Error> {
205        if self.rgb.is_none()
206            && let CssColor::RGBA(rgba) = color
207        {
208            self.rgb = Some((
209                f64::from(rgba.red),
210                f64::from(rgba.green),
211                f64::from(rgba.blue),
212            ));
213        }
214        Ok(())
215    }
216}
217
218/// Parse one CSS color value and return its sRGB channels when lightningcss can
219/// normalize it to RGB. Supports hex, named colors, rgb(), hsl(), and hwb().
220#[must_use]
221pub fn parse_css_color_rgb(value: &str) -> Option<(f64, f64, f64)> {
222    crate::parse_style_bounded(value, || css_color_rgb_unbounded(value)).flatten()
223}
224
225fn css_color_rgb_unbounded(value: &str) -> Option<(f64, f64, f64)> {
226    if let Ok(color) = CssColor::parse_string(value)
227        && let Some(rgb) = concrete_rgb(&color)
228    {
229        return Some(rgb);
230    }
231    if let Some(color) = parse_declaration_color(value)
232        && let Some(rgb) = concrete_rgb(&color)
233    {
234        return Some(rgb);
235    }
236    parse_css_color_rgb_via_stylesheet(value)
237}
238
239fn concrete_rgb(color: &CssColor) -> Option<(f64, f64, f64)> {
240    let CssColor::RGBA(rgba) = color else {
241        return None;
242    };
243    Some((
244        f64::from(rgba.red),
245        f64::from(rgba.green),
246        f64::from(rgba.blue),
247    ))
248}
249
250fn parse_declaration_color(value: &str) -> Option<CssColor> {
251    let mut input = ParserInput::new(value);
252    let mut parser = Parser::new(&mut input);
253    let color = parser
254        .parse_until_before(Delimiter::Semicolon, |input| {
255            let color = CssColor::parse(input)?;
256            let _ = input.try_parse(parse_important);
257            input.expect_exhausted()?;
258            Ok(color)
259        })
260        .ok()?;
261    if !parser.is_exhausted() {
262        parser.expect_semicolon().ok()?;
263        parser.expect_exhausted().ok()?;
264    }
265    Some(color)
266}
267
268fn parse_css_color_rgb_via_stylesheet(value: &str) -> Option<(f64, f64, f64)> {
269    let source = format!(".x{{color:{value};}}");
270    let options = ParserOptions {
271        error_recovery: true,
272        ..ParserOptions::default()
273    };
274    let mut stylesheet = StyleSheet::parse(&source, options).ok()?;
275    let mut collector = FirstRgbColorCollector::default();
276    let _ = collector.visit_stylesheet(&mut stylesheet);
277    collector.rgb
278}
279
280fn sorted_vec(set: FxHashSet<String>) -> Vec<String> {
281    let mut values: Vec<String> = set.into_iter().collect();
282    values.sort_unstable();
283    values
284}
285
286/// Recursively walk rules, tracking style-rule nesting depth. Grouping rules
287/// (`@media` / `@supports` / `@container` / `@layer {}` / `@document` /
288/// `@starting-style` / `@scope`) pass their nesting depth through unchanged;
289/// only nesting INSIDE a style rule increases the depth.
290fn walk_rules(rules: &[CssRule<'_>], depth: u8, acc: &mut Accumulator) {
291    for rule in rules {
292        match rule {
293            CssRule::Style(style) => {
294                record_style_rule(style, depth, acc);
295                walk_rules(&style.rules.0, depth.saturating_add(1), acc);
296            }
297            CssRule::Media(rule) => walk_rules(&rule.rules.0, depth, acc),
298            CssRule::Supports(rule) => walk_rules(&rule.rules.0, depth, acc),
299            CssRule::Container(rule) => walk_rules(&rule.rules.0, depth, acc),
300            CssRule::LayerBlock(rule) => {
301                // A named `@layer a { }` both declares and populates layer `a`.
302                if let Some(name) = &rule.name {
303                    let name = layer_name_string(name);
304                    acc.declared_layers.insert(name.clone());
305                    acc.populated_layers.insert(name);
306                }
307                walk_rules(&rule.rules.0, depth, acc);
308            }
309            CssRule::MozDocument(rule) => walk_rules(&rule.rules.0, depth, acc),
310            CssRule::StartingStyle(rule) => walk_rules(&rule.rules.0, depth, acc),
311            CssRule::Scope(rule) => walk_rules(&rule.rules.0, depth, acc),
312            CssRule::Nesting(rule) => {
313                record_style_rule(&rule.style, depth, acc);
314                walk_rules(&rule.style.rules.0, depth.saturating_add(1), acc);
315            }
316            _ => record_leaf_rule(rule, acc),
317        }
318    }
319}
320
321/// Record a rule that holds no nested style rules: declarations nested in a
322/// style rule, layer order, registered properties, font faces and keyframes.
323fn record_leaf_rule(rule: &CssRule<'_>, acc: &mut Accumulator) {
324    match rule {
325        CssRule::LayerStatement(stmt) => {
326            // `@layer a, b, c;` declares ordering but populates nothing.
327            for name in &stmt.names {
328                acc.declared_layers.insert(layer_name_string(name));
329            }
330        }
331        CssRule::Property(prop) => {
332            acc.registered_custom_properties
333                .insert(prop.name.0.to_string());
334        }
335        CssRule::FontFace(font_face) => {
336            for property in &font_face.properties {
337                if let FontFaceProperty::FontFamily(family) = property
338                    && let Some(name) = font_family_name(family)
339                {
340                    acc.defined_font_faces.insert(name);
341                }
342            }
343        }
344        CssRule::NestedDeclarations(nested) => record_nested_declarations(nested, acc),
345        CssRule::Keyframes(keyframes) => {
346            acc.defined_keyframes
347                .insert(keyframes_name_string(&keyframes.name));
348        }
349        _ => {}
350    }
351}
352
353fn layer_name_string(name: &lightningcss::rules::layer::LayerName<'_>) -> String {
354    name.0
355        .iter()
356        .map(std::string::ToString::to_string)
357        .collect::<Vec<_>>()
358        .join(".")
359}
360
361fn keyframes_name_string(name: &KeyframesName<'_>) -> String {
362    match name {
363        KeyframesName::Ident(ident) => ident.0.to_string(),
364        KeyframesName::Custom(value) => value.to_string(),
365    }
366}
367
368fn collect_animation_name(name: &AnimationName<'_>, out: &mut FxHashSet<String>) {
369    if let AnimationName::Ident(ident) = name {
370        out.insert(ident.0.to_string());
371    }
372}
373
374fn record_style_rule(style: &StyleRule<'_>, depth: u8, acc: &mut Accumulator) {
375    let normal = style.declarations.declarations.len();
376    let important = style.declarations.important_declarations.len();
377    let declaration_count = normal + important;
378
379    let analytics = &mut acc.analytics;
380    analytics.rule_count = analytics.rule_count.saturating_add(1);
381    analytics.total_declarations = analytics
382        .total_declarations
383        .saturating_add(saturate_u32(declaration_count));
384    analytics.important_declarations = analytics
385        .important_declarations
386        .saturating_add(saturate_u32(important));
387    if declaration_count == 0 && !has_nested_declarations(&style.rules.0) {
388        analytics.empty_rule_count = analytics.empty_rule_count.saturating_add(1);
389    }
390    analytics.max_nesting_depth = analytics.max_nesting_depth.max(depth);
391
392    let (a, b, c, complexity) = rule_selector_metrics(style);
393    let mut metric = CssRuleMetric {
394        line: style.loc.line.saturating_add(1),
395        col: style.loc.column,
396        specificity_a: a,
397        specificity_b: b,
398        specificity_c: c,
399        complexity,
400        declaration_count: saturate_u16(declaration_count),
401        important_count: saturate_u16(important),
402        nesting_depth: depth,
403        selector: String::new(),
404    };
405
406    if is_notable(&metric) {
407        if analytics.notable_rules.len() < MAX_NOTABLE_RULES {
408            metric.selector = style
409                .selectors
410                .to_css_string(PrinterOptions::default())
411                .unwrap_or_default();
412            analytics.notable_rules.push(metric);
413        } else {
414            analytics.notable_truncated = true;
415        }
416    }
417
418    // Fingerprint the declaration block (sorted, !important-tagged) for cross-file
419    // duplicate-block detection, gated on the minimum block size and a per-file cap.
420    if declaration_count >= MIN_BLOCK_DECLARATIONS
421        && analytics.declaration_blocks.len() < MAX_DECLARATION_BLOCKS
422        && let Some(fingerprint) = declaration_block_fingerprint(style)
423    {
424        analytics.declaration_blocks.push(CssDeclarationBlock {
425            fingerprint,
426            line: style.loc.line.saturating_add(1),
427            declaration_count: saturate_u16(declaration_count),
428        });
429    }
430
431    collect_rule_property_tokens(&style.declarations, acc, style.loc.line.saturating_add(1));
432}
433
434/// Whether the child rules of a style rule hold declarations that apply to the
435/// style rule itself. lightningcss stores a declaration after a nested rule
436/// (`.a { &:hover {} color: red; }`) and a declaration in a nested at-rule
437/// (`.a { @media (...) { color: red; } }`) as nested declarations, not in the
438/// own block of the style rule. A nested style rule has its own selector, so
439/// its declarations do not count here.
440fn has_nested_declarations(rules: &[CssRule<'_>]) -> bool {
441    rules.iter().any(|rule| match rule {
442        CssRule::NestedDeclarations(nested) => !nested.declarations.is_empty(),
443        CssRule::Media(rule) => has_nested_declarations(&rule.rules.0),
444        CssRule::Supports(rule) => has_nested_declarations(&rule.rules.0),
445        CssRule::Container(rule) => has_nested_declarations(&rule.rules.0),
446        CssRule::LayerBlock(rule) => has_nested_declarations(&rule.rules.0),
447        CssRule::StartingStyle(rule) => has_nested_declarations(&rule.rules.0),
448        CssRule::Scope(rule) => has_nested_declarations(&rule.rules.0),
449        _ => false,
450    })
451}
452
453/// Fold bare declarations of a nested at-rule into the totals and token sets.
454/// For `.a { @media (...) { animation: x 1s; } }`, lightningcss stores the
455/// declarations inside the `@media` block as a nested-declarations rule with
456/// no selector. Without this, a `@keyframes` that only such a block uses is
457/// reported as unreferenced. The block is not a new style rule, so the rule
458/// count and the per-rule metrics stay as they are.
459fn record_nested_declarations(nested: &NestedDeclarationsRule<'_>, acc: &mut Accumulator) {
460    let block = &nested.declarations;
461    let important = block.important_declarations.len();
462    let analytics = &mut acc.analytics;
463    analytics.total_declarations = analytics
464        .total_declarations
465        .saturating_add(saturate_u32(block.declarations.len() + important));
466    analytics.important_declarations = analytics
467        .important_declarations
468        .saturating_add(saturate_u32(important));
469    collect_rule_property_tokens(block, acc, nested.loc.line.saturating_add(1));
470}
471
472/// Scan a rule's declarations (normal + `!important`) for design-token values,
473/// custom-property definitions, and `@keyframes` / font-family references,
474/// folding them into `acc`. Colors and `var()` references are collected
475/// separately by the value visitor.
476fn collect_rule_property_tokens(
477    block: &DeclarationBlock<'_>,
478    acc: &mut Accumulator,
479    rule_line: u32,
480) {
481    for property in block
482        .declarations
483        .iter()
484        .chain(block.important_declarations.iter())
485    {
486        collect_property_tokens(property, acc, rule_line);
487        collect_raw_style_value(property, acc, rule_line);
488    }
489}
490
491/// Fold a single declaration's design-token value, custom-property definition,
492/// `@keyframes` reference, or font-family reference into `acc`.
493fn collect_property_tokens(property: &Property<'_>, acc: &mut Accumulator, rule_line: u32) {
494    match property {
495        Property::FontSize(font_size) => {
496            insert_rendered_css(font_size, &mut acc.font_sizes);
497        }
498        Property::ZIndex(z_index) => {
499            insert_rendered_css(z_index, &mut acc.z_indexes);
500        }
501        // Shadow / radius / line-height tokens (design-token-sprawl axes).
502        // The INNER value is serialized (not the property), so the vendor
503        // prefix is dropped and `-webkit-box-shadow: X` collapses to the same
504        // distinct value as `box-shadow: X` rather than inflating the count.
505        Property::BoxShadow(shadows, _) => collect_box_shadow_tokens(shadows, acc),
506        Property::BorderRadius(radius, _) => {
507            insert_rendered_css(radius, &mut acc.border_radii);
508        }
509        Property::LineHeight(line_height) => {
510            insert_rendered_css(line_height, &mut acc.line_heights);
511        }
512        Property::Custom(custom) => {
513            collect_custom_property_tokens(custom, property, acc, rule_line);
514        }
515        Property::AnimationName(names, _) => {
516            let mut found = FxHashSet::default();
517            collect_animation_references(names, &mut found);
518            record_keyframe_references(acc, found, rule_line);
519        }
520        Property::Animation(animations, _) => {
521            let mut found = FxHashSet::default();
522            for animation in animations {
523                collect_animation_name(&animation.name, &mut found);
524            }
525            record_keyframe_references(acc, found, rule_line);
526        }
527        Property::Unparsed(unparsed) => {
528            let mut found = FxHashSet::default();
529            collect_unparsed_animation_references(unparsed, &mut found);
530            record_keyframe_references(acc, found, rule_line);
531        }
532        Property::FontFamily(families) => {
533            collect_font_family_references(families, &mut acc.referenced_font_families);
534        }
535        Property::Font(font) => {
536            collect_font_family_references(&font.family, &mut acc.referenced_font_families);
537        }
538        _ => {}
539    }
540}
541
542fn insert_rendered_css<T: ToCss>(value: &T, out: &mut FxHashSet<String>) {
543    if let Ok(rendered) = value.to_css_string(PrinterOptions::default()) {
544        out.insert(rendered);
545    }
546}
547
548/// Whether `property` is a `grid-template-areas` with no rows. lightningcss
549/// 1.0.0-alpha.72 closes an indent that it never opened when it prints one,
550/// and the subtraction overflows.
551fn is_empty_grid_template_areas(property: &Property<'_>) -> bool {
552    matches!(
553        property,
554        Property::GridTemplateAreas(GridTemplateAreas::Areas { areas, .. }) if areas.is_empty()
555    )
556}
557
558fn collect_raw_style_value(property: &Property<'_>, acc: &mut Accumulator, line: u32) {
559    if acc.analytics.raw_style_values.len() >= MAX_RAW_STYLE_VALUES {
560        return;
561    }
562    if is_empty_grid_template_areas(property) {
563        return;
564    }
565    let Ok(rendered) = property.to_css_string(false, PrinterOptions::default()) else {
566        return;
567    };
568    let Some((property_name, value)) = rendered.split_once(':') else {
569        return;
570    };
571    let property_name = property_name.trim().to_ascii_lowercase();
572    if property_name.starts_with("--") {
573        return;
574    }
575    let value = value.trim().trim_end_matches(';').trim().to_string();
576    let Some(axis) = raw_style_axis(&property_name, &value) else {
577        return;
578    };
579    if !is_raw_style_literal(&value) {
580        return;
581    }
582    let key = format!("{axis}:{property_name}:{value}:{line}");
583    if !acc.raw_style_value_keys.insert(key) {
584        return;
585    }
586    acc.analytics.raw_style_values.push(CssRawStyleValue {
587        axis: axis.to_string(),
588        property: property_name,
589        value,
590        line,
591    });
592}
593
594fn raw_style_axis(property_name: &str, value: &str) -> Option<&'static str> {
595    if property_name.contains("color") && looks_like_color_literal(value) {
596        return Some("color");
597    }
598    match property_name {
599        "font-size" => Some("font-size"),
600        "line-height" => Some("line-height"),
601        "border-radius"
602        | "border-top-left-radius"
603        | "border-top-right-radius"
604        | "border-bottom-right-radius"
605        | "border-bottom-left-radius" => Some("radius"),
606        "box-shadow" | "text-shadow" => Some("shadow"),
607        _ => None,
608    }
609}
610
611fn is_raw_style_literal(value: &str) -> bool {
612    let lower = value.to_ascii_lowercase();
613    if lower.contains("var(") || lower.contains("token(") || lower.contains("theme(") {
614        return false;
615    }
616    if matches!(
617        lower.as_str(),
618        "0" | "none"
619            | "normal"
620            | "inherit"
621            | "initial"
622            | "unset"
623            | "revert"
624            | "currentcolor"
625            | "transparent"
626    ) {
627        return false;
628    }
629    lower.chars().any(|ch| ch.is_ascii_digit()) || looks_like_color_literal(&lower)
630}
631
632fn looks_like_color_literal(value: &str) -> bool {
633    let lower = value.to_ascii_lowercase();
634    lower.starts_with('#')
635        || lower.contains("rgb(")
636        || lower.contains("rgba(")
637        || lower.contains("hsl(")
638        || lower.contains("hsla(")
639        || lower.contains("oklch(")
640        || lower.contains("color-mix(")
641        || matches!(
642            lower.as_str(),
643            "red"
644                | "blue"
645                | "green"
646                | "black"
647                | "white"
648                | "gray"
649                | "grey"
650                | "transparent"
651                | "yellow"
652                | "orange"
653                | "purple"
654                | "pink"
655        )
656}
657
658fn collect_box_shadow_tokens(shadows: &[BoxShadow], acc: &mut Accumulator) {
659    let rendered: Vec<String> = shadows
660        .iter()
661        .filter_map(|shadow| shadow.to_css_string(PrinterOptions::default()).ok())
662        .collect();
663    if !rendered.is_empty() && rendered.len() == shadows.len() {
664        acc.box_shadows.insert(rendered.join(", "));
665    }
666}
667
668/// Add the `@keyframes` names of one declaration to `acc`, with the first
669/// rule line that references each name.
670fn record_keyframe_references(acc: &mut Accumulator, names: FxHashSet<String>, rule_line: u32) {
671    for name in names {
672        acc.keyframe_reference_lines
673            .entry(name.clone())
674            .and_modify(|line| *line = (*line).min(rule_line))
675            .or_insert(rule_line);
676        acc.referenced_keyframes.insert(name);
677    }
678}
679
680fn collect_animation_references(names: &[AnimationName<'_>], out: &mut FxHashSet<String>) {
681    for name in names {
682        collect_animation_name(name, out);
683    }
684}
685
686/// The CSS-wide keywords plus `none`. In an `animation-name` list these are the
687/// only identifiers that are not keyframe names.
688const ANIMATION_NAME_KEYWORDS: &[&str] = &[
689    "none",
690    "initial",
691    "inherit",
692    "unset",
693    "revert",
694    "revert-layer",
695];
696
697/// Keywords that can fill a non-name slot of an `animation` shorthand layer.
698/// The shorthand also rejects every keyword of [`ANIMATION_NAME_KEYWORDS`].
699const ANIMATION_SHORTHAND_KEYWORDS: &[&str] = &[
700    "linear",
701    "ease",
702    "ease-in",
703    "ease-out",
704    "ease-in-out",
705    "step-start",
706    "step-end",
707    "infinite",
708    "normal",
709    "reverse",
710    "alternate",
711    "alternate-reverse",
712    "forwards",
713    "backwards",
714    "both",
715    "running",
716    "paused",
717    "auto",
718    "replace",
719    "add",
720    "accumulate",
721];
722
723/// Credit the literal keyframe names in an `animation` / `animation-name`
724/// declaration that lightningcss keeps as a raw token list because the value
725/// contains `var()` or `env()`, for example
726/// `animation: pulse var(--duration) ease` (issue #3349).
727///
728/// lightningcss also keeps an invalid value as raw tokens. The browser drops
729/// such a declaration, so a value without `var()` or `env()` credits nothing.
730/// In each comma-separated layer, a top-level identifier counts only when it
731/// is the one non-keyword identifier of that layer, so a `var()` in the name
732/// slot or an unknown keyword stays unresolved.
733fn collect_unparsed_animation_references(
734    unparsed: &UnparsedProperty<'_>,
735    out: &mut FxHashSet<String>,
736) {
737    let is_shorthand = match unparsed.property_id {
738        PropertyId::Animation(_) => true,
739        PropertyId::AnimationName(_) => false,
740        _ => return,
741    };
742    if !has_substitution(&unparsed.value.0) {
743        return;
744    }
745    for layer in unparsed
746        .value
747        .0
748        .split(|token| matches!(token, TokenOrValue::Token(Token::Comma)))
749    {
750        if let Some(name) = layer_animation_name(layer, is_shorthand) {
751            out.insert(name);
752        }
753    }
754}
755
756/// Returns `true` when a token list holds a `var()` or `env()` at any depth.
757fn has_substitution(tokens: &[TokenOrValue<'_>]) -> bool {
758    tokens.iter().any(|token| match token {
759        TokenOrValue::Var(_) | TokenOrValue::Env(_) => true,
760        TokenOrValue::Function(function) => has_substitution(&function.arguments.0),
761        _ => false,
762    })
763}
764
765/// Returns the keyframe name of one animation layer when exactly one
766/// top-level identifier in it is not a keyword.
767fn layer_animation_name(layer: &[TokenOrValue<'_>], is_shorthand: bool) -> Option<String> {
768    let is_keyword = |ident: &str| {
769        ANIMATION_NAME_KEYWORDS
770            .iter()
771            .chain(if is_shorthand {
772                ANIMATION_SHORTHAND_KEYWORDS.iter()
773            } else {
774                [].iter()
775            })
776            .any(|keyword| ident.eq_ignore_ascii_case(keyword))
777    };
778    let mut names = layer.iter().filter_map(|token| match token {
779        TokenOrValue::Token(Token::Ident(ident)) if !is_keyword(ident) => Some(ident.to_string()),
780        TokenOrValue::AnimationName(AnimationName::Ident(ident)) => Some(ident.0.to_string()),
781        _ => None,
782    });
783    let name = names.next()?;
784    names.next().is_none().then_some(name)
785}
786
787fn collect_font_family_references(families: &[FontFamily<'_>], out: &mut FxHashSet<String>) {
788    for family in families {
789        if let Some(name) = font_family_name(family) {
790            out.insert(name);
791        }
792    }
793}
794
795/// Record a custom-property definition and credit any font-family string / ident
796/// values referenced inside its raw token stream.
797fn collect_custom_property_tokens(
798    custom: &CustomProperty<'_>,
799    property: &Property<'_>,
800    acc: &mut Accumulator,
801    rule_line: u32,
802) {
803    if let CustomPropertyName::Custom(name) = &custom.name {
804        let name = name.0.to_string();
805        acc.defined_custom_properties.insert(name.clone());
806        if let Ok(rendered) = property.to_css_string(false, PrinterOptions::default())
807            && let Some((_, value)) = rendered.split_once(':')
808        {
809            let value = value.trim().trim_end_matches(';').trim();
810            if !value.is_empty() {
811                acc.analytics
812                    .custom_property_definitions
813                    .push(CssCustomPropertyDefinition {
814                        name,
815                        value: value.to_string(),
816                        line: rule_line,
817                    });
818            }
819        }
820    }
821    // A custom-property value can REFERENCE a font family without a
822    // `font-family:` declaration: a Tailwind v4 `--font-*` theme token
823    // (`--font-display: "Departure Mono", monospace`) is the canonical
824    // case. lightningcss's `Property::FontFamily` / `Property::Font`
825    // arms above never see this (a `--*:` declaration is an opaque
826    // token stream), so scan the raw tokens for string / ident values
827    // and credit them as referenced families. Generic keywords
828    // (`serif`, `monospace`) never appear in `defined_font_faces`, so
829    // crediting them here is inert; the `unused_font_faces`
830    // set-difference only ever drops a genuinely-declared family.
831    for token in &custom.value.0 {
832        if let TokenOrValue::Token(Token::String(value) | Token::Ident(value)) = token {
833            acc.referenced_font_families.insert(value.to_string());
834        }
835    }
836}
837
838/// Fingerprint a rule's declaration block: serialize each declaration (tagging
839/// `!important` ones, which lightningcss stores without the flag, so they do not
840/// collide with their non-important twin), sort for order-insensitivity, join,
841/// and xxh3-hash. Returns `None` if any declaration fails to serialize, so a
842/// partial block is never fingerprinted (a false duplicate match would be worse
843/// than missing one).
844fn declaration_block_fingerprint(style: &StyleRule<'_>) -> Option<u64> {
845    let block = &style.declarations;
846    let mut parts: Vec<String> =
847        Vec::with_capacity(block.declarations.len() + block.important_declarations.len());
848    for decl in &block.declarations {
849        parts.push(decl.to_css_string(false, PrinterOptions::default()).ok()?);
850    }
851    for decl in &block.important_declarations {
852        // `important = true` renders the `!important` suffix, so a block with an
853        // important declaration never collides with its non-important twin.
854        parts.push(decl.to_css_string(true, PrinterOptions::default()).ok()?);
855    }
856    parts.sort_unstable();
857    Some(xxhash_rust::xxh3::xxh3_64(parts.join(";").as_bytes()))
858}
859
860/// Return the rule's `(specificity_a, specificity_b, specificity_c, complexity)`
861/// taking the most specific selector and the most complex selector across the
862/// rule's selector list.
863fn rule_selector_metrics(style: &StyleRule<'_>) -> (u16, u16, u16, u16) {
864    let mut max_spec = 0u32;
865    let mut a = 0u16;
866    let mut b = 0u16;
867    let mut c = 0u16;
868    let mut complexity = 0u16;
869    for selector in &style.selectors.0 {
870        let spec = selector.specificity();
871        if spec >= max_spec {
872            max_spec = spec;
873            a = specificity_component(spec, 20);
874            b = specificity_component(spec, 10);
875            c = specificity_component(spec, 0);
876        }
877        complexity = complexity.max(selector_complexity(selector));
878    }
879    (a, b, c, complexity)
880}
881
882fn specificity_component(specificity: u32, shift: u32) -> u16 {
883    saturate_u16_u32((specificity >> shift) & SPECIFICITY_COMPONENT_MASK)
884}
885
886fn is_notable(metric: &CssRuleMetric) -> bool {
887    metric.specificity_a >= 1
888        || metric.complexity > MAX_PLAIN_COMPLEXITY
889        || metric.important_count >= 1
890        || metric.nesting_depth >= NOTABLE_NESTING_DEPTH
891}
892
893fn selector_complexity(selector: &Selector<'_>) -> u16 {
894    let mut count = 0u16;
895    count_components(selector, &mut count);
896    count
897}
898
899fn count_components(selector: &Selector<'_>, count: &mut u16) {
900    for component in selector.iter_raw_match_order() {
901        *count = count.saturating_add(1);
902        match component {
903            Component::Is(list)
904            | Component::Where(list)
905            | Component::Has(list)
906            | Component::Negation(list)
907            | Component::Any(_, list) => {
908                for nested in list.as_ref() {
909                    count_components(nested, count);
910                }
911            }
912            Component::Slotted(nested) | Component::Host(Some(nested)) => {
913                count_components(nested, count);
914            }
915            Component::NthOf(data) => {
916                for nested in data.selectors() {
917                    count_components(nested, count);
918                }
919            }
920            _ => {}
921        }
922    }
923}
924
925fn saturate_u32(value: usize) -> u32 {
926    u32::try_from(value).unwrap_or(u32::MAX)
927}
928
929fn saturate_u16(value: usize) -> u16 {
930    u16::try_from(value).unwrap_or(u16::MAX)
931}
932
933fn saturate_u16_u32(value: u32) -> u16 {
934    u16::try_from(value).unwrap_or(u16::MAX)
935}
936
937#[cfg(all(test, not(miri)))]
938mod tests {
939    use super::*;
940
941    fn analytics(source: &str) -> CssAnalytics {
942        compute_css_analytics(source).expect("standard CSS parses")
943    }
944
945    #[test]
946    fn recovers_partial_metrics_around_a_malformed_rule() {
947        // Error recovery skips the broken rule and still records the valid one,
948        // so a file with one bad rule is not lost wholesale.
949        let a = analytics("#main { color: red; } @@@ broken @@@ .ok { color: blue; }");
950        assert!(a.rule_count >= 1);
951        assert!(a.notable_rules.iter().any(|r| r.specificity_a == 1));
952    }
953
954    #[test]
955    fn counts_declarations_and_important() {
956        let a = analytics(".a { color: red; width: 1px !important; }");
957        assert_eq!(a.rule_count, 1);
958        assert_eq!(a.total_declarations, 2);
959        assert_eq!(a.important_declarations, 1);
960    }
961
962    #[test]
963    fn id_selector_is_notable_with_specificity() {
964        let a = analytics("#main { color: red; }");
965        assert_eq!(a.notable_rules.len(), 1);
966        let rule = &a.notable_rules[0];
967        assert_eq!(rule.specificity_a, 1);
968        assert_eq!(rule.specificity_b, 0);
969        assert_eq!(rule.specificity_c, 0);
970    }
971
972    #[test]
973    fn plain_class_rule_is_not_notable() {
974        let a = analytics(".btn { color: red; }");
975        assert!(a.notable_rules.is_empty(), "got {:?}", a.notable_rules);
976        assert_eq!(a.rule_count, 1);
977    }
978
979    #[test]
980    fn important_declaration_makes_rule_notable() {
981        let a = analytics(".btn { color: red !important; }");
982        assert_eq!(a.notable_rules.len(), 1);
983        assert_eq!(a.notable_rules[0].important_count, 1);
984    }
985
986    #[test]
987    fn empty_rule_counted() {
988        let a = analytics(".a { } .b { color: red; }");
989        assert_eq!(a.rule_count, 2);
990        assert_eq!(a.empty_rule_count, 1);
991    }
992
993    #[test]
994    fn complex_selector_is_notable() {
995        // Five compound selectors joined by combinators exceeds the floor.
996        let a = analytics("div > ul > li > a > span { color: red; }");
997        assert_eq!(a.notable_rules.len(), 1);
998        assert!(a.notable_rules[0].complexity > MAX_PLAIN_COMPLEXITY);
999    }
1000
1001    #[test]
1002    fn nesting_depth_tracked() {
1003        let a = analytics(".a { .b { .c { .d { color: red; } } } }");
1004        assert!(a.max_nesting_depth >= 3, "got {}", a.max_nesting_depth);
1005        // The depth-3 rule (`.d`) crosses the nesting floor.
1006        assert!(
1007            a.notable_rules
1008                .iter()
1009                .any(|r| r.nesting_depth >= NOTABLE_NESTING_DEPTH)
1010        );
1011    }
1012
1013    #[test]
1014    fn specificity_takes_most_specific_selector_in_list() {
1015        let a = analytics("#id, .cls { color: red; }");
1016        assert_eq!(a.notable_rules.len(), 1);
1017        // `#id` (1,0,0) is more specific than `.cls` (0,1,0).
1018        assert_eq!(a.notable_rules[0].specificity_a, 1);
1019    }
1020
1021    #[test]
1022    fn line_is_one_based() {
1023        let a = analytics("\n\n#main { color: red; }");
1024        assert_eq!(a.notable_rules[0].line, 3);
1025    }
1026
1027    #[test]
1028    fn media_query_rules_walked() {
1029        let a = analytics("@media (min-width: 600px) { #main { color: red; } }");
1030        assert_eq!(a.rule_count, 1);
1031        assert_eq!(a.notable_rules.len(), 1);
1032        assert_eq!(a.notable_rules[0].specificity_a, 1);
1033    }
1034
1035    #[test]
1036    fn collects_distinct_colors() {
1037        let a = analytics(".a { color: red; } .b { color: blue; } .c { color: red; }");
1038        assert_eq!(a.colors.len(), 2, "distinct colors deduped: {:?}", a.colors);
1039    }
1040
1041    #[test]
1042    fn parses_theme_color_values_to_rgb() {
1043        assert_eq!(parse_css_color_rgb("#f00"), Some((255.0, 0.0, 0.0)));
1044        assert_eq!(parse_css_color_rgb("rgb(255 0 0)"), Some((255.0, 0.0, 0.0)));
1045        assert_eq!(
1046            parse_css_color_rgb("hsl(0 100% 50%)"),
1047            Some((255.0, 0.0, 0.0))
1048        );
1049        assert!(parse_css_color_rgb("var(--brand)").is_none());
1050    }
1051
1052    #[test]
1053    fn direct_color_parser_matches_stylesheet_parser_corpus() {
1054        let values = [
1055            // Hex and named colors.
1056            "#000",
1057            "#fff",
1058            "#f00",
1059            "#0f08",
1060            "#112233",
1061            "#11223344",
1062            "#abcdef",
1063            "#ABCDEF",
1064            "red",
1065            "rebeccapurple",
1066            "transparent",
1067            // Functional RGB syntax, alpha, and clamping.
1068            "rgb(255 0 0)",
1069            "rgb(100% 0% 0%)",
1070            "rgb(255, 0, 0)",
1071            "rgba(255, 0, 0, 0.5)",
1072            "rgba(255 0 0 / 0)",
1073            "rgba(255 0 0 / 1)",
1074            "rgb(255 0 0 / 25%)",
1075            "rgb(300 -10 0)",
1076            // HSL and HWB normalization.
1077            "hsl(0 100% 50%)",
1078            "hsl(120deg 100% 25% / 0.5)",
1079            "hsla(240, 100%, 50%, 25%)",
1080            "hwb(0 0% 0%)",
1081            "hwb(120 10% 20% / 50%)",
1082            // CSS whitespace and comments.
1083            " red ",
1084            "\t#f00\n",
1085            "rgb( 255  0  0 / .5 )",
1086            "r/**/ed",
1087            "rgb(255/**/ 0 0)",
1088            "/* before */ red /* after */",
1089            // Valid CSS colors that do not resolve to a concrete RGBA value.
1090            "currentColor",
1091            "CURRENTCOLOR",
1092            "CanvasText",
1093            "ButtonFace",
1094            "AccentColorText",
1095            "var(--brand)",
1096            "color-mix(in srgb, red 50%, blue)",
1097            "lab(50% 40 30)",
1098            "lch(50% 40 30)",
1099            "oklab(50% .1 .1)",
1100            "oklch(50% .1 30)",
1101            "color(display-p3 1 0 0)",
1102            // Malformed or trailing input.
1103            "",
1104            "#ff",
1105            "not-a-color",
1106            "rgb(255 0)",
1107            "red junk",
1108            "red, blue",
1109            "red !important junk",
1110            "red ! important junk",
1111            "red !important !important",
1112            "red,",
1113            // Declaration-level syntax accepted by the old wrapper.
1114            "red !important",
1115            "red ! important",
1116            "red ! IMPORTANT",
1117            "red !/**/important",
1118            "red/**/!important",
1119            "red ! important;",
1120            "red !important ;",
1121            "red !important; color: blue",
1122            "red !important; junk",
1123            "#f00!important",
1124            "red;",
1125            "red ; ",
1126            "red;;",
1127            "red; junk",
1128            "red; color: blue",
1129            "red; --custom: value",
1130            "red; :junk",
1131            // Error-recovery syntax that requires the stylesheet fallback.
1132            "not-a-color; color: blue",
1133            "var(--x); color: blue",
1134            "red; @media {}",
1135            "red; --x: }",
1136            "currentColor; color: blue",
1137            "CanvasText; color: blue",
1138            "lab(50% 40 30); color: blue",
1139            "color(display-p3 1 0 0); color: blue",
1140            "red; color: blue !important",
1141            "rgb(1 2 3); color: blue !important",
1142        ];
1143
1144        let mismatches = values
1145            .into_iter()
1146            .filter_map(|value| {
1147                let direct = parse_css_color_rgb(value);
1148                let stylesheet = parse_css_color_rgb_via_stylesheet(value);
1149                (direct != stylesheet).then_some((value, direct, stylesheet))
1150            })
1151            .collect::<Vec<_>>();
1152        assert!(mismatches.is_empty(), "parser mismatches: {mismatches:#?}");
1153    }
1154
1155    #[test]
1156    fn collects_colors_nested_in_shorthands() {
1157        // The color inside the `border` shorthand must be caught, not just the
1158        // standalone `background` color: that is the point of the value visitor.
1159        let a = analytics(".a { border: 1px solid green; background: yellow; }");
1160        assert!(
1161            a.colors.len() >= 2,
1162            "shorthand + standalone colors collected: {:?}",
1163            a.colors
1164        );
1165    }
1166
1167    #[test]
1168    fn collects_distinct_font_sizes() {
1169        let a =
1170            analytics(".a { font-size: 14px; } .b { font-size: 14px; } .c { font-size: 1rem; }");
1171        assert_eq!(a.font_sizes.len(), 2, "got {:?}", a.font_sizes);
1172    }
1173
1174    #[test]
1175    fn collects_located_raw_style_values_but_skips_tokenized_values() {
1176        let a = analytics(
1177            ".a { color: red; font-size: 14px; margin-top: 1rem; z-index: 10; color: transparent; }\n.b { border-radius: 6px; }",
1178        );
1179        assert!(
1180            a.raw_style_values
1181                .iter()
1182                .any(|value| value.axis == "color" && value.property == "color"),
1183            "raw color should be located: {:?}",
1184            a.raw_style_values
1185        );
1186        assert!(
1187            a.raw_style_values
1188                .iter()
1189                .any(|value| value.axis == "font-size" && value.value == "14px"),
1190            "raw font size should be located: {:?}",
1191            a.raw_style_values
1192        );
1193        assert!(
1194            a.raw_style_values
1195                .iter()
1196                .any(|value| value.axis == "radius" && value.line == 2),
1197            "raw radius should be located on the second rule: {:?}",
1198            a.raw_style_values
1199        );
1200        assert!(
1201            !a.raw_style_values
1202                .iter()
1203                .any(|value| value.property == "margin-top"),
1204            "layout spacing should not be a raw-value candidate: {:?}",
1205            a.raw_style_values
1206        );
1207        assert!(
1208            !a.raw_style_values
1209                .iter()
1210                .any(|value| value.property == "z-index"),
1211            "z-index should stay a scale summary, not an audit candidate: {:?}",
1212            a.raw_style_values
1213        );
1214        assert!(
1215            !a.raw_style_values
1216                .iter()
1217                .any(|value| value.value == "transparent"),
1218            "transparent should behave like a reset keyword: {:?}",
1219            a.raw_style_values
1220        );
1221    }
1222
1223    #[test]
1224    fn collects_distinct_z_indexes() {
1225        let a = analytics(".a { z-index: 10; } .b { z-index: 10; } .c { z-index: 999; }");
1226        assert_eq!(a.z_indexes.len(), 2, "got {:?}", a.z_indexes);
1227    }
1228
1229    #[test]
1230    fn collects_defined_and_referenced_custom_properties() {
1231        let a = analytics(":root { --brand: red; --unused: blue; }\n.a { color: var(--brand); }");
1232        assert!(
1233            a.defined_custom_properties.contains(&"--brand".to_string()),
1234            "defined: {:?}",
1235            a.defined_custom_properties
1236        );
1237        assert!(
1238            a.defined_custom_properties
1239                .contains(&"--unused".to_string())
1240        );
1241        assert!(
1242            a.referenced_custom_properties
1243                .contains(&"--brand".to_string()),
1244            "referenced: {:?}",
1245            a.referenced_custom_properties
1246        );
1247        assert!(
1248            !a.referenced_custom_properties
1249                .contains(&"--unused".to_string()),
1250            "--unused has no var() reference"
1251        );
1252    }
1253
1254    #[test]
1255    fn keyframe_references_have_the_line_of_the_first_rule() {
1256        let a = analytics(
1257            ".a {\n  color: red;\n}\n\n.toast {\n  animation: fade-in 1s;\n}\n\
1258             .b { animation-name: fade-in, spin; }\n",
1259        );
1260        assert_eq!(
1261            a.keyframe_reference_lines,
1262            vec![("fade-in".to_string(), 5), ("spin".to_string(), 8)]
1263        );
1264    }
1265
1266    #[test]
1267    fn collects_defined_and_referenced_keyframes() {
1268        let a = analytics(
1269            "@keyframes spin { from {} to {} }\n@keyframes unused { from {} }\n.a { animation-name: spin; }",
1270        );
1271        assert!(a.defined_keyframes.contains(&"spin".to_string()));
1272        assert!(a.defined_keyframes.contains(&"unused".to_string()));
1273        assert!(a.referenced_keyframes.contains(&"spin".to_string()));
1274        assert!(
1275            !a.referenced_keyframes.contains(&"unused".to_string()),
1276            "no animation references `unused`"
1277        );
1278    }
1279
1280    #[test]
1281    fn declarations_in_nested_at_rule_reference_keyframes() {
1282        // Native nesting: an `@media` block inside a style rule holds bare
1283        // declarations, which lightningcss stores as nested declarations.
1284        let a = analytics(
1285            ".pulse {\n  animation: moving 1s ease-out;\n  @media (prefers-reduced-motion: reduce) {\n    animation: still 1s step-end !important;\n  }\n}\n\
1286             @keyframes moving { from { opacity: 0; } to { opacity: 1; } }\n\
1287             @keyframes still { from, to { opacity: 1; } }",
1288        );
1289        assert_eq!(
1290            a.referenced_keyframes,
1291            vec!["moving".to_string(), "still".to_string()]
1292        );
1293        assert_eq!(a.total_declarations, 2);
1294        assert_eq!(a.important_declarations, 1);
1295    }
1296
1297    #[test]
1298    fn declarations_after_nested_rule_count_as_rule_declarations() {
1299        // A declaration after a nested rule is stored as nested declarations
1300        // in the parent rule. The parent rule is not empty.
1301        let a = analytics(
1302            ".c {\n  &:hover { color: blue; }\n  animation: fade 1s;\n  font-family: Brand, sans-serif;\n}\n\
1303             .empty {}\n\
1304             @keyframes fade { from { opacity: 0; } }",
1305        );
1306        assert_eq!(a.referenced_keyframes, vec!["fade".to_string()]);
1307        assert!(
1308            a.referenced_font_families.contains(&"Brand".to_string()),
1309            "{:?}",
1310            a.referenced_font_families
1311        );
1312        assert_eq!(a.total_declarations, 3);
1313        assert_eq!(a.empty_rule_count, 1);
1314    }
1315
1316    #[test]
1317    fn rule_with_only_nested_at_rule_declarations_is_not_empty() {
1318        // The `@media` declarations apply to `.a`. A nested style rule has its
1319        // own selector, so `.b` with only `&:hover` stays empty.
1320        let a = analytics(
1321            ".a {\n  @media (min-width: 1px) {\n    color: red;\n  }\n}\n\
1322             .b {\n  &:hover { color: blue; }\n}",
1323        );
1324        assert_eq!(a.empty_rule_count, 1);
1325    }
1326
1327    #[test]
1328    fn nested_at_rule_defines_custom_properties() {
1329        let a = analytics(
1330            ".a {\n  color: red;\n  @supports (display: grid) {\n    --gap: 2rem;\n  }\n}",
1331        );
1332        assert!(
1333            a.defined_custom_properties.contains(&"--gap".to_string()),
1334            "{:?}",
1335            a.defined_custom_properties
1336        );
1337    }
1338
1339    #[test]
1340    fn animation_shorthand_references_keyframes() {
1341        let a = analytics("@keyframes pulse { from {} }\n.a { animation: pulse 1s infinite; }");
1342        assert!(
1343            a.referenced_keyframes.contains(&"pulse".to_string()),
1344            "referenced: {:?}",
1345            a.referenced_keyframes
1346        );
1347    }
1348
1349    #[test]
1350    fn animation_shorthand_with_var_references_keyframes() {
1351        // A `var()` in the shorthand makes lightningcss keep the declaration as
1352        // an unparsed token list. The literal name must still be credited.
1353        let a = analytics(
1354            "@keyframes pulse { from {} }\n\
1355             .a { animation: pulse var(--duration) ease; }",
1356        );
1357        assert_eq!(a.referenced_keyframes, vec!["pulse".to_string()]);
1358    }
1359
1360    #[test]
1361    fn animation_shorthand_with_var_credits_each_comma_layer() {
1362        let a = analytics(
1363            "@keyframes fade { from {} }\n@keyframes slide { from {} }\n\
1364             .a { animation: fade 1s infinite, slide var(--d) cubic-bezier(0, 0, 1, 1) both; }\n\
1365             .b { -webkit-animation: fade var(--d); }",
1366        );
1367        assert_eq!(
1368            a.referenced_keyframes,
1369            vec!["fade".to_string(), "slide".to_string()]
1370        );
1371    }
1372
1373    #[test]
1374    fn var_in_animation_name_position_stays_unresolved() {
1375        let a = analytics(
1376            "@keyframes pulse { from {} }\n\
1377             .a { animation: var(--name) 1s ease-in-out infinite alternate both; }\n\
1378             .b { animation-name: var(--other); }",
1379        );
1380        assert!(
1381            a.referenced_keyframes.is_empty(),
1382            "no literal name: {:?}",
1383            a.referenced_keyframes
1384        );
1385    }
1386
1387    #[test]
1388    fn invalid_animation_value_credits_no_keyframe() {
1389        // An invalid value also reaches the unparsed path. The browser drops
1390        // the declaration, so no name in it counts as a reference.
1391        let a = analytics(
1392            "@keyframes spin { from {} }\n\
1393             .a { animation: spin 1s smooth; }\n\
1394             .b { animation: spin 1x; }",
1395        );
1396        assert!(
1397            a.referenced_keyframes.is_empty(),
1398            "invalid values credit nothing: {:?}",
1399            a.referenced_keyframes
1400        );
1401    }
1402
1403    #[test]
1404    fn ambiguous_var_layer_credits_no_keyframe() {
1405        // Two non-keyword identifiers in one layer leave the name unknown.
1406        let a = analytics(".a { animation: spin var(--d) smooth, fade var(--d); }");
1407        assert_eq!(a.referenced_keyframes, vec!["fade".to_string()]);
1408    }
1409
1410    #[test]
1411    fn animation_composition_keywords_are_not_names() {
1412        let a = analytics(".a { animation: x var(--d) replace add accumulate; }");
1413        assert_eq!(a.referenced_keyframes, vec!["x".to_string()]);
1414    }
1415
1416    #[test]
1417    fn var_nested_in_function_reaches_the_name() {
1418        let a = analytics(".a { animation: pulse calc(var(--d) * 2) ease; }");
1419        assert_eq!(a.referenced_keyframes, vec!["pulse".to_string()]);
1420    }
1421
1422    #[test]
1423    fn animation_name_list_with_var_credits_easing_named_keyframe() {
1424        // In `animation-name`, only `none` and the CSS-wide keywords are not
1425        // names, so a keyframe called `ease` counts.
1426        let a = analytics(
1427            "@keyframes ease { from {} }\n\
1428             .a { animation-name: var(--x), ease, none, inherit; }",
1429        );
1430        assert_eq!(a.referenced_keyframes, vec!["ease".to_string()]);
1431    }
1432
1433    #[test]
1434    fn animation_name_list_with_var_credits_literal_names() {
1435        let a = analytics(
1436            "@keyframes spin { from {} }\n\
1437             .a { animation-name: var(--first), spin; }",
1438        );
1439        assert_eq!(a.referenced_keyframes, vec!["spin".to_string()]);
1440    }
1441
1442    #[test]
1443    fn fingerprints_blocks_at_floor_order_insensitive() {
1444        // Two 4-declaration rules with the same declarations in different order
1445        // share a fingerprint; a 3-declaration rule is below the floor and is
1446        // not fingerprinted.
1447        let a = analytics(
1448            ".x { color: red; margin: 1px; padding: 2px; top: 3px; }\n\
1449             .y { top: 3px; padding: 2px; margin: 1px; color: red; }\n\
1450             .z { color: red; margin: 1px; padding: 2px; }\n",
1451        );
1452        assert_eq!(
1453            a.declaration_blocks.len(),
1454            2,
1455            "two 4-decl rules fingerprinted, the 3-decl one skipped: {:?}",
1456            a.declaration_blocks
1457        );
1458        assert_eq!(
1459            a.declaration_blocks[0].fingerprint, a.declaration_blocks[1].fingerprint,
1460            "same declarations in different order share a fingerprint"
1461        );
1462        assert_eq!(a.declaration_blocks[0].declaration_count, 4);
1463    }
1464
1465    #[test]
1466    fn important_distinguishes_block_fingerprint() {
1467        let a = analytics(
1468            ".x { color: red; margin: 1px; padding: 2px; top: 3px; }\n\
1469             .y { color: red !important; margin: 1px; padding: 2px; top: 3px; }\n",
1470        );
1471        assert_eq!(a.declaration_blocks.len(), 2);
1472        assert_ne!(
1473            a.declaration_blocks[0].fingerprint, a.declaration_blocks[1].fingerprint,
1474            "!important changes the block fingerprint"
1475        );
1476    }
1477
1478    #[test]
1479    fn var_referenced_and_token_defined_values_are_not_counted_as_distinct() {
1480        // Load-bearing for the v3 styling-health sprawl drift sub-term: the
1481        // distinct-value sets (box_shadows / border_radii / line_heights) count
1482        // ONLY hardcoded literals. A value referenced via `var(--*)` parses as
1483        // `Property::Unparsed` in lightningcss, so it never reaches the typed
1484        // `Property::BoxShadow` / `BorderRadius` / `LineHeight` arms, and a token
1485        // DEFINITION (`--x: 4px`) is a `Property::Custom`. Both are therefore
1486        // invisible to the sprawl counts. This is what makes a well-tokenized
1487        // design system score 0 sprawl regardless of how many tokens it defines;
1488        // the v3 grade's entire FP-safety rests on this lightningcss behavior, so
1489        // it is pinned here (a future lightningcss change that typed `var()` values
1490        // would break tokenized systems silently and must trip this test).
1491        let tokenized = analytics(
1492            ":root { --r: 4px; --s: 0 1px 2px #0000001a; --lh: 1.5; }\n\
1493             .a { border-radius: var(--r); box-shadow: var(--s); line-height: var(--lh); }\n\
1494             .b { border-radius: var(--r); box-shadow: var(--s); line-height: var(--lh); }\n",
1495        );
1496        assert!(
1497            tokenized.border_radii.is_empty(),
1498            "var()-referenced radii are not counted: {:?}",
1499            tokenized.border_radii
1500        );
1501        assert!(
1502            tokenized.box_shadows.is_empty(),
1503            "var()-referenced shadows are not counted: {:?}",
1504            tokenized.box_shadows
1505        );
1506        assert!(
1507            tokenized.line_heights.is_empty(),
1508            "var()-referenced line-heights are not counted: {:?}",
1509            tokenized.line_heights
1510        );
1511
1512        // Control: hardcoded literal values ARE counted, so the sprawl signal is
1513        // not simply inert. Two distinct hardcoded radii / shadows / line-heights.
1514        let hardcoded = analytics(
1515            ".a { border-radius: 4px; box-shadow: 0 1px 2px #0000001a; line-height: 1.4; }\n\
1516             .b { border-radius: 6px; box-shadow: 0 2px 4px #0000001f; line-height: 1.6; }\n",
1517        );
1518        assert_eq!(
1519            hardcoded.border_radii.len(),
1520            2,
1521            "distinct hardcoded radii counted: {:?}",
1522            hardcoded.border_radii
1523        );
1524        assert_eq!(
1525            hardcoded.box_shadows.len(),
1526            2,
1527            "distinct hardcoded shadows counted: {:?}",
1528            hardcoded.box_shadows
1529        );
1530        assert_eq!(
1531            hardcoded.line_heights.len(),
1532            2,
1533            "distinct hardcoded line-heights counted: {:?}",
1534            hardcoded.line_heights
1535        );
1536    }
1537}