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.
116pub(crate) fn 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.
132pub(crate) fn 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
270pub(crate) fn 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    /// Whether the stylesheet has a Tailwind `@plugin` at-rule outside
692    /// comments and strings.
693    pub has_plugin_directive: bool,
694}
695
696/// Scan one stylesheet for `@theme` tokens, `@apply` tokens and `var()` reads.
697///
698/// The result is equal to the three separate scans, but the comment and string
699/// mask runs at most once for the source.
700#[must_use]
701pub fn scan_stylesheet_tokens(source: &str) -> StylesheetTokens {
702    let has_theme = source.contains("@theme");
703    let has_apply = source.contains("@apply");
704    let has_var = source.contains("var(");
705    let has_plugin = source.contains(PLUGIN_AT_RULE);
706    if !(has_theme || has_apply || has_var || has_plugin) {
707        return StylesheetTokens::default();
708    }
709    let masked = mask_theme_source(source);
710    StylesheetTokens {
711        theme: if has_theme {
712            theme_scan_from_masked(source, &masked)
713        } else {
714            ThemeScan::default()
715        },
716        apply_tokens_located: if has_apply {
717            apply_tokens_from_masked(source, &masked)
718        } else {
719            Vec::new()
720        },
721        css_var_reads_located: if has_var {
722            css_var_reads_from_masked(source, &masked)
723        } else {
724            Vec::new()
725        },
726        has_plugin_directive: has_plugin && has_plugin_at_rule(&masked),
727    }
728}
729
730const PLUGIN_AT_RULE: &str = "@plugin";
731
732/// Whether `masked` (comments and strings blanked) has an `@plugin` at-rule.
733/// `@plugins` or `@plugin-x` is another at-rule name.
734fn has_plugin_at_rule(masked: &str) -> bool {
735    masked.match_indices(PLUGIN_AT_RULE).any(|(start, _)| {
736        masked[start + PLUGIN_AT_RULE.len()..]
737            .bytes()
738            .next()
739            .is_none_or(|next| !(next.is_ascii_alphanumeric() || next == b'-' || next == b'_'))
740    })
741}
742
743/// Extract class names from a CSS module file as named exports.
744///
745/// For standard CSS, lightningcss parses the source into an AST and supplies the
746/// authoritative set of class-selector names; the byte-offset scanner then
747/// locates each name's [`Span`] in the ORIGINAL `source` (pointing at the bare
748/// class name, no leading dot) so downstream `compute_line_offsets` resolves the
749/// real declaration line and column instead of falling back to line:1 col:0
750/// (issue #549). For SCSS (Sass syntax lightningcss does not parse) and for any
751/// CSS that fails to parse outright, the regex-only scanner is used unchanged.
752pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
753    css_module_exports(source, &mask_css_comments(source, is_scss), is_scss)
754}
755
756/// [`extract_css_module_exports`] with the comment mask of `source` from
757/// [`mask_css_comments`], so a caller that has the mask does not compute it
758/// again.
759fn css_module_exports(source: &str, comment_masked: &str, is_scss: bool) -> Vec<ExportInfo> {
760    if !is_scss && let Some(class_set) = lightningcss_class_set(source) {
761        return scan_css_module_exports(comment_masked, Some(&class_set));
762    }
763    scan_css_module_exports(comment_masked, None)
764}
765
766/// Scan the comment-masked source for `.class` tokens and emit one
767/// [`ExportInfo`] per distinct class (first occurrence wins), with a [`Span`]
768/// pointing at the post-dot identifier. The mask keeps byte offsets, so the
769/// span is also valid in the original source.
770///
771/// When `class_filter` is `Some`, only tokens present in the AST-derived set are
772/// emitted, so the parser owns the membership decision and the scanner owns only
773/// span location. When `class_filter` is `None` (SCSS / parse-failure fallback),
774/// the at-rule prelude is masked to keep `@layer foo.bar` / `@import ...
775/// layer(...)` segments from being mistaken for classes.
776fn scan_css_module_exports(
777    comment_masked: &str,
778    class_filter: Option<&FxHashSet<String>>,
779) -> Vec<ExportInfo> {
780    let masked = mask_css_module_class_candidates(comment_masked, class_filter.is_some());
781    let mut seen = FxHashSet::default();
782    let mut exports = Vec::new();
783    for cap in CSS_CLASS_RE.captures_iter(&masked) {
784        if let Some(m) = cap.get(1) {
785            push_css_class_export(m, class_filter, &mut seen, &mut exports);
786        }
787    }
788    exports
789}
790
791fn mask_css_module_class_candidates(comment_masked: &str, has_class_filter: bool) -> String {
792    let mut masked = mask_with_whitespace(comment_masked, &CSS_NON_SELECTOR_RE);
793    masked = mask_view_transition_arguments(&masked);
794    if !has_class_filter {
795        masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
796        masked = mask_sass_module_members(&masked);
797    }
798    mask_css_module_global_scopes(masked)
799}
800
801const GLOBAL_KEYWORD: &str = ":global";
802const LOCAL_KEYWORD: &str = ":local";
803
804/// A CSS Modules scope keyword (`:global` or `:local`) at a byte offset.
805#[derive(Clone, Copy)]
806struct ScopeKeyword {
807    is_global: bool,
808    len: usize,
809    /// The keyword opens a `(...)` argument, as in `:global(.foo)`.
810    has_argument: bool,
811}
812
813/// Return the CSS Modules scope keyword that starts at `bytes[i]`, if any.
814/// A longer identifier such as `:global-ish` is not a scope keyword.
815fn scope_keyword_at(bytes: &[u8], i: usize) -> Option<ScopeKeyword> {
816    let rest = &bytes[i..];
817    let (is_global, len) = if rest.starts_with(GLOBAL_KEYWORD.as_bytes()) {
818        (true, GLOBAL_KEYWORD.len())
819    } else if rest.starts_with(LOCAL_KEYWORD.as_bytes()) {
820        (false, LOCAL_KEYWORD.len())
821    } else {
822        return None;
823    };
824    let next = rest.get(len).copied();
825    if next.is_some_and(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') {
826        return None;
827    }
828    Some(ScopeKeyword {
829        is_global,
830        len,
831        has_argument: next == Some(b'('),
832    })
833}
834
835/// Replace each bare `:global` / `:local` keyword (without a `(...)` argument)
836/// with spaces of equal length, so lightningcss can parse the rule.
837pub(crate) fn blank_bare_css_module_scope_keywords(source: &str) -> std::borrow::Cow<'_, str> {
838    if !source.contains(GLOBAL_KEYWORD) && !source.contains(LOCAL_KEYWORD) {
839        return std::borrow::Cow::Borrowed(source);
840    }
841    let bytes = source.as_bytes();
842    let mut out = source.to_string();
843    let mut i = 0;
844    while i < bytes.len() {
845        match scope_keyword_at(bytes, i) {
846            Some(keyword) => {
847                if !keyword.has_argument {
848                    out.replace_range(i..i + keyword.len, &" ".repeat(keyword.len));
849                }
850                i += keyword.len;
851            }
852            None => i += 1,
853        }
854    }
855    std::borrow::Cow::Owned(out)
856}
857
858/// The scope of one open parenthesis in a selector.
859#[derive(Clone, Copy, PartialEq, Eq)]
860enum ParenScope {
861    Global,
862    Local,
863    Other,
864}
865
866/// Selector scope state for [`mask_css_module_global_scopes`].
867struct GlobalScopeScan {
868    /// The scope that each open `{` block gives to its nested rules.
869    block_global: Vec<bool>,
870    /// The scope of the current selector, changed by a bare `:global`/`:local`.
871    selector_global: bool,
872    parens: Vec<ParenScope>,
873}
874
875impl GlobalScopeScan {
876    fn inherited(&self) -> bool {
877        self.block_global.last().copied().unwrap_or(false)
878    }
879
880    /// End the current selector or declaration. The next one starts in the
881    /// scope of the enclosing block.
882    fn reset_selector(&mut self) {
883        self.selector_global = self.inherited();
884        self.parens.clear();
885    }
886
887    /// A `:global(...)` or `:local(...)` argument sets the scope for its
888    /// content. Otherwise the selector scope applies.
889    fn is_global(&self) -> bool {
890        self.parens
891            .iter()
892            .rev()
893            .find(|scope| **scope != ParenScope::Other)
894            .map_or(self.selector_global, |scope| *scope == ParenScope::Global)
895    }
896}
897
898/// Blank the `.` of each class token in a CSS Modules global scope, so the
899/// class scanner does not report it. CSS Modules do not put such a class in
900/// the class map of the module (issue #3311).
901///
902/// The input must have comments and strings masked already. These forms make
903/// a global scope:
904/// - `:global(.a .b)`: the classes in the argument are global.
905/// - a bare `:global`: the rest of the selector is global, until a bare
906///   `:local`, a `:local(...)` argument, or the next selector in the list.
907/// - a rule whose selector ends in a global scope: its nested rules start in
908///   the global scope, as Sass and `postcss-nested` compile them.
909///
910/// A source without a block `{` (a `#{` interpolation does not count) uses the
911/// indented Sass syntax, so a line end also ends the selector there.
912fn mask_css_module_global_scopes(masked: String) -> String {
913    if !masked.contains(GLOBAL_KEYWORD) {
914        return masked;
915    }
916    let indented = !masked
917        .match_indices('{')
918        .any(|(i, _)| i == 0 || masked.as_bytes()[i - 1] != b'#');
919    let bytes = masked.as_bytes();
920    let mut blank = Vec::new();
921    let mut scan = GlobalScopeScan {
922        block_global: Vec::new(),
923        selector_global: false,
924        parens: Vec::new(),
925    };
926    let mut i = 0;
927    while i < bytes.len() {
928        if let Some(keyword) = scope_keyword_at(bytes, i) {
929            if keyword.has_argument {
930                scan.parens.push(if keyword.is_global {
931                    ParenScope::Global
932                } else {
933                    ParenScope::Local
934                });
935                i += keyword.len + 1;
936                continue;
937            }
938            if scan.parens.is_empty() {
939                scan.selector_global = keyword.is_global;
940            }
941            i += keyword.len;
942            continue;
943        }
944        match bytes[i] {
945            b'#' if bytes.get(i + 1) == Some(&b'{') => {
946                i = scss_interpolation_end(bytes, i + 2);
947                continue;
948            }
949            b'(' => scan.parens.push(ParenScope::Other),
950            b')' => {
951                scan.parens.pop();
952            }
953            b',' if scan.parens.is_empty() => scan.selector_global = scan.inherited(),
954            b'{' => {
955                scan.block_global.push(scan.selector_global);
956                scan.reset_selector();
957            }
958            b'}' => {
959                scan.block_global.pop();
960                scan.reset_selector();
961            }
962            b';' => scan.reset_selector(),
963            b'\n' if indented => scan.reset_selector(),
964            b'.' if scan.is_global()
965                && bytes
966                    .get(i + 1)
967                    .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_') =>
968            {
969                blank.push(i);
970            }
971            _ => {}
972        }
973        i += 1;
974    }
975    let mut out = masked;
976    for offset in blank {
977        out.replace_range(offset..=offset, " ");
978    }
979    out
980}
981
982/// Return the offset after the `}` that closes a SCSS `#{...}` interpolation
983/// whose content starts at `start`.
984fn scss_interpolation_end(bytes: &[u8], start: usize) -> usize {
985    let mut depth = 1usize;
986    let mut i = start;
987    while i < bytes.len() {
988        match bytes[i] {
989            b'{' => depth += 1,
990            b'}' => {
991                depth -= 1;
992                if depth == 0 {
993                    return i + 1;
994                }
995            }
996            _ => {}
997        }
998        i += 1;
999    }
1000    bytes.len()
1001}
1002
1003fn push_css_class_export(
1004    class_match: regex::Match<'_>,
1005    class_filter: Option<&FxHashSet<String>>,
1006    seen: &mut FxHashSet<String>,
1007    exports: &mut Vec<ExportInfo>,
1008) {
1009    let class_name = class_match.as_str().to_string();
1010    if class_filter.is_some_and(|filter| !filter.contains(&class_name)) {
1011        return;
1012    }
1013    if seen.insert(class_name.clone()) {
1014        exports.push(css_class_export(class_name, class_match));
1015    }
1016}
1017
1018fn css_class_export(class_name: String, class_match: regex::Match<'_>) -> ExportInfo {
1019    #[expect(
1020        clippy::cast_possible_truncation,
1021        reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
1022    )]
1023    let span = Span::new(class_match.start() as u32, class_match.end() as u32);
1024    ExportInfo {
1025        name: ExportName::Named(class_name),
1026        local_name: None,
1027        is_type_only: false,
1028        visibility: VisibilityTag::None,
1029        expected_unused_reason: None,
1030        span,
1031        members: Vec::new(),
1032        is_side_effect_used: false,
1033        super_class: None,
1034        deprecated: false,
1035        deprecated_reason: None,
1036    }
1037}
1038
1039/// Build the import edges for a CSS/SCSS source: every `@import`/`@use`/etc.
1040/// directive plus a synthetic `tailwindcss` side-effect import when `@apply` or
1041/// `@tailwind` is present.
1042fn build_css_imports(stripped: &str, is_scss: bool) -> Vec<ImportInfo> {
1043    let mut imports = Vec::new();
1044
1045    for css_source in import_sources_from_masked(stripped, is_scss) {
1046        imports.push(ImportInfo {
1047            source: css_source.normalized,
1048            imported_name: if css_source.is_plugin {
1049                ImportedName::Default
1050            } else {
1051                ImportedName::SideEffect
1052            },
1053            local_name: String::new(),
1054            is_type_only: false,
1055            is_type_only_star: false,
1056            from_style: false,
1057            span: css_source.span,
1058            source_span: css_source.span,
1059        });
1060    }
1061
1062    let has_apply = CSS_APPLY_RE.is_match(stripped);
1063    let has_tailwind = CSS_TAILWIND_RE.is_match(stripped);
1064    if has_apply || has_tailwind {
1065        imports.push(ImportInfo {
1066            source: "tailwindcss".to_string(),
1067            imported_name: ImportedName::SideEffect,
1068            local_name: String::new(),
1069            is_type_only: false,
1070            is_type_only_star: false,
1071            from_style: false,
1072            span: Span::default(),
1073            source_span: Span::default(),
1074        });
1075    }
1076
1077    imports
1078}
1079
1080/// Parse a CSS, SCSS, Sass or Less file: the `@import`, `@use`, `@forward`,
1081/// `@plugin`, `@apply` and `@tailwind` directives, and the packages that its
1082/// `url()` values name.
1083pub(crate) fn parse_css_to_module(
1084    file_id: FileId,
1085    path: &Path,
1086    source: &str,
1087    content_hash: u64,
1088) -> ModuleInfo {
1089    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
1090    let is_scss = path
1091        .extension()
1092        .and_then(|e| e.to_str())
1093        .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
1094
1095    let stripped = crate::css_mask::mask_sass_shorthand(mask_css_comments(source, is_scss), path);
1096    let mut imports = build_css_imports(&stripped, is_scss);
1097    let exports = if is_css_module_file(path) {
1098        crate::css_composes::push_composes_from_imports(&stripped, &mut imports);
1099        css_module_exports(source, &stripped, is_scss)
1100    } else {
1101        Vec::new()
1102    };
1103
1104    // CSS has no JS-level structure, so the AST-derived fields stay empty.
1105    let mut info =
1106        crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
1107            file_id,
1108            content_hash,
1109            source,
1110            parsed_suppressions,
1111            imports,
1112            exports,
1113        });
1114    info.package_path_references =
1115        crate::css_url::package_url_references(&stripped).into_boxed_slice();
1116    info
1117}
1118
1119#[cfg(all(test, not(miri)))]
1120#[path = "css_scan_cost_tests.rs"]
1121mod scan_cost_tests;
1122
1123#[cfg(all(test, not(miri)))]
1124mod tests {
1125    use super::*;
1126
1127    /// Helper to collect export names as strings from `extract_css_module_exports`.
1128    fn export_names(source: &str) -> Vec<String> {
1129        extract_css_module_exports(source, false)
1130            .into_iter()
1131            .filter_map(|e| match e.name {
1132                ExportName::Named(n) => Some(n),
1133                ExportName::Default => None,
1134            })
1135            .collect()
1136    }
1137
1138    #[test]
1139    fn is_css_file_css() {
1140        assert!(is_css_file(Path::new("styles.css")));
1141    }
1142
1143    #[test]
1144    fn is_css_file_scss() {
1145        assert!(is_css_file(Path::new("styles.scss")));
1146    }
1147
1148    #[test]
1149    fn is_css_file_sass() {
1150        assert!(is_css_file(Path::new("styles.sass")));
1151    }
1152
1153    #[test]
1154    fn is_css_file_less() {
1155        assert!(is_css_file(Path::new("styles.less")));
1156    }
1157
1158    #[test]
1159    fn is_css_file_rejects_js() {
1160        assert!(!is_css_file(Path::new("app.js")));
1161    }
1162
1163    #[test]
1164    fn is_css_file_rejects_ts() {
1165        assert!(!is_css_file(Path::new("app.ts")));
1166    }
1167
1168    #[test]
1169    fn is_css_file_rejects_no_extension() {
1170        assert!(!is_css_file(Path::new("Makefile")));
1171    }
1172
1173    #[test]
1174    fn is_css_module_file_module_css() {
1175        assert!(is_css_module_file(Path::new("Component.module.css")));
1176    }
1177
1178    #[test]
1179    fn is_css_module_file_module_scss() {
1180        assert!(is_css_module_file(Path::new("Component.module.scss")));
1181    }
1182
1183    #[test]
1184    fn is_css_module_file_rejects_plain_css() {
1185        assert!(!is_css_module_file(Path::new("styles.css")));
1186    }
1187
1188    #[test]
1189    fn is_css_module_file_rejects_plain_scss() {
1190        assert!(!is_css_module_file(Path::new("styles.scss")));
1191    }
1192
1193    #[test]
1194    fn is_css_module_file_rejects_module_js() {
1195        assert!(!is_css_module_file(Path::new("utils.module.js")));
1196    }
1197
1198    #[test]
1199    fn extracts_single_class() {
1200        let names = export_names(".foo { color: red; }");
1201        assert_eq!(names, vec!["foo"]);
1202    }
1203
1204    #[test]
1205    fn extracts_multiple_classes() {
1206        let names = export_names(".foo { } .bar { }");
1207        assert_eq!(names, vec!["foo", "bar"]);
1208    }
1209
1210    #[test]
1211    fn extracts_nested_classes() {
1212        let names = export_names(".foo .bar { color: red; }");
1213        assert!(names.contains(&"foo".to_string()));
1214        assert!(names.contains(&"bar".to_string()));
1215    }
1216
1217    #[test]
1218    fn extracts_hyphenated_class() {
1219        let names = export_names(".my-class { }");
1220        assert_eq!(names, vec!["my-class"]);
1221    }
1222
1223    #[test]
1224    fn extracts_camel_case_class() {
1225        let names = export_names(".myClass { }");
1226        assert_eq!(names, vec!["myClass"]);
1227    }
1228
1229    fn scss_export_names(source: &str) -> Vec<String> {
1230        extract_css_module_exports(source, true)
1231            .into_iter()
1232            .filter_map(|e| match e.name {
1233                ExportName::Named(n) => Some(n),
1234                ExportName::Default => None,
1235            })
1236            .collect()
1237    }
1238
1239    #[test]
1240    fn skips_class_inside_global_pseudo() {
1241        // CSS Modules do not put a `:global(.foo)` class in the class map.
1242        let names = export_names(":global(.globalClass) { color: red; }");
1243        assert!(names.is_empty(), "got {names:?}");
1244    }
1245
1246    #[test]
1247    fn keeps_local_class_next_to_global_pseudo() {
1248        // Issue #3311.
1249        let names = export_names(".wrapper :global(.selector) { color: red; }");
1250        assert_eq!(names, vec!["wrapper"]);
1251    }
1252
1253    #[test]
1254    fn skips_every_class_inside_global_pseudo_with_descendants() {
1255        let names = export_names(".panel :global(.outer .inner.mod) { color: red; }");
1256        assert_eq!(names, vec!["panel"]);
1257    }
1258
1259    #[test]
1260    fn skips_classes_after_bare_global() {
1261        let names = export_names(".lead :global .first .second { color: red; }");
1262        assert_eq!(names, vec!["lead"]);
1263    }
1264
1265    #[test]
1266    fn bare_global_stops_at_local() {
1267        let names = export_names(":global .g1 :local(.l1) .g2 :local .l2 .l3, .l4 { color: red; }");
1268        assert_eq!(names, vec!["l1", "l2", "l3", "l4"]);
1269    }
1270
1271    #[test]
1272    fn bare_global_stops_at_comma() {
1273        let names = export_names(":global .g1, .l1 :is(.l2, .l3) { color: red; }");
1274        assert_eq!(names, vec!["l1", "l2", "l3"]);
1275    }
1276
1277    #[test]
1278    fn global_class_inside_media_query_is_skipped() {
1279        let names = export_names("@media (min-width: 1px) { .media :global(.g) { color: red; } }");
1280        assert_eq!(names, vec!["media"]);
1281    }
1282
1283    #[test]
1284    fn class_both_local_and_global_stays_exported_at_local_span() {
1285        let source = ":global(.both) { color: red; }\n.both { color: blue; }";
1286        let exports = extract_css_module_exports(source, false);
1287        assert_eq!(exports.len(), 1);
1288        let span = exports[0].span;
1289        assert_eq!(&source[span.start as usize..span.end as usize], "both");
1290        assert!(
1291            span.start > 20,
1292            "span must point at the local rule: {span:?}"
1293        );
1294    }
1295
1296    #[test]
1297    fn composes_keeps_local_classes() {
1298        let names = export_names(
1299            ".base { color: red; }\n.button { composes: base; composes: g from global; }",
1300        );
1301        assert_eq!(names, vec!["base", "button"]);
1302    }
1303
1304    #[test]
1305    fn global_in_strings_and_comments_has_no_effect() {
1306        let names =
1307            export_names("/* :global */ .a { content: \":global\"; }\n.b :global(.c) { }\n.d { }");
1308        assert_eq!(names, vec!["a", "b", "d"]);
1309    }
1310
1311    #[test]
1312    fn scss_skips_global_pseudo_and_global_block() {
1313        let names = scss_export_names(
1314            ".card {\n  :global(.g1) { color: red; }\n  .title { color: blue; }\n}\n\
1315             :global {\n  .g2 { color: red; }\n  .g3 { :local(.l1) { color: red; } }\n}\n\
1316             .after { color: blue; }",
1317        );
1318        assert_eq!(names, vec!["card", "title", "l1", "after"]);
1319    }
1320
1321    #[test]
1322    fn scss_bare_global_in_parent_reaches_nested_rules() {
1323        let names = scss_export_names(
1324            ".a :global .b {\n  .c { color: red; }\n  &:hover { color: blue; }\n}\n.d { }",
1325        );
1326        assert_eq!(names, vec!["a", "d"]);
1327    }
1328
1329    #[test]
1330    fn scss_interpolation_does_not_end_global_scope() {
1331        let names = scss_export_names("$n: x;\n.a :global .b-#{$n} .c { }\n.d { }");
1332        assert_eq!(names, vec!["a", "d"]);
1333    }
1334
1335    #[test]
1336    fn sass_indented_bare_global_ends_at_line_end() {
1337        let names = scss_export_names(".a :global .b\n  color: red\n.c\n  color: blue\n");
1338        assert_eq!(names, vec!["a", "c"]);
1339    }
1340
1341    #[test]
1342    fn sass_indented_with_interpolation_still_ends_global_at_line_end() {
1343        let names = scss_export_names(
1344            ".a :global .b\n  color: red\n.c-#{$x}\n  color: blue\n.d\n  color: blue\n",
1345        );
1346        // The scanner keeps the static prefix `c-` of an interpolated class.
1347        assert_eq!(names, vec!["a", "c-", "d"]);
1348    }
1349
1350    #[test]
1351    fn global_like_pseudo_names_are_not_global() {
1352        let names = export_names(".a:global-ish .b { }");
1353        assert!(names.contains(&"b".to_string()), "got {names:?}");
1354    }
1355
1356    #[test]
1357    fn extracts_class_inside_local_pseudo() {
1358        let names = export_names(":local(.localClass) { color: red; }");
1359        assert_eq!(names, vec!["localClass"]);
1360    }
1361
1362    #[test]
1363    fn extracts_classes_inside_negation() {
1364        let names = export_names(".btn:not(.disabled) { }");
1365        assert!(names.contains(&"btn".to_string()), "got {names:?}");
1366        assert!(names.contains(&"disabled".to_string()), "got {names:?}");
1367    }
1368
1369    #[test]
1370    fn extracts_classes_inside_is_and_where() {
1371        let names = export_names(":is(.a, .b) :where(.c) { }");
1372        for expected in ["a", "b", "c"] {
1373            assert!(
1374                names.contains(&expected.to_string()),
1375                "missing {expected} in {names:?}"
1376            );
1377        }
1378    }
1379
1380    #[test]
1381    fn extracts_underscore_class() {
1382        let names = export_names("._hidden { } .__wrapper { }");
1383        assert!(names.contains(&"_hidden".to_string()));
1384        assert!(names.contains(&"__wrapper".to_string()));
1385    }
1386
1387    #[test]
1388    fn pseudo_selector_hover() {
1389        let names = export_names(".foo:hover { color: blue; }");
1390        assert_eq!(names, vec!["foo"]);
1391    }
1392
1393    #[test]
1394    fn pseudo_selector_focus() {
1395        let names = export_names(".input:focus { outline: none; }");
1396        assert_eq!(names, vec!["input"]);
1397    }
1398
1399    #[test]
1400    fn pseudo_element_before() {
1401        let names = export_names(".icon::before { content: ''; }");
1402        assert_eq!(names, vec!["icon"]);
1403    }
1404
1405    #[test]
1406    fn combined_pseudo_selectors() {
1407        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
1408        assert_eq!(names, vec!["btn"]);
1409    }
1410
1411    #[test]
1412    fn classes_inside_media_query() {
1413        let names = export_names(
1414            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
1415        );
1416        assert!(names.contains(&"mobile-nav".to_string()));
1417        assert!(names.contains(&"desktop-nav".to_string()));
1418    }
1419
1420    #[test]
1421    fn classes_inside_multi_line_media_query() {
1422        let names =
1423            export_names("@media\n  screen and (min-width: 600px)\n{\n  .real { color: red; }\n}");
1424        assert_eq!(names, vec!["real"]);
1425    }
1426
1427    #[test]
1428    fn at_layer_statement_does_not_export() {
1429        let names = export_names("@layer foo.bar;");
1430        assert!(names.is_empty(), "got {names:?}");
1431        let names = export_names("@layer foo.bar, foo.baz;");
1432        assert!(names.is_empty(), "got {names:?}");
1433    }
1434
1435    #[test]
1436    fn at_layer_block_keeps_body_classes() {
1437        let names = export_names("@layer foo.bar { .root { color: red; } }");
1438        assert_eq!(names, vec!["root"]);
1439    }
1440
1441    #[test]
1442    fn at_layer_multiline_prelude_keeps_body_classes() {
1443        let names = export_names("@layer\n  foo.bar\n{ .root { color: red; } }");
1444        assert_eq!(names, vec!["root"]);
1445    }
1446
1447    #[test]
1448    fn at_layer_with_nested_media_keeps_body() {
1449        let names =
1450            export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1451        assert_eq!(names, vec!["real"]);
1452    }
1453
1454    #[test]
1455    fn at_import_with_layer_attribute_does_not_export() {
1456        let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1457        assert!(names.is_empty(), "got {names:?}");
1458    }
1459
1460    #[test]
1461    fn class_then_at_layer_does_not_leak_prelude() {
1462        let names =
1463            export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1464        assert_eq!(names, vec!["outer", "inner"]);
1465    }
1466
1467    #[test]
1468    fn at_scope_keeps_selector_list_classes() {
1469        let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1470        assert!(names.contains(&"parent".to_string()), "got {names:?}");
1471        assert!(names.contains(&"child".to_string()), "got {names:?}");
1472        assert!(names.contains(&"title".to_string()), "got {names:?}");
1473    }
1474
1475    #[test]
1476    fn at_keyframes_numeric_step_is_not_class() {
1477        let names = export_names(
1478            "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1479        );
1480        assert!(names.is_empty(), "got {names:?}");
1481    }
1482
1483    #[test]
1484    fn at_webkit_keyframes_keeps_body_classes() {
1485        let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1486        assert_eq!(names, vec!["real"]);
1487    }
1488
1489    #[test]
1490    fn deduplicates_repeated_class() {
1491        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1492        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1493    }
1494
1495    #[test]
1496    fn empty_source() {
1497        let names = export_names("");
1498        assert!(names.is_empty());
1499    }
1500
1501    #[test]
1502    fn no_classes() {
1503        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1504        assert!(names.is_empty());
1505    }
1506
1507    #[test]
1508    fn ignores_classes_in_block_comments() {
1509        let names = export_names("/* .fake { } */ .real { }");
1510        assert!(!names.contains(&"fake".to_string()));
1511        assert!(names.contains(&"real".to_string()));
1512    }
1513
1514    #[test]
1515    fn ignores_classes_in_scss_line_comments() {
1516        let exports = extract_css_module_exports("// .fake\n.real { }", true);
1517        let names: Vec<_> = exports
1518            .iter()
1519            .filter_map(|e| match &e.name {
1520                ExportName::Named(n) => Some(n.as_str()),
1521                ExportName::Default => None,
1522            })
1523            .collect();
1524        assert_eq!(names, vec!["real"]);
1525    }
1526
1527    #[test]
1528    fn ignores_classes_in_strings() {
1529        let names = export_names(r#".real { content: ".fake"; }"#);
1530        assert!(names.contains(&"real".to_string()));
1531        assert!(!names.contains(&"fake".to_string()));
1532    }
1533
1534    #[test]
1535    fn ignores_classes_in_url() {
1536        let names = export_names(".real { background: url(./images/hero.png); }");
1537        assert!(names.contains(&"real".to_string()));
1538        assert!(!names.contains(&"png".to_string()));
1539    }
1540
1541    #[test]
1542    fn mask_css_block_comment() {
1543        let source = "/* removed */ .kept { }";
1544        let result = mask_css_comments(source, false);
1545        assert!(!result.contains("removed"));
1546        assert_eq!(result.len(), source.len());
1547        assert_eq!(result.find(".kept"), source.find(".kept"));
1548    }
1549
1550    #[test]
1551    fn mask_scss_line_comment() {
1552        let source = "// removed\n.kept { }";
1553        let result = mask_css_comments(source, true);
1554        assert!(!result.contains("removed"));
1555        assert_eq!(result.len(), source.len());
1556        assert_eq!(result.find(".kept"), source.find(".kept"));
1557    }
1558
1559    #[test]
1560    fn mask_scss_preserves_css_outside_comments() {
1561        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1562        let result = mask_css_comments(source, true);
1563        assert!(result.contains(".visible"));
1564    }
1565
1566    #[test]
1567    fn url_import_http() {
1568        assert!(is_css_url_import("http://example.com/style.css"));
1569    }
1570
1571    #[test]
1572    fn url_import_https() {
1573        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1574    }
1575
1576    #[test]
1577    fn url_import_data() {
1578        assert!(is_css_url_import("data:text/css;base64,abc"));
1579    }
1580
1581    #[test]
1582    fn url_import_local_not_skipped() {
1583        assert!(!is_css_url_import("./local.css"));
1584    }
1585
1586    #[test]
1587    fn url_import_bare_specifier_not_skipped() {
1588        assert!(!is_css_url_import("tailwindcss"));
1589    }
1590
1591    #[test]
1592    fn normalize_relative_dot_path_unchanged() {
1593        assert_eq!(
1594            normalize_css_import_path("./reset.css".to_string(), false),
1595            "./reset.css"
1596        );
1597    }
1598
1599    #[test]
1600    fn normalize_parent_relative_path_unchanged() {
1601        assert_eq!(
1602            normalize_css_import_path("../shared.scss".to_string(), false),
1603            "../shared.scss"
1604        );
1605    }
1606
1607    #[test]
1608    fn normalize_absolute_path_unchanged() {
1609        assert_eq!(
1610            normalize_css_import_path("/styles/main.css".to_string(), false),
1611            "/styles/main.css"
1612        );
1613    }
1614
1615    #[test]
1616    fn normalize_url_unchanged() {
1617        assert_eq!(
1618            normalize_css_import_path("https://example.com/style.css".to_string(), false),
1619            "https://example.com/style.css"
1620        );
1621    }
1622
1623    #[test]
1624    fn normalize_bare_css_gets_dot_slash() {
1625        assert_eq!(
1626            normalize_css_import_path("app.css".to_string(), false),
1627            "./app.css"
1628        );
1629    }
1630
1631    #[test]
1632    fn normalize_css_package_subpath_stays_bare() {
1633        assert_eq!(
1634            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1635            "tailwindcss/theme.css"
1636        );
1637    }
1638
1639    #[test]
1640    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1641        assert_eq!(
1642            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1643            "highlight.js/styles/github.css"
1644        );
1645    }
1646
1647    #[test]
1648    fn normalize_bare_scss_gets_dot_slash() {
1649        assert_eq!(
1650            normalize_css_import_path("vars.scss".to_string(), false),
1651            "./vars.scss"
1652        );
1653    }
1654
1655    #[test]
1656    fn normalize_bare_sass_gets_dot_slash() {
1657        assert_eq!(
1658            normalize_css_import_path("main.sass".to_string(), false),
1659            "./main.sass"
1660        );
1661    }
1662
1663    #[test]
1664    fn normalize_bare_less_gets_dot_slash() {
1665        assert_eq!(
1666            normalize_css_import_path("theme.less".to_string(), false),
1667            "./theme.less"
1668        );
1669    }
1670
1671    #[test]
1672    fn normalize_bare_js_extension_stays_bare() {
1673        assert_eq!(
1674            normalize_css_import_path("module.js".to_string(), false),
1675            "module.js"
1676        );
1677    }
1678
1679    #[test]
1680    fn normalize_scss_bare_partial_gets_dot_slash() {
1681        assert_eq!(
1682            normalize_css_import_path("variables".to_string(), true),
1683            "./variables"
1684        );
1685    }
1686
1687    #[test]
1688    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1689        assert_eq!(
1690            normalize_css_import_path("base/reset".to_string(), true),
1691            "./base/reset"
1692        );
1693    }
1694
1695    #[test]
1696    fn normalize_scss_builtin_stays_bare() {
1697        assert_eq!(
1698            normalize_css_import_path("sass:math".to_string(), true),
1699            "sass:math"
1700        );
1701    }
1702
1703    #[test]
1704    fn normalize_scss_relative_path_unchanged() {
1705        assert_eq!(
1706            normalize_css_import_path("../styles/variables".to_string(), true),
1707            "../styles/variables"
1708        );
1709    }
1710
1711    #[test]
1712    fn normalize_css_bare_extensionless_stays_bare() {
1713        assert_eq!(
1714            normalize_css_import_path("tailwindcss".to_string(), false),
1715            "tailwindcss"
1716        );
1717    }
1718
1719    #[test]
1720    fn normalize_scoped_package_with_css_extension_stays_bare() {
1721        assert_eq!(
1722            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1723            "@fontsource/monaspace-neon/400.css"
1724        );
1725    }
1726
1727    #[test]
1728    fn normalize_scoped_package_with_scss_extension_stays_bare() {
1729        assert_eq!(
1730            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1731            "@company/design-system/tokens.scss"
1732        );
1733    }
1734
1735    #[test]
1736    fn normalize_scoped_package_without_extension_stays_bare() {
1737        assert_eq!(
1738            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1739            "@fallow/design-system/styles"
1740        );
1741    }
1742
1743    #[test]
1744    fn normalize_scoped_package_extensionless_scss_stays_bare() {
1745        assert_eq!(
1746            normalize_css_import_path("@company/tokens".to_string(), true),
1747            "@company/tokens"
1748        );
1749    }
1750
1751    #[test]
1752    fn normalize_path_alias_with_css_extension_stays_bare() {
1753        assert_eq!(
1754            normalize_css_import_path("@/components/Button.css".to_string(), false),
1755            "@/components/Button.css"
1756        );
1757    }
1758
1759    #[test]
1760    fn normalize_path_alias_extensionless_stays_bare() {
1761        assert_eq!(
1762            normalize_css_import_path("@/styles/variables".to_string(), false),
1763            "@/styles/variables"
1764        );
1765    }
1766
1767    #[test]
1768    fn mask_css_no_comments() {
1769        let source = ".foo { color: red; }";
1770        assert_eq!(mask_css_comments(source, false), source);
1771    }
1772
1773    #[test]
1774    fn mask_css_multiple_block_comments() {
1775        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1776        let result = mask_css_comments(source, false);
1777        assert!(!result.contains("comment-one"));
1778        assert!(!result.contains("comment-two"));
1779        assert!(result.contains(".foo"));
1780        assert!(result.contains(".bar"));
1781    }
1782
1783    #[test]
1784    fn mask_scss_does_not_affect_non_scss() {
1785        let source = "// this stays\n.foo { }";
1786        let result = mask_css_comments(source, false);
1787        assert!(result.contains("// this stays"));
1788    }
1789
1790    #[test]
1791    fn css_module_parses_suppressions() {
1792        let info = parse_css_to_module(
1793            fallow_types::discover::FileId(0),
1794            Path::new("Component.module.css"),
1795            "/* fallow-ignore-file */\n.btn { color: red; }",
1796            0,
1797        );
1798        assert!(!info.suppressions.is_empty());
1799        assert_eq!(info.suppressions[0].line, 0);
1800    }
1801
1802    #[test]
1803    fn extracts_class_starting_with_underscore() {
1804        let names = export_names("._private { } .__dunder { }");
1805        assert!(names.contains(&"_private".to_string()));
1806        assert!(names.contains(&"__dunder".to_string()));
1807    }
1808
1809    #[test]
1810    fn ignores_id_selectors() {
1811        let names = export_names("#myId { color: red; }");
1812        assert!(!names.contains(&"myId".to_string()));
1813    }
1814
1815    #[test]
1816    fn ignores_element_selectors() {
1817        let names = export_names("div { color: red; } span { }");
1818        assert!(names.is_empty());
1819    }
1820
1821    #[test]
1822    fn extract_css_imports_at_import_quoted() {
1823        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1824        assert_eq!(imports, vec!["./reset.css"]);
1825    }
1826
1827    #[test]
1828    fn extract_css_imports_package_subpath_stays_bare() {
1829        let imports =
1830            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1831        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1832    }
1833
1834    #[test]
1835    fn extract_css_imports_at_import_url() {
1836        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1837        assert_eq!(imports, vec!["./reset.css"]);
1838    }
1839
1840    #[test]
1841    fn extract_css_imports_skips_remote_urls() {
1842        let imports =
1843            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1844        assert!(imports.is_empty());
1845    }
1846
1847    #[test]
1848    fn extract_css_imports_scss_use_normalizes_partial() {
1849        let imports = extract_css_imports(r#"@use "variables";"#, true);
1850        assert_eq!(imports, vec!["./variables"]);
1851    }
1852
1853    #[test]
1854    fn extract_css_imports_scss_forward_normalizes_partial() {
1855        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1856        assert_eq!(imports, vec!["./tokens"]);
1857    }
1858
1859    #[test]
1860    fn extract_css_imports_skips_comments() {
1861        let imports = extract_css_imports(
1862            r#"/* @import "./hidden.scss"; */
1863@use "real";"#,
1864            true,
1865        );
1866        assert_eq!(imports, vec!["./real"]);
1867    }
1868
1869    #[test]
1870    fn extract_css_imports_at_plugin_keeps_package_bare() {
1871        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1872        assert_eq!(imports, vec!["daisyui"]);
1873    }
1874
1875    #[test]
1876    fn extract_css_imports_at_plugin_tracks_relative_file() {
1877        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1878        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1879    }
1880
1881    #[test]
1882    fn extract_css_imports_scss_at_import_kept_relative() {
1883        let imports = extract_css_imports(r"@import 'Foo';", true);
1884        assert_eq!(imports, vec!["./Foo"]);
1885    }
1886
1887    #[test]
1888    fn extract_css_imports_additional_data_string_body() {
1889        let body = r#"@use "./src/styles/global.scss";"#;
1890        let imports = extract_css_imports(body, true);
1891        assert_eq!(imports, vec!["./src/styles/global.scss"]);
1892    }
1893
1894    /// Resolve a span's start to (line, col) using the same primitives the
1895    /// downstream pipeline uses in `crates/core/src/analyze/unused_exports.rs`.
1896    fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1897        let offsets = fallow_types::extract::compute_line_offsets(source);
1898        fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1899    }
1900
1901    #[test]
1902    fn span_points_at_real_class_declaration_line() {
1903        let source = "\n\n\n\n.foo { color: red; }\n";
1904        let exports = extract_css_module_exports(source, false);
1905        assert_eq!(exports.len(), 1);
1906        let span = exports[0].span;
1907        let (line, col) = span_line_col(source, span.start);
1908        assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1909        assert_eq!(
1910            col, 1,
1911            "column points at `f` in `.foo` (post-dot identifier)"
1912        );
1913        assert_eq!(
1914            &source[span.start as usize..span.end as usize],
1915            "foo",
1916            "span range must slice to the class identifier in the original source"
1917        );
1918    }
1919
1920    #[test]
1921    fn span_survives_multibyte_comment_prefix() {
1922        let source = "/* \u{2713} */\n.foo { }";
1923        let exports = extract_css_module_exports(source, false);
1924        assert_eq!(exports.len(), 1);
1925        let span = exports[0].span;
1926        assert!(
1927            source.is_char_boundary(span.start as usize),
1928            "span.start must lie on a UTF-8 char boundary"
1929        );
1930        assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1931    }
1932
1933    #[test]
1934    fn span_skips_at_layer_prelude_dot_segments() {
1935        let source = "@layer foo.bar { }\n.root { }\n";
1936        let exports = extract_css_module_exports(source, false);
1937        let names: Vec<_> = exports
1938            .iter()
1939            .filter_map(|e| match &e.name {
1940                ExportName::Named(n) => Some(n.as_str()),
1941                ExportName::Default => None,
1942            })
1943            .collect();
1944        assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1945        let span = exports[0].span;
1946        let (line, _col) = span_line_col(source, span.start);
1947        assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1948        assert_eq!(&source[span.start as usize..span.end as usize], "root");
1949    }
1950
1951    #[test]
1952    fn span_skips_classes_in_strings() {
1953        let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1954        let exports = extract_css_module_exports(source, false);
1955        let names: Vec<_> = exports
1956            .iter()
1957            .filter_map(|e| match &e.name {
1958                ExportName::Named(n) => Some(n.as_str()),
1959                ExportName::Default => None,
1960            })
1961            .collect();
1962        assert_eq!(names, vec!["real", "also-real"]);
1963        for export in &exports {
1964            let span = export.span;
1965            let slice = &source[span.start as usize..span.end as usize];
1966            match &export.name {
1967                ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1968                ExportName::Default => unreachable!("CSS modules emit only named exports"),
1969            }
1970        }
1971    }
1972
1973    #[test]
1974    fn span_deduplicates_to_first_occurrence() {
1975        let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1976        let exports = extract_css_module_exports(source, false);
1977        assert_eq!(exports.len(), 1);
1978        let (line, _col) = span_line_col(source, exports[0].span.start);
1979        assert_eq!(
1980            line, 1,
1981            "first occurrence wins for deduplicated class names"
1982        );
1983    }
1984
1985    #[test]
1986    fn span_inside_media_query() {
1987        let source =
1988            "@media (max-width: 768px) {\n  .mobile { display: block; }\n  .desktop { }\n}\n";
1989        let exports = extract_css_module_exports(source, false);
1990        let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1991            .iter()
1992            .filter_map(|e| match &e.name {
1993                ExportName::Named(n) => Some((n.as_str(), e.span)),
1994                ExportName::Default => None,
1995            })
1996            .collect();
1997        let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1998        let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1999        assert_eq!(mobile_line, 2);
2000        assert_eq!(desktop_line, 3);
2001    }
2002
2003    #[test]
2004    fn at_layer_only_module_emits_no_exports() {
2005        let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
2006        assert!(exports.is_empty());
2007    }
2008
2009    #[test]
2010    fn parse_css_to_module_resolves_real_line_offsets() {
2011        let source = "\n\n\n\n.foo { color: red; }\n";
2012        let info = parse_css_to_module(
2013            fallow_types::discover::FileId(0),
2014            Path::new("Component.module.css"),
2015            source,
2016            0,
2017        );
2018        assert_eq!(info.exports.len(), 1);
2019        let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
2020            &info.line_offsets,
2021            info.exports[0].span.start,
2022        );
2023        assert_eq!(line, 5, "downstream line must equal the source line");
2024    }
2025
2026    fn theme_token_names(source: &str) -> Vec<String> {
2027        scan_theme_blocks(source)
2028            .tokens
2029            .into_iter()
2030            .map(|t| t.name)
2031            .collect()
2032    }
2033
2034    #[test]
2035    fn theme_single_block_collects_tokens() {
2036        let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
2037        assert_eq!(names, vec!["color-brand", "radius-card"]);
2038    }
2039
2040    #[test]
2041    fn theme_token_values_are_normalized() {
2042        let scan = scan_theme_blocks("@theme {\n  --color-brand: rgb( 255 0 0 );\n}");
2043        assert_eq!(scan.tokens[0].name, "color-brand");
2044        assert_eq!(scan.tokens[0].value, "rgb( 255 0 0 )");
2045    }
2046
2047    #[test]
2048    fn theme_dashed_multi_segment_names() {
2049        let names = theme_token_names(
2050            "@theme {\n  --font-weight-heavy: 900;\n  --inset-shadow-glow: 0 0 4px red;\n}",
2051        );
2052        assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
2053    }
2054
2055    #[test]
2056    fn theme_inline_and_static_modifiers() {
2057        assert_eq!(
2058            theme_token_names("@theme inline { --color-a: red; }"),
2059            vec!["color-a"]
2060        );
2061        assert_eq!(
2062            theme_token_names("@theme static { --color-b: red; }"),
2063            vec!["color-b"]
2064        );
2065    }
2066
2067    #[test]
2068    fn theme_multiple_blocks_union() {
2069        let names = theme_token_names(
2070            "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
2071        );
2072        assert_eq!(names, vec!["color-a", "spacing-gutter"]);
2073    }
2074
2075    #[test]
2076    fn theme_reset_form_excluded() {
2077        // `--color-*: initial` is a namespace reset directive, not a token.
2078        let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
2079        assert_eq!(names, vec!["color-brand"]);
2080    }
2081
2082    #[test]
2083    fn theme_no_block_yields_nothing() {
2084        assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
2085    }
2086
2087    #[test]
2088    fn theme_line_numbers() {
2089        let scan = scan_theme_blocks("@theme {\n  --color-a: red;\n  --radius-b: 4px;\n}");
2090        assert_eq!(scan.tokens[0].line, 2);
2091        assert_eq!(scan.tokens[1].line, 3);
2092    }
2093
2094    #[test]
2095    fn theme_token_backs_token_via_var() {
2096        let scan = scan_theme_blocks(
2097            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
2098        );
2099        assert!(
2100            scan.theme_var_reads
2101                .iter()
2102                .any(|(name, _)| name == "color-brand")
2103        );
2104    }
2105
2106    #[test]
2107    fn theme_var_read_carries_line() {
2108        // The `var(--color-brand)` read sits on line 3 of the source; the located
2109        // theme-var read must carry that 1-based line for the reverse index.
2110        let scan = scan_theme_blocks(
2111            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
2112        );
2113        assert_eq!(
2114            scan.theme_var_reads,
2115            vec![("color-brand".to_string(), 3u32)]
2116        );
2117    }
2118
2119    #[test]
2120    fn css_var_reads_locate_outside_theme_and_exclude_interior() {
2121        // A regular-CSS `var(--color-brand)` read is located (css-var surface);
2122        // a read inside the `@theme` interior is the distinct theme-var surface
2123        // and MUST be excluded here so the two kinds never double-count.
2124        let source = "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}\n\n.btn {\n  color: var(--color-brand);\n}\n";
2125        assert_eq!(
2126            extract_css_var_reads_located(source),
2127            vec![("color-brand".to_string(), 7u32)],
2128            "only the .btn read (line 7) is a css-var; the @theme-interior read is excluded"
2129        );
2130
2131        // A source whose only `var()` read is inside `@theme` yields no css-var.
2132        assert!(
2133            extract_css_var_reads_located("@theme {\n  --a: #fff;\n  --b: var(--a);\n}",)
2134                .is_empty(),
2135            "a @theme-interior-only var() read is not a css-var consumer"
2136        );
2137    }
2138
2139    #[test]
2140    fn css_var_reads_line_match_naive_reference_on_dense_line() {
2141        // Many `var()` reads packed onto a single long line (the pathological
2142        // zero-newline prefix) plus one trailing read on the next line: the
2143        // incremental line counter must agree byte-for-byte with the naive
2144        // per-match prefix rescan. No `@theme`, comments, strings, or `url()`,
2145        // so masking is identity and every read is a css-var read.
2146        use std::fmt::Write as _;
2147        let mut src = String::from(".x {");
2148        for i in 0..500 {
2149            let _ = write!(src, " color: var(--t{i});");
2150        }
2151        src.push_str(" }\n.y { color: var(--tail); }\n");
2152
2153        let got = extract_css_var_reads_located(&src);
2154
2155        // Reference: recompute each read's line via a full prefix rescan.
2156        let want: Vec<(String, u32)> = CSS_VAR_REF_RE
2157            .captures_iter(&src)
2158            .filter_map(|cap| cap.get(0).zip(cap.get(1)))
2159            .map(|(whole, name)| {
2160                (
2161                    name.as_str().to_owned(),
2162                    line_at_offset(&src, whole.start()),
2163                )
2164            })
2165            .collect();
2166
2167        assert_eq!(got, want);
2168        assert!(got.len() > 500, "expected the dense line plus the trailer");
2169        // The trailer sits on line 2; the packed reads all sit on line 1.
2170        assert_eq!(got.last().map(|(_, l)| *l), Some(2));
2171        assert!(got[..got.len() - 1].iter().all(|(_, l)| *l == 1));
2172    }
2173
2174    #[test]
2175    fn apply_token_lines_match_naive_reference_on_dense_line() {
2176        use std::fmt::Write as _;
2177        let mut src = String::from("/* a\n b */\n.x {");
2178        for i in 0..300 {
2179            let _ = write!(src, " @apply p-{i};");
2180        }
2181        src.push_str(" }\n\n.y { @apply tail-a tail-b; }\r\n.z { @apply last; }\n");
2182
2183        let got = extract_apply_tokens_located(&src);
2184
2185        let masked = mask_theme_source(&src);
2186        let want: Vec<(String, u32)> = CSS_APPLY_RE
2187            .find_iter(&masked)
2188            .flat_map(|m| {
2189                let line = line_at_offset(&src, m.start());
2190                m.as_str()
2191                    .trim_start_matches("@apply")
2192                    .split_whitespace()
2193                    .map(move |token| (token.to_owned(), line))
2194            })
2195            .collect();
2196
2197        assert_eq!(got, want);
2198        assert_eq!(got.len(), 303);
2199        assert!(got[..300].iter().all(|(_, line)| *line == 3));
2200        assert_eq!(
2201            &got[300..],
2202            &[
2203                ("tail-a".to_owned(), 5),
2204                ("tail-b".to_owned(), 5),
2205                ("last".to_owned(), 6),
2206            ]
2207        );
2208    }
2209
2210    #[test]
2211    fn theme_string_braces_do_not_truncate_block() {
2212        let scan = scan_theme_blocks(
2213            "@theme {\n  --font-label: \"}\";\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
2214        );
2215        assert_eq!(
2216            scan.tokens
2217                .iter()
2218                .map(|token| token.name.as_str())
2219                .collect::<Vec<_>>(),
2220            vec!["font-label", "color-brand", "color-button"]
2221        );
2222        assert!(
2223            scan.theme_var_reads
2224                .iter()
2225                .any(|(name, _)| name == "color-brand")
2226        );
2227    }
2228
2229    #[test]
2230    fn theme_nested_keyframes_body_not_collected() {
2231        // `@keyframes` inside `@theme` (for `--animate-*`) must not surface its
2232        // step selectors or interior as theme tokens.
2233        let names = theme_token_names(
2234            "@theme {\n  --animate-spin: spin 1s linear infinite;\n  @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
2235        );
2236        assert_eq!(names, vec!["animate-spin"]);
2237    }
2238
2239    #[test]
2240    fn theme_comment_block_ignored() {
2241        let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
2242        assert!(names.is_empty(), "got {names:?}");
2243    }
2244
2245    #[test]
2246    fn theme_deduplicates_repeated_token() {
2247        let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
2248        assert_eq!(names, vec!["color-a"]);
2249    }
2250
2251    #[test]
2252    fn apply_tokens_basic() {
2253        let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
2254        assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
2255    }
2256
2257    #[test]
2258    fn apply_tokens_strips_important() {
2259        let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
2260        assert_eq!(tokens, vec!["text-brand", "font-bold"]);
2261    }
2262
2263    #[test]
2264    fn apply_tokens_ignored_in_comments() {
2265        let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
2266        assert!(tokens.is_empty(), "got {tokens:?}");
2267    }
2268}