Skip to main content

fallow_extract/
css.rs

1//! CSS/SCSS file parsing and CSS Module class name extraction.
2//!
3//! Handles `@import`, `@use`, `@forward`, `@plugin`, `@apply`, `@tailwind` directives,
4//! and extracts class names as named exports from `.module.css`/`.module.scss` files.
5//!
6//! Extraction is a deliberate hybrid, not a half-finished migration. lightningcss
7//! owns the membership decision for standard CSS (which `.token` occurrences are
8//! genuine class selectors, via `lightningcss_class_set`); the regex scanners own
9//! span location and the entire SCSS path. lightningcss parses standard CSS only,
10//! not SCSS syntax (`@use`, `@forward`, `//` line comments, `$variables`), so SCSS
11//! files are gated away from the parser and the regex chain stays as permanent
12//! infrastructure rather than a transitional step toward an all-parser tokenizer.
13
14use std::path::Path;
15use std::sync::LazyLock;
16
17use lightningcss::rules::CssRule;
18use lightningcss::selector::{Component, PseudoClass, Selector, SelectorList};
19use lightningcss::stylesheet::{ParserOptions, StyleSheet};
20use oxc_span::Span;
21use rustc_hash::FxHashSet;
22
23use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
24use fallow_types::discover::FileId;
25
26/// Regex to extract CSS @import sources.
27/// Matches: @import "path"; @import 'path'; @import url("path"); @import url('path'); @import url(path);
28static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
29    crate::static_regex(
30        r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
31    )
32});
33
34/// Regex to extract SCSS @use and @forward sources.
35/// Matches: @use "path"; @use 'path'; @forward "path"; @forward 'path';
36static SCSS_USE_RE: LazyLock<regex::Regex> =
37    LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
38
39/// Regex to extract Tailwind CSS @plugin sources.
40/// Matches: @plugin "package"; @plugin 'package'; @plugin "./local-plugin.js";
41static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
42    LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
43
44/// Regex to extract @apply class references.
45/// Matches: @apply class1 class2 class3;
46static CSS_APPLY_RE: LazyLock<regex::Regex> =
47    LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
48
49/// Regex to extract @tailwind directives.
50/// Matches: @tailwind base; @tailwind components; @tailwind utilities;
51static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
52    LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
53
54/// Regex to match CSS block comments (`/* ... */`) for stripping before extraction.
55static CSS_COMMENT_RE: LazyLock<regex::Regex> =
56    LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
57
58/// Regex to match SCSS single-line comments (`// ...`) for stripping before extraction.
59static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
60    LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
61
62/// Regex to extract CSS class names from selectors.
63/// Matches `.className` in selectors. Applied after stripping comments, strings, and URLs.
64static CSS_CLASS_RE: LazyLock<regex::Regex> =
65    LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
66
67/// Regex to strip quoted strings and `url(...)` content from CSS before class extraction.
68/// Prevents false positives from `content: ".foo"` and `url(./path/file.ext)`.
69static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
70    LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
71
72/// Regex to strip the prelude of `@layer` and `@import` at-rules before
73/// CSS-Modules class extraction. Matches the `@keyword` plus everything up to
74/// (but not including) the next `;` or `{`, so block bodies are preserved.
75///
76/// Narrow allowlist by design (issue #540): only at-rules whose preludes
77/// legitimately carry dot-separated identifiers without selector semantics are
78/// stripped. `@layer foo.bar` (CSS Cascading & Inheritance L5) lists layer
79/// names; `@import url("x.css") layer(theme.button)` carries a parenthesised
80/// layer reference. `@scope (.foo) to (.bar)` keeps its existing behavior
81/// because the prelude IS a selector list and `.foo` / `.bar` are real class
82/// references that the user may want to surface as exports.
83static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
84    LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
85
86pub(crate) fn is_css_file(path: &Path) -> bool {
87    path.extension()
88        .and_then(|e| e.to_str())
89        .is_some_and(|ext| matches!(ext, "css" | "scss" | "sass" | "less"))
90}
91
92/// A CSS import source with both the literal source and fallow's resolver-normalized form.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct CssImportSource {
95    /// The import source exactly as it appeared in `@import` / `@use` / `@forward` / `@plugin`.
96    pub raw: String,
97    /// The source normalized for fallow's resolver (`variables` -> `./variables` in SCSS).
98    pub normalized: String,
99    /// Whether this source came from Tailwind CSS `@plugin`.
100    pub is_plugin: bool,
101    /// Span of the source specifier in the original CSS/SCSS input.
102    pub span: Span,
103}
104
105fn is_css_module_file(path: &Path) -> bool {
106    is_css_file(path)
107        && path
108            .file_stem()
109            .and_then(|s| s.to_str())
110            .is_some_and(|stem| stem.ends_with(".module"))
111}
112
113/// Returns true if a CSS import source is a remote URL or data URI that should be skipped.
114fn is_css_url_import(source: &str) -> bool {
115    source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
116}
117
118/// Normalize a CSS/SCSS import path to use `./` prefix for relative paths.
119/// Bare file names such as `reset.css` stay relative for CSS ergonomics, while
120/// package subpaths such as `tailwindcss/theme.css` stay bare so bundler-style
121/// package CSS imports resolve through `node_modules`.
122///
123/// When `is_scss` is true, extensionless specifiers that are not SCSS built-in
124/// modules (`sass:*`) are treated as relative imports (SCSS partial convention).
125/// This handles `@use 'variables'` resolving to `./_variables.scss`.
126///
127/// Scoped npm packages (`@scope/pkg`) are always kept bare, even when they have
128/// CSS extensions (e.g., `@fontsource/monaspace-neon/400.css`). Bundlers like
129/// Vite resolve these from node_modules, not as relative paths.
130fn normalize_css_import_path(path: String, is_scss: bool) -> String {
131    if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
132        return path;
133    }
134    if path.starts_with('@') && path.contains('/') {
135        return path;
136    }
137    let path_ref = std::path::Path::new(&path);
138    if !is_scss
139        && path.contains('/')
140        && path_ref
141            .extension()
142            .and_then(|e| e.to_str())
143            .is_some_and(is_style_extension)
144    {
145        return path;
146    }
147    let ext = std::path::Path::new(&path)
148        .extension()
149        .and_then(|e| e.to_str());
150    match ext {
151        Some(e) if is_style_extension(e) => format!("./{path}"),
152        _ => {
153            if is_scss && !path.contains(':') {
154                format!("./{path}")
155            } else {
156                path
157            }
158        }
159    }
160}
161
162fn is_style_extension(ext: &str) -> bool {
163    ext.eq_ignore_ascii_case("css")
164        || ext.eq_ignore_ascii_case("scss")
165        || ext.eq_ignore_ascii_case("sass")
166        || ext.eq_ignore_ascii_case("less")
167}
168
169/// Strip comments from CSS/SCSS source to avoid matching directives inside comments.
170#[cfg(test)]
171fn strip_css_comments(source: &str, is_scss: bool) -> String {
172    let stripped = CSS_COMMENT_RE.replace_all(source, "");
173    if is_scss {
174        SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
175    } else {
176        stripped.into_owned()
177    }
178}
179
180fn mask_css_comments(source: &str, is_scss: bool) -> String {
181    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
182    if is_scss {
183        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
184    }
185    masked
186}
187
188/// Normalize a Tailwind CSS `@plugin` target.
189///
190/// Unlike SCSS `@use`, extensionless targets such as `daisyui` are package
191/// specifiers, not local partials. Keep bare specifiers bare and only preserve
192/// explicit relative/root-relative paths.
193fn normalize_css_plugin_path(path: String) -> String {
194    path
195}
196
197/// Extract `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
198///
199/// Returns both the raw source and the normalized source. URL imports
200/// (`http://`, `https://`, `data:`) are skipped. Use [`extract_css_imports`]
201/// when only the normalized form is needed.
202///
203/// Regex-based by design: this path also handles the SCSS `@use` / `@forward`
204/// forms, which lightningcss does not parse, so unlike class extraction there is
205/// no parser-backed set to defer the membership decision to.
206#[must_use]
207pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
208    let stripped = mask_css_comments(source, is_scss);
209    let mut out = Vec::new();
210
211    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
212        let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
213        if let Some(m) = raw {
214            let (src, span) = trimmed_match_with_span(m);
215            if !src.is_empty() && !is_css_url_import(&src) {
216                out.push(CssImportSource {
217                    normalized: normalize_css_import_path(src.clone(), is_scss),
218                    raw: src,
219                    is_plugin: false,
220                    span,
221                });
222            }
223        }
224    }
225
226    if is_scss {
227        for cap in SCSS_USE_RE.captures_iter(&stripped) {
228            if let Some(m) = cap.get(1) {
229                let (raw, span) = trimmed_match_with_span(m);
230                out.push(CssImportSource {
231                    normalized: normalize_css_import_path(raw.clone(), true),
232                    raw,
233                    is_plugin: false,
234                    span,
235                });
236            }
237        }
238    }
239
240    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
241        if let Some(m) = cap.get(1) {
242            let (raw, span) = trimmed_match_with_span(m);
243            if !raw.is_empty() && !is_css_url_import(&raw) {
244                out.push(CssImportSource {
245                    normalized: normalize_css_plugin_path(raw.clone()),
246                    raw,
247                    is_plugin: true,
248                    span,
249                });
250            }
251        }
252    }
253
254    out
255}
256
257fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
258    let raw = m.as_str();
259    let trimmed_start = raw.len() - raw.trim_start().len();
260    let trimmed_end = raw.trim_end().len();
261    let start = m.start() + trimmed_start;
262    let end = m.start() + trimmed_end;
263    (raw.trim().to_string(), Span::new(start as u32, end as u32))
264}
265
266/// Extract normalized `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
267///
268/// Returns specifiers normalized via `normalize_css_import_path`. URL imports
269/// (`http://`, `https://`, `data:`) are skipped. Used by callers that only need
270/// entry/dependency source paths; callers that need import kind information
271/// should use [`extract_css_import_sources`].
272#[must_use]
273pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
274    extract_css_import_sources(source, is_scss)
275        .into_iter()
276        .map(|source| source.normalized)
277        .collect()
278}
279
280/// Opening of a Tailwind v4 `@theme` block: `@theme`, optional modifier keywords
281/// (`inline` / `static` / `reference` / `default`), then the `{`. Matches up to
282/// and including the brace so the caller can brace-match the body from `end()`.
283static CSS_THEME_OPEN_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
284    crate::static_regex(r"@theme(?:\s+(?:inline|static|reference|default))*\s*\{")
285});
286
287/// A `var(--custom-property)` reference, capturing the dashed-ident name without
288/// the leading `--`. Used only to credit a theme token read by another theme
289/// token inside a `@theme` interior (lightningcss skips the unknown at-rule).
290static CSS_VAR_REF_RE: LazyLock<regex::Regex> =
291    LazyLock::new(|| crate::static_regex(r"var\(\s*--([A-Za-z0-9_-]+)"));
292
293/// A Tailwind v4 `@theme` token definition: the custom-property name WITHOUT the
294/// leading `--` (e.g. `color-brand`) and its 1-based line in the source.
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct ThemeTokenDef {
297    /// The custom-property name with the `--` prefix stripped (`color-brand`).
298    pub name: String,
299    /// The normalized top-level declaration value, with internal whitespace
300    /// collapsed. Empty only when the value could not be recovered.
301    pub value: String,
302    /// 1-based line of the declaration in the original source.
303    pub line: u32,
304}
305
306/// Result of scanning a CSS source for Tailwind v4 `@theme` blocks.
307#[derive(Debug, Clone, Default, PartialEq, Eq)]
308pub struct ThemeScan {
309    /// Custom-property tokens DEFINED at the top level of a `@theme` block, with
310    /// the `*`-reset form (`--color-*: initial`) and bare-namespace declarations
311    /// excluded. Deduped by name (first definition wins for the line).
312    pub tokens: Vec<ThemeTokenDef>,
313    /// Custom-property names (without `--`) READ via `var()` anywhere inside a
314    /// `@theme` block interior, each paired with the 1-based source line of the
315    /// `var(` token. lightningcss does not descend into the unknown `@theme`
316    /// at-rule, so these reads are invisible to `CssAnalytics`; a token backing
317    /// another token (`--color-button: var(--color-brand)`) keeps the backing
318    /// token live.
319    pub theme_var_reads: Vec<(String, u32)>,
320}
321
322/// Scan a CSS source for Tailwind v4 `@theme` blocks, returning the defined
323/// design tokens plus the custom properties read via `var()` inside those blocks.
324///
325/// Tailwind v4 is CSS-first, so `@theme { --color-brand: #f00; }` is the unit of
326/// a user-authored design token. lightningcss treats `@theme` as an unknown
327/// at-rule and skips it, so this is a separate brace-matching pass (comments and
328/// strings masked first so braces / semicolons inside them never break the block
329/// boundary). Only top-level `--ident: value` declarations are tokens; declarations
330/// inside a nested block (e.g. `@keyframes` for `--animate-*`) are not.
331#[must_use]
332pub fn scan_theme_blocks(source: &str) -> ThemeScan {
333    // Fast path: skip the masking allocation for the common no-`@theme` file.
334    if !source.contains("@theme") {
335        return ThemeScan::default();
336    }
337    let masked = mask_theme_source(source);
338    let mut out = ThemeScan::default();
339    let mut seen: FxHashSet<String> = FxHashSet::default();
340    for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
341        let body_start = open.end();
342        let body_end = find_theme_body_end(&masked, body_start);
343        collect_theme_declarations(&mut ThemeDeclarationScan {
344            source,
345            masked: &masked,
346            start: body_start,
347            end: body_end,
348            out: &mut out.tokens,
349            seen: &mut seen,
350        });
351        collect_theme_var_reads(
352            source,
353            &masked,
354            body_start,
355            body_end,
356            &mut out.theme_var_reads,
357        );
358    }
359    out
360}
361
362/// Located regular-CSS `var(--token)` reads OUTSIDE any `@theme` block interior:
363/// `(name, line)` per read, with the `--` stripped from the name. `@theme`-
364/// interior reads are deliberately excluded here (they are located separately by
365/// [`scan_theme_blocks`] as the distinct `theme-var` surface), so the two read
366/// kinds never double-count. Comments / strings / `url()` are masked first, so a
367/// `var()` inside those regions is never matched.
368#[must_use]
369pub fn extract_css_var_reads_located(source: &str) -> Vec<(String, u32)> {
370    if !source.contains("var(") {
371        return Vec::new();
372    }
373    let masked = mask_theme_source(source);
374    // Byte ranges of every `@theme { ... }` interior, so reads inside them are
375    // skipped (they are the `theme-var` surface, located elsewhere).
376    let mut theme_bodies: Vec<(usize, usize)> = Vec::new();
377    if masked.contains("@theme") {
378        for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
379            let body_start = open.end();
380            let body_end = find_theme_body_end(&masked, body_start);
381            theme_bodies.push((body_start, body_end));
382        }
383    }
384    let in_theme = |offset: usize| theme_bodies.iter().any(|&(s, e)| offset >= s && offset < e);
385    let mut out = Vec::new();
386    // Incremental line counter: `captures_iter` yields matches in source order, so
387    // advance from the previous read's offset instead of rescanning the whole
388    // prefix per read (issue #1843 follow-up). Masking preserves byte offsets 1:1,
389    // but newlines are counted over `source` (comment masking blanks newlines in
390    // `masked`), matching the original `line_at_offset(source, ..)`.
391    let mut last_pos = 0usize;
392    let mut last_line = 1u32;
393    for cap in CSS_VAR_REF_RE.captures_iter(&masked) {
394        let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
395            continue;
396        };
397        if in_theme(whole.start()) {
398            continue;
399        }
400        let offset = whole.start();
401        last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
402        last_pos = offset;
403        out.push((name.as_str().to_owned(), last_line));
404    }
405    out
406}
407
408/// Mask comments, strings, and `url(...)` while preserving byte offsets so
409/// braces inside those regions never affect `@theme` block matching.
410fn mask_theme_source(source: &str) -> String {
411    mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE)
412}
413
414/// Brace-match from just after a `@theme {` opener to its partner.
415fn find_theme_body_end(masked: &str, body_start: usize) -> usize {
416    let bytes = masked.as_bytes();
417    let mut depth = 1usize;
418    let mut i = body_start;
419    while i < bytes.len() {
420        match bytes[i] {
421            b'{' => depth += 1,
422            b'}' => {
423                depth -= 1;
424                if depth == 0 {
425                    break;
426                }
427            }
428            _ => {}
429        }
430        i += 1;
431    }
432    i.min(bytes.len())
433}
434
435fn collect_theme_var_reads(
436    source: &str,
437    masked: &str,
438    body_start: usize,
439    body_end: usize,
440    out: &mut Vec<(String, u32)>,
441) {
442    let Some(body) = masked.get(body_start..body_end) else {
443        return;
444    };
445    // Incremental line counter: matches arrive in source order, so advance from
446    // the previous read's offset instead of rescanning the whole prefix per read
447    // (issue #1843 follow-up). Starting from offset 0 keeps the first read's line
448    // identical to `line_at_offset(source, offset)`.
449    let mut last_pos = 0usize;
450    let mut last_line = 1u32;
451    for cap in CSS_VAR_REF_RE.captures_iter(body) {
452        let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
453            continue;
454        };
455        // Absolute byte offset of the `var(` token start in the original source
456        // (masking preserves byte offsets 1:1).
457        let offset = body_start + whole.start();
458        last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
459        last_pos = offset;
460        out.push((name.as_str().to_owned(), last_line));
461    }
462}
463
464/// 1-based line number of `offset` in `source`, counting `\n` up to (but not
465/// including) the byte at `offset`. Out-of-range offsets clamp to line 1.
466fn line_at_offset(source: &str, offset: usize) -> u32 {
467    let count = source
468        .get(..offset)
469        .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
470    u32::try_from(1 + count).unwrap_or(u32::MAX)
471}
472
473/// Count the `\n` bytes in `source[from..to]`, returning 0 for a reversed or
474/// out-of-range span. Feeds an incremental 1-based line counter across regex
475/// matches that arrive in source order, replacing the O(matches * n) per-match
476/// `source[..offset]` prefix rescan (issue #1843 follow-up: worst on a single
477/// long line with no newlines).
478fn newlines_between(source: &str, from: usize, to: usize) -> u32 {
479    let count = source
480        .get(from..to)
481        .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
482    u32::try_from(count).unwrap_or(u32::MAX)
483}
484
485/// Walk a masked `@theme` body collecting top-level `--ident: value` declarations
486/// as tokens. Tracks brace depth so declarations inside a nested block (e.g. an
487/// `@keyframes` for `--animate-*`) are skipped, and statement position so only a
488/// `--ident` at a declaration start counts. The `*`-reset form (`--color-*`) is
489/// excluded because the `*` breaks the ident scan before the `:`.
490fn collect_theme_declarations(scan: &mut ThemeDeclarationScan<'_, '_>) {
491    let bytes = scan.masked.as_bytes();
492    let mut depth = 0usize;
493    let mut expect_decl = true;
494    let mut i = scan.start;
495    while i < scan.end {
496        let b = bytes[i];
497        match b {
498            b'{' => {
499                depth += 1;
500                expect_decl = false;
501                i += 1;
502            }
503            b'}' => {
504                depth = depth.saturating_sub(1);
505                if depth == 0 {
506                    expect_decl = true;
507                }
508                i += 1;
509            }
510            b';' => {
511                if depth == 0 {
512                    expect_decl = true;
513                }
514                i += 1;
515            }
516            _ if b.is_ascii_whitespace() => i += 1,
517            _ => {
518                if depth == 0 && expect_decl {
519                    expect_decl = false;
520                    i = scan_theme_declaration(scan, b, i);
521                } else {
522                    i += 1;
523                }
524            }
525        }
526    }
527}
528
529struct ThemeDeclarationScan<'a, 'b> {
530    source: &'a str,
531    masked: &'a str,
532    start: usize,
533    end: usize,
534    out: &'b mut Vec<ThemeTokenDef>,
535    seen: &'b mut FxHashSet<String>,
536}
537
538/// At a declaration start, harvest a `--ident:` custom-property name and return
539/// the cursor advanced past the scanned ident. Returns `i + 1` for any non-`--`
540/// declaration start.
541fn scan_theme_declaration(scan: &mut ThemeDeclarationScan<'_, '_>, b: u8, i: usize) -> usize {
542    let bytes = scan.masked.as_bytes();
543    if !(b == b'-' && bytes.get(i + 1) == Some(&b'-')) {
544        return i + 1;
545    }
546    let id_start = i;
547    let mut j = i;
548    while j < scan.end {
549        let c = bytes[j];
550        if c == b'-' || c == b'_' || c.is_ascii_alphanumeric() {
551            j += 1;
552        } else {
553            break;
554        }
555    }
556    let mut k = j;
557    while k < scan.end && bytes[k].is_ascii_whitespace() {
558        k += 1;
559    }
560    // Only a `--ident:` (no `*` before the colon) is a token.
561    if k < scan.end && bytes[k] == b':' {
562        let name = &scan.masked[id_start + 2..j];
563        if !name.is_empty() && scan.seen.insert(name.to_owned()) {
564            let value = theme_declaration_value(scan.source, scan.masked, k + 1, scan.end);
565            let line = 1 + scan
566                .source
567                .get(..id_start)
568                .map_or(0, |s| s.bytes().filter(|&x| x == b'\n').count());
569            scan.out.push(ThemeTokenDef {
570                name: name.to_owned(),
571                value,
572                line: u32::try_from(line).unwrap_or(u32::MAX),
573            });
574        }
575    }
576    j
577}
578
579fn theme_declaration_value(source: &str, masked: &str, start: usize, end: usize) -> String {
580    let bytes = masked.as_bytes();
581    let mut depth = 0usize;
582    let mut i = start;
583    while i < end {
584        match bytes[i] {
585            b'{' => depth += 1,
586            b'}' => {
587                if depth == 0 {
588                    break;
589                }
590                depth -= 1;
591            }
592            b';' if depth == 0 => break,
593            _ => {}
594        }
595        i += 1;
596    }
597    source
598        .get(start..i)
599        .unwrap_or_default()
600        .split_whitespace()
601        .collect::<Vec<_>>()
602        .join(" ")
603}
604
605/// Extract the utility tokens referenced in `@apply` directive bodies across a
606/// CSS source (comment / string masked). `@apply rounded-card font-bold;` yields
607/// `["rounded-card", "font-bold"]`. The leading-`!` and trailing-`!` important
608/// modifiers and a bare `!important` token are stripped, so a theme token whose
609/// utility is applied only via `@apply` is credited as used.
610#[must_use]
611pub fn extract_apply_tokens(source: &str) -> Vec<String> {
612    // Fast path: skip the masking allocation for the common no-`@apply` file.
613    if !source.contains("@apply") {
614        return Vec::new();
615    }
616    let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
617    let mut out = Vec::new();
618    for m in CSS_APPLY_RE.find_iter(&masked) {
619        let body = m.as_str().trim_start_matches("@apply");
620        for token in body.split_whitespace() {
621            let token = token.trim_matches('!');
622            if token.is_empty() || token == "important" {
623                continue;
624            }
625            out.push(token.to_owned());
626        }
627    }
628    out
629}
630
631/// Like [`extract_apply_tokens`], but pairs each class-shaped token with the
632/// 1-based source line of its `@apply` directive. Used by the token-consumer
633/// reverse index to locate `@apply`-surface consumers; masking preserves byte
634/// offsets so the directive line is recoverable from the match start.
635#[must_use]
636pub fn extract_apply_tokens_located(source: &str) -> Vec<(String, u32)> {
637    if !source.contains("@apply") {
638        return Vec::new();
639    }
640    let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
641    let mut out = Vec::new();
642    for m in CSS_APPLY_RE.find_iter(&masked) {
643        let line = line_at_offset(source, m.start());
644        let body = m.as_str().trim_start_matches("@apply");
645        for token in body.split_whitespace() {
646            let token = token.trim_matches('!');
647            if token.is_empty() || token == "important" {
648                continue;
649            }
650            out.push((token.to_owned(), line));
651        }
652    }
653    out
654}
655
656/// Mask every regex match in `src` with ASCII spaces (`0x20`) of equal byte
657/// length, so byte offsets in the returned string correspond 1:1 to byte
658/// offsets in the original.
659///
660/// Used to neutralise CSS comments, quoted strings, `url(...)`, and at-rule
661/// preludes before scanning for `.class` selectors, while preserving the
662/// original-source positions that callers need to populate `ExportInfo.span`
663/// (issue #549). The `regex` crate guarantees match boundaries respect UTF-8
664/// char boundaries, so the masked buffer is always valid UTF-8.
665fn mask_with_whitespace(src: &str, re: &regex::Regex) -> String {
666    let mut out = String::with_capacity(src.len());
667    let mut cursor = 0;
668    for m in re.find_iter(src) {
669        out.push_str(&src[cursor..m.start()]);
670        for _ in m.start()..m.end() {
671            out.push(' ');
672        }
673        cursor = m.end();
674    }
675    out.push_str(&src[cursor..]);
676    out
677}
678
679/// Collect the authoritative set of class-selector names from a CSS source by
680/// parsing it into a real AST (lightningcss). Returns `None` only on a
681/// catastrophic parse failure (Sass syntax that is not standard CSS), in which
682/// case the caller falls back to the regex scanner. With `error_recovery` on,
683/// individual malformed rules are recovered silently and contribute a partial
684/// set rather than triggering the fallback, so a broken rule drops only its own
685/// classes (a conservative miss) instead of returning `None`.
686///
687/// This is the source of truth for which `.token` occurrences are genuine class
688/// selectors. It natively excludes `@layer foo.bar` layer names, `@import ...
689/// layer(theme.button)` layer references, `@keyframes` step selectors, id and
690/// element selectors, and the contents of comments / strings / `url()`, which
691/// the older regex-only scanner had to approximate with a stack of masking
692/// passes. Classes nested inside `:is()` / `:where()` / `:not()` / `:has()` /
693/// `:any()` / `::slotted()` / `:host()` / `:nth-child(... of ...)` are
694/// collected too, matching the regex scanner's "every `.class` token" behavior.
695fn lightningcss_class_set(source: &str) -> Option<FxHashSet<String>> {
696    let options = ParserOptions {
697        // Recover from individual malformed rules so a single bad rule does not
698        // discard class names from the rest of the file.
699        error_recovery: true,
700        // These files are `.module.css` / `.module.scss`, so parse in CSS Modules
701        // mode. That makes the `:local()` / `:global()` pseudo-classes parse as
702        // real selectors rather than erroring, so classes wrapped in them are
703        // collected (matching the regex scanner). Renaming is a print-time
704        // concern, so the AST class names stay the original author-written names.
705        css_modules: Some(lightningcss::css_modules::Config::default()),
706        ..ParserOptions::default()
707    };
708    let stylesheet = StyleSheet::parse(source, options).ok()?;
709    let mut classes = FxHashSet::default();
710    collect_classes_from_rules(&stylesheet.rules.0, &mut classes);
711    Some(classes)
712}
713
714/// Recursively collect class-selector names from a list of CSS rules, descending
715/// into every grouping rule (`@media`, `@supports`, `@container`, `@layer {}`,
716/// `@document`, `@starting-style`, `@scope`, nested style rules) so a class
717/// declared anywhere contributes to the set.
718fn collect_classes_from_rules(rules: &[CssRule<'_>], classes: &mut FxHashSet<String>) {
719    for rule in rules {
720        match rule {
721            CssRule::Style(style) => {
722                collect_classes_from_selector_list(&style.selectors, classes);
723                collect_classes_from_rules(&style.rules.0, classes);
724            }
725            CssRule::Media(rule) => collect_classes_from_rules(&rule.rules.0, classes),
726            CssRule::Supports(rule) => collect_classes_from_rules(&rule.rules.0, classes),
727            CssRule::Container(rule) => collect_classes_from_rules(&rule.rules.0, classes),
728            CssRule::LayerBlock(rule) => collect_classes_from_rules(&rule.rules.0, classes),
729            CssRule::MozDocument(rule) => collect_classes_from_rules(&rule.rules.0, classes),
730            CssRule::StartingStyle(rule) => collect_classes_from_rules(&rule.rules.0, classes),
731            CssRule::Nesting(rule) => {
732                collect_classes_from_selector_list(&rule.style.selectors, classes);
733                collect_classes_from_rules(&rule.style.rules.0, classes);
734            }
735            CssRule::Scope(rule) => {
736                if let Some(scope_start) = &rule.scope_start {
737                    collect_classes_from_selector_list(scope_start, classes);
738                }
739                if let Some(scope_end) = &rule.scope_end {
740                    collect_classes_from_selector_list(scope_end, classes);
741                }
742                collect_classes_from_rules(&rule.rules.0, classes);
743            }
744            _ => {}
745        }
746    }
747}
748
749fn collect_classes_from_selector_list(list: &SelectorList<'_>, classes: &mut FxHashSet<String>) {
750    for selector in &list.0 {
751        collect_classes_from_selector(selector, classes);
752    }
753}
754
755fn collect_classes_from_selector(selector: &Selector<'_>, classes: &mut FxHashSet<String>) {
756    for component in selector.iter_raw_match_order() {
757        match component {
758            Component::Class(name) => {
759                classes.insert(name.0.to_string());
760            }
761            Component::Is(list)
762            | Component::Where(list)
763            | Component::Has(list)
764            | Component::Negation(list)
765            | Component::Any(_, list) => {
766                for nested in list.as_ref() {
767                    collect_classes_from_selector(nested, classes);
768                }
769            }
770            Component::Slotted(nested) | Component::Host(Some(nested)) => {
771                collect_classes_from_selector(nested, classes);
772            }
773            Component::NthOf(data) => {
774                for nested in data.selectors() {
775                    collect_classes_from_selector(nested, classes);
776                }
777            }
778            // CSS Modules `:local(.foo)` / `:global(.foo)` wrap a real selector.
779            Component::NonTSPseudoClass(
780                PseudoClass::Local { selector } | PseudoClass::Global { selector },
781            ) => collect_classes_from_selector(selector, classes),
782            _ => {}
783        }
784    }
785}
786
787/// Extract class names from a CSS module file as named exports.
788///
789/// For standard CSS, lightningcss parses the source into an AST and supplies the
790/// authoritative set of class-selector names; the byte-offset scanner then
791/// locates each name's [`Span`] in the ORIGINAL `source` (pointing at the bare
792/// class name, no leading dot) so downstream `compute_line_offsets` resolves the
793/// real declaration line and column instead of falling back to line:1 col:0
794/// (issue #549). For SCSS (Sass syntax lightningcss does not parse) and for any
795/// CSS that fails to parse outright, the regex-only scanner is used unchanged.
796pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
797    if !is_scss && let Some(class_set) = lightningcss_class_set(source) {
798        return scan_css_module_exports(source, is_scss, Some(&class_set));
799    }
800    scan_css_module_exports(source, is_scss, None)
801}
802
803/// Scan `source` for `.class` tokens and emit one [`ExportInfo`] per distinct
804/// class (first occurrence wins), with a [`Span`] pointing at the post-dot
805/// identifier in the original source.
806///
807/// When `class_filter` is `Some`, only tokens present in the AST-derived set are
808/// emitted, so the parser owns the membership decision and the scanner owns only
809/// span location. When `class_filter` is `None` (SCSS / parse-failure fallback),
810/// the at-rule prelude is masked to keep `@layer foo.bar` / `@import ...
811/// layer(...)` segments from being mistaken for classes.
812fn scan_css_module_exports(
813    source: &str,
814    is_scss: bool,
815    class_filter: Option<&FxHashSet<String>>,
816) -> Vec<ExportInfo> {
817    let masked = mask_css_module_class_candidates(source, is_scss, class_filter.is_some());
818    let mut seen = FxHashSet::default();
819    let mut exports = Vec::new();
820    for cap in CSS_CLASS_RE.captures_iter(&masked) {
821        if let Some(m) = cap.get(1) {
822            push_css_class_export(m, class_filter, &mut seen, &mut exports);
823        }
824    }
825    exports
826}
827
828fn mask_css_module_class_candidates(source: &str, is_scss: bool, has_class_filter: bool) -> String {
829    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
830    if is_scss {
831        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
832    }
833    masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
834    if !has_class_filter {
835        masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
836    }
837    masked
838}
839
840fn push_css_class_export(
841    class_match: regex::Match<'_>,
842    class_filter: Option<&FxHashSet<String>>,
843    seen: &mut FxHashSet<String>,
844    exports: &mut Vec<ExportInfo>,
845) {
846    let class_name = class_match.as_str().to_string();
847    if class_filter.is_some_and(|filter| !filter.contains(&class_name)) {
848        return;
849    }
850    if seen.insert(class_name.clone()) {
851        exports.push(css_class_export(class_name, class_match));
852    }
853}
854
855fn css_class_export(class_name: String, class_match: regex::Match<'_>) -> ExportInfo {
856    #[expect(
857        clippy::cast_possible_truncation,
858        reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
859    )]
860    let span = Span::new(class_match.start() as u32, class_match.end() as u32);
861    ExportInfo {
862        name: ExportName::Named(class_name),
863        local_name: None,
864        is_type_only: false,
865        visibility: VisibilityTag::None,
866        expected_unused_reason: None,
867        span,
868        members: Vec::new(),
869        is_side_effect_used: false,
870        super_class: None,
871    }
872}
873
874/// Build the import edges for a CSS/SCSS source: every `@import`/`@use`/etc.
875/// directive plus a synthetic `tailwindcss` side-effect import when `@apply` or
876/// `@tailwind` is present.
877fn build_css_imports(source: &str, stripped: &str, is_scss: bool) -> Vec<ImportInfo> {
878    let mut imports = Vec::new();
879
880    for css_source in extract_css_import_sources(source, is_scss) {
881        imports.push(ImportInfo {
882            source: css_source.normalized,
883            imported_name: if css_source.is_plugin {
884                ImportedName::Default
885            } else {
886                ImportedName::SideEffect
887            },
888            local_name: String::new(),
889            is_type_only: false,
890            from_style: false,
891            span: css_source.span,
892            source_span: css_source.span,
893        });
894    }
895
896    let has_apply = CSS_APPLY_RE.is_match(stripped);
897    let has_tailwind = CSS_TAILWIND_RE.is_match(stripped);
898    if has_apply || has_tailwind {
899        imports.push(ImportInfo {
900            source: "tailwindcss".to_string(),
901            imported_name: ImportedName::SideEffect,
902            local_name: String::new(),
903            is_type_only: false,
904            from_style: false,
905            span: Span::default(),
906            source_span: Span::default(),
907        });
908    }
909
910    imports
911}
912
913/// Parse a CSS/SCSS file, extracting @import, @use, @forward, @plugin, @apply, and @tailwind directives.
914pub(crate) fn parse_css_to_module(
915    file_id: FileId,
916    path: &Path,
917    source: &str,
918    content_hash: u64,
919) -> ModuleInfo {
920    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
921    let is_scss = path
922        .extension()
923        .and_then(|e| e.to_str())
924        .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
925
926    let stripped = mask_css_comments(source, is_scss);
927    let imports = build_css_imports(source, &stripped, is_scss);
928
929    let exports = if is_css_module_file(path) {
930        extract_css_module_exports(source, is_scss)
931    } else {
932        Vec::new()
933    };
934
935    css_module_info(
936        file_id,
937        content_hash,
938        source,
939        parsed_suppressions,
940        imports,
941        exports,
942    )
943}
944
945/// Assemble the `ModuleInfo` for a CSS/SCSS file: the import/export edges plus
946/// the line offsets and suppressions; all AST-derived fields stay empty since
947/// CSS carries no JS-level structure. Pure plumbing struct literal.
948fn css_module_info(
949    file_id: FileId,
950    content_hash: u64,
951    source: &str,
952    parsed_suppressions: crate::suppress::ParsedSuppressions,
953    imports: Vec<ImportInfo>,
954    exports: Vec<ExportInfo>,
955) -> ModuleInfo {
956    crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
957        file_id,
958        content_hash,
959        source,
960        parsed_suppressions,
961        imports,
962        exports,
963    })
964}
965
966#[cfg(all(test, not(miri)))]
967mod tests {
968    use super::*;
969
970    /// Helper to collect export names as strings from `extract_css_module_exports`.
971    fn export_names(source: &str) -> Vec<String> {
972        extract_css_module_exports(source, false)
973            .into_iter()
974            .filter_map(|e| match e.name {
975                ExportName::Named(n) => Some(n),
976                ExportName::Default => None,
977            })
978            .collect()
979    }
980
981    #[test]
982    fn is_css_file_css() {
983        assert!(is_css_file(Path::new("styles.css")));
984    }
985
986    #[test]
987    fn is_css_file_scss() {
988        assert!(is_css_file(Path::new("styles.scss")));
989    }
990
991    #[test]
992    fn is_css_file_sass() {
993        assert!(is_css_file(Path::new("styles.sass")));
994    }
995
996    #[test]
997    fn is_css_file_less() {
998        assert!(is_css_file(Path::new("styles.less")));
999    }
1000
1001    #[test]
1002    fn is_css_file_rejects_js() {
1003        assert!(!is_css_file(Path::new("app.js")));
1004    }
1005
1006    #[test]
1007    fn is_css_file_rejects_ts() {
1008        assert!(!is_css_file(Path::new("app.ts")));
1009    }
1010
1011    #[test]
1012    fn is_css_file_rejects_no_extension() {
1013        assert!(!is_css_file(Path::new("Makefile")));
1014    }
1015
1016    #[test]
1017    fn is_css_module_file_module_css() {
1018        assert!(is_css_module_file(Path::new("Component.module.css")));
1019    }
1020
1021    #[test]
1022    fn is_css_module_file_module_scss() {
1023        assert!(is_css_module_file(Path::new("Component.module.scss")));
1024    }
1025
1026    #[test]
1027    fn is_css_module_file_rejects_plain_css() {
1028        assert!(!is_css_module_file(Path::new("styles.css")));
1029    }
1030
1031    #[test]
1032    fn is_css_module_file_rejects_plain_scss() {
1033        assert!(!is_css_module_file(Path::new("styles.scss")));
1034    }
1035
1036    #[test]
1037    fn is_css_module_file_rejects_module_js() {
1038        assert!(!is_css_module_file(Path::new("utils.module.js")));
1039    }
1040
1041    #[test]
1042    fn extracts_single_class() {
1043        let names = export_names(".foo { color: red; }");
1044        assert_eq!(names, vec!["foo"]);
1045    }
1046
1047    #[test]
1048    fn extracts_multiple_classes() {
1049        let names = export_names(".foo { } .bar { }");
1050        assert_eq!(names, vec!["foo", "bar"]);
1051    }
1052
1053    #[test]
1054    fn extracts_nested_classes() {
1055        let names = export_names(".foo .bar { color: red; }");
1056        assert!(names.contains(&"foo".to_string()));
1057        assert!(names.contains(&"bar".to_string()));
1058    }
1059
1060    #[test]
1061    fn extracts_hyphenated_class() {
1062        let names = export_names(".my-class { }");
1063        assert_eq!(names, vec!["my-class"]);
1064    }
1065
1066    #[test]
1067    fn extracts_camel_case_class() {
1068        let names = export_names(".myClass { }");
1069        assert_eq!(names, vec!["myClass"]);
1070    }
1071
1072    #[test]
1073    fn extracts_class_inside_global_pseudo() {
1074        // CSS Modules `:global(.foo)` must surface `foo`: the parser understands
1075        // the wrapped selector, which the regex scanner could not on its own.
1076        let names = export_names(":global(.globalClass) { color: red; }");
1077        assert_eq!(names, vec!["globalClass"]);
1078    }
1079
1080    #[test]
1081    fn extracts_class_inside_local_pseudo() {
1082        let names = export_names(":local(.localClass) { color: red; }");
1083        assert_eq!(names, vec!["localClass"]);
1084    }
1085
1086    #[test]
1087    fn extracts_classes_inside_negation() {
1088        let names = export_names(".btn:not(.disabled) { }");
1089        assert!(names.contains(&"btn".to_string()), "got {names:?}");
1090        assert!(names.contains(&"disabled".to_string()), "got {names:?}");
1091    }
1092
1093    #[test]
1094    fn extracts_classes_inside_is_and_where() {
1095        let names = export_names(":is(.a, .b) :where(.c) { }");
1096        for expected in ["a", "b", "c"] {
1097            assert!(
1098                names.contains(&expected.to_string()),
1099                "missing {expected} in {names:?}"
1100            );
1101        }
1102    }
1103
1104    #[test]
1105    fn extracts_underscore_class() {
1106        let names = export_names("._hidden { } .__wrapper { }");
1107        assert!(names.contains(&"_hidden".to_string()));
1108        assert!(names.contains(&"__wrapper".to_string()));
1109    }
1110
1111    #[test]
1112    fn pseudo_selector_hover() {
1113        let names = export_names(".foo:hover { color: blue; }");
1114        assert_eq!(names, vec!["foo"]);
1115    }
1116
1117    #[test]
1118    fn pseudo_selector_focus() {
1119        let names = export_names(".input:focus { outline: none; }");
1120        assert_eq!(names, vec!["input"]);
1121    }
1122
1123    #[test]
1124    fn pseudo_element_before() {
1125        let names = export_names(".icon::before { content: ''; }");
1126        assert_eq!(names, vec!["icon"]);
1127    }
1128
1129    #[test]
1130    fn combined_pseudo_selectors() {
1131        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
1132        assert_eq!(names, vec!["btn"]);
1133    }
1134
1135    #[test]
1136    fn classes_inside_media_query() {
1137        let names = export_names(
1138            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
1139        );
1140        assert!(names.contains(&"mobile-nav".to_string()));
1141        assert!(names.contains(&"desktop-nav".to_string()));
1142    }
1143
1144    #[test]
1145    fn classes_inside_multi_line_media_query() {
1146        let names =
1147            export_names("@media\n  screen and (min-width: 600px)\n{\n  .real { color: red; }\n}");
1148        assert_eq!(names, vec!["real"]);
1149    }
1150
1151    #[test]
1152    fn at_layer_statement_does_not_export() {
1153        let names = export_names("@layer foo.bar;");
1154        assert!(names.is_empty(), "got {names:?}");
1155        let names = export_names("@layer foo.bar, foo.baz;");
1156        assert!(names.is_empty(), "got {names:?}");
1157    }
1158
1159    #[test]
1160    fn at_layer_block_keeps_body_classes() {
1161        let names = export_names("@layer foo.bar { .root { color: red; } }");
1162        assert_eq!(names, vec!["root"]);
1163    }
1164
1165    #[test]
1166    fn at_layer_multiline_prelude_keeps_body_classes() {
1167        let names = export_names("@layer\n  foo.bar\n{ .root { color: red; } }");
1168        assert_eq!(names, vec!["root"]);
1169    }
1170
1171    #[test]
1172    fn at_layer_with_nested_media_keeps_body() {
1173        let names =
1174            export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1175        assert_eq!(names, vec!["real"]);
1176    }
1177
1178    #[test]
1179    fn at_import_with_layer_attribute_does_not_export() {
1180        let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1181        assert!(names.is_empty(), "got {names:?}");
1182    }
1183
1184    #[test]
1185    fn class_then_at_layer_does_not_leak_prelude() {
1186        let names =
1187            export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1188        assert_eq!(names, vec!["outer", "inner"]);
1189    }
1190
1191    #[test]
1192    fn at_scope_keeps_selector_list_classes() {
1193        let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1194        assert!(names.contains(&"parent".to_string()), "got {names:?}");
1195        assert!(names.contains(&"child".to_string()), "got {names:?}");
1196        assert!(names.contains(&"title".to_string()), "got {names:?}");
1197    }
1198
1199    #[test]
1200    fn at_keyframes_numeric_step_is_not_class() {
1201        let names = export_names(
1202            "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1203        );
1204        assert!(names.is_empty(), "got {names:?}");
1205    }
1206
1207    #[test]
1208    fn at_webkit_keyframes_keeps_body_classes() {
1209        let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1210        assert_eq!(names, vec!["real"]);
1211    }
1212
1213    #[test]
1214    fn deduplicates_repeated_class() {
1215        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1216        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1217    }
1218
1219    #[test]
1220    fn empty_source() {
1221        let names = export_names("");
1222        assert!(names.is_empty());
1223    }
1224
1225    #[test]
1226    fn no_classes() {
1227        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1228        assert!(names.is_empty());
1229    }
1230
1231    #[test]
1232    fn ignores_classes_in_block_comments() {
1233        let names = export_names("/* .fake { } */ .real { }");
1234        assert!(!names.contains(&"fake".to_string()));
1235        assert!(names.contains(&"real".to_string()));
1236    }
1237
1238    #[test]
1239    fn ignores_classes_in_scss_line_comments() {
1240        let exports = extract_css_module_exports("// .fake\n.real { }", true);
1241        let names: Vec<_> = exports
1242            .iter()
1243            .filter_map(|e| match &e.name {
1244                ExportName::Named(n) => Some(n.as_str()),
1245                ExportName::Default => None,
1246            })
1247            .collect();
1248        assert_eq!(names, vec!["real"]);
1249    }
1250
1251    #[test]
1252    fn ignores_classes_in_strings() {
1253        let names = export_names(r#".real { content: ".fake"; }"#);
1254        assert!(names.contains(&"real".to_string()));
1255        assert!(!names.contains(&"fake".to_string()));
1256    }
1257
1258    #[test]
1259    fn ignores_classes_in_url() {
1260        let names = export_names(".real { background: url(./images/hero.png); }");
1261        assert!(names.contains(&"real".to_string()));
1262        assert!(!names.contains(&"png".to_string()));
1263    }
1264
1265    #[test]
1266    fn strip_css_block_comment() {
1267        let result = strip_css_comments("/* removed */ .kept { }", false);
1268        assert!(!result.contains("removed"));
1269        assert!(result.contains(".kept"));
1270    }
1271
1272    #[test]
1273    fn strip_scss_line_comment() {
1274        let result = strip_css_comments("// removed\n.kept { }", true);
1275        assert!(!result.contains("removed"));
1276        assert!(result.contains(".kept"));
1277    }
1278
1279    #[test]
1280    fn strip_scss_preserves_css_outside_comments() {
1281        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1282        let result = strip_css_comments(source, true);
1283        assert!(result.contains(".visible"));
1284    }
1285
1286    #[test]
1287    fn url_import_http() {
1288        assert!(is_css_url_import("http://example.com/style.css"));
1289    }
1290
1291    #[test]
1292    fn url_import_https() {
1293        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1294    }
1295
1296    #[test]
1297    fn url_import_data() {
1298        assert!(is_css_url_import("data:text/css;base64,abc"));
1299    }
1300
1301    #[test]
1302    fn url_import_local_not_skipped() {
1303        assert!(!is_css_url_import("./local.css"));
1304    }
1305
1306    #[test]
1307    fn url_import_bare_specifier_not_skipped() {
1308        assert!(!is_css_url_import("tailwindcss"));
1309    }
1310
1311    #[test]
1312    fn normalize_relative_dot_path_unchanged() {
1313        assert_eq!(
1314            normalize_css_import_path("./reset.css".to_string(), false),
1315            "./reset.css"
1316        );
1317    }
1318
1319    #[test]
1320    fn normalize_parent_relative_path_unchanged() {
1321        assert_eq!(
1322            normalize_css_import_path("../shared.scss".to_string(), false),
1323            "../shared.scss"
1324        );
1325    }
1326
1327    #[test]
1328    fn normalize_absolute_path_unchanged() {
1329        assert_eq!(
1330            normalize_css_import_path("/styles/main.css".to_string(), false),
1331            "/styles/main.css"
1332        );
1333    }
1334
1335    #[test]
1336    fn normalize_url_unchanged() {
1337        assert_eq!(
1338            normalize_css_import_path("https://example.com/style.css".to_string(), false),
1339            "https://example.com/style.css"
1340        );
1341    }
1342
1343    #[test]
1344    fn normalize_bare_css_gets_dot_slash() {
1345        assert_eq!(
1346            normalize_css_import_path("app.css".to_string(), false),
1347            "./app.css"
1348        );
1349    }
1350
1351    #[test]
1352    fn normalize_css_package_subpath_stays_bare() {
1353        assert_eq!(
1354            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1355            "tailwindcss/theme.css"
1356        );
1357    }
1358
1359    #[test]
1360    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1361        assert_eq!(
1362            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1363            "highlight.js/styles/github.css"
1364        );
1365    }
1366
1367    #[test]
1368    fn normalize_bare_scss_gets_dot_slash() {
1369        assert_eq!(
1370            normalize_css_import_path("vars.scss".to_string(), false),
1371            "./vars.scss"
1372        );
1373    }
1374
1375    #[test]
1376    fn normalize_bare_sass_gets_dot_slash() {
1377        assert_eq!(
1378            normalize_css_import_path("main.sass".to_string(), false),
1379            "./main.sass"
1380        );
1381    }
1382
1383    #[test]
1384    fn normalize_bare_less_gets_dot_slash() {
1385        assert_eq!(
1386            normalize_css_import_path("theme.less".to_string(), false),
1387            "./theme.less"
1388        );
1389    }
1390
1391    #[test]
1392    fn normalize_bare_js_extension_stays_bare() {
1393        assert_eq!(
1394            normalize_css_import_path("module.js".to_string(), false),
1395            "module.js"
1396        );
1397    }
1398
1399    #[test]
1400    fn normalize_scss_bare_partial_gets_dot_slash() {
1401        assert_eq!(
1402            normalize_css_import_path("variables".to_string(), true),
1403            "./variables"
1404        );
1405    }
1406
1407    #[test]
1408    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1409        assert_eq!(
1410            normalize_css_import_path("base/reset".to_string(), true),
1411            "./base/reset"
1412        );
1413    }
1414
1415    #[test]
1416    fn normalize_scss_builtin_stays_bare() {
1417        assert_eq!(
1418            normalize_css_import_path("sass:math".to_string(), true),
1419            "sass:math"
1420        );
1421    }
1422
1423    #[test]
1424    fn normalize_scss_relative_path_unchanged() {
1425        assert_eq!(
1426            normalize_css_import_path("../styles/variables".to_string(), true),
1427            "../styles/variables"
1428        );
1429    }
1430
1431    #[test]
1432    fn normalize_css_bare_extensionless_stays_bare() {
1433        assert_eq!(
1434            normalize_css_import_path("tailwindcss".to_string(), false),
1435            "tailwindcss"
1436        );
1437    }
1438
1439    #[test]
1440    fn normalize_scoped_package_with_css_extension_stays_bare() {
1441        assert_eq!(
1442            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1443            "@fontsource/monaspace-neon/400.css"
1444        );
1445    }
1446
1447    #[test]
1448    fn normalize_scoped_package_with_scss_extension_stays_bare() {
1449        assert_eq!(
1450            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1451            "@company/design-system/tokens.scss"
1452        );
1453    }
1454
1455    #[test]
1456    fn normalize_scoped_package_without_extension_stays_bare() {
1457        assert_eq!(
1458            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1459            "@fallow/design-system/styles"
1460        );
1461    }
1462
1463    #[test]
1464    fn normalize_scoped_package_extensionless_scss_stays_bare() {
1465        assert_eq!(
1466            normalize_css_import_path("@company/tokens".to_string(), true),
1467            "@company/tokens"
1468        );
1469    }
1470
1471    #[test]
1472    fn normalize_path_alias_with_css_extension_stays_bare() {
1473        assert_eq!(
1474            normalize_css_import_path("@/components/Button.css".to_string(), false),
1475            "@/components/Button.css"
1476        );
1477    }
1478
1479    #[test]
1480    fn normalize_path_alias_extensionless_stays_bare() {
1481        assert_eq!(
1482            normalize_css_import_path("@/styles/variables".to_string(), false),
1483            "@/styles/variables"
1484        );
1485    }
1486
1487    #[test]
1488    fn strip_css_no_comments() {
1489        let source = ".foo { color: red; }";
1490        assert_eq!(strip_css_comments(source, false), source);
1491    }
1492
1493    #[test]
1494    fn strip_css_multiple_block_comments() {
1495        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1496        let result = strip_css_comments(source, false);
1497        assert!(!result.contains("comment-one"));
1498        assert!(!result.contains("comment-two"));
1499        assert!(result.contains(".foo"));
1500        assert!(result.contains(".bar"));
1501    }
1502
1503    #[test]
1504    fn strip_scss_does_not_affect_non_scss() {
1505        let source = "// this stays\n.foo { }";
1506        let result = strip_css_comments(source, false);
1507        assert!(result.contains("// this stays"));
1508    }
1509
1510    #[test]
1511    fn css_module_parses_suppressions() {
1512        let info = parse_css_to_module(
1513            fallow_types::discover::FileId(0),
1514            Path::new("Component.module.css"),
1515            "/* fallow-ignore-file */\n.btn { color: red; }",
1516            0,
1517        );
1518        assert!(!info.suppressions.is_empty());
1519        assert_eq!(info.suppressions[0].line, 0);
1520    }
1521
1522    #[test]
1523    fn extracts_class_starting_with_underscore() {
1524        let names = export_names("._private { } .__dunder { }");
1525        assert!(names.contains(&"_private".to_string()));
1526        assert!(names.contains(&"__dunder".to_string()));
1527    }
1528
1529    #[test]
1530    fn ignores_id_selectors() {
1531        let names = export_names("#myId { color: red; }");
1532        assert!(!names.contains(&"myId".to_string()));
1533    }
1534
1535    #[test]
1536    fn ignores_element_selectors() {
1537        let names = export_names("div { color: red; } span { }");
1538        assert!(names.is_empty());
1539    }
1540
1541    #[test]
1542    fn extract_css_imports_at_import_quoted() {
1543        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1544        assert_eq!(imports, vec!["./reset.css"]);
1545    }
1546
1547    #[test]
1548    fn extract_css_imports_package_subpath_stays_bare() {
1549        let imports =
1550            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1551        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1552    }
1553
1554    #[test]
1555    fn extract_css_imports_at_import_url() {
1556        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1557        assert_eq!(imports, vec!["./reset.css"]);
1558    }
1559
1560    #[test]
1561    fn extract_css_imports_skips_remote_urls() {
1562        let imports =
1563            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1564        assert!(imports.is_empty());
1565    }
1566
1567    #[test]
1568    fn extract_css_imports_scss_use_normalizes_partial() {
1569        let imports = extract_css_imports(r#"@use "variables";"#, true);
1570        assert_eq!(imports, vec!["./variables"]);
1571    }
1572
1573    #[test]
1574    fn extract_css_imports_scss_forward_normalizes_partial() {
1575        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1576        assert_eq!(imports, vec!["./tokens"]);
1577    }
1578
1579    #[test]
1580    fn extract_css_imports_skips_comments() {
1581        let imports = extract_css_imports(
1582            r#"/* @import "./hidden.scss"; */
1583@use "real";"#,
1584            true,
1585        );
1586        assert_eq!(imports, vec!["./real"]);
1587    }
1588
1589    #[test]
1590    fn extract_css_imports_at_plugin_keeps_package_bare() {
1591        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1592        assert_eq!(imports, vec!["daisyui"]);
1593    }
1594
1595    #[test]
1596    fn extract_css_imports_at_plugin_tracks_relative_file() {
1597        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1598        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1599    }
1600
1601    #[test]
1602    fn extract_css_imports_scss_at_import_kept_relative() {
1603        let imports = extract_css_imports(r"@import 'Foo';", true);
1604        assert_eq!(imports, vec!["./Foo"]);
1605    }
1606
1607    #[test]
1608    fn extract_css_imports_additional_data_string_body() {
1609        let body = r#"@use "./src/styles/global.scss";"#;
1610        let imports = extract_css_imports(body, true);
1611        assert_eq!(imports, vec!["./src/styles/global.scss"]);
1612    }
1613
1614    #[test]
1615    fn mask_with_whitespace_preserves_byte_length() {
1616        let src = "/* hello */ .foo { }";
1617        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1618        assert_eq!(masked.len(), src.len());
1619        assert!(masked.is_char_boundary(src.len()));
1620    }
1621
1622    #[test]
1623    fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1624        let src = "/* \u{2713} */ .foo { }";
1625        let foo_offset = src.find(".foo").expect("`.foo` present");
1626        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1627        assert_eq!(masked.len(), src.len());
1628        assert_eq!(masked.find(".foo"), Some(foo_offset));
1629    }
1630
1631    /// Resolve a span's start to (line, col) using the same primitives the
1632    /// downstream pipeline uses in `crates/core/src/analyze/unused_exports.rs`.
1633    fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1634        let offsets = fallow_types::extract::compute_line_offsets(source);
1635        fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1636    }
1637
1638    #[test]
1639    fn span_points_at_real_class_declaration_line() {
1640        let source = "\n\n\n\n.foo { color: red; }\n";
1641        let exports = extract_css_module_exports(source, false);
1642        assert_eq!(exports.len(), 1);
1643        let span = exports[0].span;
1644        let (line, col) = span_line_col(source, span.start);
1645        assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1646        assert_eq!(
1647            col, 1,
1648            "column points at `f` in `.foo` (post-dot identifier)"
1649        );
1650        assert_eq!(
1651            &source[span.start as usize..span.end as usize],
1652            "foo",
1653            "span range must slice to the class identifier in the original source"
1654        );
1655    }
1656
1657    #[test]
1658    fn span_survives_multibyte_comment_prefix() {
1659        let source = "/* \u{2713} */\n.foo { }";
1660        let exports = extract_css_module_exports(source, false);
1661        assert_eq!(exports.len(), 1);
1662        let span = exports[0].span;
1663        assert!(
1664            source.is_char_boundary(span.start as usize),
1665            "span.start must lie on a UTF-8 char boundary"
1666        );
1667        assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1668    }
1669
1670    #[test]
1671    fn span_skips_at_layer_prelude_dot_segments() {
1672        let source = "@layer foo.bar { }\n.root { }\n";
1673        let exports = extract_css_module_exports(source, false);
1674        let names: Vec<_> = exports
1675            .iter()
1676            .filter_map(|e| match &e.name {
1677                ExportName::Named(n) => Some(n.as_str()),
1678                ExportName::Default => None,
1679            })
1680            .collect();
1681        assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1682        let span = exports[0].span;
1683        let (line, _col) = span_line_col(source, span.start);
1684        assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1685        assert_eq!(&source[span.start as usize..span.end as usize], "root");
1686    }
1687
1688    #[test]
1689    fn span_skips_classes_in_strings() {
1690        let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1691        let exports = extract_css_module_exports(source, false);
1692        let names: Vec<_> = exports
1693            .iter()
1694            .filter_map(|e| match &e.name {
1695                ExportName::Named(n) => Some(n.as_str()),
1696                ExportName::Default => None,
1697            })
1698            .collect();
1699        assert_eq!(names, vec!["real", "also-real"]);
1700        for export in &exports {
1701            let span = export.span;
1702            let slice = &source[span.start as usize..span.end as usize];
1703            match &export.name {
1704                ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1705                ExportName::Default => unreachable!("CSS modules emit only named exports"),
1706            }
1707        }
1708    }
1709
1710    #[test]
1711    fn span_deduplicates_to_first_occurrence() {
1712        let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1713        let exports = extract_css_module_exports(source, false);
1714        assert_eq!(exports.len(), 1);
1715        let (line, _col) = span_line_col(source, exports[0].span.start);
1716        assert_eq!(
1717            line, 1,
1718            "first occurrence wins for deduplicated class names"
1719        );
1720    }
1721
1722    #[test]
1723    fn span_inside_media_query() {
1724        let source =
1725            "@media (max-width: 768px) {\n  .mobile { display: block; }\n  .desktop { }\n}\n";
1726        let exports = extract_css_module_exports(source, false);
1727        let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1728            .iter()
1729            .filter_map(|e| match &e.name {
1730                ExportName::Named(n) => Some((n.as_str(), e.span)),
1731                ExportName::Default => None,
1732            })
1733            .collect();
1734        let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1735        let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1736        assert_eq!(mobile_line, 2);
1737        assert_eq!(desktop_line, 3);
1738    }
1739
1740    #[test]
1741    fn at_layer_only_module_emits_no_exports() {
1742        let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1743        assert!(exports.is_empty());
1744    }
1745
1746    #[test]
1747    fn parse_css_to_module_resolves_real_line_offsets() {
1748        let source = "\n\n\n\n.foo { color: red; }\n";
1749        let info = parse_css_to_module(
1750            fallow_types::discover::FileId(0),
1751            Path::new("Component.module.css"),
1752            source,
1753            0,
1754        );
1755        assert_eq!(info.exports.len(), 1);
1756        let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1757            &info.line_offsets,
1758            info.exports[0].span.start,
1759        );
1760        assert_eq!(line, 5, "downstream line must equal the source line");
1761    }
1762
1763    fn theme_token_names(source: &str) -> Vec<String> {
1764        scan_theme_blocks(source)
1765            .tokens
1766            .into_iter()
1767            .map(|t| t.name)
1768            .collect()
1769    }
1770
1771    #[test]
1772    fn theme_single_block_collects_tokens() {
1773        let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
1774        assert_eq!(names, vec!["color-brand", "radius-card"]);
1775    }
1776
1777    #[test]
1778    fn theme_token_values_are_normalized() {
1779        let scan = scan_theme_blocks("@theme {\n  --color-brand: rgb( 255 0 0 );\n}");
1780        assert_eq!(scan.tokens[0].name, "color-brand");
1781        assert_eq!(scan.tokens[0].value, "rgb( 255 0 0 )");
1782    }
1783
1784    #[test]
1785    fn theme_dashed_multi_segment_names() {
1786        let names = theme_token_names(
1787            "@theme {\n  --font-weight-heavy: 900;\n  --inset-shadow-glow: 0 0 4px red;\n}",
1788        );
1789        assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
1790    }
1791
1792    #[test]
1793    fn theme_inline_and_static_modifiers() {
1794        assert_eq!(
1795            theme_token_names("@theme inline { --color-a: red; }"),
1796            vec!["color-a"]
1797        );
1798        assert_eq!(
1799            theme_token_names("@theme static { --color-b: red; }"),
1800            vec!["color-b"]
1801        );
1802    }
1803
1804    #[test]
1805    fn theme_multiple_blocks_union() {
1806        let names = theme_token_names(
1807            "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
1808        );
1809        assert_eq!(names, vec!["color-a", "spacing-gutter"]);
1810    }
1811
1812    #[test]
1813    fn theme_reset_form_excluded() {
1814        // `--color-*: initial` is a namespace reset directive, not a token.
1815        let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
1816        assert_eq!(names, vec!["color-brand"]);
1817    }
1818
1819    #[test]
1820    fn theme_no_block_yields_nothing() {
1821        assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
1822    }
1823
1824    #[test]
1825    fn theme_line_numbers() {
1826        let scan = scan_theme_blocks("@theme {\n  --color-a: red;\n  --radius-b: 4px;\n}");
1827        assert_eq!(scan.tokens[0].line, 2);
1828        assert_eq!(scan.tokens[1].line, 3);
1829    }
1830
1831    #[test]
1832    fn theme_token_backs_token_via_var() {
1833        let scan = scan_theme_blocks(
1834            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1835        );
1836        assert!(
1837            scan.theme_var_reads
1838                .iter()
1839                .any(|(name, _)| name == "color-brand")
1840        );
1841    }
1842
1843    #[test]
1844    fn theme_var_read_carries_line() {
1845        // The `var(--color-brand)` read sits on line 3 of the source; the located
1846        // theme-var read must carry that 1-based line for the reverse index.
1847        let scan = scan_theme_blocks(
1848            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1849        );
1850        assert_eq!(
1851            scan.theme_var_reads,
1852            vec![("color-brand".to_string(), 3u32)]
1853        );
1854    }
1855
1856    #[test]
1857    fn css_var_reads_locate_outside_theme_and_exclude_interior() {
1858        // A regular-CSS `var(--color-brand)` read is located (css-var surface);
1859        // a read inside the `@theme` interior is the distinct theme-var surface
1860        // and MUST be excluded here so the two kinds never double-count.
1861        let source = "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}\n\n.btn {\n  color: var(--color-brand);\n}\n";
1862        assert_eq!(
1863            extract_css_var_reads_located(source),
1864            vec![("color-brand".to_string(), 7u32)],
1865            "only the .btn read (line 7) is a css-var; the @theme-interior read is excluded"
1866        );
1867
1868        // A source whose only `var()` read is inside `@theme` yields no css-var.
1869        assert!(
1870            extract_css_var_reads_located("@theme {\n  --a: #fff;\n  --b: var(--a);\n}",)
1871                .is_empty(),
1872            "a @theme-interior-only var() read is not a css-var consumer"
1873        );
1874    }
1875
1876    #[test]
1877    fn css_var_reads_line_match_naive_reference_on_dense_line() {
1878        // Many `var()` reads packed onto a single long line (the pathological
1879        // zero-newline prefix) plus one trailing read on the next line: the
1880        // incremental line counter must agree byte-for-byte with the naive
1881        // per-match prefix rescan. No `@theme`, comments, strings, or `url()`,
1882        // so masking is identity and every read is a css-var read.
1883        use std::fmt::Write as _;
1884        let mut src = String::from(".x {");
1885        for i in 0..500 {
1886            let _ = write!(src, " color: var(--t{i});");
1887        }
1888        src.push_str(" }\n.y { color: var(--tail); }\n");
1889
1890        let got = extract_css_var_reads_located(&src);
1891
1892        // Reference: recompute each read's line via a full prefix rescan.
1893        let want: Vec<(String, u32)> = CSS_VAR_REF_RE
1894            .captures_iter(&src)
1895            .filter_map(|cap| cap.get(0).zip(cap.get(1)))
1896            .map(|(whole, name)| {
1897                (
1898                    name.as_str().to_owned(),
1899                    line_at_offset(&src, whole.start()),
1900                )
1901            })
1902            .collect();
1903
1904        assert_eq!(got, want);
1905        assert!(got.len() > 500, "expected the dense line plus the trailer");
1906        // The trailer sits on line 2; the packed reads all sit on line 1.
1907        assert_eq!(got.last().map(|(_, l)| *l), Some(2));
1908        assert!(got[..got.len() - 1].iter().all(|(_, l)| *l == 1));
1909    }
1910
1911    #[test]
1912    fn theme_string_braces_do_not_truncate_block() {
1913        let scan = scan_theme_blocks(
1914            "@theme {\n  --font-label: \"}\";\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1915        );
1916        assert_eq!(
1917            scan.tokens
1918                .iter()
1919                .map(|token| token.name.as_str())
1920                .collect::<Vec<_>>(),
1921            vec!["font-label", "color-brand", "color-button"]
1922        );
1923        assert!(
1924            scan.theme_var_reads
1925                .iter()
1926                .any(|(name, _)| name == "color-brand")
1927        );
1928    }
1929
1930    #[test]
1931    fn theme_nested_keyframes_body_not_collected() {
1932        // `@keyframes` inside `@theme` (for `--animate-*`) must not surface its
1933        // step selectors or interior as theme tokens.
1934        let names = theme_token_names(
1935            "@theme {\n  --animate-spin: spin 1s linear infinite;\n  @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
1936        );
1937        assert_eq!(names, vec!["animate-spin"]);
1938    }
1939
1940    #[test]
1941    fn theme_comment_block_ignored() {
1942        let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
1943        assert!(names.is_empty(), "got {names:?}");
1944    }
1945
1946    #[test]
1947    fn theme_deduplicates_repeated_token() {
1948        let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
1949        assert_eq!(names, vec!["color-a"]);
1950    }
1951
1952    #[test]
1953    fn apply_tokens_basic() {
1954        let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
1955        assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
1956    }
1957
1958    #[test]
1959    fn apply_tokens_strips_important() {
1960        let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
1961        assert_eq!(tokens, vec!["text-brand", "font-bold"]);
1962    }
1963
1964    #[test]
1965    fn apply_tokens_ignored_in_comments() {
1966        let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
1967        assert!(tokens.is_empty(), "got {tokens:?}");
1968    }
1969}