scoped-sass 0.1.0

Procedural macros for compiling scoped Sass modules into Rust code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Procedural macros for compiling scoped Sass files into Rust modules.
//!
//! This crate exposes two main macros:
//!
//! - [`scoped_scss!`] compiles a single `.scss` or `.sass` file into one Rust module.
//! - [`scoped_scss_auto!`] scans a directory recursively and generates a nested module tree.
//!
//! [`scoped_sass_auto!`] is a shorter alias for [`scoped_scss_auto!`].
//!
//! # Example
//!
//! ```ignore
//! use scoped_sass::scoped_scss;
//!
//! scoped_scss!(pub mod button, "src/components/button.scss");
//!
//! fn render() {
//!     let css = button::CSS;
//!     let root_class = button::classes::root;
//! }
//! ```
//!
//! # Leptos integration
//!
//! The auto macros generate `global_styles()` and `app_styles()` helpers
//! that return `impl leptos::prelude::IntoView`, so consumers should depend on `leptos`
//! when using [`scoped_scss_auto!`] or [`scoped_sass_auto!`].

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{format_ident, quote};
use scoped_sass_core::ScopedModule;
use std::collections::{BTreeMap, HashSet};
use std::env;
use std::fs;
use std::io;
use std::path::{Component, Path, PathBuf};
use syn::parse::{Parse, ParseStream};
use syn::{Ident, LitStr, Result, Token, Visibility, parse_macro_input};

struct ScopedScssInput {
    vis: Visibility,
    _mod_token: Token![mod],
    module_name: Ident,
    _comma: Token![,],
    scss_path: LitStr,
}

impl Parse for ScopedScssInput {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(Self {
            vis: input.parse()?,
            _mod_token: input.parse()?,
            module_name: input.parse()?,
            _comma: input.parse()?,
            scss_path: input.parse()?,
        })
    }
}

struct ScopedScssAutoInput {
    vis: Visibility,
    _comma: Token![,],
    source_dir: LitStr,
    inject: bool,
    output_file: Option<LitStr>,
    href: Option<LitStr>,
}

#[derive(Default)]
struct ModuleTreeNode {
    children: BTreeMap<String, ModuleTreeNode>,
    module: Option<ScopedModuleEntry>,
}

struct ScopedModuleEntry {
    absolute_path: PathBuf,
    compiled: ScopedModule,
}

impl Parse for ScopedScssAutoInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let vis: Visibility = input.parse()?;
        let comma: Token![,] = input.parse()?;
        let source_dir: LitStr = input.parse()?;

        let mut inject = true;
        let mut output_file: Option<LitStr> = None;
        let mut href: Option<LitStr> = None;

        while !input.is_empty() {
            let _: Token![,] = input.parse()?;
            let key: Ident = input.parse()?;
            let _: Token![=] = input.parse()?;

            if key == "inject" {
                let value: syn::LitBool = input.parse()?;
                inject = value.value();
            } else if key == "output_file" {
                let value: LitStr = input.parse()?;
                output_file = Some(value);
            } else if key == "href" {
                let value: LitStr = input.parse()?;
                href = Some(value);
            } else {
                return Err(syn::Error::new(
                    key.span(),
                    "Unknown option. Supported: inject = <bool>, output_file = \"<path>\", href = \"<url>\"",
                ));
            }
        }

        Ok(Self {
            vis,
            _comma: comma,
            source_dir,
            inject,
            output_file,
            href,
        })
    }
}

/// Compiles a single Sass file into a Rust module with scoped class names.
///
/// The macro accepts the form:
///
/// ```text
/// scoped_scss!(<visibility> mod <module_name>, "<path/to/file.scss>");
/// ```
///
/// The path is resolved relative to `CARGO_MANIFEST_DIR`.
///
/// The generated module contains:
///
/// - `CSS`: the transformed CSS with deterministic scoped suffixes
/// - `SUFFIX`: the suffix applied to local class selectors
/// - `classes::<name>` constants for every discovered source class
///
/// # Example
///
/// ```ignore
/// use scoped_sass::scoped_scss;
///
/// scoped_scss!(pub mod button, "src/components/button.scss");
///
/// fn render() {
///     let css = button::CSS;
///     let root_class = button::classes::root;
/// }
/// ```
#[proc_macro]
pub fn scoped_scss(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ScopedScssInput);

    let manifest_dir = match std::env::var("CARGO_MANIFEST_DIR") {
        Ok(value) => value,
        Err(err) => {
            return syn::Error::new(
                Span::call_site(),
                format!("CARGO_MANIFEST_DIR is not available: {err}"),
            )
            .to_compile_error()
            .into();
        }
    };

    let relative = input.scss_path.value();
    let absolute_path = PathBuf::from(manifest_dir).join(&relative);
    if !absolute_path.exists() {
        return syn::Error::new(
            input.scss_path.span(),
            format!("SCSS file not found: {}", absolute_path.display()),
        )
        .to_compile_error()
        .into();
    }

    let compiled = match scoped_sass_core::compile_module_file(&absolute_path, Default::default())
    {
        Ok(module) => module,
        Err(err) => {
            return syn::Error::new(
                input.scss_path.span(),
                format!(
                    "Failed to compile scoped SCSS '{}': {err}",
                    absolute_path.display()
                ),
            )
            .to_compile_error()
            .into();
        }
    };

    module_tokens(&input.vis, &input.module_name, &absolute_path, &compiled).into()
}

/// Compiles every Sass file under a directory and generates a nested module tree.
///
/// The macro accepts the form:
///
/// ```text
/// scoped_scss_auto!(
///     <visibility>,
///     "<source_dir>"
///     [, inject = <bool>]
///     [, output_file = "<path>"]
///     [, href = "<url>"]
/// );
/// ```
///
/// The source directory is resolved relative to `CARGO_MANIFEST_DIR`.
///
/// Generated items include:
///
/// - `pub mod scoped { ... }` with one module per discovered Sass file
/// - `global_styles()` for inline style injection
/// - `app_styles()` as the high-level application stylesheet entry point
/// - `cls!(...)` for joining optional and required class fragments
///
/// When `inject = true`, the generated style helpers render inline `<style>` elements
/// using `leptos`. When `inject = false` and `output_file` is set, `app_styles()`
/// renders an `@import` reference instead.
///
/// # Example
///
/// ```ignore
/// use scoped_sass::scoped_scss_auto;
///
/// scoped_scss_auto!(
///     pub,
///     "src",
///     inject = true,
///     output_file = "public/styles/scoped.generated.css"
/// );
///
/// fn render() {
///     let root_class = scoped::components::button::classes::root;
///     let styles = app_styles();
/// }
/// ```
#[proc_macro]
pub fn scoped_scss_auto(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ScopedScssAutoInput);

    let manifest_dir = match std::env::var("CARGO_MANIFEST_DIR") {
        Ok(value) => PathBuf::from(value),
        Err(err) => {
            return syn::Error::new(
                Span::call_site(),
                format!("CARGO_MANIFEST_DIR is not available: {err}"),
            )
            .to_compile_error()
            .into();
        }
    };

    let source_dir = manifest_dir.join(input.source_dir.value());
    if !source_dir.exists() {
        return syn::Error::new(
            input.source_dir.span(),
            format!("Source directory not found: {}", source_dir.display()),
        )
        .to_compile_error()
        .into();
    }

    let running_in_rust_analyzer = is_rust_analyzer();

    let mut scss_files = Vec::new();
    if let Err(err) = collect_scss_files(&source_dir, &mut scss_files) {
        return syn::Error::new(
            input.source_dir.span(),
            format!(
                "Failed to scan source directory '{}': {err}",
                source_dir.display()
            ),
        )
        .to_compile_error()
        .into();
    }
    scss_files.sort();

    let mut module_tree = ModuleTreeNode::default();
    let mut style_items = Vec::new();
    let mut merged_css = String::new();

    for scss_path in &scss_files {
        let relative_path = scss_path.strip_prefix(&source_dir).unwrap_or(scss_path);
        let mut module_path_segments = Vec::<String>::new();
        if let Some(parent) = relative_path.parent() {
            for component in parent.components() {
                let Component::Normal(segment) = component else {
                    continue;
                };
                module_path_segments.push(sanitize_ident(&segment.to_string_lossy()));
            }
        }

        let Some(stem) = scss_path.file_stem().and_then(|s| s.to_str()) else {
            return syn::Error::new(
                Span::call_site(),
                format!("Invalid SCSS file name: {}", scss_path.display()),
            )
            .to_compile_error()
            .into();
        };

        let module_name = sanitize_ident(stem);
        module_path_segments.push(module_name);

        let compiled = match scoped_sass_core::compile_module_file(scss_path, Default::default())
        {
            Ok(module) => module,
            Err(err) => {
                return syn::Error::new(
                    Span::call_site(),
                    format!(
                        "Failed to compile scoped SCSS '{}': {err}",
                        scss_path.display()
                    ),
                )
                .to_compile_error()
                .into();
            }
        };
        let css_for_merge = compiled.css.clone();

        if let Err(err) = insert_module_into_tree(
            &mut module_tree,
            &module_path_segments,
            scss_path.to_path_buf(),
            compiled,
        ) {
            return syn::Error::new(Span::call_site(), err)
                .to_compile_error()
                .into();
        }

        let css_path = module_path_segments
            .iter()
            .map(|segment| format_ident!("{}", segment))
            .collect::<Vec<_>>();
        style_items.push(quote! { leptos::html::style().child(scoped::#(#css_path::)*CSS) });

        if !merged_css.is_empty() {
            merged_css.push('\n');
        }
        merged_css.push_str(&css_for_merge);
    }

    if let Some(output_file) = &input.output_file
        && !running_in_rust_analyzer
    {
        let output_path = manifest_dir.join(output_file.value());
        if let Err(err) = write_if_changed(&output_path, &merged_css) {
            return syn::Error::new(
                output_file.span(),
                format!(
                    "Failed to write generated stylesheet '{}': {err}",
                    output_path.display()
                ),
            )
            .to_compile_error()
            .into();
        }
    }

    let global_styles = if !input.inject || style_items.is_empty() {
        quote! {
            pub fn global_styles() -> impl leptos::prelude::IntoView {
                ()
            }
        }
    } else {
        quote! {
            pub fn global_styles() -> impl leptos::prelude::IntoView {
                (#(#style_items),*)
            }
        }
    };

    let app_styles = if input.inject && !style_items.is_empty() {
        quote! {
            pub fn app_styles() -> impl leptos::prelude::IntoView {
                global_styles()
            }
        }
    } else if let Some(output_file) = &input.output_file {
        let href = input
            .href
            .as_ref()
            .map(|v| v.value())
            .unwrap_or_else(|| default_href_from_output_path(&output_file.value()));
        let import_css = LitStr::new(&format!("@import url('{href}');"), Span::call_site());

        quote! {
            pub fn app_styles() -> impl leptos::prelude::IntoView {
                leptos::html::style().child(#import_css)
            }
        }
    } else {
        quote! {
            pub fn app_styles() -> impl leptos::prelude::IntoView {
                ()
            }
        }
    };

    let vis = &input.vis;
    let scoped_tree = scoped_tree_tokens(&module_tree);
    let expanded = quote! {
        #vis mod scoped {
            pub trait ClsArg {
                fn push_to(self, out: &mut ::std::vec::Vec<::std::string::String>);
            }

            impl ClsArg for &str {
                fn push_to(self, out: &mut ::std::vec::Vec<::std::string::String>) {
                    if !self.is_empty() {
                        out.push(self.to_string());
                    }
                }
            }

            impl ClsArg for String {
                fn push_to(self, out: &mut ::std::vec::Vec<::std::string::String>) {
                    if !self.is_empty() {
                        out.push(self);
                    }
                }
            }

            impl ClsArg for &String {
                fn push_to(self, out: &mut ::std::vec::Vec<::std::string::String>) {
                    if !self.is_empty() {
                        out.push(self.clone());
                    }
                }
            }

            impl<T> ClsArg for Option<T>
            where
                T: ClsArg,
            {
                fn push_to(self, out: &mut ::std::vec::Vec<::std::string::String>) {
                    if let Some(value) = self {
                        value.push_to(out);
                    }
                }
            }

            pub fn push_cls_arg<T>(out: &mut ::std::vec::Vec<::std::string::String>, value: T)
            where
                T: ClsArg,
            {
                value.push_to(out);
            }

            #(#scoped_tree)*
        }

        #[allow(unused_macros)]
        macro_rules! cls {
            ($($arg:expr),* $(,)?) => {{
                let mut __parts: ::std::vec::Vec<::std::string::String> = ::std::vec::Vec::new();
                $(
                    $crate::scoped::push_cls_arg(&mut __parts, $arg);
                )*
                __parts.join(" ")
            }};
        }

        #[allow(unused_imports)]
        pub(crate) use cls;

        #global_styles
        #app_styles
    };

    let _ = write_generated_rust_snapshot(&manifest_dir, &expanded);

    expanded.into()
}

/// Alias for [`scoped_scss_auto!`].
///
/// This exists for users who prefer a shorter macro name.
#[proc_macro]
pub fn scoped_sass_auto(input: TokenStream) -> TokenStream {
    scoped_scss_auto(input)
}

fn collect_scss_files(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_scss_files(&path, out)?;
            continue;
        }

        let ext = path.extension().and_then(|e| e.to_str());
        if matches!(ext, Some("scss") | Some("sass")) {
            out.push(path);
        }
    }
    Ok(())
}

fn write_if_changed(path: &Path, content: &str) -> std::io::Result<()> {
    if let Ok(current) = fs::read_to_string(path)
        && current == content
    {
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, content)
}

fn module_tokens(
    vis: &Visibility,
    module_name: &Ident,
    absolute_path: &Path,
    compiled: &ScopedModule,
) -> proc_macro2::TokenStream {
    let module_body = module_body_tokens(absolute_path, compiled);
    quote! {
        #vis mod #module_name {
            #module_body
        }
    }
}

fn module_body_tokens(absolute_path: &Path, compiled: &ScopedModule) -> proc_macro2::TokenStream {
    let mut used_field_names = HashSet::new();
    let mut field_idents = Vec::new();
    let mut field_values = Vec::new();
    for (class_name, transformed) in &compiled.classes {
        let base = sanitize_ident(class_name);
        let mut candidate = base.clone();
        let mut idx = 1usize;
        while !used_field_names.insert(candidate.clone()) {
            idx += 1;
            candidate = format!("{base}_{idx}");
        }

        field_idents.push(format_ident!("{}", candidate));
        field_values.push(transformed.clone());
    }

    let classes_module = if field_idents.is_empty() {
        quote! {}
    } else {
        quote! {
            pub mod classes {
                #(#[allow(non_upper_case_globals)] pub const #field_idents: &'static str = #field_values;)*
            }
        }
    };

    let abs_lit = LitStr::new(&absolute_path.to_string_lossy(), Span::call_site());
    let css_lit = LitStr::new(&compiled.css, Span::call_site());
    let suffix_lit = LitStr::new(&compiled.suffix, Span::call_site());
    let dependency_literals = compiled
        .dependencies
        .iter()
        .map(|dependency| LitStr::new(dependency, Span::call_site()))
        .collect::<Vec<_>>();
    let dependency_tracker_idents = dependency_literals
        .iter()
        .enumerate()
        .map(|(idx, _)| format_ident!("_SCSS_TRACKER_{idx}"))
        .collect::<Vec<_>>();

    quote! {
        #[allow(dead_code)]
        const _SCSS_TRACKER: &str = include_str!(#abs_lit);
        #(#[allow(dead_code)] const #dependency_tracker_idents: &str = include_str!(#dependency_literals);)*

        pub const CSS: &str = #css_lit;
        pub const SUFFIX: &str = #suffix_lit;

        #classes_module
    }
}

fn insert_module_into_tree(
    root: &mut ModuleTreeNode,
    segments: &[String],
    absolute_path: PathBuf,
    compiled: ScopedModule,
) -> std::result::Result<(), String> {
    if segments.is_empty() {
        return Err("Cannot insert scoped module with empty path".to_string());
    }

    let mut node = root;
    for segment in segments {
        node = node.children.entry(segment.clone()).or_default();
    }

    if node.module.is_some() {
        return Err(format!(
            "Duplicate SCSS module path '{}'",
            segments.join("::")
        ));
    }

    node.module = Some(ScopedModuleEntry {
        absolute_path,
        compiled,
    });
    Ok(())
}

fn scoped_tree_tokens(root: &ModuleTreeNode) -> Vec<proc_macro2::TokenStream> {
    root.children
        .iter()
        .map(|(segment, node)| {
            let segment_ident = format_ident!("{}", segment);
            let inner_items = scoped_tree_node_items(node);
            quote! {
                pub mod #segment_ident {
                    #(#inner_items)*
                }
            }
        })
        .collect::<Vec<_>>()
}

fn scoped_tree_node_items(node: &ModuleTreeNode) -> Vec<proc_macro2::TokenStream> {
    let mut items = Vec::new();

    if let Some(module) = &node.module {
        items.push(module_body_tokens(&module.absolute_path, &module.compiled));
    }

    for (segment, child) in &node.children {
        let segment_ident = format_ident!("{}", segment);
        let child_items = scoped_tree_node_items(child);
        items.push(quote! {
            pub mod #segment_ident {
                #(#child_items)*
            }
        });
    }

    items
}

fn sanitize_ident(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        if ch.is_ascii_alphanumeric() || ch == '_' {
            out.push(ch);
        } else {
            out.push('_');
        }
    }

    if out.is_empty() {
        out.push_str("class_name");
    }
    if out
        .chars()
        .next()
        .map(|c| c.is_ascii_digit())
        .unwrap_or(false)
    {
        out.insert(0, '_');
    }
    out
}

fn default_href_from_output_path(output_path: &str) -> String {
    if output_path.starts_with('/') {
        output_path.to_string()
    } else {
        format!("/{output_path}")
    }
}

fn is_rust_analyzer() -> bool {
    std::env::var_os("RUST_ANALYZER_INTERNALS_DO_NOT_USE").is_some()
}

fn write_generated_rust_snapshot(
    manifest_dir: &Path,
    expanded: &proc_macro2::TokenStream,
) -> io::Result<()> {
    let crate_name = manifest_dir
        .file_name()
        .and_then(|v| v.to_str())
        .unwrap_or("crate");

    let content = format!(
        "// @generated by scoped_sass\n// crate: {}\n\n{}\n",
        crate_name, expanded
    );
    write_if_changed(&default_snapshot_path(manifest_dir), &content)?;
    write_if_changed(&rust_analyzer_snapshot_path(manifest_dir), &content)
}

fn target_root_for_macro(manifest_dir: &Path) -> PathBuf {
    if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
        return PathBuf::from(target_dir);
    }
    if let Ok(out_dir) = env::var("OUT_DIR")
        && let Some(root) = target_root_from_out_dir(Path::new(&out_dir))
    {
        return root;
    }
    if let Some(workspace_root) = find_workspace_root(manifest_dir) {
        return workspace_root.join("target");
    }
    manifest_dir.join("target")
}

fn target_root_from_out_dir(out_dir: &Path) -> Option<PathBuf> {
    for ancestor in out_dir.ancestors() {
        if ancestor.file_name().is_some_and(|n| n == "target") {
            return Some(ancestor.to_path_buf());
        }
    }
    None
}

fn find_workspace_root(start_dir: &Path) -> Option<PathBuf> {
    for dir in start_dir.ancestors() {
        let manifest = dir.join("Cargo.toml");
        let Ok(contents) = fs::read_to_string(&manifest) else {
            continue;
        };
        if contents.contains("[workspace]") {
            return Some(dir.to_path_buf());
        }
    }
    None
}

fn sanitize_file_name(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
            out.push(ch);
        } else {
            out.push('_');
        }
    }
    if out.is_empty() {
        "crate".to_string()
    } else {
        out
    }
}

fn snapshot_file_name_for(manifest_dir: &Path) -> String {
    let crate_name = manifest_dir
        .file_name()
        .and_then(|v| v.to_str())
        .unwrap_or("crate");
    format!(
        "{}.scoped_styles.generated.rs",
        sanitize_file_name(crate_name)
    )
}

fn default_snapshot_path(manifest_dir: &Path) -> PathBuf {
    let target_root = target_root_for_macro(manifest_dir);
    target_root
        .join("scoped_sass_cache/generated_rust")
        .join(snapshot_file_name_for(manifest_dir))
}

fn rust_analyzer_snapshot_path(manifest_dir: &Path) -> PathBuf {
    let base_target = if let Some(workspace_root) = find_workspace_root(manifest_dir) {
        workspace_root.join("target")
    } else {
        target_root_for_macro(manifest_dir)
    };
    base_target
        .join("rust-analyzer/scoped_sass_cache/generated_rust")
        .join(snapshot_file_name_for(manifest_dir))
}