Skip to main content

fallow_extract/
css.rs

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