aboutsummaryrefslogtreecommitdiff
path: root/macros/src/util/syn_path.rs
blob: 26e2597e42a4ea6ef55a7360c56ee64414ed5fde (plain)
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
use std::fmt::Write;

use quote::ToTokens;
use syn::punctuated::Pair;

pub trait SynPathExt
{
    /// Converts the [`syn::Path`] to a [`String`].
    fn to_string(&self) -> String;
}

impl SynPathExt for syn::Path
{
    fn to_string(&self) -> String
    {
        self.segments.pairs().map(Pair::into_tuple).fold(
            String::new(),
            |mut acc, (segment, opt_punct)| {
                let segment_ident = &segment.ident;

                write!(
                    acc,
                    "{segment_ident}{}",
                    opt_punct
                        .map(|punct| punct.to_token_stream().to_string())
                        .unwrap_or_default()
                )
                .ok();

                acc
            },
        )
    }
}

macro_rules! syn_path {
    ($first_segment: ident $(::$segment: ident)*) => {
        ::syn::Path {
            leading_colon: None,
            segments: ::syn::punctuated::Punctuated::from_iter([
                $crate::util::syn_path::syn_path_segment!($first_segment),
                $($crate::util::syn_path::syn_path_segment!($segment),)*
            ])
        }
    };
}

macro_rules! syn_path_segment {
    ($segment: ident) => {
        ::syn::PathSegment {
            ident: ::proc_macro2::Ident::new(
                stringify!($segment),
                ::proc_macro2::Span::call_site(),
            ),
            arguments: ::syn::PathArguments::None,
        }
    };
}

pub(crate) use {syn_path, syn_path_segment};