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