1use std::path::Path;
16use std::sync::LazyLock;
17
18use oxc_span::Span;
19use rustc_hash::FxHashSet;
20
21use crate::css_mask::{
22 is_indented_stylesheet, mask_sass_module_members, mask_view_transition_arguments,
23 mask_with_whitespace,
24};
25use crate::css_module_classes::lightningcss_class_set;
26use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
27use fallow_types::discover::FileId;
28
29static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
32 crate::static_regex(
33 r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
34 )
35});
36
37static SCSS_USE_RE: LazyLock<regex::Regex> =
40 LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
41
42static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
45 LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
46
47static CSS_APPLY_RE: LazyLock<regex::Regex> =
50 LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
51
52static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
55 LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
56
57static CSS_COMMENT_RE: LazyLock<regex::Regex> =
59 LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
60
61static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
63 LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
64
65static CSS_CLASS_RE: LazyLock<regex::Regex> =
68 LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
69
70static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
73 LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|(?i:url)\([^)]*\)"#));
74
75static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
87 LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
88
89pub(crate) fn is_css_file(path: &Path) -> bool {
90 path.extension()
91 .and_then(|e| e.to_str())
92 .is_some_and(|ext| matches!(ext, "css" | "scss" | "sass" | "less"))
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct CssImportSource {
98 pub raw: String,
100 pub normalized: String,
102 pub is_plugin: bool,
104 pub span: Span,
106}
107
108fn is_css_module_file(path: &Path) -> bool {
109 is_css_file(path)
110 && path
111 .file_stem()
112 .and_then(|s| s.to_str())
113 .is_some_and(|stem| stem.ends_with(".module"))
114}
115
116pub(crate) fn is_css_url_import(source: &str) -> bool {
118 source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
119}
120
121pub(crate) fn normalize_css_import_path(path: String, is_scss: bool) -> String {
134 if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
135 return path;
136 }
137 if path.starts_with('@') && path.contains('/') {
138 return path;
139 }
140 let path_ref = std::path::Path::new(&path);
141 if !is_scss
142 && path.contains('/')
143 && path_ref
144 .extension()
145 .and_then(|e| e.to_str())
146 .is_some_and(is_style_extension)
147 {
148 return path;
149 }
150 let ext = std::path::Path::new(&path)
151 .extension()
152 .and_then(|e| e.to_str());
153 match ext {
154 Some(e) if is_style_extension(e) => format!("./{path}"),
155 _ => {
156 if is_scss && !path.contains(':') {
157 format!("./{path}")
158 } else {
159 path
160 }
161 }
162 }
163}
164
165fn is_style_extension(ext: &str) -> bool {
166 ext.eq_ignore_ascii_case("css")
167 || ext.eq_ignore_ascii_case("scss")
168 || ext.eq_ignore_ascii_case("sass")
169 || ext.eq_ignore_ascii_case("less")
170}
171
172#[cfg(test)]
173thread_local! {
174 static COMMENT_MASK_PASSES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
176 static LINE_LOOKUP_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
179}
180
181#[cfg(test)]
182fn note_line_lookup_bytes(bytes: usize) {
183 LINE_LOOKUP_BYTES.with(|read| read.set(read.get() + bytes));
184}
185
186pub(crate) fn mask_css_comments(source: &str, is_scss: bool) -> String {
187 #[cfg(test)]
188 COMMENT_MASK_PASSES.with(|passes| passes.set(passes.get() + 1));
189 crate::css_masked_bytes::add(source.len() as u64);
190 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
191 if is_scss {
192 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
193 }
194 masked
195}
196
197fn normalize_css_plugin_path(path: String) -> String {
203 path
204}
205
206#[must_use]
216pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
217 import_sources_from_masked(&mask_css_comments(source, is_scss), is_scss)
218}
219
220pub(crate) fn import_sources_from_masked(stripped: &str, is_scss: bool) -> Vec<CssImportSource> {
223 let mut out = Vec::new();
224
225 for cap in CSS_IMPORT_RE.captures_iter(stripped) {
226 let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
227 if let Some(m) = raw {
228 let (src, span) = trimmed_match_with_span(m);
229 if !src.is_empty() && !is_css_url_import(&src) {
230 out.push(CssImportSource {
231 normalized: normalize_css_import_path(src.clone(), is_scss),
232 raw: src,
233 is_plugin: false,
234 span,
235 });
236 }
237 }
238 }
239
240 if is_scss {
241 for cap in SCSS_USE_RE.captures_iter(stripped) {
242 if let Some(m) = cap.get(1).filter(|m| !m.as_str().trim().is_empty()) {
243 let (raw, span) = trimmed_match_with_span(m);
244 out.push(CssImportSource {
245 normalized: normalize_css_import_path(raw.clone(), true),
246 raw,
247 is_plugin: false,
248 span,
249 });
250 }
251 }
252 }
253
254 for cap in CSS_PLUGIN_RE.captures_iter(stripped) {
255 if let Some(m) = cap.get(1) {
256 let (raw, span) = trimmed_match_with_span(m);
257 if !raw.is_empty() && !is_css_url_import(&raw) {
258 out.push(CssImportSource {
259 normalized: normalize_css_plugin_path(raw.clone()),
260 raw,
261 is_plugin: true,
262 span,
263 });
264 }
265 }
266 }
267
268 out
269}
270
271pub(crate) fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
272 let raw = m.as_str();
273 let trimmed_start = raw.len() - raw.trim_start().len();
274 let trimmed_end = raw.trim_end().len().max(trimmed_start);
275 let start = m.start() + trimmed_start;
276 let end = m.start() + trimmed_end;
277 (raw.trim().to_string(), Span::new(start as u32, end as u32))
278}
279
280#[must_use]
287pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
288 extract_css_import_sources(source, is_scss)
289 .into_iter()
290 .map(|source| source.normalized)
291 .collect()
292}
293
294static CSS_THEME_OPEN_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
298 crate::static_regex(r"@theme(?:\s+(?:inline|static|reference|default))*\s*\{")
299});
300
301static CSS_VAR_REF_RE: LazyLock<regex::Regex> =
305 LazyLock::new(|| crate::static_regex(r"var\(\s*--([A-Za-z0-9_-]+)"));
306
307#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct ThemeTokenDef {
311 pub name: String,
313 pub value: String,
316 pub line: u32,
318}
319
320#[derive(Debug, Clone, Default, PartialEq, Eq)]
322pub struct ThemeScan {
323 pub tokens: Vec<ThemeTokenDef>,
327 pub theme_var_reads: Vec<(String, u32)>,
334}
335
336#[must_use]
346pub fn scan_theme_blocks(source: &str) -> ThemeScan {
347 if !source.contains("@theme") {
349 return ThemeScan::default();
350 }
351 theme_scan_from_masked(source, &mask_theme_source(source))
352}
353
354fn theme_scan_from_masked(source: &str, masked: &str) -> ThemeScan {
356 let mut out = ThemeScan::default();
357 let mut seen: FxHashSet<String> = FxHashSet::default();
358 for open in CSS_THEME_OPEN_RE.find_iter(masked) {
359 let body_start = open.end();
360 let body_end = find_theme_body_end(masked, body_start);
361 collect_theme_declarations(&mut ThemeDeclarationScan {
362 source,
363 masked,
364 start: body_start,
365 end: body_end,
366 out: &mut out.tokens,
367 seen: &mut seen,
368 });
369 collect_theme_var_reads(
370 source,
371 masked,
372 body_start,
373 body_end,
374 &mut out.theme_var_reads,
375 );
376 }
377 out
378}
379
380#[must_use]
387pub fn extract_css_var_reads_located(source: &str) -> Vec<(String, u32)> {
388 if !source.contains("var(") {
389 return Vec::new();
390 }
391 css_var_reads_from_masked(source, &mask_theme_source(source))
392}
393
394fn css_var_reads_from_masked(source: &str, masked: &str) -> Vec<(String, u32)> {
397 let mut theme_bodies: Vec<(usize, usize)> = Vec::new();
400 if masked.contains("@theme") {
401 for open in CSS_THEME_OPEN_RE.find_iter(masked) {
402 let body_start = open.end();
403 let body_end = find_theme_body_end(masked, body_start);
404 theme_bodies.push((body_start, body_end));
405 }
406 }
407 let in_theme = |offset: usize| theme_bodies.iter().any(|&(s, e)| offset >= s && offset < e);
408 let mut out = Vec::new();
409 let mut last_pos = 0usize;
415 let mut last_line = 1u32;
416 for cap in CSS_VAR_REF_RE.captures_iter(masked) {
417 let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
418 continue;
419 };
420 if in_theme(whole.start()) {
421 continue;
422 }
423 let offset = whole.start();
424 last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
425 last_pos = offset;
426 out.push((name.as_str().to_owned(), last_line));
427 }
428 out
429}
430
431fn mask_theme_source(source: &str) -> String {
434 mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE)
435}
436
437fn find_theme_body_end(masked: &str, body_start: usize) -> usize {
439 let bytes = masked.as_bytes();
440 let mut depth = 1usize;
441 let mut i = body_start;
442 while i < bytes.len() {
443 match bytes[i] {
444 b'{' => depth += 1,
445 b'}' => {
446 depth -= 1;
447 if depth == 0 {
448 break;
449 }
450 }
451 _ => {}
452 }
453 i += 1;
454 }
455 i.min(bytes.len())
456}
457
458fn collect_theme_var_reads(
459 source: &str,
460 masked: &str,
461 body_start: usize,
462 body_end: usize,
463 out: &mut Vec<(String, u32)>,
464) {
465 let Some(body) = masked.get(body_start..body_end) else {
466 return;
467 };
468 let mut last_pos = 0usize;
473 let mut last_line = 1u32;
474 for cap in CSS_VAR_REF_RE.captures_iter(body) {
475 let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
476 continue;
477 };
478 let offset = body_start + whole.start();
481 last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
482 last_pos = offset;
483 out.push((name.as_str().to_owned(), last_line));
484 }
485}
486
487#[cfg(test)]
491fn line_at_offset(source: &str, offset: usize) -> u32 {
492 note_line_lookup_bytes(offset);
493 let count = source
494 .get(..offset)
495 .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
496 u32::try_from(1 + count).unwrap_or(u32::MAX)
497}
498
499fn newlines_between(source: &str, from: usize, to: usize) -> u32 {
505 #[cfg(test)]
506 note_line_lookup_bytes(to.saturating_sub(from));
507 let count = source
508 .get(from..to)
509 .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
510 u32::try_from(count).unwrap_or(u32::MAX)
511}
512
513fn collect_theme_declarations(scan: &mut ThemeDeclarationScan<'_, '_>) {
519 let bytes = scan.masked.as_bytes();
520 let mut depth = 0usize;
521 let mut expect_decl = true;
522 let mut i = scan.start;
523 while i < scan.end {
524 let b = bytes[i];
525 match b {
526 b'{' => {
527 depth += 1;
528 expect_decl = false;
529 i += 1;
530 }
531 b'}' => {
532 depth = depth.saturating_sub(1);
533 if depth == 0 {
534 expect_decl = true;
535 }
536 i += 1;
537 }
538 b';' => {
539 if depth == 0 {
540 expect_decl = true;
541 }
542 i += 1;
543 }
544 _ if b.is_ascii_whitespace() => i += 1,
545 _ => {
546 if depth == 0 && expect_decl {
547 expect_decl = false;
548 i = scan_theme_declaration(scan, b, i);
549 } else {
550 i += 1;
551 }
552 }
553 }
554 }
555}
556
557struct ThemeDeclarationScan<'a, 'b> {
558 source: &'a str,
559 masked: &'a str,
560 start: usize,
561 end: usize,
562 out: &'b mut Vec<ThemeTokenDef>,
563 seen: &'b mut FxHashSet<String>,
564}
565
566fn scan_theme_declaration(scan: &mut ThemeDeclarationScan<'_, '_>, b: u8, i: usize) -> usize {
570 let bytes = scan.masked.as_bytes();
571 if !(b == b'-' && bytes.get(i + 1) == Some(&b'-')) {
572 return i + 1;
573 }
574 let id_start = i;
575 let mut j = i;
576 while j < scan.end {
577 let c = bytes[j];
578 if c == b'-' || c == b'_' || c.is_ascii_alphanumeric() {
579 j += 1;
580 } else {
581 break;
582 }
583 }
584 let mut k = j;
585 while k < scan.end && bytes[k].is_ascii_whitespace() {
586 k += 1;
587 }
588 if k < scan.end && bytes[k] == b':' {
590 let name = &scan.masked[id_start + 2..j];
591 if !name.is_empty() && scan.seen.insert(name.to_owned()) {
592 let value = theme_declaration_value(scan.source, scan.masked, k + 1, scan.end);
593 let line = 1 + scan
594 .source
595 .get(..id_start)
596 .map_or(0, |s| s.bytes().filter(|&x| x == b'\n').count());
597 scan.out.push(ThemeTokenDef {
598 name: name.to_owned(),
599 value,
600 line: u32::try_from(line).unwrap_or(u32::MAX),
601 });
602 }
603 }
604 j
605}
606
607fn theme_declaration_value(source: &str, masked: &str, start: usize, end: usize) -> String {
608 let bytes = masked.as_bytes();
609 let mut depth = 0usize;
610 let mut i = start;
611 while i < end {
612 match bytes[i] {
613 b'{' => depth += 1,
614 b'}' => {
615 if depth == 0 {
616 break;
617 }
618 depth -= 1;
619 }
620 b';' if depth == 0 => break,
621 _ => {}
622 }
623 i += 1;
624 }
625 source
626 .get(start..i)
627 .unwrap_or_default()
628 .split_whitespace()
629 .collect::<Vec<_>>()
630 .join(" ")
631}
632
633#[must_use]
639pub fn extract_apply_tokens(source: &str) -> Vec<String> {
640 extract_apply_tokens_located(source)
641 .into_iter()
642 .map(|(token, _line)| token)
643 .collect()
644}
645
646#[must_use]
651pub fn extract_apply_tokens_located(source: &str) -> Vec<(String, u32)> {
652 if !source.contains("@apply") {
654 return Vec::new();
655 }
656 apply_tokens_from_masked(source, &mask_theme_source(source))
657}
658
659fn apply_tokens_from_masked(source: &str, masked: &str) -> Vec<(String, u32)> {
662 let mut out = Vec::new();
663 let ends: &[char] = if is_indented_stylesheet(masked) {
664 &[';', '}', '\n']
665 } else {
666 &[';', '}']
667 };
668 let mut last_pos = 0usize;
669 let mut line = 1u32;
670 let mut directives = masked
671 .match_indices("@apply")
672 .filter(|(start, keyword)| masked[start + keyword.len()..].starts_with(char::is_whitespace))
673 .peekable();
674 while let Some((start, keyword)) = directives.next() {
675 line = line.saturating_add(newlines_between(source, last_pos, start));
676 last_pos = start;
677 let next = directives
678 .peek()
679 .map_or(masked.len(), |(offset, _)| *offset);
680 let rest = masked[start + keyword.len()..next].trim_start();
681 let body = rest
682 .split_once(ends)
683 .map_or_else(|| rest.lines().next().unwrap_or_default(), |(body, _)| body);
684 for token in body.split_whitespace() {
685 let token = token.trim_matches('!');
686 if token.is_empty() || token == "important" {
687 continue;
688 }
689 out.push((token.to_owned(), line));
690 }
691 }
692 out
693}
694
695#[derive(Debug, Clone, Default, PartialEq, Eq)]
698pub struct StylesheetTokens {
699 pub theme: ThemeScan,
701 pub apply_tokens_located: Vec<(String, u32)>,
703 pub css_var_reads_located: Vec<(String, u32)>,
705 pub has_plugin_directive: bool,
708}
709
710#[must_use]
715pub fn scan_stylesheet_tokens(source: &str) -> StylesheetTokens {
716 let has_theme = source.contains("@theme");
717 let has_apply = source.contains("@apply");
718 let has_var = source.contains("var(");
719 let has_plugin = source.contains(PLUGIN_AT_RULE);
720 if !(has_theme || has_apply || has_var || has_plugin) {
721 return StylesheetTokens::default();
722 }
723 let masked = mask_theme_source(source);
724 StylesheetTokens {
725 theme: if has_theme {
726 theme_scan_from_masked(source, &masked)
727 } else {
728 ThemeScan::default()
729 },
730 apply_tokens_located: if has_apply {
731 apply_tokens_from_masked(source, &masked)
732 } else {
733 Vec::new()
734 },
735 css_var_reads_located: if has_var {
736 css_var_reads_from_masked(source, &masked)
737 } else {
738 Vec::new()
739 },
740 has_plugin_directive: has_plugin && has_plugin_at_rule(&masked),
741 }
742}
743
744const PLUGIN_AT_RULE: &str = "@plugin";
745
746fn has_plugin_at_rule(masked: &str) -> bool {
749 masked.match_indices(PLUGIN_AT_RULE).any(|(start, _)| {
750 masked[start + PLUGIN_AT_RULE.len()..]
751 .bytes()
752 .next()
753 .is_none_or(|next| !(next.is_ascii_alphanumeric() || next == b'-' || next == b'_'))
754 })
755}
756
757pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
767 css_module_exports(source, &mask_css_comments(source, is_scss), is_scss)
768}
769
770fn css_module_exports(source: &str, comment_masked: &str, is_scss: bool) -> Vec<ExportInfo> {
774 if !is_scss && let Some(class_set) = lightningcss_class_set(source) {
775 return scan_css_module_exports(comment_masked, Some(&class_set));
776 }
777 scan_css_module_exports(comment_masked, None)
778}
779
780fn scan_css_module_exports(
791 comment_masked: &str,
792 class_filter: Option<&FxHashSet<String>>,
793) -> Vec<ExportInfo> {
794 let masked = mask_css_module_class_candidates(comment_masked, class_filter.is_some());
795 let mut seen = FxHashSet::default();
796 let mut exports = Vec::new();
797 for cap in CSS_CLASS_RE.captures_iter(&masked) {
798 if let Some(m) = cap.get(1) {
799 push_css_class_export(m, class_filter, &mut seen, &mut exports);
800 }
801 }
802 exports
803}
804
805fn mask_css_module_class_candidates(comment_masked: &str, has_class_filter: bool) -> String {
806 let mut masked = mask_with_whitespace(comment_masked, &CSS_NON_SELECTOR_RE);
807 masked = mask_view_transition_arguments(&masked);
808 if !has_class_filter {
809 masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
810 masked = mask_sass_module_members(&masked);
811 }
812 mask_css_module_global_scopes(masked)
813}
814
815const GLOBAL_KEYWORD: &str = ":global";
816const LOCAL_KEYWORD: &str = ":local";
817
818#[derive(Clone, Copy)]
820struct ScopeKeyword {
821 is_global: bool,
822 len: usize,
823 has_argument: bool,
825}
826
827fn scope_keyword_at(bytes: &[u8], i: usize) -> Option<ScopeKeyword> {
830 let rest = &bytes[i..];
831 let (is_global, len) = if rest.starts_with(GLOBAL_KEYWORD.as_bytes()) {
832 (true, GLOBAL_KEYWORD.len())
833 } else if rest.starts_with(LOCAL_KEYWORD.as_bytes()) {
834 (false, LOCAL_KEYWORD.len())
835 } else {
836 return None;
837 };
838 let next = rest.get(len).copied();
839 if next.is_some_and(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') {
840 return None;
841 }
842 Some(ScopeKeyword {
843 is_global,
844 len,
845 has_argument: next == Some(b'('),
846 })
847}
848
849pub(crate) fn blank_bare_css_module_scope_keywords(source: &str) -> std::borrow::Cow<'_, str> {
852 if !source.contains(GLOBAL_KEYWORD) && !source.contains(LOCAL_KEYWORD) {
853 return std::borrow::Cow::Borrowed(source);
854 }
855 let bytes = source.as_bytes();
856 let mut out = source.to_string();
857 let mut i = 0;
858 while i < bytes.len() {
859 match scope_keyword_at(bytes, i) {
860 Some(keyword) => {
861 if !keyword.has_argument {
862 out.replace_range(i..i + keyword.len, &" ".repeat(keyword.len));
863 }
864 i += keyword.len;
865 }
866 None => i += 1,
867 }
868 }
869 std::borrow::Cow::Owned(out)
870}
871
872#[derive(Clone, Copy, PartialEq, Eq)]
874enum ParenScope {
875 Global,
876 Local,
877 Other,
878}
879
880struct GlobalScopeScan {
882 block_global: Vec<bool>,
884 selector_global: bool,
886 parens: Vec<ParenScope>,
887}
888
889impl GlobalScopeScan {
890 fn inherited(&self) -> bool {
891 self.block_global.last().copied().unwrap_or(false)
892 }
893
894 fn reset_selector(&mut self) {
897 self.selector_global = self.inherited();
898 self.parens.clear();
899 }
900
901 fn is_global(&self) -> bool {
904 self.parens
905 .iter()
906 .rev()
907 .find(|scope| **scope != ParenScope::Other)
908 .map_or(self.selector_global, |scope| *scope == ParenScope::Global)
909 }
910}
911
912fn mask_css_module_global_scopes(masked: String) -> String {
927 if !masked.contains(GLOBAL_KEYWORD) {
928 return masked;
929 }
930 let indented = is_indented_stylesheet(&masked);
931 let bytes = masked.as_bytes();
932 let mut blank = Vec::new();
933 let mut scan = GlobalScopeScan {
934 block_global: Vec::new(),
935 selector_global: false,
936 parens: Vec::new(),
937 };
938 let mut i = 0;
939 while i < bytes.len() {
940 if let Some(keyword) = scope_keyword_at(bytes, i) {
941 if keyword.has_argument {
942 scan.parens.push(if keyword.is_global {
943 ParenScope::Global
944 } else {
945 ParenScope::Local
946 });
947 i += keyword.len + 1;
948 continue;
949 }
950 if scan.parens.is_empty() {
951 scan.selector_global = keyword.is_global;
952 }
953 i += keyword.len;
954 continue;
955 }
956 match bytes[i] {
957 b'#' if bytes.get(i + 1) == Some(&b'{') => {
958 i = scss_interpolation_end(bytes, i + 2);
959 continue;
960 }
961 b'(' => scan.parens.push(ParenScope::Other),
962 b')' => {
963 scan.parens.pop();
964 }
965 b',' if scan.parens.is_empty() => scan.selector_global = scan.inherited(),
966 b'{' => {
967 scan.block_global.push(scan.selector_global);
968 scan.reset_selector();
969 }
970 b'}' => {
971 scan.block_global.pop();
972 scan.reset_selector();
973 }
974 b';' => scan.reset_selector(),
975 b'\n' if indented => scan.reset_selector(),
976 b'.' if scan.is_global()
977 && bytes
978 .get(i + 1)
979 .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_') =>
980 {
981 blank.push(i);
982 }
983 _ => {}
984 }
985 i += 1;
986 }
987 let mut out = masked;
988 for offset in blank {
989 out.replace_range(offset..=offset, " ");
990 }
991 out
992}
993
994fn scss_interpolation_end(bytes: &[u8], start: usize) -> usize {
997 let mut depth = 1usize;
998 let mut i = start;
999 while i < bytes.len() {
1000 match bytes[i] {
1001 b'{' => depth += 1,
1002 b'}' => {
1003 depth -= 1;
1004 if depth == 0 {
1005 return i + 1;
1006 }
1007 }
1008 _ => {}
1009 }
1010 i += 1;
1011 }
1012 bytes.len()
1013}
1014
1015fn push_css_class_export(
1016 class_match: regex::Match<'_>,
1017 class_filter: Option<&FxHashSet<String>>,
1018 seen: &mut FxHashSet<String>,
1019 exports: &mut Vec<ExportInfo>,
1020) {
1021 let class_name = class_match.as_str().to_string();
1022 if class_filter.is_some_and(|filter| !filter.contains(&class_name)) {
1023 return;
1024 }
1025 if seen.insert(class_name.clone()) {
1026 exports.push(css_class_export(class_name, class_match));
1027 }
1028}
1029
1030fn css_class_export(class_name: String, class_match: regex::Match<'_>) -> ExportInfo {
1031 #[expect(
1032 clippy::cast_possible_truncation,
1033 reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
1034 )]
1035 let span = Span::new(class_match.start() as u32, class_match.end() as u32);
1036 ExportInfo {
1037 name: ExportName::Named(class_name),
1038 local_name: None,
1039 is_type_only: false,
1040 visibility: VisibilityTag::None,
1041 expected_unused_reason: None,
1042 span,
1043 members: Vec::new(),
1044 is_side_effect_used: false,
1045 super_class: None,
1046 deprecated: false,
1047 deprecated_reason: None,
1048 }
1049}
1050
1051fn build_css_imports(stripped: &str, is_scss: bool) -> Vec<ImportInfo> {
1055 let mut imports = Vec::new();
1056
1057 for css_source in import_sources_from_masked(stripped, is_scss) {
1058 imports.push(ImportInfo {
1059 source: css_source.normalized,
1060 imported_name: if css_source.is_plugin {
1061 ImportedName::Default
1062 } else {
1063 ImportedName::SideEffect
1064 },
1065 local_name: String::new(),
1066 is_type_only: false,
1067 is_type_only_star: false,
1068 from_style: false,
1069 span: css_source.span,
1070 source_span: css_source.span,
1071 });
1072 }
1073
1074 let has_apply = CSS_APPLY_RE.is_match(stripped);
1075 let has_tailwind = CSS_TAILWIND_RE.is_match(stripped);
1076 if has_apply || has_tailwind {
1077 imports.push(ImportInfo {
1078 source: "tailwindcss".to_string(),
1079 imported_name: ImportedName::SideEffect,
1080 local_name: String::new(),
1081 is_type_only: false,
1082 is_type_only_star: false,
1083 from_style: false,
1084 span: Span::default(),
1085 source_span: Span::default(),
1086 });
1087 }
1088
1089 imports
1090}
1091
1092pub(crate) fn parse_css_to_module(
1096 file_id: FileId,
1097 path: &Path,
1098 source: &str,
1099 content_hash: u64,
1100) -> ModuleInfo {
1101 let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
1102 let is_scss = path
1103 .extension()
1104 .and_then(|e| e.to_str())
1105 .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
1106
1107 let stripped = crate::css_mask::mask_sass_shorthand(mask_css_comments(source, is_scss), path);
1108 let mut imports = build_css_imports(&stripped, is_scss);
1109 let exports = if is_css_module_file(path) {
1110 crate::css_composes::push_composes_from_imports(&stripped, &mut imports);
1111 css_module_exports(source, &stripped, is_scss)
1112 } else {
1113 Vec::new()
1114 };
1115
1116 let mut info =
1118 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
1119 file_id,
1120 content_hash,
1121 source,
1122 parsed_suppressions,
1123 imports,
1124 exports,
1125 });
1126 info.package_path_references =
1127 crate::css_url::package_url_references(&stripped).into_boxed_slice();
1128 info
1129}
1130
1131#[cfg(all(test, not(miri)))]
1132#[path = "css_scan_cost_tests.rs"]
1133mod scan_cost_tests;
1134
1135#[cfg(all(test, not(miri)))]
1136mod tests {
1137 use super::*;
1138
1139 fn export_names(source: &str) -> Vec<String> {
1141 extract_css_module_exports(source, false)
1142 .into_iter()
1143 .filter_map(|e| match e.name {
1144 ExportName::Named(n) => Some(n),
1145 ExportName::Default => None,
1146 })
1147 .collect()
1148 }
1149
1150 #[test]
1151 fn is_css_file_css() {
1152 assert!(is_css_file(Path::new("styles.css")));
1153 }
1154
1155 #[test]
1156 fn is_css_file_scss() {
1157 assert!(is_css_file(Path::new("styles.scss")));
1158 }
1159
1160 #[test]
1161 fn is_css_file_sass() {
1162 assert!(is_css_file(Path::new("styles.sass")));
1163 }
1164
1165 #[test]
1166 fn is_css_file_less() {
1167 assert!(is_css_file(Path::new("styles.less")));
1168 }
1169
1170 #[test]
1171 fn is_css_file_rejects_js() {
1172 assert!(!is_css_file(Path::new("app.js")));
1173 }
1174
1175 #[test]
1176 fn is_css_file_rejects_ts() {
1177 assert!(!is_css_file(Path::new("app.ts")));
1178 }
1179
1180 #[test]
1181 fn is_css_file_rejects_no_extension() {
1182 assert!(!is_css_file(Path::new("Makefile")));
1183 }
1184
1185 #[test]
1186 fn is_css_module_file_module_css() {
1187 assert!(is_css_module_file(Path::new("Component.module.css")));
1188 }
1189
1190 #[test]
1191 fn is_css_module_file_module_scss() {
1192 assert!(is_css_module_file(Path::new("Component.module.scss")));
1193 }
1194
1195 #[test]
1196 fn is_css_module_file_rejects_plain_css() {
1197 assert!(!is_css_module_file(Path::new("styles.css")));
1198 }
1199
1200 #[test]
1201 fn is_css_module_file_rejects_plain_scss() {
1202 assert!(!is_css_module_file(Path::new("styles.scss")));
1203 }
1204
1205 #[test]
1206 fn is_css_module_file_rejects_module_js() {
1207 assert!(!is_css_module_file(Path::new("utils.module.js")));
1208 }
1209
1210 #[test]
1211 fn extracts_single_class() {
1212 let names = export_names(".foo { color: red; }");
1213 assert_eq!(names, vec!["foo"]);
1214 }
1215
1216 #[test]
1217 fn extracts_multiple_classes() {
1218 let names = export_names(".foo { } .bar { }");
1219 assert_eq!(names, vec!["foo", "bar"]);
1220 }
1221
1222 #[test]
1223 fn extracts_nested_classes() {
1224 let names = export_names(".foo .bar { color: red; }");
1225 assert!(names.contains(&"foo".to_string()));
1226 assert!(names.contains(&"bar".to_string()));
1227 }
1228
1229 #[test]
1230 fn extracts_hyphenated_class() {
1231 let names = export_names(".my-class { }");
1232 assert_eq!(names, vec!["my-class"]);
1233 }
1234
1235 #[test]
1236 fn extracts_camel_case_class() {
1237 let names = export_names(".myClass { }");
1238 assert_eq!(names, vec!["myClass"]);
1239 }
1240
1241 fn scss_export_names(source: &str) -> Vec<String> {
1242 extract_css_module_exports(source, true)
1243 .into_iter()
1244 .filter_map(|e| match e.name {
1245 ExportName::Named(n) => Some(n),
1246 ExportName::Default => None,
1247 })
1248 .collect()
1249 }
1250
1251 #[test]
1252 fn skips_class_inside_global_pseudo() {
1253 let names = export_names(":global(.globalClass) { color: red; }");
1255 assert!(names.is_empty(), "got {names:?}");
1256 }
1257
1258 #[test]
1259 fn keeps_local_class_next_to_global_pseudo() {
1260 let names = export_names(".wrapper :global(.selector) { color: red; }");
1262 assert_eq!(names, vec!["wrapper"]);
1263 }
1264
1265 #[test]
1266 fn skips_every_class_inside_global_pseudo_with_descendants() {
1267 let names = export_names(".panel :global(.outer .inner.mod) { color: red; }");
1268 assert_eq!(names, vec!["panel"]);
1269 }
1270
1271 #[test]
1272 fn skips_classes_after_bare_global() {
1273 let names = export_names(".lead :global .first .second { color: red; }");
1274 assert_eq!(names, vec!["lead"]);
1275 }
1276
1277 #[test]
1278 fn bare_global_stops_at_local() {
1279 let names = export_names(":global .g1 :local(.l1) .g2 :local .l2 .l3, .l4 { color: red; }");
1280 assert_eq!(names, vec!["l1", "l2", "l3", "l4"]);
1281 }
1282
1283 #[test]
1284 fn bare_global_stops_at_comma() {
1285 let names = export_names(":global .g1, .l1 :is(.l2, .l3) { color: red; }");
1286 assert_eq!(names, vec!["l1", "l2", "l3"]);
1287 }
1288
1289 #[test]
1290 fn global_class_inside_media_query_is_skipped() {
1291 let names = export_names("@media (min-width: 1px) { .media :global(.g) { color: red; } }");
1292 assert_eq!(names, vec!["media"]);
1293 }
1294
1295 #[test]
1296 fn class_both_local_and_global_stays_exported_at_local_span() {
1297 let source = ":global(.both) { color: red; }\n.both { color: blue; }";
1298 let exports = extract_css_module_exports(source, false);
1299 assert_eq!(exports.len(), 1);
1300 let span = exports[0].span;
1301 assert_eq!(&source[span.start as usize..span.end as usize], "both");
1302 assert!(
1303 span.start > 20,
1304 "span must point at the local rule: {span:?}"
1305 );
1306 }
1307
1308 #[test]
1309 fn composes_keeps_local_classes() {
1310 let names = export_names(
1311 ".base { color: red; }\n.button { composes: base; composes: g from global; }",
1312 );
1313 assert_eq!(names, vec!["base", "button"]);
1314 }
1315
1316 #[test]
1317 fn global_in_strings_and_comments_has_no_effect() {
1318 let names =
1319 export_names("/* :global */ .a { content: \":global\"; }\n.b :global(.c) { }\n.d { }");
1320 assert_eq!(names, vec!["a", "b", "d"]);
1321 }
1322
1323 #[test]
1324 fn scss_skips_global_pseudo_and_global_block() {
1325 let names = scss_export_names(
1326 ".card {\n :global(.g1) { color: red; }\n .title { color: blue; }\n}\n\
1327 :global {\n .g2 { color: red; }\n .g3 { :local(.l1) { color: red; } }\n}\n\
1328 .after { color: blue; }",
1329 );
1330 assert_eq!(names, vec!["card", "title", "l1", "after"]);
1331 }
1332
1333 #[test]
1334 fn scss_bare_global_in_parent_reaches_nested_rules() {
1335 let names = scss_export_names(
1336 ".a :global .b {\n .c { color: red; }\n &:hover { color: blue; }\n}\n.d { }",
1337 );
1338 assert_eq!(names, vec!["a", "d"]);
1339 }
1340
1341 #[test]
1342 fn scss_interpolation_does_not_end_global_scope() {
1343 let names = scss_export_names("$n: x;\n.a :global .b-#{$n} .c { }\n.d { }");
1344 assert_eq!(names, vec!["a", "d"]);
1345 }
1346
1347 #[test]
1348 fn sass_indented_bare_global_ends_at_line_end() {
1349 let names = scss_export_names(".a :global .b\n color: red\n.c\n color: blue\n");
1350 assert_eq!(names, vec!["a", "c"]);
1351 }
1352
1353 #[test]
1354 fn sass_indented_with_interpolation_still_ends_global_at_line_end() {
1355 let names = scss_export_names(
1356 ".a :global .b\n color: red\n.c-#{$x}\n color: blue\n.d\n color: blue\n",
1357 );
1358 assert_eq!(names, vec!["a", "c-", "d"]);
1360 }
1361
1362 #[test]
1363 fn global_like_pseudo_names_are_not_global() {
1364 let names = export_names(".a:global-ish .b { }");
1365 assert!(names.contains(&"b".to_string()), "got {names:?}");
1366 }
1367
1368 #[test]
1369 fn extracts_class_inside_local_pseudo() {
1370 let names = export_names(":local(.localClass) { color: red; }");
1371 assert_eq!(names, vec!["localClass"]);
1372 }
1373
1374 #[test]
1375 fn extracts_classes_inside_negation() {
1376 let names = export_names(".btn:not(.disabled) { }");
1377 assert!(names.contains(&"btn".to_string()), "got {names:?}");
1378 assert!(names.contains(&"disabled".to_string()), "got {names:?}");
1379 }
1380
1381 #[test]
1382 fn extracts_classes_inside_is_and_where() {
1383 let names = export_names(":is(.a, .b) :where(.c) { }");
1384 for expected in ["a", "b", "c"] {
1385 assert!(
1386 names.contains(&expected.to_string()),
1387 "missing {expected} in {names:?}"
1388 );
1389 }
1390 }
1391
1392 #[test]
1393 fn extracts_underscore_class() {
1394 let names = export_names("._hidden { } .__wrapper { }");
1395 assert!(names.contains(&"_hidden".to_string()));
1396 assert!(names.contains(&"__wrapper".to_string()));
1397 }
1398
1399 #[test]
1400 fn pseudo_selector_hover() {
1401 let names = export_names(".foo:hover { color: blue; }");
1402 assert_eq!(names, vec!["foo"]);
1403 }
1404
1405 #[test]
1406 fn pseudo_selector_focus() {
1407 let names = export_names(".input:focus { outline: none; }");
1408 assert_eq!(names, vec!["input"]);
1409 }
1410
1411 #[test]
1412 fn pseudo_element_before() {
1413 let names = export_names(".icon::before { content: ''; }");
1414 assert_eq!(names, vec!["icon"]);
1415 }
1416
1417 #[test]
1418 fn combined_pseudo_selectors() {
1419 let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
1420 assert_eq!(names, vec!["btn"]);
1421 }
1422
1423 #[test]
1424 fn classes_inside_media_query() {
1425 let names = export_names(
1426 "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
1427 );
1428 assert!(names.contains(&"mobile-nav".to_string()));
1429 assert!(names.contains(&"desktop-nav".to_string()));
1430 }
1431
1432 #[test]
1433 fn classes_inside_multi_line_media_query() {
1434 let names =
1435 export_names("@media\n screen and (min-width: 600px)\n{\n .real { color: red; }\n}");
1436 assert_eq!(names, vec!["real"]);
1437 }
1438
1439 #[test]
1440 fn at_layer_statement_does_not_export() {
1441 let names = export_names("@layer foo.bar;");
1442 assert!(names.is_empty(), "got {names:?}");
1443 let names = export_names("@layer foo.bar, foo.baz;");
1444 assert!(names.is_empty(), "got {names:?}");
1445 }
1446
1447 #[test]
1448 fn at_layer_block_keeps_body_classes() {
1449 let names = export_names("@layer foo.bar { .root { color: red; } }");
1450 assert_eq!(names, vec!["root"]);
1451 }
1452
1453 #[test]
1454 fn at_layer_multiline_prelude_keeps_body_classes() {
1455 let names = export_names("@layer\n foo.bar\n{ .root { color: red; } }");
1456 assert_eq!(names, vec!["root"]);
1457 }
1458
1459 #[test]
1460 fn at_layer_with_nested_media_keeps_body() {
1461 let names =
1462 export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1463 assert_eq!(names, vec!["real"]);
1464 }
1465
1466 #[test]
1467 fn at_import_with_layer_attribute_does_not_export() {
1468 let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1469 assert!(names.is_empty(), "got {names:?}");
1470 }
1471
1472 #[test]
1473 fn class_then_at_layer_does_not_leak_prelude() {
1474 let names =
1475 export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1476 assert_eq!(names, vec!["outer", "inner"]);
1477 }
1478
1479 #[test]
1480 fn at_scope_keeps_selector_list_classes() {
1481 let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1482 assert!(names.contains(&"parent".to_string()), "got {names:?}");
1483 assert!(names.contains(&"child".to_string()), "got {names:?}");
1484 assert!(names.contains(&"title".to_string()), "got {names:?}");
1485 }
1486
1487 #[test]
1488 fn at_keyframes_numeric_step_is_not_class() {
1489 let names = export_names(
1490 "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1491 );
1492 assert!(names.is_empty(), "got {names:?}");
1493 }
1494
1495 #[test]
1496 fn at_webkit_keyframes_keeps_body_classes() {
1497 let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1498 assert_eq!(names, vec!["real"]);
1499 }
1500
1501 #[test]
1502 fn deduplicates_repeated_class() {
1503 let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1504 assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1505 }
1506
1507 #[test]
1508 fn empty_source() {
1509 let names = export_names("");
1510 assert!(names.is_empty());
1511 }
1512
1513 #[test]
1514 fn no_classes() {
1515 let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1516 assert!(names.is_empty());
1517 }
1518
1519 #[test]
1520 fn ignores_classes_in_block_comments() {
1521 let names = export_names("/* .fake { } */ .real { }");
1522 assert!(!names.contains(&"fake".to_string()));
1523 assert!(names.contains(&"real".to_string()));
1524 }
1525
1526 #[test]
1527 fn ignores_classes_in_scss_line_comments() {
1528 let exports = extract_css_module_exports("// .fake\n.real { }", true);
1529 let names: Vec<_> = exports
1530 .iter()
1531 .filter_map(|e| match &e.name {
1532 ExportName::Named(n) => Some(n.as_str()),
1533 ExportName::Default => None,
1534 })
1535 .collect();
1536 assert_eq!(names, vec!["real"]);
1537 }
1538
1539 #[test]
1540 fn ignores_classes_in_strings() {
1541 let names = export_names(r#".real { content: ".fake"; }"#);
1542 assert!(names.contains(&"real".to_string()));
1543 assert!(!names.contains(&"fake".to_string()));
1544 }
1545
1546 #[test]
1547 fn ignores_classes_in_url() {
1548 let names = export_names(".real { background: url(./images/hero.png); }");
1549 assert!(names.contains(&"real".to_string()));
1550 assert!(!names.contains(&"png".to_string()));
1551 }
1552
1553 #[test]
1554 fn mask_css_block_comment() {
1555 let source = "/* removed */ .kept { }";
1556 let result = mask_css_comments(source, false);
1557 assert!(!result.contains("removed"));
1558 assert_eq!(result.len(), source.len());
1559 assert_eq!(result.find(".kept"), source.find(".kept"));
1560 }
1561
1562 #[test]
1563 fn mask_scss_line_comment() {
1564 let source = "// removed\n.kept { }";
1565 let result = mask_css_comments(source, true);
1566 assert!(!result.contains("removed"));
1567 assert_eq!(result.len(), source.len());
1568 assert_eq!(result.find(".kept"), source.find(".kept"));
1569 }
1570
1571 #[test]
1572 fn mask_scss_preserves_css_outside_comments() {
1573 let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1574 let result = mask_css_comments(source, true);
1575 assert!(result.contains(".visible"));
1576 }
1577
1578 #[test]
1579 fn url_import_http() {
1580 assert!(is_css_url_import("http://example.com/style.css"));
1581 }
1582
1583 #[test]
1584 fn url_import_https() {
1585 assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1586 }
1587
1588 #[test]
1589 fn url_import_data() {
1590 assert!(is_css_url_import("data:text/css;base64,abc"));
1591 }
1592
1593 #[test]
1594 fn url_import_local_not_skipped() {
1595 assert!(!is_css_url_import("./local.css"));
1596 }
1597
1598 #[test]
1599 fn url_import_bare_specifier_not_skipped() {
1600 assert!(!is_css_url_import("tailwindcss"));
1601 }
1602
1603 #[test]
1604 fn normalize_relative_dot_path_unchanged() {
1605 assert_eq!(
1606 normalize_css_import_path("./reset.css".to_string(), false),
1607 "./reset.css"
1608 );
1609 }
1610
1611 #[test]
1612 fn normalize_parent_relative_path_unchanged() {
1613 assert_eq!(
1614 normalize_css_import_path("../shared.scss".to_string(), false),
1615 "../shared.scss"
1616 );
1617 }
1618
1619 #[test]
1620 fn normalize_absolute_path_unchanged() {
1621 assert_eq!(
1622 normalize_css_import_path("/styles/main.css".to_string(), false),
1623 "/styles/main.css"
1624 );
1625 }
1626
1627 #[test]
1628 fn normalize_url_unchanged() {
1629 assert_eq!(
1630 normalize_css_import_path("https://example.com/style.css".to_string(), false),
1631 "https://example.com/style.css"
1632 );
1633 }
1634
1635 #[test]
1636 fn normalize_bare_css_gets_dot_slash() {
1637 assert_eq!(
1638 normalize_css_import_path("app.css".to_string(), false),
1639 "./app.css"
1640 );
1641 }
1642
1643 #[test]
1644 fn normalize_css_package_subpath_stays_bare() {
1645 assert_eq!(
1646 normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1647 "tailwindcss/theme.css"
1648 );
1649 }
1650
1651 #[test]
1652 fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1653 assert_eq!(
1654 normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1655 "highlight.js/styles/github.css"
1656 );
1657 }
1658
1659 #[test]
1660 fn normalize_bare_scss_gets_dot_slash() {
1661 assert_eq!(
1662 normalize_css_import_path("vars.scss".to_string(), false),
1663 "./vars.scss"
1664 );
1665 }
1666
1667 #[test]
1668 fn normalize_bare_sass_gets_dot_slash() {
1669 assert_eq!(
1670 normalize_css_import_path("main.sass".to_string(), false),
1671 "./main.sass"
1672 );
1673 }
1674
1675 #[test]
1676 fn normalize_bare_less_gets_dot_slash() {
1677 assert_eq!(
1678 normalize_css_import_path("theme.less".to_string(), false),
1679 "./theme.less"
1680 );
1681 }
1682
1683 #[test]
1684 fn normalize_bare_js_extension_stays_bare() {
1685 assert_eq!(
1686 normalize_css_import_path("module.js".to_string(), false),
1687 "module.js"
1688 );
1689 }
1690
1691 #[test]
1692 fn normalize_scss_bare_partial_gets_dot_slash() {
1693 assert_eq!(
1694 normalize_css_import_path("variables".to_string(), true),
1695 "./variables"
1696 );
1697 }
1698
1699 #[test]
1700 fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1701 assert_eq!(
1702 normalize_css_import_path("base/reset".to_string(), true),
1703 "./base/reset"
1704 );
1705 }
1706
1707 #[test]
1708 fn normalize_scss_builtin_stays_bare() {
1709 assert_eq!(
1710 normalize_css_import_path("sass:math".to_string(), true),
1711 "sass:math"
1712 );
1713 }
1714
1715 #[test]
1716 fn normalize_scss_relative_path_unchanged() {
1717 assert_eq!(
1718 normalize_css_import_path("../styles/variables".to_string(), true),
1719 "../styles/variables"
1720 );
1721 }
1722
1723 #[test]
1724 fn normalize_css_bare_extensionless_stays_bare() {
1725 assert_eq!(
1726 normalize_css_import_path("tailwindcss".to_string(), false),
1727 "tailwindcss"
1728 );
1729 }
1730
1731 #[test]
1732 fn normalize_scoped_package_with_css_extension_stays_bare() {
1733 assert_eq!(
1734 normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1735 "@fontsource/monaspace-neon/400.css"
1736 );
1737 }
1738
1739 #[test]
1740 fn normalize_scoped_package_with_scss_extension_stays_bare() {
1741 assert_eq!(
1742 normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1743 "@company/design-system/tokens.scss"
1744 );
1745 }
1746
1747 #[test]
1748 fn normalize_scoped_package_without_extension_stays_bare() {
1749 assert_eq!(
1750 normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1751 "@fallow/design-system/styles"
1752 );
1753 }
1754
1755 #[test]
1756 fn normalize_scoped_package_extensionless_scss_stays_bare() {
1757 assert_eq!(
1758 normalize_css_import_path("@company/tokens".to_string(), true),
1759 "@company/tokens"
1760 );
1761 }
1762
1763 #[test]
1764 fn normalize_path_alias_with_css_extension_stays_bare() {
1765 assert_eq!(
1766 normalize_css_import_path("@/components/Button.css".to_string(), false),
1767 "@/components/Button.css"
1768 );
1769 }
1770
1771 #[test]
1772 fn normalize_path_alias_extensionless_stays_bare() {
1773 assert_eq!(
1774 normalize_css_import_path("@/styles/variables".to_string(), false),
1775 "@/styles/variables"
1776 );
1777 }
1778
1779 #[test]
1780 fn mask_css_no_comments() {
1781 let source = ".foo { color: red; }";
1782 assert_eq!(mask_css_comments(source, false), source);
1783 }
1784
1785 #[test]
1786 fn mask_css_multiple_block_comments() {
1787 let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1788 let result = mask_css_comments(source, false);
1789 assert!(!result.contains("comment-one"));
1790 assert!(!result.contains("comment-two"));
1791 assert!(result.contains(".foo"));
1792 assert!(result.contains(".bar"));
1793 }
1794
1795 #[test]
1796 fn mask_scss_does_not_affect_non_scss() {
1797 let source = "// this stays\n.foo { }";
1798 let result = mask_css_comments(source, false);
1799 assert!(result.contains("// this stays"));
1800 }
1801
1802 #[test]
1803 fn css_module_parses_suppressions() {
1804 let info = parse_css_to_module(
1805 fallow_types::discover::FileId(0),
1806 Path::new("Component.module.css"),
1807 "/* fallow-ignore-file */\n.btn { color: red; }",
1808 0,
1809 );
1810 assert!(!info.suppressions.is_empty());
1811 assert_eq!(info.suppressions[0].line, 0);
1812 }
1813
1814 #[test]
1815 fn extracts_class_starting_with_underscore() {
1816 let names = export_names("._private { } .__dunder { }");
1817 assert!(names.contains(&"_private".to_string()));
1818 assert!(names.contains(&"__dunder".to_string()));
1819 }
1820
1821 #[test]
1822 fn ignores_id_selectors() {
1823 let names = export_names("#myId { color: red; }");
1824 assert!(!names.contains(&"myId".to_string()));
1825 }
1826
1827 #[test]
1828 fn ignores_element_selectors() {
1829 let names = export_names("div { color: red; } span { }");
1830 assert!(names.is_empty());
1831 }
1832
1833 #[test]
1834 fn extract_css_imports_at_import_quoted() {
1835 let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1836 assert_eq!(imports, vec!["./reset.css"]);
1837 }
1838
1839 #[test]
1840 fn extract_css_imports_package_subpath_stays_bare() {
1841 let imports =
1842 extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1843 assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1844 }
1845
1846 #[test]
1847 fn extract_css_imports_at_import_url() {
1848 let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1849 assert_eq!(imports, vec!["./reset.css"]);
1850 }
1851
1852 #[test]
1853 fn extract_css_imports_skips_remote_urls() {
1854 let imports =
1855 extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1856 assert!(imports.is_empty());
1857 }
1858
1859 #[test]
1860 fn extract_css_imports_scss_use_normalizes_partial() {
1861 let imports = extract_css_imports(r#"@use "variables";"#, true);
1862 assert_eq!(imports, vec!["./variables"]);
1863 }
1864
1865 #[test]
1866 fn extract_css_imports_scss_forward_normalizes_partial() {
1867 let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1868 assert_eq!(imports, vec!["./tokens"]);
1869 }
1870
1871 #[test]
1872 fn extract_css_imports_skips_comments() {
1873 let imports = extract_css_imports(
1874 r#"/* @import "./hidden.scss"; */
1875@use "real";"#,
1876 true,
1877 );
1878 assert_eq!(imports, vec!["./real"]);
1879 }
1880
1881 #[test]
1882 fn extract_css_imports_at_plugin_keeps_package_bare() {
1883 let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1884 assert_eq!(imports, vec!["daisyui"]);
1885 }
1886
1887 #[test]
1888 fn extract_css_imports_at_plugin_tracks_relative_file() {
1889 let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1890 assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1891 }
1892
1893 #[test]
1894 fn extract_css_imports_scss_at_import_kept_relative() {
1895 let imports = extract_css_imports(r"@import 'Foo';", true);
1896 assert_eq!(imports, vec!["./Foo"]);
1897 }
1898
1899 #[test]
1900 fn extract_css_imports_additional_data_string_body() {
1901 let body = r#"@use "./src/styles/global.scss";"#;
1902 let imports = extract_css_imports(body, true);
1903 assert_eq!(imports, vec!["./src/styles/global.scss"]);
1904 }
1905
1906 fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1909 let offsets = fallow_types::extract::compute_line_offsets(source);
1910 fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1911 }
1912
1913 #[test]
1914 fn span_points_at_real_class_declaration_line() {
1915 let source = "\n\n\n\n.foo { color: red; }\n";
1916 let exports = extract_css_module_exports(source, false);
1917 assert_eq!(exports.len(), 1);
1918 let span = exports[0].span;
1919 let (line, col) = span_line_col(source, span.start);
1920 assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1921 assert_eq!(
1922 col, 1,
1923 "column points at `f` in `.foo` (post-dot identifier)"
1924 );
1925 assert_eq!(
1926 &source[span.start as usize..span.end as usize],
1927 "foo",
1928 "span range must slice to the class identifier in the original source"
1929 );
1930 }
1931
1932 #[test]
1933 fn span_survives_multibyte_comment_prefix() {
1934 let source = "/* \u{2713} */\n.foo { }";
1935 let exports = extract_css_module_exports(source, false);
1936 assert_eq!(exports.len(), 1);
1937 let span = exports[0].span;
1938 assert!(
1939 source.is_char_boundary(span.start as usize),
1940 "span.start must lie on a UTF-8 char boundary"
1941 );
1942 assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1943 }
1944
1945 #[test]
1946 fn span_skips_at_layer_prelude_dot_segments() {
1947 let source = "@layer foo.bar { }\n.root { }\n";
1948 let exports = extract_css_module_exports(source, false);
1949 let names: Vec<_> = exports
1950 .iter()
1951 .filter_map(|e| match &e.name {
1952 ExportName::Named(n) => Some(n.as_str()),
1953 ExportName::Default => None,
1954 })
1955 .collect();
1956 assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1957 let span = exports[0].span;
1958 let (line, _col) = span_line_col(source, span.start);
1959 assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1960 assert_eq!(&source[span.start as usize..span.end as usize], "root");
1961 }
1962
1963 #[test]
1964 fn span_skips_classes_in_strings() {
1965 let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1966 let exports = extract_css_module_exports(source, false);
1967 let names: Vec<_> = exports
1968 .iter()
1969 .filter_map(|e| match &e.name {
1970 ExportName::Named(n) => Some(n.as_str()),
1971 ExportName::Default => None,
1972 })
1973 .collect();
1974 assert_eq!(names, vec!["real", "also-real"]);
1975 for export in &exports {
1976 let span = export.span;
1977 let slice = &source[span.start as usize..span.end as usize];
1978 match &export.name {
1979 ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1980 ExportName::Default => unreachable!("CSS modules emit only named exports"),
1981 }
1982 }
1983 }
1984
1985 #[test]
1986 fn span_deduplicates_to_first_occurrence() {
1987 let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1988 let exports = extract_css_module_exports(source, false);
1989 assert_eq!(exports.len(), 1);
1990 let (line, _col) = span_line_col(source, exports[0].span.start);
1991 assert_eq!(
1992 line, 1,
1993 "first occurrence wins for deduplicated class names"
1994 );
1995 }
1996
1997 #[test]
1998 fn span_inside_media_query() {
1999 let source =
2000 "@media (max-width: 768px) {\n .mobile { display: block; }\n .desktop { }\n}\n";
2001 let exports = extract_css_module_exports(source, false);
2002 let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
2003 .iter()
2004 .filter_map(|e| match &e.name {
2005 ExportName::Named(n) => Some((n.as_str(), e.span)),
2006 ExportName::Default => None,
2007 })
2008 .collect();
2009 let mobile_line = span_line_col(source, by_name["mobile"].start).0;
2010 let desktop_line = span_line_col(source, by_name["desktop"].start).0;
2011 assert_eq!(mobile_line, 2);
2012 assert_eq!(desktop_line, 3);
2013 }
2014
2015 #[test]
2016 fn at_layer_only_module_emits_no_exports() {
2017 let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
2018 assert!(exports.is_empty());
2019 }
2020
2021 #[test]
2022 fn parse_css_to_module_resolves_real_line_offsets() {
2023 let source = "\n\n\n\n.foo { color: red; }\n";
2024 let info = parse_css_to_module(
2025 fallow_types::discover::FileId(0),
2026 Path::new("Component.module.css"),
2027 source,
2028 0,
2029 );
2030 assert_eq!(info.exports.len(), 1);
2031 let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
2032 &info.line_offsets,
2033 info.exports[0].span.start,
2034 );
2035 assert_eq!(line, 5, "downstream line must equal the source line");
2036 }
2037
2038 fn theme_token_names(source: &str) -> Vec<String> {
2039 scan_theme_blocks(source)
2040 .tokens
2041 .into_iter()
2042 .map(|t| t.name)
2043 .collect()
2044 }
2045
2046 #[test]
2047 fn theme_single_block_collects_tokens() {
2048 let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
2049 assert_eq!(names, vec!["color-brand", "radius-card"]);
2050 }
2051
2052 #[test]
2053 fn theme_token_values_are_normalized() {
2054 let scan = scan_theme_blocks("@theme {\n --color-brand: rgb( 255 0 0 );\n}");
2055 assert_eq!(scan.tokens[0].name, "color-brand");
2056 assert_eq!(scan.tokens[0].value, "rgb( 255 0 0 )");
2057 }
2058
2059 #[test]
2060 fn theme_dashed_multi_segment_names() {
2061 let names = theme_token_names(
2062 "@theme {\n --font-weight-heavy: 900;\n --inset-shadow-glow: 0 0 4px red;\n}",
2063 );
2064 assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
2065 }
2066
2067 #[test]
2068 fn theme_inline_and_static_modifiers() {
2069 assert_eq!(
2070 theme_token_names("@theme inline { --color-a: red; }"),
2071 vec!["color-a"]
2072 );
2073 assert_eq!(
2074 theme_token_names("@theme static { --color-b: red; }"),
2075 vec!["color-b"]
2076 );
2077 }
2078
2079 #[test]
2080 fn theme_multiple_blocks_union() {
2081 let names = theme_token_names(
2082 "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
2083 );
2084 assert_eq!(names, vec!["color-a", "spacing-gutter"]);
2085 }
2086
2087 #[test]
2088 fn theme_reset_form_excluded() {
2089 let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
2091 assert_eq!(names, vec!["color-brand"]);
2092 }
2093
2094 #[test]
2095 fn theme_no_block_yields_nothing() {
2096 assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
2097 }
2098
2099 #[test]
2100 fn theme_line_numbers() {
2101 let scan = scan_theme_blocks("@theme {\n --color-a: red;\n --radius-b: 4px;\n}");
2102 assert_eq!(scan.tokens[0].line, 2);
2103 assert_eq!(scan.tokens[1].line, 3);
2104 }
2105
2106 #[test]
2107 fn theme_token_backs_token_via_var() {
2108 let scan = scan_theme_blocks(
2109 "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
2110 );
2111 assert!(
2112 scan.theme_var_reads
2113 .iter()
2114 .any(|(name, _)| name == "color-brand")
2115 );
2116 }
2117
2118 #[test]
2119 fn theme_var_read_carries_line() {
2120 let scan = scan_theme_blocks(
2123 "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
2124 );
2125 assert_eq!(
2126 scan.theme_var_reads,
2127 vec![("color-brand".to_string(), 3u32)]
2128 );
2129 }
2130
2131 #[test]
2132 fn css_var_reads_locate_outside_theme_and_exclude_interior() {
2133 let source = "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}\n\n.btn {\n color: var(--color-brand);\n}\n";
2137 assert_eq!(
2138 extract_css_var_reads_located(source),
2139 vec![("color-brand".to_string(), 7u32)],
2140 "only the .btn read (line 7) is a css-var; the @theme-interior read is excluded"
2141 );
2142
2143 assert!(
2145 extract_css_var_reads_located("@theme {\n --a: #fff;\n --b: var(--a);\n}",)
2146 .is_empty(),
2147 "a @theme-interior-only var() read is not a css-var consumer"
2148 );
2149 }
2150
2151 #[test]
2152 fn css_var_reads_line_match_naive_reference_on_dense_line() {
2153 use std::fmt::Write as _;
2159 let mut src = String::from(".x {");
2160 for i in 0..500 {
2161 let _ = write!(src, " color: var(--t{i});");
2162 }
2163 src.push_str(" }\n.y { color: var(--tail); }\n");
2164
2165 let got = extract_css_var_reads_located(&src);
2166
2167 let want: Vec<(String, u32)> = CSS_VAR_REF_RE
2169 .captures_iter(&src)
2170 .filter_map(|cap| cap.get(0).zip(cap.get(1)))
2171 .map(|(whole, name)| {
2172 (
2173 name.as_str().to_owned(),
2174 line_at_offset(&src, whole.start()),
2175 )
2176 })
2177 .collect();
2178
2179 assert_eq!(got, want);
2180 assert!(got.len() > 500, "expected the dense line plus the trailer");
2181 assert_eq!(got.last().map(|(_, l)| *l), Some(2));
2183 assert!(got[..got.len() - 1].iter().all(|(_, l)| *l == 1));
2184 }
2185
2186 #[test]
2187 fn apply_token_lines_match_naive_reference_on_dense_line() {
2188 use std::fmt::Write as _;
2189 let mut src = String::from("/* a\n b */\n.x {");
2190 for i in 0..300 {
2191 let _ = write!(src, " @apply p-{i};");
2192 }
2193 src.push_str(" }\n\n.y { @apply tail-a tail-b; }\r\n.z { @apply last; }\n");
2194
2195 let got = extract_apply_tokens_located(&src);
2196
2197 let masked = mask_theme_source(&src);
2198 let want: Vec<(String, u32)> = CSS_APPLY_RE
2199 .find_iter(&masked)
2200 .flat_map(|m| {
2201 let line = line_at_offset(&src, m.start());
2202 m.as_str()
2203 .trim_start_matches("@apply")
2204 .split_whitespace()
2205 .map(move |token| (token.to_owned(), line))
2206 })
2207 .collect();
2208
2209 assert_eq!(got, want);
2210 assert_eq!(got.len(), 303);
2211 assert!(got[..300].iter().all(|(_, line)| *line == 3));
2212 assert_eq!(
2213 &got[300..],
2214 &[
2215 ("tail-a".to_owned(), 5),
2216 ("tail-b".to_owned(), 5),
2217 ("last".to_owned(), 6),
2218 ]
2219 );
2220 }
2221
2222 #[test]
2223 fn theme_string_braces_do_not_truncate_block() {
2224 let scan = scan_theme_blocks(
2225 "@theme {\n --font-label: \"}\";\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
2226 );
2227 assert_eq!(
2228 scan.tokens
2229 .iter()
2230 .map(|token| token.name.as_str())
2231 .collect::<Vec<_>>(),
2232 vec!["font-label", "color-brand", "color-button"]
2233 );
2234 assert!(
2235 scan.theme_var_reads
2236 .iter()
2237 .any(|(name, _)| name == "color-brand")
2238 );
2239 }
2240
2241 #[test]
2242 fn theme_nested_keyframes_body_not_collected() {
2243 let names = theme_token_names(
2246 "@theme {\n --animate-spin: spin 1s linear infinite;\n @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
2247 );
2248 assert_eq!(names, vec!["animate-spin"]);
2249 }
2250
2251 #[test]
2252 fn theme_comment_block_ignored() {
2253 let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
2254 assert!(names.is_empty(), "got {names:?}");
2255 }
2256
2257 #[test]
2258 fn theme_deduplicates_repeated_token() {
2259 let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
2260 assert_eq!(names, vec!["color-a"]);
2261 }
2262}