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
185pub(crate) fn 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`].
221pub(crate) fn 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, Sass or Less file: the `@import`, `@use`, `@forward`,
1063/// `@plugin`, `@apply` and `@tailwind` directives, and the packages that its
1064/// `url()` values name.
1065pub(crate) fn parse_css_to_module(
1066    file_id: FileId,
1067    path: &Path,
1068    source: &str,
1069    content_hash: u64,
1070) -> ModuleInfo {
1071    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
1072    let is_scss = path
1073        .extension()
1074        .and_then(|e| e.to_str())
1075        .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
1076
1077    let stripped = crate::css_mask::mask_sass_shorthand(mask_css_comments(source, is_scss), path);
1078    let imports = build_css_imports(&stripped, is_scss);
1079
1080    let exports = if is_css_module_file(path) {
1081        css_module_exports(source, &stripped, is_scss)
1082    } else {
1083        Vec::new()
1084    };
1085
1086    // CSS has no JS-level structure, so the AST-derived fields stay empty.
1087    let mut info =
1088        crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
1089            file_id,
1090            content_hash,
1091            source,
1092            parsed_suppressions,
1093            imports,
1094            exports,
1095        });
1096    info.package_path_references =
1097        crate::css_url::package_url_references(&stripped).into_boxed_slice();
1098    info
1099}
1100
1101#[cfg(all(test, not(miri)))]
1102mod tests {
1103    use super::*;
1104
1105    /// Helper to collect export names as strings from `extract_css_module_exports`.
1106    fn export_names(source: &str) -> Vec<String> {
1107        extract_css_module_exports(source, false)
1108            .into_iter()
1109            .filter_map(|e| match e.name {
1110                ExportName::Named(n) => Some(n),
1111                ExportName::Default => None,
1112            })
1113            .collect()
1114    }
1115
1116    #[test]
1117    fn is_css_file_css() {
1118        assert!(is_css_file(Path::new("styles.css")));
1119    }
1120
1121    #[test]
1122    fn is_css_file_scss() {
1123        assert!(is_css_file(Path::new("styles.scss")));
1124    }
1125
1126    #[test]
1127    fn is_css_file_sass() {
1128        assert!(is_css_file(Path::new("styles.sass")));
1129    }
1130
1131    #[test]
1132    fn is_css_file_less() {
1133        assert!(is_css_file(Path::new("styles.less")));
1134    }
1135
1136    #[test]
1137    fn is_css_file_rejects_js() {
1138        assert!(!is_css_file(Path::new("app.js")));
1139    }
1140
1141    #[test]
1142    fn is_css_file_rejects_ts() {
1143        assert!(!is_css_file(Path::new("app.ts")));
1144    }
1145
1146    #[test]
1147    fn is_css_file_rejects_no_extension() {
1148        assert!(!is_css_file(Path::new("Makefile")));
1149    }
1150
1151    #[test]
1152    fn is_css_module_file_module_css() {
1153        assert!(is_css_module_file(Path::new("Component.module.css")));
1154    }
1155
1156    #[test]
1157    fn is_css_module_file_module_scss() {
1158        assert!(is_css_module_file(Path::new("Component.module.scss")));
1159    }
1160
1161    #[test]
1162    fn is_css_module_file_rejects_plain_css() {
1163        assert!(!is_css_module_file(Path::new("styles.css")));
1164    }
1165
1166    #[test]
1167    fn is_css_module_file_rejects_plain_scss() {
1168        assert!(!is_css_module_file(Path::new("styles.scss")));
1169    }
1170
1171    #[test]
1172    fn is_css_module_file_rejects_module_js() {
1173        assert!(!is_css_module_file(Path::new("utils.module.js")));
1174    }
1175
1176    #[test]
1177    fn extracts_single_class() {
1178        let names = export_names(".foo { color: red; }");
1179        assert_eq!(names, vec!["foo"]);
1180    }
1181
1182    #[test]
1183    fn extracts_multiple_classes() {
1184        let names = export_names(".foo { } .bar { }");
1185        assert_eq!(names, vec!["foo", "bar"]);
1186    }
1187
1188    #[test]
1189    fn extracts_nested_classes() {
1190        let names = export_names(".foo .bar { color: red; }");
1191        assert!(names.contains(&"foo".to_string()));
1192        assert!(names.contains(&"bar".to_string()));
1193    }
1194
1195    #[test]
1196    fn extracts_hyphenated_class() {
1197        let names = export_names(".my-class { }");
1198        assert_eq!(names, vec!["my-class"]);
1199    }
1200
1201    #[test]
1202    fn extracts_camel_case_class() {
1203        let names = export_names(".myClass { }");
1204        assert_eq!(names, vec!["myClass"]);
1205    }
1206
1207    fn scss_export_names(source: &str) -> Vec<String> {
1208        extract_css_module_exports(source, true)
1209            .into_iter()
1210            .filter_map(|e| match e.name {
1211                ExportName::Named(n) => Some(n),
1212                ExportName::Default => None,
1213            })
1214            .collect()
1215    }
1216
1217    #[test]
1218    fn skips_class_inside_global_pseudo() {
1219        // CSS Modules do not put a `:global(.foo)` class in the class map.
1220        let names = export_names(":global(.globalClass) { color: red; }");
1221        assert!(names.is_empty(), "got {names:?}");
1222    }
1223
1224    #[test]
1225    fn keeps_local_class_next_to_global_pseudo() {
1226        // Issue #3311.
1227        let names = export_names(".wrapper :global(.selector) { color: red; }");
1228        assert_eq!(names, vec!["wrapper"]);
1229    }
1230
1231    #[test]
1232    fn skips_every_class_inside_global_pseudo_with_descendants() {
1233        let names = export_names(".panel :global(.outer .inner.mod) { color: red; }");
1234        assert_eq!(names, vec!["panel"]);
1235    }
1236
1237    #[test]
1238    fn skips_classes_after_bare_global() {
1239        let names = export_names(".lead :global .first .second { color: red; }");
1240        assert_eq!(names, vec!["lead"]);
1241    }
1242
1243    #[test]
1244    fn bare_global_stops_at_local() {
1245        let names = export_names(":global .g1 :local(.l1) .g2 :local .l2 .l3, .l4 { color: red; }");
1246        assert_eq!(names, vec!["l1", "l2", "l3", "l4"]);
1247    }
1248
1249    #[test]
1250    fn bare_global_stops_at_comma() {
1251        let names = export_names(":global .g1, .l1 :is(.l2, .l3) { color: red; }");
1252        assert_eq!(names, vec!["l1", "l2", "l3"]);
1253    }
1254
1255    #[test]
1256    fn global_class_inside_media_query_is_skipped() {
1257        let names = export_names("@media (min-width: 1px) { .media :global(.g) { color: red; } }");
1258        assert_eq!(names, vec!["media"]);
1259    }
1260
1261    #[test]
1262    fn class_both_local_and_global_stays_exported_at_local_span() {
1263        let source = ":global(.both) { color: red; }\n.both { color: blue; }";
1264        let exports = extract_css_module_exports(source, false);
1265        assert_eq!(exports.len(), 1);
1266        let span = exports[0].span;
1267        assert_eq!(&source[span.start as usize..span.end as usize], "both");
1268        assert!(
1269            span.start > 20,
1270            "span must point at the local rule: {span:?}"
1271        );
1272    }
1273
1274    #[test]
1275    fn composes_keeps_local_classes() {
1276        let names = export_names(
1277            ".base { color: red; }\n.button { composes: base; composes: g from global; }",
1278        );
1279        assert_eq!(names, vec!["base", "button"]);
1280    }
1281
1282    #[test]
1283    fn global_in_strings_and_comments_has_no_effect() {
1284        let names =
1285            export_names("/* :global */ .a { content: \":global\"; }\n.b :global(.c) { }\n.d { }");
1286        assert_eq!(names, vec!["a", "b", "d"]);
1287    }
1288
1289    #[test]
1290    fn scss_skips_global_pseudo_and_global_block() {
1291        let names = scss_export_names(
1292            ".card {\n  :global(.g1) { color: red; }\n  .title { color: blue; }\n}\n\
1293             :global {\n  .g2 { color: red; }\n  .g3 { :local(.l1) { color: red; } }\n}\n\
1294             .after { color: blue; }",
1295        );
1296        assert_eq!(names, vec!["card", "title", "l1", "after"]);
1297    }
1298
1299    #[test]
1300    fn scss_bare_global_in_parent_reaches_nested_rules() {
1301        let names = scss_export_names(
1302            ".a :global .b {\n  .c { color: red; }\n  &:hover { color: blue; }\n}\n.d { }",
1303        );
1304        assert_eq!(names, vec!["a", "d"]);
1305    }
1306
1307    #[test]
1308    fn scss_interpolation_does_not_end_global_scope() {
1309        let names = scss_export_names("$n: x;\n.a :global .b-#{$n} .c { }\n.d { }");
1310        assert_eq!(names, vec!["a", "d"]);
1311    }
1312
1313    #[test]
1314    fn sass_indented_bare_global_ends_at_line_end() {
1315        let names = scss_export_names(".a :global .b\n  color: red\n.c\n  color: blue\n");
1316        assert_eq!(names, vec!["a", "c"]);
1317    }
1318
1319    #[test]
1320    fn sass_indented_with_interpolation_still_ends_global_at_line_end() {
1321        let names = scss_export_names(
1322            ".a :global .b\n  color: red\n.c-#{$x}\n  color: blue\n.d\n  color: blue\n",
1323        );
1324        // The scanner keeps the static prefix `c-` of an interpolated class.
1325        assert_eq!(names, vec!["a", "c-", "d"]);
1326    }
1327
1328    #[test]
1329    fn global_like_pseudo_names_are_not_global() {
1330        let names = export_names(".a:global-ish .b { }");
1331        assert!(names.contains(&"b".to_string()), "got {names:?}");
1332    }
1333
1334    #[test]
1335    fn extracts_class_inside_local_pseudo() {
1336        let names = export_names(":local(.localClass) { color: red; }");
1337        assert_eq!(names, vec!["localClass"]);
1338    }
1339
1340    #[test]
1341    fn extracts_classes_inside_negation() {
1342        let names = export_names(".btn:not(.disabled) { }");
1343        assert!(names.contains(&"btn".to_string()), "got {names:?}");
1344        assert!(names.contains(&"disabled".to_string()), "got {names:?}");
1345    }
1346
1347    #[test]
1348    fn extracts_classes_inside_is_and_where() {
1349        let names = export_names(":is(.a, .b) :where(.c) { }");
1350        for expected in ["a", "b", "c"] {
1351            assert!(
1352                names.contains(&expected.to_string()),
1353                "missing {expected} in {names:?}"
1354            );
1355        }
1356    }
1357
1358    #[test]
1359    fn extracts_underscore_class() {
1360        let names = export_names("._hidden { } .__wrapper { }");
1361        assert!(names.contains(&"_hidden".to_string()));
1362        assert!(names.contains(&"__wrapper".to_string()));
1363    }
1364
1365    #[test]
1366    fn pseudo_selector_hover() {
1367        let names = export_names(".foo:hover { color: blue; }");
1368        assert_eq!(names, vec!["foo"]);
1369    }
1370
1371    #[test]
1372    fn pseudo_selector_focus() {
1373        let names = export_names(".input:focus { outline: none; }");
1374        assert_eq!(names, vec!["input"]);
1375    }
1376
1377    #[test]
1378    fn pseudo_element_before() {
1379        let names = export_names(".icon::before { content: ''; }");
1380        assert_eq!(names, vec!["icon"]);
1381    }
1382
1383    #[test]
1384    fn combined_pseudo_selectors() {
1385        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
1386        assert_eq!(names, vec!["btn"]);
1387    }
1388
1389    #[test]
1390    fn classes_inside_media_query() {
1391        let names = export_names(
1392            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
1393        );
1394        assert!(names.contains(&"mobile-nav".to_string()));
1395        assert!(names.contains(&"desktop-nav".to_string()));
1396    }
1397
1398    #[test]
1399    fn classes_inside_multi_line_media_query() {
1400        let names =
1401            export_names("@media\n  screen and (min-width: 600px)\n{\n  .real { color: red; }\n}");
1402        assert_eq!(names, vec!["real"]);
1403    }
1404
1405    #[test]
1406    fn at_layer_statement_does_not_export() {
1407        let names = export_names("@layer foo.bar;");
1408        assert!(names.is_empty(), "got {names:?}");
1409        let names = export_names("@layer foo.bar, foo.baz;");
1410        assert!(names.is_empty(), "got {names:?}");
1411    }
1412
1413    #[test]
1414    fn at_layer_block_keeps_body_classes() {
1415        let names = export_names("@layer foo.bar { .root { color: red; } }");
1416        assert_eq!(names, vec!["root"]);
1417    }
1418
1419    #[test]
1420    fn at_layer_multiline_prelude_keeps_body_classes() {
1421        let names = export_names("@layer\n  foo.bar\n{ .root { color: red; } }");
1422        assert_eq!(names, vec!["root"]);
1423    }
1424
1425    #[test]
1426    fn at_layer_with_nested_media_keeps_body() {
1427        let names =
1428            export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1429        assert_eq!(names, vec!["real"]);
1430    }
1431
1432    #[test]
1433    fn at_import_with_layer_attribute_does_not_export() {
1434        let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1435        assert!(names.is_empty(), "got {names:?}");
1436    }
1437
1438    #[test]
1439    fn class_then_at_layer_does_not_leak_prelude() {
1440        let names =
1441            export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1442        assert_eq!(names, vec!["outer", "inner"]);
1443    }
1444
1445    #[test]
1446    fn at_scope_keeps_selector_list_classes() {
1447        let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1448        assert!(names.contains(&"parent".to_string()), "got {names:?}");
1449        assert!(names.contains(&"child".to_string()), "got {names:?}");
1450        assert!(names.contains(&"title".to_string()), "got {names:?}");
1451    }
1452
1453    #[test]
1454    fn at_keyframes_numeric_step_is_not_class() {
1455        let names = export_names(
1456            "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1457        );
1458        assert!(names.is_empty(), "got {names:?}");
1459    }
1460
1461    #[test]
1462    fn at_webkit_keyframes_keeps_body_classes() {
1463        let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1464        assert_eq!(names, vec!["real"]);
1465    }
1466
1467    #[test]
1468    fn deduplicates_repeated_class() {
1469        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1470        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1471    }
1472
1473    #[test]
1474    fn empty_source() {
1475        let names = export_names("");
1476        assert!(names.is_empty());
1477    }
1478
1479    #[test]
1480    fn no_classes() {
1481        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1482        assert!(names.is_empty());
1483    }
1484
1485    #[test]
1486    fn ignores_classes_in_block_comments() {
1487        let names = export_names("/* .fake { } */ .real { }");
1488        assert!(!names.contains(&"fake".to_string()));
1489        assert!(names.contains(&"real".to_string()));
1490    }
1491
1492    #[test]
1493    fn ignores_classes_in_scss_line_comments() {
1494        let exports = extract_css_module_exports("// .fake\n.real { }", true);
1495        let names: Vec<_> = exports
1496            .iter()
1497            .filter_map(|e| match &e.name {
1498                ExportName::Named(n) => Some(n.as_str()),
1499                ExportName::Default => None,
1500            })
1501            .collect();
1502        assert_eq!(names, vec!["real"]);
1503    }
1504
1505    #[test]
1506    fn ignores_classes_in_strings() {
1507        let names = export_names(r#".real { content: ".fake"; }"#);
1508        assert!(names.contains(&"real".to_string()));
1509        assert!(!names.contains(&"fake".to_string()));
1510    }
1511
1512    #[test]
1513    fn ignores_classes_in_url() {
1514        let names = export_names(".real { background: url(./images/hero.png); }");
1515        assert!(names.contains(&"real".to_string()));
1516        assert!(!names.contains(&"png".to_string()));
1517    }
1518
1519    #[test]
1520    fn mask_css_block_comment() {
1521        let source = "/* removed */ .kept { }";
1522        let result = mask_css_comments(source, false);
1523        assert!(!result.contains("removed"));
1524        assert_eq!(result.len(), source.len());
1525        assert_eq!(result.find(".kept"), source.find(".kept"));
1526    }
1527
1528    #[test]
1529    fn mask_scss_line_comment() {
1530        let source = "// removed\n.kept { }";
1531        let result = mask_css_comments(source, true);
1532        assert!(!result.contains("removed"));
1533        assert_eq!(result.len(), source.len());
1534        assert_eq!(result.find(".kept"), source.find(".kept"));
1535    }
1536
1537    #[test]
1538    fn mask_scss_preserves_css_outside_comments() {
1539        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1540        let result = mask_css_comments(source, true);
1541        assert!(result.contains(".visible"));
1542    }
1543
1544    #[test]
1545    fn url_import_http() {
1546        assert!(is_css_url_import("http://example.com/style.css"));
1547    }
1548
1549    #[test]
1550    fn url_import_https() {
1551        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1552    }
1553
1554    #[test]
1555    fn url_import_data() {
1556        assert!(is_css_url_import("data:text/css;base64,abc"));
1557    }
1558
1559    #[test]
1560    fn url_import_local_not_skipped() {
1561        assert!(!is_css_url_import("./local.css"));
1562    }
1563
1564    #[test]
1565    fn url_import_bare_specifier_not_skipped() {
1566        assert!(!is_css_url_import("tailwindcss"));
1567    }
1568
1569    #[test]
1570    fn normalize_relative_dot_path_unchanged() {
1571        assert_eq!(
1572            normalize_css_import_path("./reset.css".to_string(), false),
1573            "./reset.css"
1574        );
1575    }
1576
1577    #[test]
1578    fn normalize_parent_relative_path_unchanged() {
1579        assert_eq!(
1580            normalize_css_import_path("../shared.scss".to_string(), false),
1581            "../shared.scss"
1582        );
1583    }
1584
1585    #[test]
1586    fn normalize_absolute_path_unchanged() {
1587        assert_eq!(
1588            normalize_css_import_path("/styles/main.css".to_string(), false),
1589            "/styles/main.css"
1590        );
1591    }
1592
1593    #[test]
1594    fn normalize_url_unchanged() {
1595        assert_eq!(
1596            normalize_css_import_path("https://example.com/style.css".to_string(), false),
1597            "https://example.com/style.css"
1598        );
1599    }
1600
1601    #[test]
1602    fn normalize_bare_css_gets_dot_slash() {
1603        assert_eq!(
1604            normalize_css_import_path("app.css".to_string(), false),
1605            "./app.css"
1606        );
1607    }
1608
1609    #[test]
1610    fn normalize_css_package_subpath_stays_bare() {
1611        assert_eq!(
1612            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1613            "tailwindcss/theme.css"
1614        );
1615    }
1616
1617    #[test]
1618    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1619        assert_eq!(
1620            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1621            "highlight.js/styles/github.css"
1622        );
1623    }
1624
1625    #[test]
1626    fn normalize_bare_scss_gets_dot_slash() {
1627        assert_eq!(
1628            normalize_css_import_path("vars.scss".to_string(), false),
1629            "./vars.scss"
1630        );
1631    }
1632
1633    #[test]
1634    fn normalize_bare_sass_gets_dot_slash() {
1635        assert_eq!(
1636            normalize_css_import_path("main.sass".to_string(), false),
1637            "./main.sass"
1638        );
1639    }
1640
1641    #[test]
1642    fn normalize_bare_less_gets_dot_slash() {
1643        assert_eq!(
1644            normalize_css_import_path("theme.less".to_string(), false),
1645            "./theme.less"
1646        );
1647    }
1648
1649    #[test]
1650    fn normalize_bare_js_extension_stays_bare() {
1651        assert_eq!(
1652            normalize_css_import_path("module.js".to_string(), false),
1653            "module.js"
1654        );
1655    }
1656
1657    #[test]
1658    fn normalize_scss_bare_partial_gets_dot_slash() {
1659        assert_eq!(
1660            normalize_css_import_path("variables".to_string(), true),
1661            "./variables"
1662        );
1663    }
1664
1665    #[test]
1666    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1667        assert_eq!(
1668            normalize_css_import_path("base/reset".to_string(), true),
1669            "./base/reset"
1670        );
1671    }
1672
1673    #[test]
1674    fn normalize_scss_builtin_stays_bare() {
1675        assert_eq!(
1676            normalize_css_import_path("sass:math".to_string(), true),
1677            "sass:math"
1678        );
1679    }
1680
1681    #[test]
1682    fn normalize_scss_relative_path_unchanged() {
1683        assert_eq!(
1684            normalize_css_import_path("../styles/variables".to_string(), true),
1685            "../styles/variables"
1686        );
1687    }
1688
1689    #[test]
1690    fn normalize_css_bare_extensionless_stays_bare() {
1691        assert_eq!(
1692            normalize_css_import_path("tailwindcss".to_string(), false),
1693            "tailwindcss"
1694        );
1695    }
1696
1697    #[test]
1698    fn normalize_scoped_package_with_css_extension_stays_bare() {
1699        assert_eq!(
1700            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1701            "@fontsource/monaspace-neon/400.css"
1702        );
1703    }
1704
1705    #[test]
1706    fn normalize_scoped_package_with_scss_extension_stays_bare() {
1707        assert_eq!(
1708            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1709            "@company/design-system/tokens.scss"
1710        );
1711    }
1712
1713    #[test]
1714    fn normalize_scoped_package_without_extension_stays_bare() {
1715        assert_eq!(
1716            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1717            "@fallow/design-system/styles"
1718        );
1719    }
1720
1721    #[test]
1722    fn normalize_scoped_package_extensionless_scss_stays_bare() {
1723        assert_eq!(
1724            normalize_css_import_path("@company/tokens".to_string(), true),
1725            "@company/tokens"
1726        );
1727    }
1728
1729    #[test]
1730    fn normalize_path_alias_with_css_extension_stays_bare() {
1731        assert_eq!(
1732            normalize_css_import_path("@/components/Button.css".to_string(), false),
1733            "@/components/Button.css"
1734        );
1735    }
1736
1737    #[test]
1738    fn normalize_path_alias_extensionless_stays_bare() {
1739        assert_eq!(
1740            normalize_css_import_path("@/styles/variables".to_string(), false),
1741            "@/styles/variables"
1742        );
1743    }
1744
1745    #[test]
1746    fn mask_css_no_comments() {
1747        let source = ".foo { color: red; }";
1748        assert_eq!(mask_css_comments(source, false), source);
1749    }
1750
1751    #[test]
1752    fn mask_css_multiple_block_comments() {
1753        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1754        let result = mask_css_comments(source, false);
1755        assert!(!result.contains("comment-one"));
1756        assert!(!result.contains("comment-two"));
1757        assert!(result.contains(".foo"));
1758        assert!(result.contains(".bar"));
1759    }
1760
1761    #[test]
1762    fn mask_scss_does_not_affect_non_scss() {
1763        let source = "// this stays\n.foo { }";
1764        let result = mask_css_comments(source, false);
1765        assert!(result.contains("// this stays"));
1766    }
1767
1768    #[test]
1769    fn css_module_parses_suppressions() {
1770        let info = parse_css_to_module(
1771            fallow_types::discover::FileId(0),
1772            Path::new("Component.module.css"),
1773            "/* fallow-ignore-file */\n.btn { color: red; }",
1774            0,
1775        );
1776        assert!(!info.suppressions.is_empty());
1777        assert_eq!(info.suppressions[0].line, 0);
1778    }
1779
1780    #[test]
1781    fn extracts_class_starting_with_underscore() {
1782        let names = export_names("._private { } .__dunder { }");
1783        assert!(names.contains(&"_private".to_string()));
1784        assert!(names.contains(&"__dunder".to_string()));
1785    }
1786
1787    #[test]
1788    fn ignores_id_selectors() {
1789        let names = export_names("#myId { color: red; }");
1790        assert!(!names.contains(&"myId".to_string()));
1791    }
1792
1793    #[test]
1794    fn ignores_element_selectors() {
1795        let names = export_names("div { color: red; } span { }");
1796        assert!(names.is_empty());
1797    }
1798
1799    #[test]
1800    fn extract_css_imports_at_import_quoted() {
1801        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1802        assert_eq!(imports, vec!["./reset.css"]);
1803    }
1804
1805    #[test]
1806    fn extract_css_imports_package_subpath_stays_bare() {
1807        let imports =
1808            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1809        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1810    }
1811
1812    #[test]
1813    fn extract_css_imports_at_import_url() {
1814        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1815        assert_eq!(imports, vec!["./reset.css"]);
1816    }
1817
1818    #[test]
1819    fn extract_css_imports_skips_remote_urls() {
1820        let imports =
1821            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1822        assert!(imports.is_empty());
1823    }
1824
1825    #[test]
1826    fn extract_css_imports_scss_use_normalizes_partial() {
1827        let imports = extract_css_imports(r#"@use "variables";"#, true);
1828        assert_eq!(imports, vec!["./variables"]);
1829    }
1830
1831    #[test]
1832    fn extract_css_imports_scss_forward_normalizes_partial() {
1833        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1834        assert_eq!(imports, vec!["./tokens"]);
1835    }
1836
1837    #[test]
1838    fn extract_css_imports_skips_comments() {
1839        let imports = extract_css_imports(
1840            r#"/* @import "./hidden.scss"; */
1841@use "real";"#,
1842            true,
1843        );
1844        assert_eq!(imports, vec!["./real"]);
1845    }
1846
1847    #[test]
1848    fn extract_css_imports_at_plugin_keeps_package_bare() {
1849        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1850        assert_eq!(imports, vec!["daisyui"]);
1851    }
1852
1853    #[test]
1854    fn extract_css_imports_at_plugin_tracks_relative_file() {
1855        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1856        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1857    }
1858
1859    #[test]
1860    fn extract_css_imports_scss_at_import_kept_relative() {
1861        let imports = extract_css_imports(r"@import 'Foo';", true);
1862        assert_eq!(imports, vec!["./Foo"]);
1863    }
1864
1865    #[test]
1866    fn extract_css_imports_additional_data_string_body() {
1867        let body = r#"@use "./src/styles/global.scss";"#;
1868        let imports = extract_css_imports(body, true);
1869        assert_eq!(imports, vec!["./src/styles/global.scss"]);
1870    }
1871
1872    /// Resolve a span's start to (line, col) using the same primitives the
1873    /// downstream pipeline uses in `crates/core/src/analyze/unused_exports.rs`.
1874    fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1875        let offsets = fallow_types::extract::compute_line_offsets(source);
1876        fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1877    }
1878
1879    #[test]
1880    fn span_points_at_real_class_declaration_line() {
1881        let source = "\n\n\n\n.foo { color: red; }\n";
1882        let exports = extract_css_module_exports(source, false);
1883        assert_eq!(exports.len(), 1);
1884        let span = exports[0].span;
1885        let (line, col) = span_line_col(source, span.start);
1886        assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1887        assert_eq!(
1888            col, 1,
1889            "column points at `f` in `.foo` (post-dot identifier)"
1890        );
1891        assert_eq!(
1892            &source[span.start as usize..span.end as usize],
1893            "foo",
1894            "span range must slice to the class identifier in the original source"
1895        );
1896    }
1897
1898    #[test]
1899    fn span_survives_multibyte_comment_prefix() {
1900        let source = "/* \u{2713} */\n.foo { }";
1901        let exports = extract_css_module_exports(source, false);
1902        assert_eq!(exports.len(), 1);
1903        let span = exports[0].span;
1904        assert!(
1905            source.is_char_boundary(span.start as usize),
1906            "span.start must lie on a UTF-8 char boundary"
1907        );
1908        assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1909    }
1910
1911    #[test]
1912    fn span_skips_at_layer_prelude_dot_segments() {
1913        let source = "@layer foo.bar { }\n.root { }\n";
1914        let exports = extract_css_module_exports(source, false);
1915        let names: Vec<_> = exports
1916            .iter()
1917            .filter_map(|e| match &e.name {
1918                ExportName::Named(n) => Some(n.as_str()),
1919                ExportName::Default => None,
1920            })
1921            .collect();
1922        assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1923        let span = exports[0].span;
1924        let (line, _col) = span_line_col(source, span.start);
1925        assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1926        assert_eq!(&source[span.start as usize..span.end as usize], "root");
1927    }
1928
1929    #[test]
1930    fn span_skips_classes_in_strings() {
1931        let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1932        let exports = extract_css_module_exports(source, false);
1933        let names: Vec<_> = exports
1934            .iter()
1935            .filter_map(|e| match &e.name {
1936                ExportName::Named(n) => Some(n.as_str()),
1937                ExportName::Default => None,
1938            })
1939            .collect();
1940        assert_eq!(names, vec!["real", "also-real"]);
1941        for export in &exports {
1942            let span = export.span;
1943            let slice = &source[span.start as usize..span.end as usize];
1944            match &export.name {
1945                ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1946                ExportName::Default => unreachable!("CSS modules emit only named exports"),
1947            }
1948        }
1949    }
1950
1951    #[test]
1952    fn span_deduplicates_to_first_occurrence() {
1953        let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1954        let exports = extract_css_module_exports(source, false);
1955        assert_eq!(exports.len(), 1);
1956        let (line, _col) = span_line_col(source, exports[0].span.start);
1957        assert_eq!(
1958            line, 1,
1959            "first occurrence wins for deduplicated class names"
1960        );
1961    }
1962
1963    #[test]
1964    fn span_inside_media_query() {
1965        let source =
1966            "@media (max-width: 768px) {\n  .mobile { display: block; }\n  .desktop { }\n}\n";
1967        let exports = extract_css_module_exports(source, false);
1968        let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1969            .iter()
1970            .filter_map(|e| match &e.name {
1971                ExportName::Named(n) => Some((n.as_str(), e.span)),
1972                ExportName::Default => None,
1973            })
1974            .collect();
1975        let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1976        let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1977        assert_eq!(mobile_line, 2);
1978        assert_eq!(desktop_line, 3);
1979    }
1980
1981    #[test]
1982    fn at_layer_only_module_emits_no_exports() {
1983        let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1984        assert!(exports.is_empty());
1985    }
1986
1987    #[test]
1988    fn parse_css_to_module_resolves_real_line_offsets() {
1989        let source = "\n\n\n\n.foo { color: red; }\n";
1990        let info = parse_css_to_module(
1991            fallow_types::discover::FileId(0),
1992            Path::new("Component.module.css"),
1993            source,
1994            0,
1995        );
1996        assert_eq!(info.exports.len(), 1);
1997        let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1998            &info.line_offsets,
1999            info.exports[0].span.start,
2000        );
2001        assert_eq!(line, 5, "downstream line must equal the source line");
2002    }
2003
2004    fn theme_token_names(source: &str) -> Vec<String> {
2005        scan_theme_blocks(source)
2006            .tokens
2007            .into_iter()
2008            .map(|t| t.name)
2009            .collect()
2010    }
2011
2012    #[test]
2013    fn theme_single_block_collects_tokens() {
2014        let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
2015        assert_eq!(names, vec!["color-brand", "radius-card"]);
2016    }
2017
2018    #[test]
2019    fn theme_token_values_are_normalized() {
2020        let scan = scan_theme_blocks("@theme {\n  --color-brand: rgb( 255 0 0 );\n}");
2021        assert_eq!(scan.tokens[0].name, "color-brand");
2022        assert_eq!(scan.tokens[0].value, "rgb( 255 0 0 )");
2023    }
2024
2025    #[test]
2026    fn theme_dashed_multi_segment_names() {
2027        let names = theme_token_names(
2028            "@theme {\n  --font-weight-heavy: 900;\n  --inset-shadow-glow: 0 0 4px red;\n}",
2029        );
2030        assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
2031    }
2032
2033    #[test]
2034    fn theme_inline_and_static_modifiers() {
2035        assert_eq!(
2036            theme_token_names("@theme inline { --color-a: red; }"),
2037            vec!["color-a"]
2038        );
2039        assert_eq!(
2040            theme_token_names("@theme static { --color-b: red; }"),
2041            vec!["color-b"]
2042        );
2043    }
2044
2045    #[test]
2046    fn theme_multiple_blocks_union() {
2047        let names = theme_token_names(
2048            "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
2049        );
2050        assert_eq!(names, vec!["color-a", "spacing-gutter"]);
2051    }
2052
2053    #[test]
2054    fn theme_reset_form_excluded() {
2055        // `--color-*: initial` is a namespace reset directive, not a token.
2056        let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
2057        assert_eq!(names, vec!["color-brand"]);
2058    }
2059
2060    #[test]
2061    fn theme_no_block_yields_nothing() {
2062        assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
2063    }
2064
2065    #[test]
2066    fn theme_line_numbers() {
2067        let scan = scan_theme_blocks("@theme {\n  --color-a: red;\n  --radius-b: 4px;\n}");
2068        assert_eq!(scan.tokens[0].line, 2);
2069        assert_eq!(scan.tokens[1].line, 3);
2070    }
2071
2072    #[test]
2073    fn theme_token_backs_token_via_var() {
2074        let scan = scan_theme_blocks(
2075            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
2076        );
2077        assert!(
2078            scan.theme_var_reads
2079                .iter()
2080                .any(|(name, _)| name == "color-brand")
2081        );
2082    }
2083
2084    #[test]
2085    fn theme_var_read_carries_line() {
2086        // The `var(--color-brand)` read sits on line 3 of the source; the located
2087        // theme-var read must carry that 1-based line for the reverse index.
2088        let scan = scan_theme_blocks(
2089            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
2090        );
2091        assert_eq!(
2092            scan.theme_var_reads,
2093            vec![("color-brand".to_string(), 3u32)]
2094        );
2095    }
2096
2097    #[test]
2098    fn css_var_reads_locate_outside_theme_and_exclude_interior() {
2099        // A regular-CSS `var(--color-brand)` read is located (css-var surface);
2100        // a read inside the `@theme` interior is the distinct theme-var surface
2101        // and MUST be excluded here so the two kinds never double-count.
2102        let source = "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}\n\n.btn {\n  color: var(--color-brand);\n}\n";
2103        assert_eq!(
2104            extract_css_var_reads_located(source),
2105            vec![("color-brand".to_string(), 7u32)],
2106            "only the .btn read (line 7) is a css-var; the @theme-interior read is excluded"
2107        );
2108
2109        // A source whose only `var()` read is inside `@theme` yields no css-var.
2110        assert!(
2111            extract_css_var_reads_located("@theme {\n  --a: #fff;\n  --b: var(--a);\n}",)
2112                .is_empty(),
2113            "a @theme-interior-only var() read is not a css-var consumer"
2114        );
2115    }
2116
2117    #[test]
2118    fn css_var_reads_line_match_naive_reference_on_dense_line() {
2119        // Many `var()` reads packed onto a single long line (the pathological
2120        // zero-newline prefix) plus one trailing read on the next line: the
2121        // incremental line counter must agree byte-for-byte with the naive
2122        // per-match prefix rescan. No `@theme`, comments, strings, or `url()`,
2123        // so masking is identity and every read is a css-var read.
2124        use std::fmt::Write as _;
2125        let mut src = String::from(".x {");
2126        for i in 0..500 {
2127            let _ = write!(src, " color: var(--t{i});");
2128        }
2129        src.push_str(" }\n.y { color: var(--tail); }\n");
2130
2131        let got = extract_css_var_reads_located(&src);
2132
2133        // Reference: recompute each read's line via a full prefix rescan.
2134        let want: Vec<(String, u32)> = CSS_VAR_REF_RE
2135            .captures_iter(&src)
2136            .filter_map(|cap| cap.get(0).zip(cap.get(1)))
2137            .map(|(whole, name)| {
2138                (
2139                    name.as_str().to_owned(),
2140                    line_at_offset(&src, whole.start()),
2141                )
2142            })
2143            .collect();
2144
2145        assert_eq!(got, want);
2146        assert!(got.len() > 500, "expected the dense line plus the trailer");
2147        // The trailer sits on line 2; the packed reads all sit on line 1.
2148        assert_eq!(got.last().map(|(_, l)| *l), Some(2));
2149        assert!(got[..got.len() - 1].iter().all(|(_, l)| *l == 1));
2150    }
2151
2152    #[test]
2153    fn apply_token_lines_match_naive_reference_on_dense_line() {
2154        use std::fmt::Write as _;
2155        let mut src = String::from("/* a\n b */\n.x {");
2156        for i in 0..300 {
2157            let _ = write!(src, " @apply p-{i};");
2158        }
2159        src.push_str(" }\n\n.y { @apply tail-a tail-b; }\r\n.z { @apply last; }\n");
2160
2161        let got = extract_apply_tokens_located(&src);
2162
2163        let masked = mask_theme_source(&src);
2164        let want: Vec<(String, u32)> = CSS_APPLY_RE
2165            .find_iter(&masked)
2166            .flat_map(|m| {
2167                let line = line_at_offset(&src, m.start());
2168                m.as_str()
2169                    .trim_start_matches("@apply")
2170                    .split_whitespace()
2171                    .map(move |token| (token.to_owned(), line))
2172            })
2173            .collect();
2174
2175        assert_eq!(got, want);
2176        assert_eq!(got.len(), 303);
2177        assert!(got[..300].iter().all(|(_, line)| *line == 3));
2178        assert_eq!(
2179            &got[300..],
2180            &[
2181                ("tail-a".to_owned(), 5),
2182                ("tail-b".to_owned(), 5),
2183                ("last".to_owned(), 6),
2184            ]
2185        );
2186    }
2187
2188    #[test]
2189    fn theme_string_braces_do_not_truncate_block() {
2190        let scan = scan_theme_blocks(
2191            "@theme {\n  --font-label: \"}\";\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
2192        );
2193        assert_eq!(
2194            scan.tokens
2195                .iter()
2196                .map(|token| token.name.as_str())
2197                .collect::<Vec<_>>(),
2198            vec!["font-label", "color-brand", "color-button"]
2199        );
2200        assert!(
2201            scan.theme_var_reads
2202                .iter()
2203                .any(|(name, _)| name == "color-brand")
2204        );
2205    }
2206
2207    #[test]
2208    fn theme_nested_keyframes_body_not_collected() {
2209        // `@keyframes` inside `@theme` (for `--animate-*`) must not surface its
2210        // step selectors or interior as theme tokens.
2211        let names = theme_token_names(
2212            "@theme {\n  --animate-spin: spin 1s linear infinite;\n  @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
2213        );
2214        assert_eq!(names, vec!["animate-spin"]);
2215    }
2216
2217    #[test]
2218    fn theme_comment_block_ignored() {
2219        let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
2220        assert!(names.is_empty(), "got {names:?}");
2221    }
2222
2223    #[test]
2224    fn theme_deduplicates_repeated_token() {
2225        let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
2226        assert_eq!(names, vec!["color-a"]);
2227    }
2228
2229    #[test]
2230    fn apply_tokens_basic() {
2231        let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
2232        assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
2233    }
2234
2235    #[test]
2236    fn apply_tokens_strips_important() {
2237        let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
2238        assert_eq!(tokens, vec!["text-brand", "font-bold"]);
2239    }
2240
2241    fn line_lookup_bytes(run: impl FnOnce()) -> usize {
2242        LINE_LOOKUP_BYTES.with(|read| read.set(0));
2243        run();
2244        LINE_LOOKUP_BYTES.with(std::cell::Cell::get)
2245    }
2246
2247    /// One dense line with `count` `@apply` directives and `var()` reads,
2248    /// followed by a few short lines.
2249    fn dense_token_stylesheet(count: usize) -> String {
2250        use std::fmt::Write as _;
2251        let mut src = String::from("@theme { --color-brand: red; }\n.x {");
2252        for i in 0..count {
2253            let _ = write!(src, " @apply p-{i}; color: var(--color-{i});");
2254        }
2255        src.push_str(" }\n.y { @apply tail; color: var(--color-tail); }\n");
2256        src
2257    }
2258
2259    #[test]
2260    fn located_token_scans_read_each_byte_once_for_lines() {
2261        for count in [400, 800] {
2262            let src = dense_token_stylesheet(count);
2263            let apply = line_lookup_bytes(|| {
2264                assert_eq!(extract_apply_tokens_located(&src).len(), count + 1);
2265            });
2266            let var_reads = line_lookup_bytes(|| {
2267                assert_eq!(extract_css_var_reads_located(&src).len(), count + 1);
2268            });
2269            let combined = line_lookup_bytes(|| {
2270                let _ = scan_stylesheet_tokens(&src);
2271            });
2272            // A prefix rescan for each match reads about count * len / 2
2273            // bytes, which is far above len.
2274            assert!(apply <= src.len(), "@apply read {apply} of {}", src.len());
2275            assert!(
2276                var_reads <= src.len(),
2277                "var() read {var_reads} of {}",
2278                src.len()
2279            );
2280            assert!(
2281                combined <= 2 * src.len(),
2282                "scan read {combined} of {}",
2283                src.len()
2284            );
2285        }
2286    }
2287
2288    fn comment_mask_passes(run: impl FnOnce()) -> u32 {
2289        COMMENT_MASK_PASSES.with(|passes| passes.set(0));
2290        run();
2291        COMMENT_MASK_PASSES.with(std::cell::Cell::get)
2292    }
2293
2294    #[test]
2295    fn a_css_module_parse_masks_comments_once() {
2296        let source = "/* a */ @import './b.css';\n.card { @apply rounded; } // c\n";
2297        for name in ["styles.module.css", "styles.module.scss", "styles.css"] {
2298            let passes = comment_mask_passes(|| {
2299                parse_css_to_module(FileId(0), Path::new(name), source, 0);
2300            });
2301            assert_eq!(passes, 1, "comment mask passes for {name}");
2302        }
2303    }
2304
2305    #[test]
2306    fn a_stylesheet_token_scan_masks_comments_once() {
2307        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";
2308        let mut scan = StylesheetTokens::default();
2309        let passes = comment_mask_passes(|| scan = scan_stylesheet_tokens(source));
2310        assert_eq!(passes, 1);
2311        assert_eq!(scan.theme, scan_theme_blocks(source));
2312        assert_eq!(
2313            scan.apply_tokens_located,
2314            extract_apply_tokens_located(source)
2315        );
2316        assert_eq!(
2317            scan.css_var_reads_located,
2318            extract_css_var_reads_located(source)
2319        );
2320    }
2321
2322    #[test]
2323    fn a_stylesheet_token_scan_skips_the_mask_without_directives() {
2324        let source = "/* plain */ .a { color: red; }";
2325        let mut scan = StylesheetTokens::default();
2326        let passes = comment_mask_passes(|| scan = scan_stylesheet_tokens(source));
2327        assert_eq!(passes, 0);
2328        assert_eq!(scan, StylesheetTokens::default());
2329    }
2330
2331    #[test]
2332    fn apply_tokens_ignored_in_comments() {
2333        let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
2334        assert!(tokens.is_empty(), "got {tokens:?}");
2335    }
2336}