Skip to main content

layline_codegen/
root.rs

1//! The runtime path and prelude spelling for generated code.
2
3use proc_macro2::{Group, Span, TokenStream, TokenTree};
4use quote::{ToTokens, format_ident, quote};
5
6/// How generated code spells prelude names.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Spelling {
9    /// Fully qualified, such as `::core::primitive::u32` and `<root>::__private::Vec`.
10    ///
11    /// For derives, whose output lands in modules where these names may be shadowed.
12    Hygienic,
13    /// Unqualified, such as `u32`, `Some` and `Vec`. For committed source.
14    Bare,
15}
16
17/// Prelude names in the root's [`Spelling`].
18///
19/// Runtime paths such as `<root>::Message` are not listed. They are always qualified.
20pub(crate) struct Prelude {
21    pub ok: TokenStream,
22    pub err: TokenStream,
23    pub some: TokenStream,
24    pub none: TokenStream,
25    pub option: TokenStream,
26    pub result: TokenStream,
27    pub vec: TokenStream,
28    pub string: TokenStream,
29    pub boxed: TokenStream,
30    pub u8: TokenStream,
31    pub u32: TokenStream,
32    pub u64: TokenStream,
33    pub usize: TokenStream,
34    pub i64: TokenStream,
35    pub bool: TokenStream,
36    qualified: bool,
37}
38
39impl Prelude {
40    /// The primitive `name`, in this prelude's spelling.
41    pub(crate) fn primitive(&self, name: &str) -> TokenStream {
42        let ident = format_ident!("{name}");
43        if self.qualified { quote!(::core::primitive::#ident) } else { quote!(#ident) }
44    }
45}
46
47/// The path to the layline runtime, and the prelude [`Spelling`].
48///
49/// Set the path when a crate renames the dependency, as in `wire = { package = "layline" }`.
50#[derive(Clone)]
51pub struct Root {
52    path: syn::Path,
53    spelling: Spelling,
54}
55
56impl Root {
57    /// A root at `path`, such as a derive's `crate = <path>`.
58    #[must_use]
59    pub fn new(path: syn::Path, spelling: Spelling) -> Self {
60        Self { path, spelling }
61    }
62
63    /// The runtime path.
64    #[must_use]
65    pub fn path(&self) -> &syn::Path {
66        &self.path
67    }
68
69    fn is_default(&self) -> bool {
70        self.path.to_token_stream().to_string()
71            == Self::default().path.to_token_stream().to_string()
72    }
73
74    /// `, crate = <path>` for the container attribute of generated derives.
75    ///
76    /// Empty for the default root, so default output matches omitting the argument.
77    pub(crate) fn crate_arg(&self) -> TokenStream {
78        if self.is_default() {
79            return TokenStream::new();
80        }
81        let path = &self.path;
82        quote! { , crate = #path }
83    }
84
85    /// The prelude names, spelled for this root.
86    pub(crate) fn prelude(&self) -> Prelude {
87        let root = &self.path;
88        match self.spelling {
89            Spelling::Hygienic => Prelude {
90                ok: quote!(::core::result::Result::Ok),
91                err: quote!(::core::result::Result::Err),
92                some: quote!(::core::option::Option::Some),
93                none: quote!(::core::option::Option::None),
94                option: quote!(::core::option::Option),
95                result: quote!(::core::result::Result),
96                vec: quote!(#root::__private::Vec),
97                string: quote!(#root::__private::String),
98                boxed: quote!(#root::__private::Box),
99                u8: quote!(::core::primitive::u8),
100                u32: quote!(::core::primitive::u32),
101                u64: quote!(::core::primitive::u64),
102                usize: quote!(::core::primitive::usize),
103                i64: quote!(::core::primitive::i64),
104                bool: quote!(::core::primitive::bool),
105                qualified: true,
106            },
107            Spelling::Bare => Prelude {
108                ok: quote!(Ok),
109                err: quote!(Err),
110                some: quote!(Some),
111                none: quote!(None),
112                option: quote!(Option),
113                result: quote!(Result),
114                vec: quote!(Vec),
115                string: quote!(String),
116                boxed: quote!(Box),
117                u8: quote!(u8),
118                u32: quote!(u32),
119                u64: quote!(u64),
120                usize: quote!(usize),
121                i64: quote!(i64),
122                bool: quote!(bool),
123                qualified: false,
124            },
125        }
126    }
127}
128
129/// `root`'s path with every token spanned to `span`.
130///
131/// `quote_spanned!` only spans the tokens it writes itself.
132#[must_use]
133pub fn respan(root: &Root, span: Span) -> TokenStream {
134    fn each(tokens: TokenStream, span: Span) -> TokenStream {
135        tokens
136            .into_iter()
137            .map(|tree| match tree {
138                TokenTree::Group(g) => {
139                    let mut re = Group::new(g.delimiter(), each(g.stream(), span));
140                    re.set_span(span);
141                    TokenTree::Group(re)
142                }
143                mut other => {
144                    other.set_span(span);
145                    other
146                }
147            })
148            .collect()
149    }
150    each(root.path.to_token_stream(), span)
151}
152
153impl Default for Root {
154    /// `::layline`, hygienic.
155    fn default() -> Self {
156        Self { path: syn::parse_quote!(::layline), spelling: Spelling::Hygienic }
157    }
158}
159
160impl ToTokens for Root {
161    fn to_tokens(&self, tokens: &mut TokenStream) {
162        self.path.to_tokens(tokens);
163    }
164}
165
166impl core::fmt::Debug for Root {
167    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
168        let spelling = match self.spelling {
169            Spelling::Hygienic => "",
170            Spelling::Bare => ", bare",
171        };
172        write!(f, "Root({}{spelling})", self.path.to_token_stream())
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::{Root, Spelling};
179    use quote::quote;
180
181    fn lowered(root: &Root) -> proc_macro2::TokenStream {
182        let p = root.prelude();
183        let (vec, u8, u32, usize, i64, result, option, some, ok, boxed) =
184            (p.vec, p.u8, p.u32, p.usize, p.i64, p.result, p.option, p.some, p.ok, p.boxed);
185        quote! {
186            pub entries: #vec<Entry>,
187            fn decode_nested(body: &[#u8], __depth: #u32) -> #result<(Self, #usize), #root::ParseError> {
188                let __n: #option<#i64> = #some(1);
189                #ok((#boxed::new(x), 0))
190            }
191        }
192    }
193
194    #[test]
195    fn a_hygienic_root_qualifies_every_prelude_name() {
196        let out = lowered(&Root::default()).to_string();
197        let want = quote! {
198            pub entries: ::layline::__private::Vec<Entry>,
199            fn decode_nested(
200                body: &[::core::primitive::u8],
201                __depth: ::core::primitive::u32
202            ) -> ::core::result::Result<(Self, ::core::primitive::usize), ::layline::ParseError> {
203                let __n: ::core::option::Option<::core::primitive::i64> =
204                    ::core::option::Option::Some(1);
205                ::core::result::Result::Ok((::layline::__private::Box::new(x), 0))
206            }
207        }
208        .to_string();
209        assert_eq!(out, want);
210    }
211
212    #[test]
213    fn a_bare_root_spells_the_prelude_bare_and_the_runtime_qualified() {
214        let root = Root::new(syn::parse_quote!(::layline), Spelling::Bare);
215        let out = lowered(&root).to_string();
216        let want = quote! {
217            pub entries: Vec<Entry>,
218            fn decode_nested(body: &[u8], __depth: u32) -> Result<(Self, usize), ::layline::ParseError> {
219                let __n: Option<i64> = Some(1);
220                Ok((Box::new(x), 0))
221            }
222        }
223        .to_string();
224        assert_eq!(out, want);
225    }
226
227    #[test]
228    fn a_named_primitive_follows_the_spelling() {
229        let bare = Root::new(syn::parse_quote!(::wire), Spelling::Bare);
230        assert_eq!(bare.prelude().primitive("u16").to_string(), "u16");
231        assert_eq!(
232            Root::default().prelude().primitive("u16").to_string(),
233            quote!(::core::primitive::u16).to_string()
234        );
235        assert_eq!(bare.prelude().vec.to_string(), "Vec");
236        assert_eq!(
237            Root::new(syn::parse_quote!(::wire), Spelling::Hygienic).prelude().vec.to_string(),
238            quote!(::wire::__private::Vec).to_string()
239        );
240    }
241
242    #[test]
243    fn only_the_default_root_writes_no_crate_arg() {
244        assert!(Root::default().crate_arg().is_empty());
245        assert!(Root::new(syn::parse_quote!(::layline), Spelling::Bare).crate_arg().is_empty());
246        assert_eq!(
247            Root::new(syn::parse_quote!(::wire), Spelling::Bare).crate_arg().to_string(),
248            quote!(, crate = ::wire).to_string()
249        );
250    }
251}