Skip to main content

derive_deftly_macros/
adhoc.rs

1//! Macro impl for adhoc template application `derive_deftly_adhoc!`
2
3use super::prelude::*;
4
5#[derive(Debug, Clone)]
6struct TemplateInvocation {
7    driver: syn::Path,
8    options: UnprocessedOptions,
9    colon: Token![:],
10    template: TokenStream,
11}
12
13impl Parse for TemplateInvocation {
14    fn parse(input: ParseStream) -> syn::Result<Self> {
15        let driver = input.parse()?;
16        let options =
17            UnprocessedOptions::parse(&input, OpContext::TemplateAdhoc)?;
18        let colon = input.parse()?;
19        let template = input.parse()?;
20        Ok(TemplateInvocation {
21            driver,
22            options,
23            colon,
24            template,
25        })
26    }
27}
28
29/// This is `derive_deftly_adhoc!`
30///
31/// It parses
32/// ```rust,ignore
33///    StructName:
34///    SOME_TOKENS
35/// ```
36/// and expand it to an invocation of
37/// ```rust,ignore
38///    derive_deftly_driver_StructName
39/// ```
40/// as per NOTES.txt.
41pub fn derive_deftly_adhoc(
42    input: TokenStream,
43) -> Result<TokenStream, syn::Error> {
44    let TemplateInvocation {
45        driver,
46        options,
47        colon,
48        template,
49    } = syn::parse2(input)?;
50
51    dprint_block!(
52        [&driver.to_token_stream(), &template],
53        "derive_deftly_adhoc! input",
54    );
55
56    let driver_mac_name = {
57        let mut name = driver;
58        let last = name.segments.last_mut().ok_or_else(|| {
59            colon.error(
60                "expected non-empty path for driver struct name, found colon",
61            )
62        })?;
63        last.ident = format_ident!("derive_deftly_driver_{}", &last.ident);
64        name
65    };
66
67    let output = quote! {
68        #driver_mac_name !{
69            { #template }
70            { ($) }
71            ( crate; [#options] ; )
72            [] []
73        }
74    };
75
76    dprint_block!(&output, "derive_deftly_adhoc! output");
77
78    Ok(output)
79}