Skip to main content

tpt_fixture_macros/
lib.rs

1//! Proc-macro internals for `tpt-fixture`. Do not use directly — depend on
2//! `tpt-fixture` instead.
3
4use proc_macro::TokenStream;
5use quote::{format_ident, quote};
6use syn::parse::{Parse, ParseStream};
7use syn::{Attribute, FnArg, Ident, ItemFn, LitStr, Pat, ReturnType, Token, Type, TypeTuple};
8
9/// Scope of a fixture.
10#[derive(Clone, Copy, PartialEq, Eq)]
11enum Scope {
12    Test,
13    Module,
14    Suite,
15}
16
17impl Scope {
18    fn as_path(&self) -> proc_macro2::TokenStream {
19        match self {
20            Scope::Test => quote!(tpt_fixture::Scope::Test),
21            Scope::Module => quote!(tpt_fixture::Scope::Module),
22            Scope::Suite => quote!(tpt_fixture::Scope::Suite),
23        }
24    }
25}
26
27/// Parsed `#[tpt_fixture(...)]` arguments.
28struct FixtureArgs {
29    scope: Scope,
30    name: Option<String>,
31}
32
33impl Default for FixtureArgs {
34    fn default() -> Self {
35        // Fixtures default to `suite` scope (initialised once, shared widely).
36        FixtureArgs {
37            scope: Scope::Suite,
38            name: None,
39        }
40    }
41}
42
43impl Parse for FixtureArgs {
44    fn parse(input: ParseStream) -> syn::Result<Self> {
45        let mut args = FixtureArgs::default();
46        while !input.is_empty() {
47            let key: Ident = input.parse()?;
48            input.parse::<Token![=]>()?;
49            match key.to_string().as_str() {
50                "scope" => {
51                    let s: LitStr = input.parse()?;
52                    args.scope = match s.value().as_str() {
53                        "test" => Scope::Test,
54                        "module" => Scope::Module,
55                        "suite" => Scope::Suite,
56                        other => {
57                            return Err(syn::Error::new(
58                                s.span(),
59                                format!("unknown scope `{other}` (expected test|module|suite)"),
60                            ))
61                        }
62                    };
63                }
64                "name" => {
65                    let s: LitStr = input.parse()?;
66                    args.name = Some(s.value());
67                }
68                other => {
69                    return Err(syn::Error::new(
70                        key.span(),
71                        format!("unknown fixture argument `{other}` (expected scope|name)"),
72                    ))
73                }
74            }
75            if input.peek(Token![,]) {
76                input.parse::<Token![,]>()?;
77            }
78        }
79        Ok(args)
80    }
81}
82
83/// Heuristically detect whether an item is a test function (so the macro should
84/// inject fixtures rather than define one). A function carrying any attribute
85/// whose final path segment is `test` (e.g. `#[test]`, `#[tokio::test]`,
86/// `#[async_std::test]`) is treated as a test.
87fn is_test_fn(item: &ItemFn) -> bool {
88    item.attrs.iter().any(|a| last_segment_is(a, "test"))
89}
90
91fn last_segment_is(attr: &Attribute, name: &str) -> bool {
92    if let Some(seg) = attr.path().segments.last() {
93        return seg.ident == name;
94    }
95    false
96}
97
98#[proc_macro_attribute]
99pub fn tpt_fixture(args: TokenStream, input: TokenStream) -> TokenStream {
100    let args = syn::parse_macro_input!(args as FixtureArgs);
101    let item = syn::parse_macro_input!(input as ItemFn);
102
103    if is_test_fn(&item) {
104        expand_test(item)
105    } else {
106        expand_definition(args, item)
107    }
108    .into()
109}
110
111/// Extract the resource type `T` from a fixture init fn's return type.
112///
113/// A plain `T` yields `T`; a tuple `(T, teardown)` yields `T`. Anything else
114/// (e.g. `-> impl Trait`) is passed through untouched and will fail with a
115/// clearer error at the `fixture_access` call site.
116fn resource_type_of(output: &ReturnType) -> proc_macro2::TokenStream {
117    if let ReturnType::Type(_, ty) = output {
118        if let Type::Tuple(TypeTuple { elems, .. }) = &**ty {
119            if elems.len() == 2 {
120                let first = elems.first().expect("tuple has 2 elements");
121                return quote! { #first };
122            }
123        }
124        return quote! { #ty };
125    }
126    // No explicit return type (`-> ()`); default to unit.
127    quote! { () }
128}
129
130/// Expand a fixture *definition*: keep the init fn (renamed) and emit a public
131/// accessor that resolves/creates the shared `Arc<T>`.
132fn expand_definition(args: FixtureArgs, mut item: ItemFn) -> proc_macro2::TokenStream {
133    let fixture_name = args
134        .name
135        .clone()
136        .unwrap_or_else(|| item.sig.ident.to_string());
137    let accessor = Ident::new(&fixture_name, item.sig.ident.span());
138    let init_fn = format_ident!("__tpt_fixture_init_{}", fixture_name);
139    let scope = args.scope.as_path();
140
141    // Rename the user's init fn so it doesn't collide with the accessor.
142    item.sig.ident = init_fn.clone();
143    let vis = &item.vis;
144    let is_async = item.sig.asyncness.is_some();
145
146    // Derive the resource type `T` from the init fn's return type: a tuple
147    // `(T, teardown)` yields `T`; a plain `T` yields `T`.
148    let res_ty = resource_type_of(&item.sig.output);
149
150    let init_expr = if is_async {
151        quote! { tpt_fixture::IntoFixture::into_fixture(tpt_fixture::block_on(#init_fn())) }
152    } else {
153        quote! { tpt_fixture::IntoFixture::into_fixture(#init_fn()) }
154    };
155
156    let accessor_fn = quote! {
157        #vis fn #accessor() -> ::std::sync::Arc<#res_ty> {
158            tpt_fixture::fixture_access(#fixture_name, #scope, || #init_expr)
159        }
160    };
161
162    quote! {
163        #item
164        #accessor_fn
165    }
166}
167
168/// Expand a test *usage*: strip fixture parameters, resolve each by calling the
169/// accessor of the same name, and wrap the body in a `TestScopeGuard` so
170/// `test`-scope teardowns run at the end (even on panic).
171fn expand_test(mut item: ItemFn) -> proc_macro2::TokenStream {
172    // Collect fixture parameter idents and their types.
173    let mut fixture_params: Vec<Ident> = Vec::new();
174    let mut new_inputs = syn::punctuated::Punctuated::<FnArg, Token![,]>::new();
175    for arg in item.sig.inputs.iter() {
176        match arg {
177            FnArg::Typed(pt) => {
178                if let Pat::Ident(pat_ident) = &*pt.pat {
179                    fixture_params.push(pat_ident.ident.clone());
180                    // Drop the parameter — it will be a local binding instead.
181                } else {
182                    new_inputs.push(arg.clone());
183                }
184            }
185            FnArg::Receiver(r) => new_inputs.push(FnArg::Receiver(r.clone())),
186        }
187    }
188    item.sig.inputs = new_inputs;
189
190    let bindings = fixture_params.iter().map(|name| {
191        quote! { let #name = #name(); }
192    });
193
194    let vis = &item.vis;
195    let attrs = &item.attrs;
196    let sig = &item.sig;
197    let block = &item.block;
198
199    quote! {
200        #(#attrs)*
201        #vis #sig {
202            let _tpt_scope_guard = tpt_fixture::TestScopeGuard;
203            #(#bindings)*
204            #block
205        }
206    }
207}