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    }
862}
863
864/// Build the import edges for a CSS/SCSS source: every `@import`/`@use`/etc.
865/// directive plus a synthetic `tailwindcss` side-effect import when `@apply` or
866/// `@tailwind` is present.
867fn build_css_imports(source: &str, stripped: &str, is_scss: bool) -> Vec<ImportInfo> {
868    let mut imports = Vec::new();
869
870    for css_source in extract_css_import_sources(source, is_scss) {
871        imports.push(ImportInfo {
872            source: css_source.normalized,
873            imported_name: if css_source.is_plugin {
874                ImportedName::Default
875            } else {
876                ImportedName::SideEffect
877            },
878            local_name: String::new(),
879            is_type_only: false,
880            is_type_only_star: false,
881            from_style: false,
882            span: css_source.span,
883            source_span: css_source.span,
884        });
885    }
886
887    let has_apply = CSS_APPLY_RE.is_match(stripped);
888    let has_tailwind = CSS_TAILWIND_RE.is_match(stripped);
889    if has_apply || has_tailwind {
890        imports.push(ImportInfo {
891            source: "tailwindcss".to_string(),
892            imported_name: ImportedName::SideEffect,
893            local_name: String::new(),
894            is_type_only: false,
895            is_type_only_star: false,
896            from_style: false,
897            span: Span::default(),
898            source_span: Span::default(),
899        });
900    }
901
902    imports
903}
904
905/// Parse a CSS/SCSS file, extracting @import, @use, @forward, @plugin, @apply, and @tailwind directives.
906pub(crate) fn parse_css_to_module(
907    file_id: FileId,
908    path: &Path,
909    source: &str,
910    content_hash: u64,
911) -> ModuleInfo {
912    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
913    let is_scss = path
914        .extension()
915        .and_then(|e| e.to_str())
916        .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
917
918    let stripped = mask_css_comments(source, is_scss);
919    let imports = build_css_imports(source, &stripped, is_scss);
920
921    let exports = if is_css_module_file(path) {
922        extract_css_module_exports(source, is_scss)
923    } else {
924        Vec::new()
925    };
926
927    css_module_info(
928        file_id,
929        content_hash,
930        source,
931        parsed_suppressions,
932        imports,
933        exports,
934    )
935}
936
937/// Assemble the `ModuleInfo` for a CSS/SCSS file: the import/export edges plus
938/// the line offsets and suppressions; all AST-derived fields stay empty since
939/// CSS carries no JS-level structure. Pure plumbing struct literal.
940fn css_module_info(
941    file_id: FileId,
942    content_hash: u64,
943    source: &str,
944    parsed_suppressions: crate::suppress::ParsedSuppressions,
945    imports: Vec<ImportInfo>,
946    exports: Vec<ExportInfo>,
947) -> ModuleInfo {
948    crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
949        file_id,
950        content_hash,
951        source,
952        parsed_suppressions,
953        imports,
954        exports,
955    })
956}
957
958#[cfg(all(test, not(miri)))]
959mod tests {
960    use super::*;
961
962    /// Helper to collect export names as strings from `extract_css_module_exports`.
963    fn export_names(source: &str) -> Vec<String> {
964        extract_css_module_exports(source, false)
965            .into_iter()
966            .filter_map(|e| match e.name {
967                ExportName::Named(n) => Some(n),
968                ExportName::Default => None,
969            })
970            .collect()
971    }
972
973    #[test]
974    fn is_css_file_css() {
975        assert!(is_css_file(Path::new("styles.css")));
976    }
977
978    #[test]
979    fn is_css_file_scss() {
980        assert!(is_css_file(Path::new("styles.scss")));
981    }
982
983    #[test]
984    fn is_css_file_sass() {
985        assert!(is_css_file(Path::new("styles.sass")));
986    }
987
988    #[test]
989    fn is_css_file_less() {
990        assert!(is_css_file(Path::new("styles.less")));
991    }
992
993    #[test]
994    fn is_css_file_rejects_js() {
995        assert!(!is_css_file(Path::new("app.js")));
996    }
997
998    #[test]
999    fn is_css_file_rejects_ts() {
1000        assert!(!is_css_file(Path::new("app.ts")));
1001    }
1002
1003    #[test]
1004    fn is_css_file_rejects_no_extension() {
1005        assert!(!is_css_file(Path::new("Makefile")));
1006    }
1007
1008    #[test]
1009    fn is_css_module_file_module_css() {
1010        assert!(is_css_module_file(Path::new("Component.module.css")));
1011    }
1012
1013    #[test]
1014    fn is_css_module_file_module_scss() {
1015        assert!(is_css_module_file(Path::new("Component.module.scss")));
1016    }
1017
1018    #[test]
1019    fn is_css_module_file_rejects_plain_css() {
1020        assert!(!is_css_module_file(Path::new("styles.css")));
1021    }
1022
1023    #[test]
1024    fn is_css_module_file_rejects_plain_scss() {
1025        assert!(!is_css_module_file(Path::new("styles.scss")));
1026    }
1027
1028    #[test]
1029    fn is_css_module_file_rejects_module_js() {
1030        assert!(!is_css_module_file(Path::new("utils.module.js")));
1031    }
1032
1033    #[test]
1034    fn extracts_single_class() {
1035        let names = export_names(".foo { color: red; }");
1036        assert_eq!(names, vec!["foo"]);
1037    }
1038
1039    #[test]
1040    fn extracts_multiple_classes() {
1041        let names = export_names(".foo { } .bar { }");
1042        assert_eq!(names, vec!["foo", "bar"]);
1043    }
1044
1045    #[test]
1046    fn extracts_nested_classes() {
1047        let names = export_names(".foo .bar { color: red; }");
1048        assert!(names.contains(&"foo".to_string()));
1049        assert!(names.contains(&"bar".to_string()));
1050    }
1051
1052    #[test]
1053    fn extracts_hyphenated_class() {
1054        let names = export_names(".my-class { }");
1055        assert_eq!(names, vec!["my-class"]);
1056    }
1057
1058    #[test]
1059    fn extracts_camel_case_class() {
1060        let names = export_names(".myClass { }");
1061        assert_eq!(names, vec!["myClass"]);
1062    }
1063
1064    #[test]
1065    fn extracts_class_inside_global_pseudo() {
1066        // CSS Modules `:global(.foo)` must surface `foo`: the parser understands
1067        // the wrapped selector, which the regex scanner could not on its own.
1068        let names = export_names(":global(.globalClass) { color: red; }");
1069        assert_eq!(names, vec!["globalClass"]);
1070    }
1071
1072    #[test]
1073    fn extracts_class_inside_local_pseudo() {
1074        let names = export_names(":local(.localClass) { color: red; }");
1075        assert_eq!(names, vec!["localClass"]);
1076    }
1077
1078    #[test]
1079    fn extracts_classes_inside_negation() {
1080        let names = export_names(".btn:not(.disabled) { }");
1081        assert!(names.contains(&"btn".to_string()), "got {names:?}");
1082        assert!(names.contains(&"disabled".to_string()), "got {names:?}");
1083    }
1084
1085    #[test]
1086    fn extracts_classes_inside_is_and_where() {
1087        let names = export_names(":is(.a, .b) :where(.c) { }");
1088        for expected in ["a", "b", "c"] {
1089            assert!(
1090                names.contains(&expected.to_string()),
1091                "missing {expected} in {names:?}"
1092            );
1093        }
1094    }
1095
1096    #[test]
1097    fn extracts_underscore_class() {
1098        let names = export_names("._hidden { } .__wrapper { }");
1099        assert!(names.contains(&"_hidden".to_string()));
1100        assert!(names.contains(&"__wrapper".to_string()));
1101    }
1102
1103    #[test]
1104    fn pseudo_selector_hover() {
1105        let names = export_names(".foo:hover { color: blue; }");
1106        assert_eq!(names, vec!["foo"]);
1107    }
1108
1109    #[test]
1110    fn pseudo_selector_focus() {
1111        let names = export_names(".input:focus { outline: none; }");
1112        assert_eq!(names, vec!["input"]);
1113    }
1114
1115    #[test]
1116    fn pseudo_element_before() {
1117        let names = export_names(".icon::before { content: ''; }");
1118        assert_eq!(names, vec!["icon"]);
1119    }
1120
1121    #[test]
1122    fn combined_pseudo_selectors() {
1123        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
1124        assert_eq!(names, vec!["btn"]);
1125    }
1126
1127    #[test]
1128    fn classes_inside_media_query() {
1129        let names = export_names(
1130            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
1131        );
1132        assert!(names.contains(&"mobile-nav".to_string()));
1133        assert!(names.contains(&"desktop-nav".to_string()));
1134    }
1135
1136    #[test]
1137    fn classes_inside_multi_line_media_query() {
1138        let names =
1139            export_names("@media\n  screen and (min-width: 600px)\n{\n  .real { color: red; }\n}");
1140        assert_eq!(names, vec!["real"]);
1141    }
1142
1143    #[test]
1144    fn at_layer_statement_does_not_export() {
1145        let names = export_names("@layer foo.bar;");
1146        assert!(names.is_empty(), "got {names:?}");
1147        let names = export_names("@layer foo.bar, foo.baz;");
1148        assert!(names.is_empty(), "got {names:?}");
1149    }
1150
1151    #[test]
1152    fn at_layer_block_keeps_body_classes() {
1153        let names = export_names("@layer foo.bar { .root { color: red; } }");
1154        assert_eq!(names, vec!["root"]);
1155    }
1156
1157    #[test]
1158    fn at_layer_multiline_prelude_keeps_body_classes() {
1159        let names = export_names("@layer\n  foo.bar\n{ .root { color: red; } }");
1160        assert_eq!(names, vec!["root"]);
1161    }
1162
1163    #[test]
1164    fn at_layer_with_nested_media_keeps_body() {
1165        let names =
1166            export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1167        assert_eq!(names, vec!["real"]);
1168    }
1169
1170    #[test]
1171    fn at_import_with_layer_attribute_does_not_export() {
1172        let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1173        assert!(names.is_empty(), "got {names:?}");
1174    }
1175
1176    #[test]
1177    fn class_then_at_layer_does_not_leak_prelude() {
1178        let names =
1179            export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1180        assert_eq!(names, vec!["outer", "inner"]);
1181    }
1182
1183    #[test]
1184    fn at_scope_keeps_selector_list_classes() {
1185        let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1186        assert!(names.contains(&"parent".to_string()), "got {names:?}");
1187        assert!(names.contains(&"child".to_string()), "got {names:?}");
1188        assert!(names.contains(&"title".to_string()), "got {names:?}");
1189    }
1190
1191    #[test]
1192    fn at_keyframes_numeric_step_is_not_class() {
1193        let names = export_names(
1194            "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1195        );
1196        assert!(names.is_empty(), "got {names:?}");
1197    }
1198
1199    #[test]
1200    fn at_webkit_keyframes_keeps_body_classes() {
1201        let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1202        assert_eq!(names, vec!["real"]);
1203    }
1204
1205    #[test]
1206    fn deduplicates_repeated_class() {
1207        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1208        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1209    }
1210
1211    #[test]
1212    fn empty_source() {
1213        let names = export_names("");
1214        assert!(names.is_empty());
1215    }
1216
1217    #[test]
1218    fn no_classes() {
1219        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1220        assert!(names.is_empty());
1221    }
1222
1223    #[test]
1224    fn ignores_classes_in_block_comments() {
1225        let names = export_names("/* .fake { } */ .real { }");
1226        assert!(!names.contains(&"fake".to_string()));
1227        assert!(names.contains(&"real".to_string()));
1228    }
1229
1230    #[test]
1231    fn ignores_classes_in_scss_line_comments() {
1232        let exports = extract_css_module_exports("// .fake\n.real { }", true);
1233        let names: Vec<_> = exports
1234            .iter()
1235            .filter_map(|e| match &e.name {
1236                ExportName::Named(n) => Some(n.as_str()),
1237                ExportName::Default => None,
1238            })
1239            .collect();
1240        assert_eq!(names, vec!["real"]);
1241    }
1242
1243    #[test]
1244    fn ignores_classes_in_strings() {
1245        let names = export_names(r#".real { content: ".fake"; }"#);
1246        assert!(names.contains(&"real".to_string()));
1247        assert!(!names.contains(&"fake".to_string()));
1248    }
1249
1250    #[test]
1251    fn ignores_classes_in_url() {
1252        let names = export_names(".real { background: url(./images/hero.png); }");
1253        assert!(names.contains(&"real".to_string()));
1254        assert!(!names.contains(&"png".to_string()));
1255    }
1256
1257    #[test]
1258    fn mask_css_block_comment() {
1259        let source = "/* removed */ .kept { }";
1260        let result = mask_css_comments(source, false);
1261        assert!(!result.contains("removed"));
1262        assert_eq!(result.len(), source.len());
1263        assert_eq!(result.find(".kept"), source.find(".kept"));
1264    }
1265
1266    #[test]
1267    fn mask_scss_line_comment() {
1268        let source = "// removed\n.kept { }";
1269        let result = mask_css_comments(source, true);
1270        assert!(!result.contains("removed"));
1271        assert_eq!(result.len(), source.len());
1272        assert_eq!(result.find(".kept"), source.find(".kept"));
1273    }
1274
1275    #[test]
1276    fn mask_scss_preserves_css_outside_comments() {
1277        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1278        let result = mask_css_comments(source, true);
1279        assert!(result.contains(".visible"));
1280    }
1281
1282    #[test]
1283    fn url_import_http() {
1284        assert!(is_css_url_import("http://example.com/style.css"));
1285    }
1286
1287    #[test]
1288    fn url_import_https() {
1289        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1290    }
1291
1292    #[test]
1293    fn url_import_data() {
1294        assert!(is_css_url_import("data:text/css;base64,abc"));
1295    }
1296
1297    #[test]
1298    fn url_import_local_not_skipped() {
1299        assert!(!is_css_url_import("./local.css"));
1300    }
1301
1302    #[test]
1303    fn url_import_bare_specifier_not_skipped() {
1304        assert!(!is_css_url_import("tailwindcss"));
1305    }
1306
1307    #[test]
1308    fn normalize_relative_dot_path_unchanged() {
1309        assert_eq!(
1310            normalize_css_import_path("./reset.css".to_string(), false),
1311            "./reset.css"
1312        );
1313    }
1314
1315    #[test]
1316    fn normalize_parent_relative_path_unchanged() {
1317        assert_eq!(
1318            normalize_css_import_path("../shared.scss".to_string(), false),
1319            "../shared.scss"
1320        );
1321    }
1322
1323    #[test]
1324    fn normalize_absolute_path_unchanged() {
1325        assert_eq!(
1326            normalize_css_import_path("/styles/main.css".to_string(), false),
1327            "/styles/main.css"
1328        );
1329    }
1330
1331    #[test]
1332    fn normalize_url_unchanged() {
1333        assert_eq!(
1334            normalize_css_import_path("https://example.com/style.css".to_string(), false),
1335            "https://example.com/style.css"
1336        );
1337    }
1338
1339    #[test]
1340    fn normalize_bare_css_gets_dot_slash() {
1341        assert_eq!(
1342            normalize_css_import_path("app.css".to_string(), false),
1343            "./app.css"
1344        );
1345    }
1346
1347    #[test]
1348    fn normalize_css_package_subpath_stays_bare() {
1349        assert_eq!(
1350            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1351            "tailwindcss/theme.css"
1352        );
1353    }
1354
1355    #[test]
1356    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1357        assert_eq!(
1358            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1359            "highlight.js/styles/github.css"
1360        );
1361    }
1362
1363    #[test]
1364    fn normalize_bare_scss_gets_dot_slash() {
1365        assert_eq!(
1366            normalize_css_import_path("vars.scss".to_string(), false),
1367            "./vars.scss"
1368        );
1369    }
1370
1371    #[test]
1372    fn normalize_bare_sass_gets_dot_slash() {
1373        assert_eq!(
1374            normalize_css_import_path("main.sass".to_string(), false),
1375            "./main.sass"
1376        );
1377    }
1378
1379    #[test]
1380    fn normalize_bare_less_gets_dot_slash() {
1381        assert_eq!(
1382            normalize_css_import_path("theme.less".to_string(), false),
1383            "./theme.less"
1384        );
1385    }
1386
1387    #[test]
1388    fn normalize_bare_js_extension_stays_bare() {
1389        assert_eq!(
1390            normalize_css_import_path("module.js".to_string(), false),
1391            "module.js"
1392        );
1393    }
1394
1395    #[test]
1396    fn normalize_scss_bare_partial_gets_dot_slash() {
1397        assert_eq!(
1398            normalize_css_import_path("variables".to_string(), true),
1399            "./variables"
1400        );
1401    }
1402
1403    #[test]
1404    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1405        assert_eq!(
1406            normalize_css_import_path("base/reset".to_string(), true),
1407            "./base/reset"
1408        );
1409    }
1410
1411    #[test]
1412    fn normalize_scss_builtin_stays_bare() {
1413        assert_eq!(
1414            normalize_css_import_path("sass:math".to_string(), true),
1415            "sass:math"
1416        );
1417    }
1418
1419    #[test]
1420    fn normalize_scss_relative_path_unchanged() {
1421        assert_eq!(
1422            normalize_css_import_path("../styles/variables".to_string(), true),
1423            "../styles/variables"
1424        );
1425    }
1426
1427    #[test]
1428    fn normalize_css_bare_extensionless_stays_bare() {
1429        assert_eq!(
1430            normalize_css_import_path("tailwindcss".to_string(), false),
1431            "tailwindcss"
1432        );
1433    }
1434
1435    #[test]
1436    fn normalize_scoped_package_with_css_extension_stays_bare() {
1437        assert_eq!(
1438            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1439            "@fontsource/monaspace-neon/400.css"
1440        );
1441    }
1442
1443    #[test]
1444    fn normalize_scoped_package_with_scss_extension_stays_bare() {
1445        assert_eq!(
1446            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1447            "@company/design-system/tokens.scss"
1448        );
1449    }
1450
1451    #[test]
1452    fn normalize_scoped_package_without_extension_stays_bare() {
1453        assert_eq!(
1454            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1455            "@fallow/design-system/styles"
1456        );
1457    }
1458
1459    #[test]
1460    fn normalize_scoped_package_extensionless_scss_stays_bare() {
1461        assert_eq!(
1462            normalize_css_import_path("@company/tokens".to_string(), true),
1463            "@company/tokens"
1464        );
1465    }
1466
1467    #[test]
1468    fn normalize_path_alias_with_css_extension_stays_bare() {
1469        assert_eq!(
1470            normalize_css_import_path("@/components/Button.css".to_string(), false),
1471            "@/components/Button.css"
1472        );
1473    }
1474
1475    #[test]
1476    fn normalize_path_alias_extensionless_stays_bare() {
1477        assert_eq!(
1478            normalize_css_import_path("@/styles/variables".to_string(), false),
1479            "@/styles/variables"
1480        );
1481    }
1482
1483    #[test]
1484    fn mask_css_no_comments() {
1485        let source = ".foo { color: red; }";
1486        assert_eq!(mask_css_comments(source, false), source);
1487    }
1488
1489    #[test]
1490    fn mask_css_multiple_block_comments() {
1491        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1492        let result = mask_css_comments(source, false);
1493        assert!(!result.contains("comment-one"));
1494        assert!(!result.contains("comment-two"));
1495        assert!(result.contains(".foo"));
1496        assert!(result.contains(".bar"));
1497    }
1498
1499    #[test]
1500    fn mask_scss_does_not_affect_non_scss() {
1501        let source = "// this stays\n.foo { }";
1502        let result = mask_css_comments(source, false);
1503        assert!(result.contains("// this stays"));
1504    }
1505
1506    #[test]
1507    fn css_module_parses_suppressions() {
1508        let info = parse_css_to_module(
1509            fallow_types::discover::FileId(0),
1510            Path::new("Component.module.css"),
1511            "/* fallow-ignore-file */\n.btn { color: red; }",
1512            0,
1513        );
1514        assert!(!info.suppressions.is_empty());
1515        assert_eq!(info.suppressions[0].line, 0);
1516    }
1517
1518    #[test]
1519    fn extracts_class_starting_with_underscore() {
1520        let names = export_names("._private { } .__dunder { }");
1521        assert!(names.contains(&"_private".to_string()));
1522        assert!(names.contains(&"__dunder".to_string()));
1523    }
1524
1525    #[test]
1526    fn ignores_id_selectors() {
1527        let names = export_names("#myId { color: red; }");
1528        assert!(!names.contains(&"myId".to_string()));
1529    }
1530
1531    #[test]
1532    fn ignores_element_selectors() {
1533        let names = export_names("div { color: red; } span { }");
1534        assert!(names.is_empty());
1535    }
1536
1537    #[test]
1538    fn extract_css_imports_at_import_quoted() {
1539        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1540        assert_eq!(imports, vec!["./reset.css"]);
1541    }
1542
1543    #[test]
1544    fn extract_css_imports_package_subpath_stays_bare() {
1545        let imports =
1546            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1547        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1548    }
1549
1550    #[test]
1551    fn extract_css_imports_at_import_url() {
1552        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1553        assert_eq!(imports, vec!["./reset.css"]);
1554    }
1555
1556    #[test]
1557    fn extract_css_imports_skips_remote_urls() {
1558        let imports =
1559            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1560        assert!(imports.is_empty());
1561    }
1562
1563    #[test]
1564    fn extract_css_imports_scss_use_normalizes_partial() {
1565        let imports = extract_css_imports(r#"@use "variables";"#, true);
1566        assert_eq!(imports, vec!["./variables"]);
1567    }
1568
1569    #[test]
1570    fn extract_css_imports_scss_forward_normalizes_partial() {
1571        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1572        assert_eq!(imports, vec!["./tokens"]);
1573    }
1574
1575    #[test]
1576    fn extract_css_imports_skips_comments() {
1577        let imports = extract_css_imports(
1578            r#"/* @import "./hidden.scss"; */
1579@use "real";"#,
1580            true,
1581        );
1582        assert_eq!(imports, vec!["./real"]);
1583    }
1584
1585    #[test]
1586    fn extract_css_imports_at_plugin_keeps_package_bare() {
1587        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1588        assert_eq!(imports, vec!["daisyui"]);
1589    }
1590
1591    #[test]
1592    fn extract_css_imports_at_plugin_tracks_relative_file() {
1593        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1594        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1595    }
1596
1597    #[test]
1598    fn extract_css_imports_scss_at_import_kept_relative() {
1599        let imports = extract_css_imports(r"@import 'Foo';", true);
1600        assert_eq!(imports, vec!["./Foo"]);
1601    }
1602
1603    #[test]
1604    fn extract_css_imports_additional_data_string_body() {
1605        let body = r#"@use "./src/styles/global.scss";"#;
1606        let imports = extract_css_imports(body, true);
1607        assert_eq!(imports, vec!["./src/styles/global.scss"]);
1608    }
1609
1610    #[test]
1611    fn mask_with_whitespace_preserves_byte_length() {
1612        let src = "/* hello */ .foo { }";
1613        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1614        assert_eq!(masked.len(), src.len());
1615        assert!(masked.is_char_boundary(src.len()));
1616    }
1617
1618    #[test]
1619    fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1620        let src = "/* \u{2713} */ .foo { }";
1621        let foo_offset = src.find(".foo").expect("`.foo` present");
1622        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1623        assert_eq!(masked.len(), src.len());
1624        assert_eq!(masked.find(".foo"), Some(foo_offset));
1625    }
1626
1627    /// Resolve a span's start to (line, col) using the same primitives the
1628    /// downstream pipeline uses in `crates/core/src/analyze/unused_exports.rs`.
1629    fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1630        let offsets = fallow_types::extract::compute_line_offsets(source);
1631        fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1632    }
1633
1634    #[test]
1635    fn span_points_at_real_class_declaration_line() {
1636        let source = "\n\n\n\n.foo { color: red; }\n";
1637        let exports = extract_css_module_exports(source, false);
1638        assert_eq!(exports.len(), 1);
1639        let span = exports[0].span;
1640        let (line, col) = span_line_col(source, span.start);
1641        assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1642        assert_eq!(
1643            col, 1,
1644            "column points at `f` in `.foo` (post-dot identifier)"
1645        );
1646        assert_eq!(
1647            &source[span.start as usize..span.end as usize],
1648            "foo",
1649            "span range must slice to the class identifier in the original source"
1650        );
1651    }
1652
1653    #[test]
1654    fn span_survives_multibyte_comment_prefix() {
1655        let source = "/* \u{2713} */\n.foo { }";
1656        let exports = extract_css_module_exports(source, false);
1657        assert_eq!(exports.len(), 1);
1658        let span = exports[0].span;
1659        assert!(
1660            source.is_char_boundary(span.start as usize),
1661            "span.start must lie on a UTF-8 char boundary"
1662        );
1663        assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1664    }
1665
1666    #[test]
1667    fn span_skips_at_layer_prelude_dot_segments() {
1668        let source = "@layer foo.bar { }\n.root { }\n";
1669        let exports = extract_css_module_exports(source, false);
1670        let names: Vec<_> = exports
1671            .iter()
1672            .filter_map(|e| match &e.name {
1673                ExportName::Named(n) => Some(n.as_str()),
1674                ExportName::Default => None,
1675            })
1676            .collect();
1677        assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1678        let span = exports[0].span;
1679        let (line, _col) = span_line_col(source, span.start);
1680        assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1681        assert_eq!(&source[span.start as usize..span.end as usize], "root");
1682    }
1683
1684    #[test]
1685    fn span_skips_classes_in_strings() {
1686        let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1687        let exports = extract_css_module_exports(source, false);
1688        let names: Vec<_> = exports
1689            .iter()
1690            .filter_map(|e| match &e.name {
1691                ExportName::Named(n) => Some(n.as_str()),
1692                ExportName::Default => None,
1693            })
1694            .collect();
1695        assert_eq!(names, vec!["real", "also-real"]);
1696        for export in &exports {
1697            let span = export.span;
1698            let slice = &source[span.start as usize..span.end as usize];
1699            match &export.name {
1700                ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1701                ExportName::Default => unreachable!("CSS modules emit only named exports"),
1702            }
1703        }
1704    }
1705
1706    #[test]
1707    fn span_deduplicates_to_first_occurrence() {
1708        let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1709        let exports = extract_css_module_exports(source, false);
1710        assert_eq!(exports.len(), 1);
1711        let (line, _col) = span_line_col(source, exports[0].span.start);
1712        assert_eq!(
1713            line, 1,
1714            "first occurrence wins for deduplicated class names"
1715        );
1716    }
1717
1718    #[test]
1719    fn span_inside_media_query() {
1720        let source =
1721            "@media (max-width: 768px) {\n  .mobile { display: block; }\n  .desktop { }\n}\n";
1722        let exports = extract_css_module_exports(source, false);
1723        let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1724            .iter()
1725            .filter_map(|e| match &e.name {
1726                ExportName::Named(n) => Some((n.as_str(), e.span)),
1727                ExportName::Default => None,
1728            })
1729            .collect();
1730        let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1731        let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1732        assert_eq!(mobile_line, 2);
1733        assert_eq!(desktop_line, 3);
1734    }
1735
1736    #[test]
1737    fn at_layer_only_module_emits_no_exports() {
1738        let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1739        assert!(exports.is_empty());
1740    }
1741
1742    #[test]
1743    fn parse_css_to_module_resolves_real_line_offsets() {
1744        let source = "\n\n\n\n.foo { color: red; }\n";
1745        let info = parse_css_to_module(
1746            fallow_types::discover::FileId(0),
1747            Path::new("Component.module.css"),
1748            source,
1749            0,
1750        );
1751        assert_eq!(info.exports.len(), 1);
1752        let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1753            &info.line_offsets,
1754            info.exports[0].span.start,
1755        );
1756        assert_eq!(line, 5, "downstream line must equal the source line");
1757    }
1758
1759    fn theme_token_names(source: &str) -> Vec<String> {
1760        scan_theme_blocks(source)
1761            .tokens
1762            .into_iter()
1763            .map(|t| t.name)
1764            .collect()
1765    }
1766
1767    #[test]
1768    fn theme_single_block_collects_tokens() {
1769        let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
1770        assert_eq!(names, vec!["color-brand", "radius-card"]);
1771    }
1772
1773    #[test]
1774    fn theme_token_values_are_normalized() {
1775        let scan = scan_theme_blocks("@theme {\n  --color-brand: rgb( 255 0 0 );\n}");
1776        assert_eq!(scan.tokens[0].name, "color-brand");
1777        assert_eq!(scan.tokens[0].value, "rgb( 255 0 0 )");
1778    }
1779
1780    #[test]
1781    fn theme_dashed_multi_segment_names() {
1782        let names = theme_token_names(
1783            "@theme {\n  --font-weight-heavy: 900;\n  --inset-shadow-glow: 0 0 4px red;\n}",
1784        );
1785        assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
1786    }
1787
1788    #[test]
1789    fn theme_inline_and_static_modifiers() {
1790        assert_eq!(
1791            theme_token_names("@theme inline { --color-a: red; }"),
1792            vec!["color-a"]
1793        );
1794        assert_eq!(
1795            theme_token_names("@theme static { --color-b: red; }"),
1796            vec!["color-b"]
1797        );
1798    }
1799
1800    #[test]
1801    fn theme_multiple_blocks_union() {
1802        let names = theme_token_names(
1803            "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
1804        );
1805        assert_eq!(names, vec!["color-a", "spacing-gutter"]);
1806    }
1807
1808    #[test]
1809    fn theme_reset_form_excluded() {
1810        // `--color-*: initial` is a namespace reset directive, not a token.
1811        let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
1812        assert_eq!(names, vec!["color-brand"]);
1813    }
1814
1815    #[test]
1816    fn theme_no_block_yields_nothing() {
1817        assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
1818    }
1819
1820    #[test]
1821    fn theme_line_numbers() {
1822        let scan = scan_theme_blocks("@theme {\n  --color-a: red;\n  --radius-b: 4px;\n}");
1823        assert_eq!(scan.tokens[0].line, 2);
1824        assert_eq!(scan.tokens[1].line, 3);
1825    }
1826
1827    #[test]
1828    fn theme_token_backs_token_via_var() {
1829        let scan = scan_theme_blocks(
1830            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1831        );
1832        assert!(
1833            scan.theme_var_reads
1834                .iter()
1835                .any(|(name, _)| name == "color-brand")
1836        );
1837    }
1838
1839    #[test]
1840    fn theme_var_read_carries_line() {
1841        // The `var(--color-brand)` read sits on line 3 of the source; the located
1842        // theme-var read must carry that 1-based line for the reverse index.
1843        let scan = scan_theme_blocks(
1844            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1845        );
1846        assert_eq!(
1847            scan.theme_var_reads,
1848            vec![("color-brand".to_string(), 3u32)]
1849        );
1850    }
1851
1852    #[test]
1853    fn css_var_reads_locate_outside_theme_and_exclude_interior() {
1854        // A regular-CSS `var(--color-brand)` read is located (css-var surface);
1855        // a read inside the `@theme` interior is the distinct theme-var surface
1856        // and MUST be excluded here so the two kinds never double-count.
1857        let source = "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}\n\n.btn {\n  color: var(--color-brand);\n}\n";
1858        assert_eq!(
1859            extract_css_var_reads_located(source),
1860            vec![("color-brand".to_string(), 7u32)],
1861            "only the .btn read (line 7) is a css-var; the @theme-interior read is excluded"
1862        );
1863
1864        // A source whose only `var()` read is inside `@theme` yields no css-var.
1865        assert!(
1866            extract_css_var_reads_located("@theme {\n  --a: #fff;\n  --b: var(--a);\n}",)
1867                .is_empty(),
1868            "a @theme-interior-only var() read is not a css-var consumer"
1869        );
1870    }
1871
1872    #[test]
1873    fn css_var_reads_line_match_naive_reference_on_dense_line() {
1874        // Many `var()` reads packed onto a single long line (the pathological
1875        // zero-newline prefix) plus one trailing read on the next line: the
1876        // incremental line counter must agree byte-for-byte with the naive
1877        // per-match prefix rescan. No `@theme`, comments, strings, or `url()`,
1878        // so masking is identity and every read is a css-var read.
1879        use std::fmt::Write as _;
1880        let mut src = String::from(".x {");
1881        for i in 0..500 {
1882            let _ = write!(src, " color: var(--t{i});");
1883        }
1884        src.push_str(" }\n.y { color: var(--tail); }\n");
1885
1886        let got = extract_css_var_reads_located(&src);
1887
1888        // Reference: recompute each read's line via a full prefix rescan.
1889        let want: Vec<(String, u32)> = CSS_VAR_REF_RE
1890            .captures_iter(&src)
1891            .filter_map(|cap| cap.get(0).zip(cap.get(1)))
1892            .map(|(whole, name)| {
1893                (
1894                    name.as_str().to_owned(),
1895                    line_at_offset(&src, whole.start()),
1896                )
1897            })
1898            .collect();
1899
1900        assert_eq!(got, want);
1901        assert!(got.len() > 500, "expected the dense line plus the trailer");
1902        // The trailer sits on line 2; the packed reads all sit on line 1.
1903        assert_eq!(got.last().map(|(_, l)| *l), Some(2));
1904        assert!(got[..got.len() - 1].iter().all(|(_, l)| *l == 1));
1905    }
1906
1907    #[test]
1908    fn theme_string_braces_do_not_truncate_block() {
1909        let scan = scan_theme_blocks(
1910            "@theme {\n  --font-label: \"}\";\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1911        );
1912        assert_eq!(
1913            scan.tokens
1914                .iter()
1915                .map(|token| token.name.as_str())
1916                .collect::<Vec<_>>(),
1917            vec!["font-label", "color-brand", "color-button"]
1918        );
1919        assert!(
1920            scan.theme_var_reads
1921                .iter()
1922                .any(|(name, _)| name == "color-brand")
1923        );
1924    }
1925
1926    #[test]
1927    fn theme_nested_keyframes_body_not_collected() {
1928        // `@keyframes` inside `@theme` (for `--animate-*`) must not surface its
1929        // step selectors or interior as theme tokens.
1930        let names = theme_token_names(
1931            "@theme {\n  --animate-spin: spin 1s linear infinite;\n  @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
1932        );
1933        assert_eq!(names, vec!["animate-spin"]);
1934    }
1935
1936    #[test]
1937    fn theme_comment_block_ignored() {
1938        let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
1939        assert!(names.is_empty(), "got {names:?}");
1940    }
1941
1942    #[test]
1943    fn theme_deduplicates_repeated_token() {
1944        let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
1945        assert_eq!(names, vec!["color-a"]);
1946    }
1947
1948    #[test]
1949    fn apply_tokens_basic() {
1950        let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
1951        assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
1952    }
1953
1954    #[test]
1955    fn apply_tokens_strips_important() {
1956        let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
1957        assert_eq!(tokens, vec!["text-brand", "font-bold"]);
1958    }
1959
1960    #[test]
1961    fn apply_tokens_ignored_in_comments() {
1962        let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
1963        assert!(tokens.is_empty(), "got {tokens:?}");
1964    }
1965}