Skip to main content

topo_macro/
lib.rs

1//! Procedural macro support crate for the `topo` crate.
2
3use proc_macro::TokenStream;
4use syn::{
5    parse_macro_input, parse_quote, spanned::Spanned, AttributeArgs, Expr, ItemFn, Lit, Meta,
6    NestedMeta,
7};
8
9#[proc_macro_attribute]
10pub fn nested(args: TokenStream, input: TokenStream) -> TokenStream {
11    let args: AttributeArgs = parse_macro_input!(args);
12    let mut input_fn: ItemFn = syn::parse(input).unwrap();
13
14    let inner_block = input_fn.block;
15    input_fn.block = if let Some(slot_expr) = slot_from_args(&args) {
16        parse_quote! {{
17            topo::call_in_slot(#slot_expr, move || #inner_block)
18        }}
19    } else {
20        parse_quote! {{ topo::call(move || #inner_block) }}
21    };
22
23    quote::quote_spanned!(input_fn.span()=>
24        #[track_caller]
25        #input_fn
26    )
27    .into()
28}
29
30/// parse the attribute arguments, retrieving an an expression to use as part of
31/// the slot
32fn slot_from_args(args: &[NestedMeta]) -> Option<Expr> {
33    assert!(args.len() <= 1);
34
35    args.get(0).map(|arg| match arg {
36        NestedMeta::Meta(Meta::NameValue(kv)) => {
37            assert!(
38                kv.path.is_ident("slot"),
39                "only `slot = \"...\" argument is supported by #[nested]"
40            );
41
42            match &kv.lit {
43                Lit::Str(l) => l.parse().unwrap(),
44                _ => panic!("`slot` argument accepts a string literal"),
45            }
46        }
47        _ => panic!("only `slot = \"...\" argument is supported by #[nested]"),
48    })
49}