1use std::path::Path;
16use std::sync::LazyLock;
17
18use lightningcss::rules::CssRule;
19use lightningcss::selector::{Component, PseudoClass, Selector, SelectorList};
20use lightningcss::stylesheet::{ParserOptions, StyleSheet};
21use oxc_span::Span;
22use rustc_hash::FxHashSet;
23
24use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
25use fallow_types::discover::FileId;
26
27static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
30 crate::static_regex(
31 r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
32 )
33});
34
35static SCSS_USE_RE: LazyLock<regex::Regex> =
38 LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
39
40static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
43 LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
44
45static CSS_APPLY_RE: LazyLock<regex::Regex> =
48 LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
49
50static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
53 LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
54
55static CSS_COMMENT_RE: LazyLock<regex::Regex> =
57 LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
58
59static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
61 LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
62
63static CSS_CLASS_RE: LazyLock<regex::Regex> =
66 LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
67
68static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
71 LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
72
73static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
85 LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
86
87pub(crate) fn is_css_file(path: &Path) -> bool {
88 path.extension()
89 .and_then(|e| e.to_str())
90 .is_some_and(|ext| matches!(ext, "css" | "scss" | "sass" | "less"))
91}
92
93#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct CssImportSource {
96 pub raw: String,
98 pub normalized: String,
100 pub is_plugin: bool,
102 pub span: Span,
104}
105
106fn is_css_module_file(path: &Path) -> bool {
107 is_css_file(path)
108 && path
109 .file_stem()
110 .and_then(|s| s.to_str())
111 .is_some_and(|stem| stem.ends_with(".module"))
112}
113
114fn is_css_url_import(source: &str) -> bool {
116 source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
117}
118
119fn normalize_css_import_path(path: String, is_scss: bool) -> String {
132 if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
133 return path;
134 }
135 if path.starts_with('@') && path.contains('/') {
136 return path;
137 }
138 let path_ref = std::path::Path::new(&path);
139 if !is_scss
140 && path.contains('/')
141 && path_ref
142 .extension()
143 .and_then(|e| e.to_str())
144 .is_some_and(is_style_extension)
145 {
146 return path;
147 }
148 let ext = std::path::Path::new(&path)
149 .extension()
150 .and_then(|e| e.to_str());
151 match ext {
152 Some(e) if is_style_extension(e) => format!("./{path}"),
153 _ => {
154 if is_scss && !path.contains(':') {
155 format!("./{path}")
156 } else {
157 path
158 }
159 }
160 }
161}
162
163fn is_style_extension(ext: &str) -> bool {
164 ext.eq_ignore_ascii_case("css")
165 || ext.eq_ignore_ascii_case("scss")
166 || ext.eq_ignore_ascii_case("sass")
167 || ext.eq_ignore_ascii_case("less")
168}
169
170fn mask_css_comments(source: &str, is_scss: bool) -> String {
171 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
172 if is_scss {
173 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
174 }
175 masked
176}
177
178fn normalize_css_plugin_path(path: String) -> String {
184 path
185}
186
187#[must_use]
197pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
198 let stripped = mask_css_comments(source, is_scss);
199 let mut out = Vec::new();
200
201 for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
202 let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
203 if let Some(m) = raw {
204 let (src, span) = trimmed_match_with_span(m);
205 if !src.is_empty() && !is_css_url_import(&src) {
206 out.push(CssImportSource {
207 normalized: normalize_css_import_path(src.clone(), is_scss),
208 raw: src,
209 is_plugin: false,
210 span,
211 });
212 }
213 }
214 }
215
216 if is_scss {
217 for cap in SCSS_USE_RE.captures_iter(&stripped) {
218 if let Some(m) = cap.get(1) {
219 let (raw, span) = trimmed_match_with_span(m);
220 out.push(CssImportSource {
221 normalized: normalize_css_import_path(raw.clone(), true),
222 raw,
223 is_plugin: false,
224 span,
225 });
226 }
227 }
228 }
229
230 for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
231 if let Some(m) = cap.get(1) {
232 let (raw, span) = trimmed_match_with_span(m);
233 if !raw.is_empty() && !is_css_url_import(&raw) {
234 out.push(CssImportSource {
235 normalized: normalize_css_plugin_path(raw.clone()),
236 raw,
237 is_plugin: true,
238 span,
239 });
240 }
241 }
242 }
243
244 out
245}
246
247fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
248 let raw = m.as_str();
249 let trimmed_start = raw.len() - raw.trim_start().len();
250 let trimmed_end = raw.trim_end().len();
251 let start = m.start() + trimmed_start;
252 let end = m.start() + trimmed_end;
253 (raw.trim().to_string(), Span::new(start as u32, end as u32))
254}
255
256#[must_use]
263pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
264 extract_css_import_sources(source, is_scss)
265 .into_iter()
266 .map(|source| source.normalized)
267 .collect()
268}
269
270static CSS_THEME_OPEN_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
274 crate::static_regex(r"@theme(?:\s+(?:inline|static|reference|default))*\s*\{")
275});
276
277static CSS_VAR_REF_RE: LazyLock<regex::Regex> =
281 LazyLock::new(|| crate::static_regex(r"var\(\s*--([A-Za-z0-9_-]+)"));
282
283#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct ThemeTokenDef {
287 pub name: String,
289 pub value: String,
292 pub line: u32,
294}
295
296#[derive(Debug, Clone, Default, PartialEq, Eq)]
298pub struct ThemeScan {
299 pub tokens: Vec<ThemeTokenDef>,
303 pub theme_var_reads: Vec<(String, u32)>,
310}
311
312#[must_use]
322pub fn scan_theme_blocks(source: &str) -> ThemeScan {
323 if !source.contains("@theme") {
325 return ThemeScan::default();
326 }
327 let masked = mask_theme_source(source);
328 let mut out = ThemeScan::default();
329 let mut seen: FxHashSet<String> = FxHashSet::default();
330 for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
331 let body_start = open.end();
332 let body_end = find_theme_body_end(&masked, body_start);
333 collect_theme_declarations(&mut ThemeDeclarationScan {
334 source,
335 masked: &masked,
336 start: body_start,
337 end: body_end,
338 out: &mut out.tokens,
339 seen: &mut seen,
340 });
341 collect_theme_var_reads(
342 source,
343 &masked,
344 body_start,
345 body_end,
346 &mut out.theme_var_reads,
347 );
348 }
349 out
350}
351
352#[must_use]
359pub fn extract_css_var_reads_located(source: &str) -> Vec<(String, u32)> {
360 if !source.contains("var(") {
361 return Vec::new();
362 }
363 let masked = mask_theme_source(source);
364 let mut theme_bodies: Vec<(usize, usize)> = Vec::new();
367 if masked.contains("@theme") {
368 for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
369 let body_start = open.end();
370 let body_end = find_theme_body_end(&masked, body_start);
371 theme_bodies.push((body_start, body_end));
372 }
373 }
374 let in_theme = |offset: usize| theme_bodies.iter().any(|&(s, e)| offset >= s && offset < e);
375 let mut out = Vec::new();
376 let mut last_pos = 0usize;
382 let mut last_line = 1u32;
383 for cap in CSS_VAR_REF_RE.captures_iter(&masked) {
384 let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
385 continue;
386 };
387 if in_theme(whole.start()) {
388 continue;
389 }
390 let offset = whole.start();
391 last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
392 last_pos = offset;
393 out.push((name.as_str().to_owned(), last_line));
394 }
395 out
396}
397
398fn mask_theme_source(source: &str) -> String {
401 mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE)
402}
403
404fn find_theme_body_end(masked: &str, body_start: usize) -> usize {
406 let bytes = masked.as_bytes();
407 let mut depth = 1usize;
408 let mut i = body_start;
409 while i < bytes.len() {
410 match bytes[i] {
411 b'{' => depth += 1,
412 b'}' => {
413 depth -= 1;
414 if depth == 0 {
415 break;
416 }
417 }
418 _ => {}
419 }
420 i += 1;
421 }
422 i.min(bytes.len())
423}
424
425fn collect_theme_var_reads(
426 source: &str,
427 masked: &str,
428 body_start: usize,
429 body_end: usize,
430 out: &mut Vec<(String, u32)>,
431) {
432 let Some(body) = masked.get(body_start..body_end) else {
433 return;
434 };
435 let mut last_pos = 0usize;
440 let mut last_line = 1u32;
441 for cap in CSS_VAR_REF_RE.captures_iter(body) {
442 let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
443 continue;
444 };
445 let offset = body_start + whole.start();
448 last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
449 last_pos = offset;
450 out.push((name.as_str().to_owned(), last_line));
451 }
452}
453
454fn line_at_offset(source: &str, offset: usize) -> u32 {
457 let count = source
458 .get(..offset)
459 .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
460 u32::try_from(1 + count).unwrap_or(u32::MAX)
461}
462
463fn newlines_between(source: &str, from: usize, to: usize) -> u32 {
469 let count = source
470 .get(from..to)
471 .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
472 u32::try_from(count).unwrap_or(u32::MAX)
473}
474
475fn collect_theme_declarations(scan: &mut ThemeDeclarationScan<'_, '_>) {
481 let bytes = scan.masked.as_bytes();
482 let mut depth = 0usize;
483 let mut expect_decl = true;
484 let mut i = scan.start;
485 while i < scan.end {
486 let b = bytes[i];
487 match b {
488 b'{' => {
489 depth += 1;
490 expect_decl = false;
491 i += 1;
492 }
493 b'}' => {
494 depth = depth.saturating_sub(1);
495 if depth == 0 {
496 expect_decl = true;
497 }
498 i += 1;
499 }
500 b';' => {
501 if depth == 0 {
502 expect_decl = true;
503 }
504 i += 1;
505 }
506 _ if b.is_ascii_whitespace() => i += 1,
507 _ => {
508 if depth == 0 && expect_decl {
509 expect_decl = false;
510 i = scan_theme_declaration(scan, b, i);
511 } else {
512 i += 1;
513 }
514 }
515 }
516 }
517}
518
519struct ThemeDeclarationScan<'a, 'b> {
520 source: &'a str,
521 masked: &'a str,
522 start: usize,
523 end: usize,
524 out: &'b mut Vec<ThemeTokenDef>,
525 seen: &'b mut FxHashSet<String>,
526}
527
528fn scan_theme_declaration(scan: &mut ThemeDeclarationScan<'_, '_>, b: u8, i: usize) -> usize {
532 let bytes = scan.masked.as_bytes();
533 if !(b == b'-' && bytes.get(i + 1) == Some(&b'-')) {
534 return i + 1;
535 }
536 let id_start = i;
537 let mut j = i;
538 while j < scan.end {
539 let c = bytes[j];
540 if c == b'-' || c == b'_' || c.is_ascii_alphanumeric() {
541 j += 1;
542 } else {
543 break;
544 }
545 }
546 let mut k = j;
547 while k < scan.end && bytes[k].is_ascii_whitespace() {
548 k += 1;
549 }
550 if k < scan.end && bytes[k] == b':' {
552 let name = &scan.masked[id_start + 2..j];
553 if !name.is_empty() && scan.seen.insert(name.to_owned()) {
554 let value = theme_declaration_value(scan.source, scan.masked, k + 1, scan.end);
555 let line = 1 + scan
556 .source
557 .get(..id_start)
558 .map_or(0, |s| s.bytes().filter(|&x| x == b'\n').count());
559 scan.out.push(ThemeTokenDef {
560 name: name.to_owned(),
561 value,
562 line: u32::try_from(line).unwrap_or(u32::MAX),
563 });
564 }
565 }
566 j
567}
568
569fn theme_declaration_value(source: &str, masked: &str, start: usize, end: usize) -> String {
570 let bytes = masked.as_bytes();
571 let mut depth = 0usize;
572 let mut i = start;
573 while i < end {
574 match bytes[i] {
575 b'{' => depth += 1,
576 b'}' => {
577 if depth == 0 {
578 break;
579 }
580 depth -= 1;
581 }
582 b';' if depth == 0 => break,
583 _ => {}
584 }
585 i += 1;
586 }
587 source
588 .get(start..i)
589 .unwrap_or_default()
590 .split_whitespace()
591 .collect::<Vec<_>>()
592 .join(" ")
593}
594
595#[must_use]
601pub fn extract_apply_tokens(source: &str) -> Vec<String> {
602 if !source.contains("@apply") {
604 return Vec::new();
605 }
606 let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
607 let mut out = Vec::new();
608 for m in CSS_APPLY_RE.find_iter(&masked) {
609 let body = m.as_str().trim_start_matches("@apply");
610 for token in body.split_whitespace() {
611 let token = token.trim_matches('!');
612 if token.is_empty() || token == "important" {
613 continue;
614 }
615 out.push(token.to_owned());
616 }
617 }
618 out
619}
620
621#[must_use]
626pub fn extract_apply_tokens_located(source: &str) -> Vec<(String, u32)> {
627 if !source.contains("@apply") {
628 return Vec::new();
629 }
630 let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
631 let mut out = Vec::new();
632 for m in CSS_APPLY_RE.find_iter(&masked) {
633 let line = line_at_offset(source, m.start());
634 let body = m.as_str().trim_start_matches("@apply");
635 for token in body.split_whitespace() {
636 let token = token.trim_matches('!');
637 if token.is_empty() || token == "important" {
638 continue;
639 }
640 out.push((token.to_owned(), line));
641 }
642 }
643 out
644}
645
646fn mask_with_whitespace(src: &str, re: ®ex::Regex) -> String {
656 let mut out = String::with_capacity(src.len());
657 let mut cursor = 0;
658 for m in re.find_iter(src) {
659 out.push_str(&src[cursor..m.start()]);
660 for _ in m.start()..m.end() {
661 out.push(' ');
662 }
663 cursor = m.end();
664 }
665 out.push_str(&src[cursor..]);
666 out
667}
668
669fn lightningcss_class_set(source: &str) -> Option<FxHashSet<String>> {
686 let options = ParserOptions {
687 error_recovery: true,
690 css_modules: Some(lightningcss::css_modules::Config::default()),
696 ..ParserOptions::default()
697 };
698 let stylesheet = StyleSheet::parse(source, options).ok()?;
699 let mut classes = FxHashSet::default();
700 collect_classes_from_rules(&stylesheet.rules.0, &mut classes);
701 Some(classes)
702}
703
704fn collect_classes_from_rules(rules: &[CssRule<'_>], classes: &mut FxHashSet<String>) {
709 for rule in rules {
710 match rule {
711 CssRule::Style(style) => {
712 collect_classes_from_selector_list(&style.selectors, classes);
713 collect_classes_from_rules(&style.rules.0, classes);
714 }
715 CssRule::Media(rule) => collect_classes_from_rules(&rule.rules.0, classes),
716 CssRule::Supports(rule) => collect_classes_from_rules(&rule.rules.0, classes),
717 CssRule::Container(rule) => collect_classes_from_rules(&rule.rules.0, classes),
718 CssRule::LayerBlock(rule) => collect_classes_from_rules(&rule.rules.0, classes),
719 CssRule::MozDocument(rule) => collect_classes_from_rules(&rule.rules.0, classes),
720 CssRule::StartingStyle(rule) => collect_classes_from_rules(&rule.rules.0, classes),
721 CssRule::Nesting(rule) => {
722 collect_classes_from_selector_list(&rule.style.selectors, classes);
723 collect_classes_from_rules(&rule.style.rules.0, classes);
724 }
725 CssRule::Scope(rule) => {
726 if let Some(scope_start) = &rule.scope_start {
727 collect_classes_from_selector_list(scope_start, classes);
728 }
729 if let Some(scope_end) = &rule.scope_end {
730 collect_classes_from_selector_list(scope_end, classes);
731 }
732 collect_classes_from_rules(&rule.rules.0, classes);
733 }
734 _ => {}
735 }
736 }
737}
738
739fn collect_classes_from_selector_list(list: &SelectorList<'_>, classes: &mut FxHashSet<String>) {
740 for selector in &list.0 {
741 collect_classes_from_selector(selector, classes);
742 }
743}
744
745fn collect_classes_from_selector(selector: &Selector<'_>, classes: &mut FxHashSet<String>) {
746 for component in selector.iter_raw_match_order() {
747 match component {
748 Component::Class(name) => {
749 classes.insert(name.0.to_string());
750 }
751 Component::Is(list)
752 | Component::Where(list)
753 | Component::Has(list)
754 | Component::Negation(list)
755 | Component::Any(_, list) => {
756 for nested in list.as_ref() {
757 collect_classes_from_selector(nested, classes);
758 }
759 }
760 Component::Slotted(nested) | Component::Host(Some(nested)) => {
761 collect_classes_from_selector(nested, classes);
762 }
763 Component::NthOf(data) => {
764 for nested in data.selectors() {
765 collect_classes_from_selector(nested, classes);
766 }
767 }
768 Component::NonTSPseudoClass(
770 PseudoClass::Local { selector } | PseudoClass::Global { selector },
771 ) => collect_classes_from_selector(selector, classes),
772 _ => {}
773 }
774 }
775}
776
777pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
787 if !is_scss && let Some(class_set) = lightningcss_class_set(source) {
788 return scan_css_module_exports(source, is_scss, Some(&class_set));
789 }
790 scan_css_module_exports(source, is_scss, None)
791}
792
793fn scan_css_module_exports(
803 source: &str,
804 is_scss: bool,
805 class_filter: Option<&FxHashSet<String>>,
806) -> Vec<ExportInfo> {
807 let masked = mask_css_module_class_candidates(source, is_scss, class_filter.is_some());
808 let mut seen = FxHashSet::default();
809 let mut exports = Vec::new();
810 for cap in CSS_CLASS_RE.captures_iter(&masked) {
811 if let Some(m) = cap.get(1) {
812 push_css_class_export(m, class_filter, &mut seen, &mut exports);
813 }
814 }
815 exports
816}
817
818fn mask_css_module_class_candidates(source: &str, is_scss: bool, has_class_filter: bool) -> String {
819 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
820 if is_scss {
821 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
822 }
823 masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
824 if !has_class_filter {
825 masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
826 }
827 masked
828}
829
830fn push_css_class_export(
831 class_match: regex::Match<'_>,
832 class_filter: Option<&FxHashSet<String>>,
833 seen: &mut FxHashSet<String>,
834 exports: &mut Vec<ExportInfo>,
835) {
836 let class_name = class_match.as_str().to_string();
837 if class_filter.is_some_and(|filter| !filter.contains(&class_name)) {
838 return;
839 }
840 if seen.insert(class_name.clone()) {
841 exports.push(css_class_export(class_name, class_match));
842 }
843}
844
845fn css_class_export(class_name: String, class_match: regex::Match<'_>) -> ExportInfo {
846 #[expect(
847 clippy::cast_possible_truncation,
848 reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
849 )]
850 let span = Span::new(class_match.start() as u32, class_match.end() as u32);
851 ExportInfo {
852 name: ExportName::Named(class_name),
853 local_name: None,
854 is_type_only: false,
855 visibility: VisibilityTag::None,
856 expected_unused_reason: None,
857 span,
858 members: Vec::new(),
859 is_side_effect_used: false,
860 super_class: None,
861 deprecated: false,
862 deprecated_reason: None,
863 }
864}
865
866fn build_css_imports(source: &str, stripped: &str, is_scss: bool) -> Vec<ImportInfo> {
870 let mut imports = Vec::new();
871
872 for css_source in extract_css_import_sources(source, is_scss) {
873 imports.push(ImportInfo {
874 source: css_source.normalized,
875 imported_name: if css_source.is_plugin {
876 ImportedName::Default
877 } else {
878 ImportedName::SideEffect
879 },
880 local_name: String::new(),
881 is_type_only: false,
882 is_type_only_star: false,
883 from_style: false,
884 span: css_source.span,
885 source_span: css_source.span,
886 });
887 }
888
889 let has_apply = CSS_APPLY_RE.is_match(stripped);
890 let has_tailwind = CSS_TAILWIND_RE.is_match(stripped);
891 if has_apply || has_tailwind {
892 imports.push(ImportInfo {
893 source: "tailwindcss".to_string(),
894 imported_name: ImportedName::SideEffect,
895 local_name: String::new(),
896 is_type_only: false,
897 is_type_only_star: false,
898 from_style: false,
899 span: Span::default(),
900 source_span: Span::default(),
901 });
902 }
903
904 imports
905}
906
907pub(crate) fn parse_css_to_module(
909 file_id: FileId,
910 path: &Path,
911 source: &str,
912 content_hash: u64,
913) -> ModuleInfo {
914 let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
915 let is_scss = path
916 .extension()
917 .and_then(|e| e.to_str())
918 .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
919
920 let stripped = mask_css_comments(source, is_scss);
921 let imports = build_css_imports(source, &stripped, is_scss);
922
923 let exports = if is_css_module_file(path) {
924 extract_css_module_exports(source, is_scss)
925 } else {
926 Vec::new()
927 };
928
929 css_module_info(
930 file_id,
931 content_hash,
932 source,
933 parsed_suppressions,
934 imports,
935 exports,
936 )
937}
938
939fn css_module_info(
943 file_id: FileId,
944 content_hash: u64,
945 source: &str,
946 parsed_suppressions: crate::suppress::ParsedSuppressions,
947 imports: Vec<ImportInfo>,
948 exports: Vec<ExportInfo>,
949) -> ModuleInfo {
950 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
951 file_id,
952 content_hash,
953 source,
954 parsed_suppressions,
955 imports,
956 exports,
957 })
958}
959
960#[cfg(all(test, not(miri)))]
961mod tests {
962 use super::*;
963
964 fn export_names(source: &str) -> Vec<String> {
966 extract_css_module_exports(source, false)
967 .into_iter()
968 .filter_map(|e| match e.name {
969 ExportName::Named(n) => Some(n),
970 ExportName::Default => None,
971 })
972 .collect()
973 }
974
975 #[test]
976 fn is_css_file_css() {
977 assert!(is_css_file(Path::new("styles.css")));
978 }
979
980 #[test]
981 fn is_css_file_scss() {
982 assert!(is_css_file(Path::new("styles.scss")));
983 }
984
985 #[test]
986 fn is_css_file_sass() {
987 assert!(is_css_file(Path::new("styles.sass")));
988 }
989
990 #[test]
991 fn is_css_file_less() {
992 assert!(is_css_file(Path::new("styles.less")));
993 }
994
995 #[test]
996 fn is_css_file_rejects_js() {
997 assert!(!is_css_file(Path::new("app.js")));
998 }
999
1000 #[test]
1001 fn is_css_file_rejects_ts() {
1002 assert!(!is_css_file(Path::new("app.ts")));
1003 }
1004
1005 #[test]
1006 fn is_css_file_rejects_no_extension() {
1007 assert!(!is_css_file(Path::new("Makefile")));
1008 }
1009
1010 #[test]
1011 fn is_css_module_file_module_css() {
1012 assert!(is_css_module_file(Path::new("Component.module.css")));
1013 }
1014
1015 #[test]
1016 fn is_css_module_file_module_scss() {
1017 assert!(is_css_module_file(Path::new("Component.module.scss")));
1018 }
1019
1020 #[test]
1021 fn is_css_module_file_rejects_plain_css() {
1022 assert!(!is_css_module_file(Path::new("styles.css")));
1023 }
1024
1025 #[test]
1026 fn is_css_module_file_rejects_plain_scss() {
1027 assert!(!is_css_module_file(Path::new("styles.scss")));
1028 }
1029
1030 #[test]
1031 fn is_css_module_file_rejects_module_js() {
1032 assert!(!is_css_module_file(Path::new("utils.module.js")));
1033 }
1034
1035 #[test]
1036 fn extracts_single_class() {
1037 let names = export_names(".foo { color: red; }");
1038 assert_eq!(names, vec!["foo"]);
1039 }
1040
1041 #[test]
1042 fn extracts_multiple_classes() {
1043 let names = export_names(".foo { } .bar { }");
1044 assert_eq!(names, vec!["foo", "bar"]);
1045 }
1046
1047 #[test]
1048 fn extracts_nested_classes() {
1049 let names = export_names(".foo .bar { color: red; }");
1050 assert!(names.contains(&"foo".to_string()));
1051 assert!(names.contains(&"bar".to_string()));
1052 }
1053
1054 #[test]
1055 fn extracts_hyphenated_class() {
1056 let names = export_names(".my-class { }");
1057 assert_eq!(names, vec!["my-class"]);
1058 }
1059
1060 #[test]
1061 fn extracts_camel_case_class() {
1062 let names = export_names(".myClass { }");
1063 assert_eq!(names, vec!["myClass"]);
1064 }
1065
1066 #[test]
1067 fn extracts_class_inside_global_pseudo() {
1068 let names = export_names(":global(.globalClass) { color: red; }");
1071 assert_eq!(names, vec!["globalClass"]);
1072 }
1073
1074 #[test]
1075 fn extracts_class_inside_local_pseudo() {
1076 let names = export_names(":local(.localClass) { color: red; }");
1077 assert_eq!(names, vec!["localClass"]);
1078 }
1079
1080 #[test]
1081 fn extracts_classes_inside_negation() {
1082 let names = export_names(".btn:not(.disabled) { }");
1083 assert!(names.contains(&"btn".to_string()), "got {names:?}");
1084 assert!(names.contains(&"disabled".to_string()), "got {names:?}");
1085 }
1086
1087 #[test]
1088 fn extracts_classes_inside_is_and_where() {
1089 let names = export_names(":is(.a, .b) :where(.c) { }");
1090 for expected in ["a", "b", "c"] {
1091 assert!(
1092 names.contains(&expected.to_string()),
1093 "missing {expected} in {names:?}"
1094 );
1095 }
1096 }
1097
1098 #[test]
1099 fn extracts_underscore_class() {
1100 let names = export_names("._hidden { } .__wrapper { }");
1101 assert!(names.contains(&"_hidden".to_string()));
1102 assert!(names.contains(&"__wrapper".to_string()));
1103 }
1104
1105 #[test]
1106 fn pseudo_selector_hover() {
1107 let names = export_names(".foo:hover { color: blue; }");
1108 assert_eq!(names, vec!["foo"]);
1109 }
1110
1111 #[test]
1112 fn pseudo_selector_focus() {
1113 let names = export_names(".input:focus { outline: none; }");
1114 assert_eq!(names, vec!["input"]);
1115 }
1116
1117 #[test]
1118 fn pseudo_element_before() {
1119 let names = export_names(".icon::before { content: ''; }");
1120 assert_eq!(names, vec!["icon"]);
1121 }
1122
1123 #[test]
1124 fn combined_pseudo_selectors() {
1125 let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
1126 assert_eq!(names, vec!["btn"]);
1127 }
1128
1129 #[test]
1130 fn classes_inside_media_query() {
1131 let names = export_names(
1132 "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
1133 );
1134 assert!(names.contains(&"mobile-nav".to_string()));
1135 assert!(names.contains(&"desktop-nav".to_string()));
1136 }
1137
1138 #[test]
1139 fn classes_inside_multi_line_media_query() {
1140 let names =
1141 export_names("@media\n screen and (min-width: 600px)\n{\n .real { color: red; }\n}");
1142 assert_eq!(names, vec!["real"]);
1143 }
1144
1145 #[test]
1146 fn at_layer_statement_does_not_export() {
1147 let names = export_names("@layer foo.bar;");
1148 assert!(names.is_empty(), "got {names:?}");
1149 let names = export_names("@layer foo.bar, foo.baz;");
1150 assert!(names.is_empty(), "got {names:?}");
1151 }
1152
1153 #[test]
1154 fn at_layer_block_keeps_body_classes() {
1155 let names = export_names("@layer foo.bar { .root { color: red; } }");
1156 assert_eq!(names, vec!["root"]);
1157 }
1158
1159 #[test]
1160 fn at_layer_multiline_prelude_keeps_body_classes() {
1161 let names = export_names("@layer\n foo.bar\n{ .root { color: red; } }");
1162 assert_eq!(names, vec!["root"]);
1163 }
1164
1165 #[test]
1166 fn at_layer_with_nested_media_keeps_body() {
1167 let names =
1168 export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1169 assert_eq!(names, vec!["real"]);
1170 }
1171
1172 #[test]
1173 fn at_import_with_layer_attribute_does_not_export() {
1174 let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1175 assert!(names.is_empty(), "got {names:?}");
1176 }
1177
1178 #[test]
1179 fn class_then_at_layer_does_not_leak_prelude() {
1180 let names =
1181 export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1182 assert_eq!(names, vec!["outer", "inner"]);
1183 }
1184
1185 #[test]
1186 fn at_scope_keeps_selector_list_classes() {
1187 let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1188 assert!(names.contains(&"parent".to_string()), "got {names:?}");
1189 assert!(names.contains(&"child".to_string()), "got {names:?}");
1190 assert!(names.contains(&"title".to_string()), "got {names:?}");
1191 }
1192
1193 #[test]
1194 fn at_keyframes_numeric_step_is_not_class() {
1195 let names = export_names(
1196 "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1197 );
1198 assert!(names.is_empty(), "got {names:?}");
1199 }
1200
1201 #[test]
1202 fn at_webkit_keyframes_keeps_body_classes() {
1203 let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1204 assert_eq!(names, vec!["real"]);
1205 }
1206
1207 #[test]
1208 fn deduplicates_repeated_class() {
1209 let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1210 assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1211 }
1212
1213 #[test]
1214 fn empty_source() {
1215 let names = export_names("");
1216 assert!(names.is_empty());
1217 }
1218
1219 #[test]
1220 fn no_classes() {
1221 let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1222 assert!(names.is_empty());
1223 }
1224
1225 #[test]
1226 fn ignores_classes_in_block_comments() {
1227 let names = export_names("/* .fake { } */ .real { }");
1228 assert!(!names.contains(&"fake".to_string()));
1229 assert!(names.contains(&"real".to_string()));
1230 }
1231
1232 #[test]
1233 fn ignores_classes_in_scss_line_comments() {
1234 let exports = extract_css_module_exports("// .fake\n.real { }", true);
1235 let names: Vec<_> = exports
1236 .iter()
1237 .filter_map(|e| match &e.name {
1238 ExportName::Named(n) => Some(n.as_str()),
1239 ExportName::Default => None,
1240 })
1241 .collect();
1242 assert_eq!(names, vec!["real"]);
1243 }
1244
1245 #[test]
1246 fn ignores_classes_in_strings() {
1247 let names = export_names(r#".real { content: ".fake"; }"#);
1248 assert!(names.contains(&"real".to_string()));
1249 assert!(!names.contains(&"fake".to_string()));
1250 }
1251
1252 #[test]
1253 fn ignores_classes_in_url() {
1254 let names = export_names(".real { background: url(./images/hero.png); }");
1255 assert!(names.contains(&"real".to_string()));
1256 assert!(!names.contains(&"png".to_string()));
1257 }
1258
1259 #[test]
1260 fn mask_css_block_comment() {
1261 let source = "/* removed */ .kept { }";
1262 let result = mask_css_comments(source, false);
1263 assert!(!result.contains("removed"));
1264 assert_eq!(result.len(), source.len());
1265 assert_eq!(result.find(".kept"), source.find(".kept"));
1266 }
1267
1268 #[test]
1269 fn mask_scss_line_comment() {
1270 let source = "// removed\n.kept { }";
1271 let result = mask_css_comments(source, true);
1272 assert!(!result.contains("removed"));
1273 assert_eq!(result.len(), source.len());
1274 assert_eq!(result.find(".kept"), source.find(".kept"));
1275 }
1276
1277 #[test]
1278 fn mask_scss_preserves_css_outside_comments() {
1279 let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1280 let result = mask_css_comments(source, true);
1281 assert!(result.contains(".visible"));
1282 }
1283
1284 #[test]
1285 fn url_import_http() {
1286 assert!(is_css_url_import("http://example.com/style.css"));
1287 }
1288
1289 #[test]
1290 fn url_import_https() {
1291 assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1292 }
1293
1294 #[test]
1295 fn url_import_data() {
1296 assert!(is_css_url_import("data:text/css;base64,abc"));
1297 }
1298
1299 #[test]
1300 fn url_import_local_not_skipped() {
1301 assert!(!is_css_url_import("./local.css"));
1302 }
1303
1304 #[test]
1305 fn url_import_bare_specifier_not_skipped() {
1306 assert!(!is_css_url_import("tailwindcss"));
1307 }
1308
1309 #[test]
1310 fn normalize_relative_dot_path_unchanged() {
1311 assert_eq!(
1312 normalize_css_import_path("./reset.css".to_string(), false),
1313 "./reset.css"
1314 );
1315 }
1316
1317 #[test]
1318 fn normalize_parent_relative_path_unchanged() {
1319 assert_eq!(
1320 normalize_css_import_path("../shared.scss".to_string(), false),
1321 "../shared.scss"
1322 );
1323 }
1324
1325 #[test]
1326 fn normalize_absolute_path_unchanged() {
1327 assert_eq!(
1328 normalize_css_import_path("/styles/main.css".to_string(), false),
1329 "/styles/main.css"
1330 );
1331 }
1332
1333 #[test]
1334 fn normalize_url_unchanged() {
1335 assert_eq!(
1336 normalize_css_import_path("https://example.com/style.css".to_string(), false),
1337 "https://example.com/style.css"
1338 );
1339 }
1340
1341 #[test]
1342 fn normalize_bare_css_gets_dot_slash() {
1343 assert_eq!(
1344 normalize_css_import_path("app.css".to_string(), false),
1345 "./app.css"
1346 );
1347 }
1348
1349 #[test]
1350 fn normalize_css_package_subpath_stays_bare() {
1351 assert_eq!(
1352 normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1353 "tailwindcss/theme.css"
1354 );
1355 }
1356
1357 #[test]
1358 fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1359 assert_eq!(
1360 normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1361 "highlight.js/styles/github.css"
1362 );
1363 }
1364
1365 #[test]
1366 fn normalize_bare_scss_gets_dot_slash() {
1367 assert_eq!(
1368 normalize_css_import_path("vars.scss".to_string(), false),
1369 "./vars.scss"
1370 );
1371 }
1372
1373 #[test]
1374 fn normalize_bare_sass_gets_dot_slash() {
1375 assert_eq!(
1376 normalize_css_import_path("main.sass".to_string(), false),
1377 "./main.sass"
1378 );
1379 }
1380
1381 #[test]
1382 fn normalize_bare_less_gets_dot_slash() {
1383 assert_eq!(
1384 normalize_css_import_path("theme.less".to_string(), false),
1385 "./theme.less"
1386 );
1387 }
1388
1389 #[test]
1390 fn normalize_bare_js_extension_stays_bare() {
1391 assert_eq!(
1392 normalize_css_import_path("module.js".to_string(), false),
1393 "module.js"
1394 );
1395 }
1396
1397 #[test]
1398 fn normalize_scss_bare_partial_gets_dot_slash() {
1399 assert_eq!(
1400 normalize_css_import_path("variables".to_string(), true),
1401 "./variables"
1402 );
1403 }
1404
1405 #[test]
1406 fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1407 assert_eq!(
1408 normalize_css_import_path("base/reset".to_string(), true),
1409 "./base/reset"
1410 );
1411 }
1412
1413 #[test]
1414 fn normalize_scss_builtin_stays_bare() {
1415 assert_eq!(
1416 normalize_css_import_path("sass:math".to_string(), true),
1417 "sass:math"
1418 );
1419 }
1420
1421 #[test]
1422 fn normalize_scss_relative_path_unchanged() {
1423 assert_eq!(
1424 normalize_css_import_path("../styles/variables".to_string(), true),
1425 "../styles/variables"
1426 );
1427 }
1428
1429 #[test]
1430 fn normalize_css_bare_extensionless_stays_bare() {
1431 assert_eq!(
1432 normalize_css_import_path("tailwindcss".to_string(), false),
1433 "tailwindcss"
1434 );
1435 }
1436
1437 #[test]
1438 fn normalize_scoped_package_with_css_extension_stays_bare() {
1439 assert_eq!(
1440 normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1441 "@fontsource/monaspace-neon/400.css"
1442 );
1443 }
1444
1445 #[test]
1446 fn normalize_scoped_package_with_scss_extension_stays_bare() {
1447 assert_eq!(
1448 normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1449 "@company/design-system/tokens.scss"
1450 );
1451 }
1452
1453 #[test]
1454 fn normalize_scoped_package_without_extension_stays_bare() {
1455 assert_eq!(
1456 normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1457 "@fallow/design-system/styles"
1458 );
1459 }
1460
1461 #[test]
1462 fn normalize_scoped_package_extensionless_scss_stays_bare() {
1463 assert_eq!(
1464 normalize_css_import_path("@company/tokens".to_string(), true),
1465 "@company/tokens"
1466 );
1467 }
1468
1469 #[test]
1470 fn normalize_path_alias_with_css_extension_stays_bare() {
1471 assert_eq!(
1472 normalize_css_import_path("@/components/Button.css".to_string(), false),
1473 "@/components/Button.css"
1474 );
1475 }
1476
1477 #[test]
1478 fn normalize_path_alias_extensionless_stays_bare() {
1479 assert_eq!(
1480 normalize_css_import_path("@/styles/variables".to_string(), false),
1481 "@/styles/variables"
1482 );
1483 }
1484
1485 #[test]
1486 fn mask_css_no_comments() {
1487 let source = ".foo { color: red; }";
1488 assert_eq!(mask_css_comments(source, false), source);
1489 }
1490
1491 #[test]
1492 fn mask_css_multiple_block_comments() {
1493 let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1494 let result = mask_css_comments(source, false);
1495 assert!(!result.contains("comment-one"));
1496 assert!(!result.contains("comment-two"));
1497 assert!(result.contains(".foo"));
1498 assert!(result.contains(".bar"));
1499 }
1500
1501 #[test]
1502 fn mask_scss_does_not_affect_non_scss() {
1503 let source = "// this stays\n.foo { }";
1504 let result = mask_css_comments(source, false);
1505 assert!(result.contains("// this stays"));
1506 }
1507
1508 #[test]
1509 fn css_module_parses_suppressions() {
1510 let info = parse_css_to_module(
1511 fallow_types::discover::FileId(0),
1512 Path::new("Component.module.css"),
1513 "/* fallow-ignore-file */\n.btn { color: red; }",
1514 0,
1515 );
1516 assert!(!info.suppressions.is_empty());
1517 assert_eq!(info.suppressions[0].line, 0);
1518 }
1519
1520 #[test]
1521 fn extracts_class_starting_with_underscore() {
1522 let names = export_names("._private { } .__dunder { }");
1523 assert!(names.contains(&"_private".to_string()));
1524 assert!(names.contains(&"__dunder".to_string()));
1525 }
1526
1527 #[test]
1528 fn ignores_id_selectors() {
1529 let names = export_names("#myId { color: red; }");
1530 assert!(!names.contains(&"myId".to_string()));
1531 }
1532
1533 #[test]
1534 fn ignores_element_selectors() {
1535 let names = export_names("div { color: red; } span { }");
1536 assert!(names.is_empty());
1537 }
1538
1539 #[test]
1540 fn extract_css_imports_at_import_quoted() {
1541 let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1542 assert_eq!(imports, vec!["./reset.css"]);
1543 }
1544
1545 #[test]
1546 fn extract_css_imports_package_subpath_stays_bare() {
1547 let imports =
1548 extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1549 assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1550 }
1551
1552 #[test]
1553 fn extract_css_imports_at_import_url() {
1554 let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1555 assert_eq!(imports, vec!["./reset.css"]);
1556 }
1557
1558 #[test]
1559 fn extract_css_imports_skips_remote_urls() {
1560 let imports =
1561 extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1562 assert!(imports.is_empty());
1563 }
1564
1565 #[test]
1566 fn extract_css_imports_scss_use_normalizes_partial() {
1567 let imports = extract_css_imports(r#"@use "variables";"#, true);
1568 assert_eq!(imports, vec!["./variables"]);
1569 }
1570
1571 #[test]
1572 fn extract_css_imports_scss_forward_normalizes_partial() {
1573 let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1574 assert_eq!(imports, vec!["./tokens"]);
1575 }
1576
1577 #[test]
1578 fn extract_css_imports_skips_comments() {
1579 let imports = extract_css_imports(
1580 r#"/* @import "./hidden.scss"; */
1581@use "real";"#,
1582 true,
1583 );
1584 assert_eq!(imports, vec!["./real"]);
1585 }
1586
1587 #[test]
1588 fn extract_css_imports_at_plugin_keeps_package_bare() {
1589 let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1590 assert_eq!(imports, vec!["daisyui"]);
1591 }
1592
1593 #[test]
1594 fn extract_css_imports_at_plugin_tracks_relative_file() {
1595 let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1596 assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1597 }
1598
1599 #[test]
1600 fn extract_css_imports_scss_at_import_kept_relative() {
1601 let imports = extract_css_imports(r"@import 'Foo';", true);
1602 assert_eq!(imports, vec!["./Foo"]);
1603 }
1604
1605 #[test]
1606 fn extract_css_imports_additional_data_string_body() {
1607 let body = r#"@use "./src/styles/global.scss";"#;
1608 let imports = extract_css_imports(body, true);
1609 assert_eq!(imports, vec!["./src/styles/global.scss"]);
1610 }
1611
1612 #[test]
1613 fn mask_with_whitespace_preserves_byte_length() {
1614 let src = "/* hello */ .foo { }";
1615 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1616 assert_eq!(masked.len(), src.len());
1617 assert!(masked.is_char_boundary(src.len()));
1618 }
1619
1620 #[test]
1621 fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1622 let src = "/* \u{2713} */ .foo { }";
1623 let foo_offset = src.find(".foo").expect("`.foo` present");
1624 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1625 assert_eq!(masked.len(), src.len());
1626 assert_eq!(masked.find(".foo"), Some(foo_offset));
1627 }
1628
1629 fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1632 let offsets = fallow_types::extract::compute_line_offsets(source);
1633 fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1634 }
1635
1636 #[test]
1637 fn span_points_at_real_class_declaration_line() {
1638 let source = "\n\n\n\n.foo { color: red; }\n";
1639 let exports = extract_css_module_exports(source, false);
1640 assert_eq!(exports.len(), 1);
1641 let span = exports[0].span;
1642 let (line, col) = span_line_col(source, span.start);
1643 assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1644 assert_eq!(
1645 col, 1,
1646 "column points at `f` in `.foo` (post-dot identifier)"
1647 );
1648 assert_eq!(
1649 &source[span.start as usize..span.end as usize],
1650 "foo",
1651 "span range must slice to the class identifier in the original source"
1652 );
1653 }
1654
1655 #[test]
1656 fn span_survives_multibyte_comment_prefix() {
1657 let source = "/* \u{2713} */\n.foo { }";
1658 let exports = extract_css_module_exports(source, false);
1659 assert_eq!(exports.len(), 1);
1660 let span = exports[0].span;
1661 assert!(
1662 source.is_char_boundary(span.start as usize),
1663 "span.start must lie on a UTF-8 char boundary"
1664 );
1665 assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1666 }
1667
1668 #[test]
1669 fn span_skips_at_layer_prelude_dot_segments() {
1670 let source = "@layer foo.bar { }\n.root { }\n";
1671 let exports = extract_css_module_exports(source, false);
1672 let names: Vec<_> = exports
1673 .iter()
1674 .filter_map(|e| match &e.name {
1675 ExportName::Named(n) => Some(n.as_str()),
1676 ExportName::Default => None,
1677 })
1678 .collect();
1679 assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1680 let span = exports[0].span;
1681 let (line, _col) = span_line_col(source, span.start);
1682 assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1683 assert_eq!(&source[span.start as usize..span.end as usize], "root");
1684 }
1685
1686 #[test]
1687 fn span_skips_classes_in_strings() {
1688 let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1689 let exports = extract_css_module_exports(source, false);
1690 let names: Vec<_> = exports
1691 .iter()
1692 .filter_map(|e| match &e.name {
1693 ExportName::Named(n) => Some(n.as_str()),
1694 ExportName::Default => None,
1695 })
1696 .collect();
1697 assert_eq!(names, vec!["real", "also-real"]);
1698 for export in &exports {
1699 let span = export.span;
1700 let slice = &source[span.start as usize..span.end as usize];
1701 match &export.name {
1702 ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1703 ExportName::Default => unreachable!("CSS modules emit only named exports"),
1704 }
1705 }
1706 }
1707
1708 #[test]
1709 fn span_deduplicates_to_first_occurrence() {
1710 let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1711 let exports = extract_css_module_exports(source, false);
1712 assert_eq!(exports.len(), 1);
1713 let (line, _col) = span_line_col(source, exports[0].span.start);
1714 assert_eq!(
1715 line, 1,
1716 "first occurrence wins for deduplicated class names"
1717 );
1718 }
1719
1720 #[test]
1721 fn span_inside_media_query() {
1722 let source =
1723 "@media (max-width: 768px) {\n .mobile { display: block; }\n .desktop { }\n}\n";
1724 let exports = extract_css_module_exports(source, false);
1725 let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1726 .iter()
1727 .filter_map(|e| match &e.name {
1728 ExportName::Named(n) => Some((n.as_str(), e.span)),
1729 ExportName::Default => None,
1730 })
1731 .collect();
1732 let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1733 let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1734 assert_eq!(mobile_line, 2);
1735 assert_eq!(desktop_line, 3);
1736 }
1737
1738 #[test]
1739 fn at_layer_only_module_emits_no_exports() {
1740 let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1741 assert!(exports.is_empty());
1742 }
1743
1744 #[test]
1745 fn parse_css_to_module_resolves_real_line_offsets() {
1746 let source = "\n\n\n\n.foo { color: red; }\n";
1747 let info = parse_css_to_module(
1748 fallow_types::discover::FileId(0),
1749 Path::new("Component.module.css"),
1750 source,
1751 0,
1752 );
1753 assert_eq!(info.exports.len(), 1);
1754 let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1755 &info.line_offsets,
1756 info.exports[0].span.start,
1757 );
1758 assert_eq!(line, 5, "downstream line must equal the source line");
1759 }
1760
1761 fn theme_token_names(source: &str) -> Vec<String> {
1762 scan_theme_blocks(source)
1763 .tokens
1764 .into_iter()
1765 .map(|t| t.name)
1766 .collect()
1767 }
1768
1769 #[test]
1770 fn theme_single_block_collects_tokens() {
1771 let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
1772 assert_eq!(names, vec!["color-brand", "radius-card"]);
1773 }
1774
1775 #[test]
1776 fn theme_token_values_are_normalized() {
1777 let scan = scan_theme_blocks("@theme {\n --color-brand: rgb( 255 0 0 );\n}");
1778 assert_eq!(scan.tokens[0].name, "color-brand");
1779 assert_eq!(scan.tokens[0].value, "rgb( 255 0 0 )");
1780 }
1781
1782 #[test]
1783 fn theme_dashed_multi_segment_names() {
1784 let names = theme_token_names(
1785 "@theme {\n --font-weight-heavy: 900;\n --inset-shadow-glow: 0 0 4px red;\n}",
1786 );
1787 assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
1788 }
1789
1790 #[test]
1791 fn theme_inline_and_static_modifiers() {
1792 assert_eq!(
1793 theme_token_names("@theme inline { --color-a: red; }"),
1794 vec!["color-a"]
1795 );
1796 assert_eq!(
1797 theme_token_names("@theme static { --color-b: red; }"),
1798 vec!["color-b"]
1799 );
1800 }
1801
1802 #[test]
1803 fn theme_multiple_blocks_union() {
1804 let names = theme_token_names(
1805 "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
1806 );
1807 assert_eq!(names, vec!["color-a", "spacing-gutter"]);
1808 }
1809
1810 #[test]
1811 fn theme_reset_form_excluded() {
1812 let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
1814 assert_eq!(names, vec!["color-brand"]);
1815 }
1816
1817 #[test]
1818 fn theme_no_block_yields_nothing() {
1819 assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
1820 }
1821
1822 #[test]
1823 fn theme_line_numbers() {
1824 let scan = scan_theme_blocks("@theme {\n --color-a: red;\n --radius-b: 4px;\n}");
1825 assert_eq!(scan.tokens[0].line, 2);
1826 assert_eq!(scan.tokens[1].line, 3);
1827 }
1828
1829 #[test]
1830 fn theme_token_backs_token_via_var() {
1831 let scan = scan_theme_blocks(
1832 "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
1833 );
1834 assert!(
1835 scan.theme_var_reads
1836 .iter()
1837 .any(|(name, _)| name == "color-brand")
1838 );
1839 }
1840
1841 #[test]
1842 fn theme_var_read_carries_line() {
1843 let scan = scan_theme_blocks(
1846 "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
1847 );
1848 assert_eq!(
1849 scan.theme_var_reads,
1850 vec![("color-brand".to_string(), 3u32)]
1851 );
1852 }
1853
1854 #[test]
1855 fn css_var_reads_locate_outside_theme_and_exclude_interior() {
1856 let source = "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}\n\n.btn {\n color: var(--color-brand);\n}\n";
1860 assert_eq!(
1861 extract_css_var_reads_located(source),
1862 vec![("color-brand".to_string(), 7u32)],
1863 "only the .btn read (line 7) is a css-var; the @theme-interior read is excluded"
1864 );
1865
1866 assert!(
1868 extract_css_var_reads_located("@theme {\n --a: #fff;\n --b: var(--a);\n}",)
1869 .is_empty(),
1870 "a @theme-interior-only var() read is not a css-var consumer"
1871 );
1872 }
1873
1874 #[test]
1875 fn css_var_reads_line_match_naive_reference_on_dense_line() {
1876 use std::fmt::Write as _;
1882 let mut src = String::from(".x {");
1883 for i in 0..500 {
1884 let _ = write!(src, " color: var(--t{i});");
1885 }
1886 src.push_str(" }\n.y { color: var(--tail); }\n");
1887
1888 let got = extract_css_var_reads_located(&src);
1889
1890 let want: Vec<(String, u32)> = CSS_VAR_REF_RE
1892 .captures_iter(&src)
1893 .filter_map(|cap| cap.get(0).zip(cap.get(1)))
1894 .map(|(whole, name)| {
1895 (
1896 name.as_str().to_owned(),
1897 line_at_offset(&src, whole.start()),
1898 )
1899 })
1900 .collect();
1901
1902 assert_eq!(got, want);
1903 assert!(got.len() > 500, "expected the dense line plus the trailer");
1904 assert_eq!(got.last().map(|(_, l)| *l), Some(2));
1906 assert!(got[..got.len() - 1].iter().all(|(_, l)| *l == 1));
1907 }
1908
1909 #[test]
1910 fn theme_string_braces_do_not_truncate_block() {
1911 let scan = scan_theme_blocks(
1912 "@theme {\n --font-label: \"}\";\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
1913 );
1914 assert_eq!(
1915 scan.tokens
1916 .iter()
1917 .map(|token| token.name.as_str())
1918 .collect::<Vec<_>>(),
1919 vec!["font-label", "color-brand", "color-button"]
1920 );
1921 assert!(
1922 scan.theme_var_reads
1923 .iter()
1924 .any(|(name, _)| name == "color-brand")
1925 );
1926 }
1927
1928 #[test]
1929 fn theme_nested_keyframes_body_not_collected() {
1930 let names = theme_token_names(
1933 "@theme {\n --animate-spin: spin 1s linear infinite;\n @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
1934 );
1935 assert_eq!(names, vec!["animate-spin"]);
1936 }
1937
1938 #[test]
1939 fn theme_comment_block_ignored() {
1940 let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
1941 assert!(names.is_empty(), "got {names:?}");
1942 }
1943
1944 #[test]
1945 fn theme_deduplicates_repeated_token() {
1946 let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
1947 assert_eq!(names, vec!["color-a"]);
1948 }
1949
1950 #[test]
1951 fn apply_tokens_basic() {
1952 let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
1953 assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
1954 }
1955
1956 #[test]
1957 fn apply_tokens_strips_important() {
1958 let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
1959 assert_eq!(tokens, vec!["text-brand", "font-bold"]);
1960 }
1961
1962 #[test]
1963 fn apply_tokens_ignored_in_comments() {
1964 let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
1965 assert!(tokens.is_empty(), "got {tokens:?}");
1966 }
1967}