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