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