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