fallow-extract 2.98.0

AST extraction engine for fallow codebase intelligence (parser, complexity, SFC / Astro / MDX / CSS)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! Structural CSS analytics computed from the parsed CSS syntax tree.
//!
//! `fallow health` consumes these on demand to surface specificity hotspots,
//! `!important` density, over-complex selectors, and deep nesting: the kind of
//! codebase-scale structural CSS slop that per-rule linters do not aggregate.
//! The metrics come from the same lightningcss parse used for CSS Module class
//! extraction. Callers gate by file extension: lightningcss parses standard CSS,
//! not Sass, so `.scss` sources are NOT passed here (with error recovery on,
//! Sass syntax recovers into a partial, inaccurate result rather than failing).
//! A hard parse failure yields `None`.

use lightningcss::printer::PrinterOptions;
use lightningcss::properties::Property;
use lightningcss::properties::animation::AnimationName;
use lightningcss::properties::custom::{CustomPropertyName, Token, TokenOrValue, Variable};
use lightningcss::properties::font::FontFamily;
use lightningcss::rules::CssRule;
use lightningcss::rules::font_face::FontFaceProperty;
use lightningcss::rules::keyframes::KeyframesName;
use lightningcss::rules::style::StyleRule;
use lightningcss::selector::{Component, Selector};
use lightningcss::stylesheet::{ParserOptions, StyleSheet};
use lightningcss::traits::ToCss;
use lightningcss::values::color::CssColor;
use lightningcss::visitor::{VisitTypes, Visitor};
use rustc_hash::FxHashSet;

use fallow_types::extract::{CssAnalytics, CssDeclarationBlock, CssRuleMetric};

/// Selector component count above which a rule is considered over-complex.
const MAX_PLAIN_COMPLEXITY: u16 = 4;

/// Style-rule nesting depth at or above which a rule is recorded.
const NOTABLE_NESTING_DEPTH: u8 = 3;

/// Upper bound on per-file recorded rules. Compiled utility frameworks can emit
/// thousands of `!important` rules; the scalar aggregates stay accurate while
/// the per-rule finding list is capped to keep output and storage bounded.
const MAX_NOTABLE_RULES: usize = 500;

/// Minimum declaration count for a rule to be fingerprinted as a duplicate-block
/// candidate. Small blocks (e.g. `display: flex; align-items: center`) repeat
/// legitimately, so the floor keeps the signal a strong copy-paste indicator.
const MIN_BLOCK_DECLARATIONS: usize = 4;

/// Upper bound on per-file declaration-block fingerprints. The `MIN_BLOCK`
/// floor already bounds compiled utility CSS (whose rules are tiny), so this
/// only guards a pathological hand-written stylesheet.
const MAX_DECLARATION_BLOCKS: usize = 2000;

/// Mask for a single 10-bit CSS specificity component.
const SPECIFICITY_COMPONENT_MASK: u32 = 0x3FF;

/// Compute structural CSS analytics for a standard-CSS stylesheet source.
///
/// Returns `None` only on a hard parse failure; with error recovery on,
/// individual malformed rules are skipped and the rest of the sheet still
/// contributes. Callers must gate by extension and NOT pass `.scss` sources:
/// Sass syntax is not standard CSS and recovers into an inaccurate partial
/// rather than `None`. Parsing runs in CSS Modules mode so `:local()` /
/// `:global()` selectors are understood.
#[must_use]
pub fn compute_css_analytics(source: &str) -> Option<CssAnalytics> {
    let options = ParserOptions {
        error_recovery: true,
        css_modules: Some(lightningcss::css_modules::Config::default()),
        ..ParserOptions::default()
    };
    let mut stylesheet = StyleSheet::parse(source, options).ok()?;

    // Pass 1: walk the rule tree for structural metrics + font-size / z-index
    // design tokens (these are top-level declaration properties).
    let mut acc = Accumulator::default();
    walk_rules(&stylesheet.rules.0, 0, &mut acc);

    // Pass 2: visit every color value (including colors nested inside shorthands
    // and gradients) for the design-token-sprawl signal. The visitor needs `&mut`,
    // so it runs after the immutable rule walk above.
    let mut collector = ValueCollector::default();
    let _ = collector.visit_stylesheet(&mut stylesheet);

    let mut analytics = acc.analytics;
    analytics.colors = sorted_vec(collector.colors);
    analytics.referenced_custom_properties = sorted_vec(collector.referenced_custom_properties);
    analytics.font_sizes = sorted_vec(acc.font_sizes);
    analytics.z_indexes = sorted_vec(acc.z_indexes);
    analytics.box_shadows = sorted_vec(acc.box_shadows);
    analytics.border_radii = sorted_vec(acc.border_radii);
    analytics.line_heights = sorted_vec(acc.line_heights);
    analytics.defined_custom_properties = sorted_vec(acc.defined_custom_properties);
    analytics.defined_keyframes = sorted_vec(acc.defined_keyframes);
    analytics.referenced_keyframes = sorted_vec(acc.referenced_keyframes);
    analytics.registered_custom_properties = sorted_vec(acc.registered_custom_properties);
    analytics.declared_layers = sorted_vec(acc.declared_layers);
    analytics.populated_layers = sorted_vec(acc.populated_layers);
    analytics.defined_font_faces = sorted_vec(acc.defined_font_faces);
    analytics.referenced_font_families = sorted_vec(acc.referenced_font_families);
    Some(analytics)
}

/// Working accumulator threaded through the rule walk: the structural analytics
/// plus the per-stylesheet sets of distinct `font-size` / `z-index` values.
#[derive(Default)]
struct Accumulator {
    analytics: CssAnalytics,
    font_sizes: FxHashSet<String>,
    z_indexes: FxHashSet<String>,
    box_shadows: FxHashSet<String>,
    border_radii: FxHashSet<String>,
    line_heights: FxHashSet<String>,
    defined_custom_properties: FxHashSet<String>,
    defined_keyframes: FxHashSet<String>,
    referenced_keyframes: FxHashSet<String>,
    registered_custom_properties: FxHashSet<String>,
    declared_layers: FxHashSet<String>,
    populated_layers: FxHashSet<String>,
    defined_font_faces: FxHashSet<String>,
    referenced_font_families: FxHashSet<String>,
}

/// The concrete family name of a `font-family` value, or `None` for a generic
/// keyword (`serif`, `sans-serif`, `monospace`, ...), which is never an authored
/// `@font-face`.
fn font_family_name(family: &FontFamily<'_>) -> Option<String> {
    match family {
        // Render the family via ToCss and strip surrounding quotes so a declared
        // `font-family: "Inter"` and a referenced `font-family: Inter` normalize
        // to the same key.
        FontFamily::FamilyName(_) => family
            .to_css_string(PrinterOptions::default())
            .ok()
            .map(|s| s.trim_matches(['"', '\'']).to_string()),
        FontFamily::Generic(_) => None,
    }
}

/// Collects value-level design tokens via the lightningcss visitor: every
/// distinct color (including colors nested in shorthands like `border` /
/// `background` and gradients, not just standalone `color:` values) and every
/// `var()` custom-property reference.
#[derive(Default)]
struct ValueCollector {
    colors: FxHashSet<String>,
    referenced_custom_properties: FxHashSet<String>,
}

impl Visitor<'_> for ValueCollector {
    type Error = std::convert::Infallible;

    fn visit_types(&self) -> VisitTypes {
        VisitTypes::COLORS | VisitTypes::VARIABLES
    }

    fn visit_color(&mut self, color: &mut CssColor) -> Result<(), Self::Error> {
        if let Ok(rendered) = color.to_css_string(PrinterOptions::default()) {
            self.colors.insert(rendered);
        }
        Ok(())
    }

    fn visit_variable(&mut self, var: &mut Variable<'_>) -> Result<(), Self::Error> {
        self.referenced_custom_properties
            .insert(var.name.ident.0.to_string());
        Ok(())
    }
}

fn sorted_vec(set: FxHashSet<String>) -> Vec<String> {
    let mut values: Vec<String> = set.into_iter().collect();
    values.sort_unstable();
    values
}

/// Recursively walk rules, tracking style-rule nesting depth. Grouping rules
/// (`@media` / `@supports` / `@container` / `@layer {}` / `@document` /
/// `@starting-style` / `@scope`) pass their nesting depth through unchanged;
/// only nesting INSIDE a style rule increases the depth.
fn walk_rules(rules: &[CssRule<'_>], depth: u8, acc: &mut Accumulator) {
    for rule in rules {
        match rule {
            CssRule::Style(style) => {
                record_style_rule(style, depth, acc);
                walk_rules(&style.rules.0, depth.saturating_add(1), acc);
            }
            CssRule::Media(rule) => walk_rules(&rule.rules.0, depth, acc),
            CssRule::Supports(rule) => walk_rules(&rule.rules.0, depth, acc),
            CssRule::Container(rule) => walk_rules(&rule.rules.0, depth, acc),
            CssRule::LayerBlock(rule) => {
                // A named `@layer a { }` both declares and populates layer `a`.
                if let Some(name) = &rule.name {
                    let name = layer_name_string(name);
                    acc.declared_layers.insert(name.clone());
                    acc.populated_layers.insert(name);
                }
                walk_rules(&rule.rules.0, depth, acc);
            }
            CssRule::LayerStatement(stmt) => {
                // `@layer a, b, c;` declares ordering but populates nothing.
                for name in &stmt.names {
                    acc.declared_layers.insert(layer_name_string(name));
                }
            }
            CssRule::Property(prop) => {
                acc.registered_custom_properties
                    .insert(prop.name.0.to_string());
            }
            CssRule::FontFace(font_face) => {
                for property in &font_face.properties {
                    if let FontFaceProperty::FontFamily(family) = property
                        && let Some(name) = font_family_name(family)
                    {
                        acc.defined_font_faces.insert(name);
                    }
                }
            }
            CssRule::MozDocument(rule) => walk_rules(&rule.rules.0, depth, acc),
            CssRule::StartingStyle(rule) => walk_rules(&rule.rules.0, depth, acc),
            CssRule::Scope(rule) => walk_rules(&rule.rules.0, depth, acc),
            CssRule::Nesting(rule) => {
                record_style_rule(&rule.style, depth, acc);
                walk_rules(&rule.style.rules.0, depth.saturating_add(1), acc);
            }
            CssRule::Keyframes(keyframes) => {
                acc.defined_keyframes
                    .insert(keyframes_name_string(&keyframes.name));
            }
            _ => {}
        }
    }
}

fn layer_name_string(name: &lightningcss::rules::layer::LayerName<'_>) -> String {
    name.0
        .iter()
        .map(std::string::ToString::to_string)
        .collect::<Vec<_>>()
        .join(".")
}

fn keyframes_name_string(name: &KeyframesName<'_>) -> String {
    match name {
        KeyframesName::Ident(ident) => ident.0.to_string(),
        KeyframesName::Custom(value) => value.to_string(),
    }
}

fn collect_animation_name(name: &AnimationName<'_>, out: &mut FxHashSet<String>) {
    if let AnimationName::Ident(ident) = name {
        out.insert(ident.0.to_string());
    }
}

fn record_style_rule(style: &StyleRule<'_>, depth: u8, acc: &mut Accumulator) {
    let normal = style.declarations.declarations.len();
    let important = style.declarations.important_declarations.len();
    let declaration_count = normal + important;

    let analytics = &mut acc.analytics;
    analytics.rule_count = analytics.rule_count.saturating_add(1);
    analytics.total_declarations = analytics
        .total_declarations
        .saturating_add(saturate_u32(declaration_count));
    analytics.important_declarations = analytics
        .important_declarations
        .saturating_add(saturate_u32(important));
    if declaration_count == 0 {
        analytics.empty_rule_count = analytics.empty_rule_count.saturating_add(1);
    }
    analytics.max_nesting_depth = analytics.max_nesting_depth.max(depth);

    let (a, b, c, complexity) = rule_selector_metrics(style);
    let metric = CssRuleMetric {
        line: style.loc.line.saturating_add(1),
        col: style.loc.column,
        specificity_a: a,
        specificity_b: b,
        specificity_c: c,
        complexity,
        declaration_count: saturate_u16(declaration_count),
        important_count: saturate_u16(important),
        nesting_depth: depth,
    };

    if is_notable(&metric) {
        if analytics.notable_rules.len() < MAX_NOTABLE_RULES {
            analytics.notable_rules.push(metric);
        } else {
            analytics.notable_truncated = true;
        }
    }

    // Fingerprint the declaration block (sorted, !important-tagged) for cross-file
    // duplicate-block detection, gated on the minimum block size and a per-file cap.
    if declaration_count >= MIN_BLOCK_DECLARATIONS
        && analytics.declaration_blocks.len() < MAX_DECLARATION_BLOCKS
        && let Some(fingerprint) = declaration_block_fingerprint(style)
    {
        analytics.declaration_blocks.push(CssDeclarationBlock {
            fingerprint,
            line: style.loc.line.saturating_add(1),
            declaration_count: saturate_u16(declaration_count),
        });
    }

    // Design-token values (font-size / z-index, authored form), custom-property
    // definitions, and animation-name references to @keyframes. Colors and
    // `var()` references are collected separately by the value visitor.
    for property in style
        .declarations
        .declarations
        .iter()
        .chain(style.declarations.important_declarations.iter())
    {
        match property {
            Property::FontSize(font_size) => {
                if let Ok(rendered) = font_size.to_css_string(PrinterOptions::default()) {
                    acc.font_sizes.insert(rendered);
                }
            }
            Property::ZIndex(z_index) => {
                if let Ok(rendered) = z_index.to_css_string(PrinterOptions::default()) {
                    acc.z_indexes.insert(rendered);
                }
            }
            // Shadow / radius / line-height tokens (design-token-sprawl axes).
            // The INNER value is serialized (not the property), so the vendor
            // prefix is dropped and `-webkit-box-shadow: X` collapses to the same
            // distinct value as `box-shadow: X` rather than inflating the count.
            Property::BoxShadow(shadows, _) => {
                let rendered: Vec<String> = shadows
                    .iter()
                    .filter_map(|shadow| shadow.to_css_string(PrinterOptions::default()).ok())
                    .collect();
                if !rendered.is_empty() && rendered.len() == shadows.len() {
                    acc.box_shadows.insert(rendered.join(", "));
                }
            }
            Property::BorderRadius(radius, _) => {
                if let Ok(rendered) = radius.to_css_string(PrinterOptions::default()) {
                    acc.border_radii.insert(rendered);
                }
            }
            Property::LineHeight(line_height) => {
                if let Ok(rendered) = line_height.to_css_string(PrinterOptions::default()) {
                    acc.line_heights.insert(rendered);
                }
            }
            Property::Custom(custom) => {
                if let CustomPropertyName::Custom(name) = &custom.name {
                    acc.defined_custom_properties.insert(name.0.to_string());
                }
                // A custom-property value can REFERENCE a font family without a
                // `font-family:` declaration: a Tailwind v4 `--font-*` theme token
                // (`--font-display: "Departure Mono", monospace`) is the canonical
                // case. lightningcss's `Property::FontFamily` / `Property::Font`
                // arms above never see this (a `--*:` declaration is an opaque
                // token stream), so scan the raw tokens for string / ident values
                // and credit them as referenced families. Generic keywords
                // (`serif`, `monospace`) never appear in `defined_font_faces`, so
                // crediting them here is inert; the `unused_font_faces`
                // set-difference only ever drops a genuinely-declared family.
                for token in &custom.value.0 {
                    if let TokenOrValue::Token(Token::String(value) | Token::Ident(value)) = token {
                        acc.referenced_font_families.insert(value.to_string());
                    }
                }
            }
            Property::AnimationName(names, _) => {
                for name in names {
                    collect_animation_name(name, &mut acc.referenced_keyframes);
                }
            }
            Property::Animation(animations, _) => {
                for animation in animations {
                    collect_animation_name(&animation.name, &mut acc.referenced_keyframes);
                }
            }
            Property::FontFamily(families) => {
                for family in families {
                    if let Some(name) = font_family_name(family) {
                        acc.referenced_font_families.insert(name);
                    }
                }
            }
            Property::Font(font) => {
                for family in &font.family {
                    if let Some(name) = font_family_name(family) {
                        acc.referenced_font_families.insert(name);
                    }
                }
            }
            _ => {}
        }
    }
}

/// Fingerprint a rule's declaration block: serialize each declaration (tagging
/// `!important` ones, which lightningcss stores without the flag, so they do not
/// collide with their non-important twin), sort for order-insensitivity, join,
/// and xxh3-hash. Returns `None` if any declaration fails to serialize, so a
/// partial block is never fingerprinted (a false duplicate match would be worse
/// than missing one).
fn declaration_block_fingerprint(style: &StyleRule<'_>) -> Option<u64> {
    let block = &style.declarations;
    let mut parts: Vec<String> =
        Vec::with_capacity(block.declarations.len() + block.important_declarations.len());
    for decl in &block.declarations {
        parts.push(decl.to_css_string(false, PrinterOptions::default()).ok()?);
    }
    for decl in &block.important_declarations {
        // `important = true` renders the `!important` suffix, so a block with an
        // important declaration never collides with its non-important twin.
        parts.push(decl.to_css_string(true, PrinterOptions::default()).ok()?);
    }
    parts.sort_unstable();
    Some(xxhash_rust::xxh3::xxh3_64(parts.join(";").as_bytes()))
}

/// Return the rule's `(specificity_a, specificity_b, specificity_c, complexity)`
/// taking the most specific selector and the most complex selector across the
/// rule's selector list.
fn rule_selector_metrics(style: &StyleRule<'_>) -> (u16, u16, u16, u16) {
    let mut max_spec = 0u32;
    let mut a = 0u16;
    let mut b = 0u16;
    let mut c = 0u16;
    let mut complexity = 0u16;
    for selector in &style.selectors.0 {
        let spec = selector.specificity();
        if spec >= max_spec {
            max_spec = spec;
            a = specificity_component(spec, 20);
            b = specificity_component(spec, 10);
            c = specificity_component(spec, 0);
        }
        complexity = complexity.max(selector_complexity(selector));
    }
    (a, b, c, complexity)
}

fn specificity_component(specificity: u32, shift: u32) -> u16 {
    saturate_u16_u32((specificity >> shift) & SPECIFICITY_COMPONENT_MASK)
}

fn is_notable(metric: &CssRuleMetric) -> bool {
    metric.specificity_a >= 1
        || metric.complexity > MAX_PLAIN_COMPLEXITY
        || metric.important_count >= 1
        || metric.nesting_depth >= NOTABLE_NESTING_DEPTH
}

fn selector_complexity(selector: &Selector<'_>) -> u16 {
    let mut count = 0u16;
    count_components(selector, &mut count);
    count
}

fn count_components(selector: &Selector<'_>, count: &mut u16) {
    for component in selector.iter_raw_match_order() {
        *count = count.saturating_add(1);
        match component {
            Component::Is(list)
            | Component::Where(list)
            | Component::Has(list)
            | Component::Negation(list)
            | Component::Any(_, list) => {
                for nested in list.as_ref() {
                    count_components(nested, count);
                }
            }
            Component::Slotted(nested) | Component::Host(Some(nested)) => {
                count_components(nested, count);
            }
            Component::NthOf(data) => {
                for nested in data.selectors() {
                    count_components(nested, count);
                }
            }
            _ => {}
        }
    }
}

fn saturate_u32(value: usize) -> u32 {
    u32::try_from(value).unwrap_or(u32::MAX)
}

fn saturate_u16(value: usize) -> u16 {
    u16::try_from(value).unwrap_or(u16::MAX)
}

fn saturate_u16_u32(value: u32) -> u16 {
    u16::try_from(value).unwrap_or(u16::MAX)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn analytics(source: &str) -> CssAnalytics {
        compute_css_analytics(source).expect("standard CSS parses")
    }

    #[test]
    fn recovers_partial_metrics_around_a_malformed_rule() {
        // Error recovery skips the broken rule and still records the valid one,
        // so a file with one bad rule is not lost wholesale.
        let a = analytics("#main { color: red; } @@@ broken @@@ .ok { color: blue; }");
        assert!(a.rule_count >= 1);
        assert!(a.notable_rules.iter().any(|r| r.specificity_a == 1));
    }

    #[test]
    fn counts_declarations_and_important() {
        let a = analytics(".a { color: red; width: 1px !important; }");
        assert_eq!(a.rule_count, 1);
        assert_eq!(a.total_declarations, 2);
        assert_eq!(a.important_declarations, 1);
    }

    #[test]
    fn id_selector_is_notable_with_specificity() {
        let a = analytics("#main { color: red; }");
        assert_eq!(a.notable_rules.len(), 1);
        let rule = &a.notable_rules[0];
        assert_eq!(rule.specificity_a, 1);
        assert_eq!(rule.specificity_b, 0);
        assert_eq!(rule.specificity_c, 0);
    }

    #[test]
    fn plain_class_rule_is_not_notable() {
        let a = analytics(".btn { color: red; }");
        assert!(a.notable_rules.is_empty(), "got {:?}", a.notable_rules);
        assert_eq!(a.rule_count, 1);
    }

    #[test]
    fn important_declaration_makes_rule_notable() {
        let a = analytics(".btn { color: red !important; }");
        assert_eq!(a.notable_rules.len(), 1);
        assert_eq!(a.notable_rules[0].important_count, 1);
    }

    #[test]
    fn empty_rule_counted() {
        let a = analytics(".a { } .b { color: red; }");
        assert_eq!(a.rule_count, 2);
        assert_eq!(a.empty_rule_count, 1);
    }

    #[test]
    fn complex_selector_is_notable() {
        // Five compound selectors joined by combinators exceeds the floor.
        let a = analytics("div > ul > li > a > span { color: red; }");
        assert_eq!(a.notable_rules.len(), 1);
        assert!(a.notable_rules[0].complexity > MAX_PLAIN_COMPLEXITY);
    }

    #[test]
    fn nesting_depth_tracked() {
        let a = analytics(".a { .b { .c { .d { color: red; } } } }");
        assert!(a.max_nesting_depth >= 3, "got {}", a.max_nesting_depth);
        // The depth-3 rule (`.d`) crosses the nesting floor.
        assert!(
            a.notable_rules
                .iter()
                .any(|r| r.nesting_depth >= NOTABLE_NESTING_DEPTH)
        );
    }

    #[test]
    fn specificity_takes_most_specific_selector_in_list() {
        let a = analytics("#id, .cls { color: red; }");
        assert_eq!(a.notable_rules.len(), 1);
        // `#id` (1,0,0) is more specific than `.cls` (0,1,0).
        assert_eq!(a.notable_rules[0].specificity_a, 1);
    }

    #[test]
    fn line_is_one_based() {
        let a = analytics("\n\n#main { color: red; }");
        assert_eq!(a.notable_rules[0].line, 3);
    }

    #[test]
    fn media_query_rules_walked() {
        let a = analytics("@media (min-width: 600px) { #main { color: red; } }");
        assert_eq!(a.rule_count, 1);
        assert_eq!(a.notable_rules.len(), 1);
        assert_eq!(a.notable_rules[0].specificity_a, 1);
    }

    #[test]
    fn collects_distinct_colors() {
        let a = analytics(".a { color: red; } .b { color: blue; } .c { color: red; }");
        assert_eq!(a.colors.len(), 2, "distinct colors deduped: {:?}", a.colors);
    }

    #[test]
    fn collects_colors_nested_in_shorthands() {
        // The color inside the `border` shorthand must be caught, not just the
        // standalone `background` color: that is the point of the value visitor.
        let a = analytics(".a { border: 1px solid green; background: yellow; }");
        assert!(
            a.colors.len() >= 2,
            "shorthand + standalone colors collected: {:?}",
            a.colors
        );
    }

    #[test]
    fn collects_distinct_font_sizes() {
        let a =
            analytics(".a { font-size: 14px; } .b { font-size: 14px; } .c { font-size: 1rem; }");
        assert_eq!(a.font_sizes.len(), 2, "got {:?}", a.font_sizes);
    }

    #[test]
    fn collects_distinct_z_indexes() {
        let a = analytics(".a { z-index: 10; } .b { z-index: 10; } .c { z-index: 999; }");
        assert_eq!(a.z_indexes.len(), 2, "got {:?}", a.z_indexes);
    }

    #[test]
    fn collects_defined_and_referenced_custom_properties() {
        let a = analytics(":root { --brand: red; --unused: blue; }\n.a { color: var(--brand); }");
        assert!(
            a.defined_custom_properties.contains(&"--brand".to_string()),
            "defined: {:?}",
            a.defined_custom_properties
        );
        assert!(
            a.defined_custom_properties
                .contains(&"--unused".to_string())
        );
        assert!(
            a.referenced_custom_properties
                .contains(&"--brand".to_string()),
            "referenced: {:?}",
            a.referenced_custom_properties
        );
        assert!(
            !a.referenced_custom_properties
                .contains(&"--unused".to_string()),
            "--unused has no var() reference"
        );
    }

    #[test]
    fn collects_defined_and_referenced_keyframes() {
        let a = analytics(
            "@keyframes spin { from {} to {} }\n@keyframes unused { from {} }\n.a { animation-name: spin; }",
        );
        assert!(a.defined_keyframes.contains(&"spin".to_string()));
        assert!(a.defined_keyframes.contains(&"unused".to_string()));
        assert!(a.referenced_keyframes.contains(&"spin".to_string()));
        assert!(
            !a.referenced_keyframes.contains(&"unused".to_string()),
            "no animation references `unused`"
        );
    }

    #[test]
    fn animation_shorthand_references_keyframes() {
        let a = analytics("@keyframes pulse { from {} }\n.a { animation: pulse 1s infinite; }");
        assert!(
            a.referenced_keyframes.contains(&"pulse".to_string()),
            "referenced: {:?}",
            a.referenced_keyframes
        );
    }

    #[test]
    fn fingerprints_blocks_at_floor_order_insensitive() {
        // Two 4-declaration rules with the same declarations in different order
        // share a fingerprint; a 3-declaration rule is below the floor and is
        // not fingerprinted.
        let a = analytics(
            ".x { color: red; margin: 1px; padding: 2px; top: 3px; }\n\
             .y { top: 3px; padding: 2px; margin: 1px; color: red; }\n\
             .z { color: red; margin: 1px; padding: 2px; }\n",
        );
        assert_eq!(
            a.declaration_blocks.len(),
            2,
            "two 4-decl rules fingerprinted, the 3-decl one skipped: {:?}",
            a.declaration_blocks
        );
        assert_eq!(
            a.declaration_blocks[0].fingerprint, a.declaration_blocks[1].fingerprint,
            "same declarations in different order share a fingerprint"
        );
        assert_eq!(a.declaration_blocks[0].declaration_count, 4);
    }

    #[test]
    fn important_distinguishes_block_fingerprint() {
        let a = analytics(
            ".x { color: red; margin: 1px; padding: 2px; top: 3px; }\n\
             .y { color: red !important; margin: 1px; padding: 2px; top: 3px; }\n",
        );
        assert_eq!(a.declaration_blocks.len(), 2);
        assert_ne!(
            a.declaration_blocks[0].fingerprint, a.declaration_blocks[1].fingerprint,
            "!important changes the block fingerprint"
        );
    }
}