Skip to main content

encore_macros/
lib.rs

1//! Procedural macros for the Encore Rust SDK. They are re-exported by the
2//! `encore` crate, which documents them and is what their output refers to:
3//! use them from there.
4
5use proc_macro::TokenStream;
6use proc_macro2::Span;
7use quote::quote;
8use syn::parse::{Parse, ParseStream};
9use syn::punctuated::Punctuated;
10use syn::{Expr, ExprLit, ItemFn, Lit, MetaNameValue, ReturnType, Token};
11
12/// The arguments of `#[encore::test]`: those of `#[tokio::test]` that choose
13/// the runtime.
14struct TestArgs {
15    multi_thread: bool,
16    worker_threads: Option<usize>,
17    /// `fixture = PATH`, or `fixture = none`.
18    fixture: Option<syn::Path>,
19}
20
21impl Parse for TestArgs {
22    fn parse(input: ParseStream) -> syn::Result<Self> {
23        let mut args = TestArgs {
24            multi_thread: false,
25            worker_threads: None,
26            fixture: None,
27        };
28        let mut flavor = None;
29        for arg in Punctuated::<MetaNameValue, Token![,]>::parse_terminated(input)? {
30            if arg.path.is_ident("fixture") {
31                let Expr::Path(path) = &arg.value else {
32                    return Err(syn::Error::new_spanned(
33                        &arg.value,
34                        "`fixture` is a fixture's path, or `none`",
35                    ));
36                };
37                args.fixture = Some(path.path.clone());
38                continue;
39            }
40            let lit = match &arg.value {
41                Expr::Lit(ExprLit { lit, .. }) => lit,
42                other => {
43                    return Err(syn::Error::new_spanned(other, "expected a literal"));
44                }
45            };
46            if arg.path.is_ident("flavor") {
47                let Lit::Str(value) = lit else {
48                    return Err(syn::Error::new_spanned(lit, "`flavor` is a string"));
49                };
50                args.multi_thread = match value.value().as_str() {
51                    "current_thread" => false,
52                    "multi_thread" => true,
53                    _ => {
54                        return Err(syn::Error::new_spanned(
55                            value,
56                            "the flavor is \"current_thread\" (the default) or \"multi_thread\"",
57                        ));
58                    }
59                };
60                flavor = Some(value.span());
61            } else if arg.path.is_ident("worker_threads") {
62                let Lit::Int(value) = lit else {
63                    return Err(syn::Error::new_spanned(lit, "`worker_threads` is a number"));
64                };
65                args.worker_threads = Some(value.base10_parse()?);
66            } else {
67                return Err(syn::Error::new_spanned(
68                    &arg.path,
69                    "unknown argument: expected `flavor`, `worker_threads` or `fixture`",
70                ));
71            }
72        }
73        if args.worker_threads.is_some() && !args.multi_thread {
74            return Err(syn::Error::new(
75                flavor.unwrap_or_else(Span::call_site),
76                "`worker_threads` needs `flavor = \"multi_thread\"`",
77            ));
78        }
79        Ok(args)
80    }
81}
82
83/// See `encore::test`.
84#[proc_macro_attribute]
85pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
86    let args = syn::parse_macro_input!(args as TestArgs);
87    let function = syn::parse_macro_input!(item as ItemFn);
88    expand_test(args, function)
89        .unwrap_or_else(syn::Error::into_compile_error)
90        .into()
91}
92
93fn expand_test(args: TestArgs, function: ItemFn) -> syn::Result<proc_macro2::TokenStream> {
94    let ItemFn {
95        attrs,
96        vis,
97        sig,
98        block,
99    } = function;
100    if !sig.inputs.is_empty() {
101        return Err(syn::Error::new_spanned(
102            &sig.inputs,
103            "a test function takes no arguments",
104        ));
105    }
106    if !sig.generics.params.is_empty() {
107        return Err(syn::Error::new_spanned(
108            &sig.generics,
109            "a test function cannot be generic",
110        ));
111    }
112    let name = &sig.ident;
113    let output = &sig.output;
114    let returns = match output {
115        ReturnType::Default => quote!(()),
116        ReturnType::Type(_, ty) => quote!(#ty),
117    };
118    let info = quote! {
119        ::encore::testing::__private::TestInfo {
120            module: ::core::module_path!(),
121            name: ::core::stringify!(#name),
122            file: ::core::file!(),
123            line: ::core::line!(),
124        }
125    };
126
127    let fixture = match &args.fixture {
128        None => quote!(::encore::testing::__private::FixtureArg::Module),
129        Some(path) if path.is_ident("none") => {
130            quote!(::encore::testing::__private::FixtureArg::None)
131        }
132        Some(path) => quote!(::encore::testing::__private::FixtureArg::Named(&#path)),
133    };
134
135    // Whether what the test returned is a failure, said here where its
136    // type is known: an `Err` is one.
137    let failed = quote! {
138        |result| {
139            #[allow(unused_imports)]
140            use ::encore::testing::__private::{FailedIfErr as _, NeverFailed as _};
141            (&::encore::testing::__private::Probe(result)).failed()
142        }
143    };
144
145    let body = if sig.asyncness.is_some() {
146        let multi_thread = args.multi_thread;
147        let worker_threads = match args.worker_threads {
148            Some(n) => quote!(::core::option::Option::Some(#n)),
149            None => quote!(::core::option::Option::None),
150        };
151        quote! {
152            ::encore::testing::__private::run::<#returns, _>(
153                #info,
154                ::encore::testing::__private::RuntimeConfig {
155                    multi_thread: #multi_thread,
156                    worker_threads: #worker_threads,
157                },
158                #fixture,
159                #failed,
160                async move #block,
161            )
162        }
163    } else {
164        if args.multi_thread {
165            return Err(syn::Error::new_spanned(
166                sig.fn_token,
167                "a runtime flavor is for an `async fn` test",
168            ));
169        }
170        quote! {
171            ::encore::testing::__private::run_sync::<#returns, _>(
172                #info,
173                #fixture,
174                #failed,
175                move || #block,
176            )
177        }
178    };
179
180    Ok(quote! {
181        #[::core::prelude::v1::test]
182        #(#attrs)*
183        #vis fn #name() #output {
184            #body
185        }
186    })
187}
188
189/// See `encore::pubsub::register`.
190#[proc_macro_attribute]
191pub fn register(args: TokenStream, item: TokenStream) -> TokenStream {
192    if !args.is_empty() {
193        return syn::Error::new(
194            Span::call_site(),
195            "`register` takes no arguments: what it registers is the `static` it is on",
196        )
197        .into_compile_error()
198        .into();
199    }
200    let item = syn::parse_macro_input!(item as syn::ItemStatic);
201    expand_subscription(item)
202        .unwrap_or_else(syn::Error::into_compile_error)
203        .into()
204}
205
206fn expand_subscription(mut item: syn::ItemStatic) -> syn::Result<proc_macro2::TokenStream> {
207    // The declaration: `Subscription::new(topic, name, handler)`, with its
208    // options chained on.
209    let mut expr = item.expr.as_mut();
210    while let Expr::MethodCall(call) = expr {
211        expr = call.receiver.as_mut();
212    }
213    let declaration = match expr {
214        Expr::Call(call) if call.args.len() == 3 => call,
215        other => {
216            return Err(syn::Error::new_spanned(
217                other,
218                "expected `Subscription::new(&TOPIC, \"name\", handler)`, optionally followed \
219                 by its options",
220            ));
221        }
222    };
223    // A handler given by name is boxed, as `Subscription::new` takes it.
224    let handler = declaration.args.last_mut().expect("three arguments");
225    if !matches!(handler, Expr::Closure(_)) {
226        *handler = syn::parse_quote!(|message| ::std::boxed::Box::pin((#handler)(message)));
227    }
228
229    let name = &item.ident;
230    Ok(quote! {
231        #item
232
233        const _: () = {
234            #[::encore::pubsub::__private::linkme::distributed_slice(
235                ::encore::pubsub::__private::SUBSCRIPTIONS
236            )]
237            #[linkme(crate = ::encore::pubsub::__private::linkme)]
238            static REGISTER: &'static dyn ::encore::pubsub::__private::AnySubscription = &#name;
239        };
240    })
241}
242
243/// See `encore::metrics::Labels`.
244#[proc_macro_derive(Labels)]
245pub fn derive_labels(input: TokenStream) -> TokenStream {
246    let input = syn::parse_macro_input!(input as syn::DeriveInput);
247    expand_labels(input)
248        .unwrap_or_else(syn::Error::into_compile_error)
249        .into()
250}
251
252fn expand_labels(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
253    use syn::ext::IdentExt;
254
255    let fields = match &input.data {
256        syn::Data::Struct(syn::DataStruct {
257            fields: syn::Fields::Named(fields),
258            ..
259        }) if !fields.named.is_empty() => &fields.named,
260        _ => {
261            return Err(syn::Error::new_spanned(
262                &input.ident,
263                "`Labels` is derived for a struct with named fields: each field is a label",
264            ));
265        }
266    };
267    let idents: Vec<&syn::Ident> = fields
268        .iter()
269        .map(|field| field.ident.as_ref().expect("named"))
270        .collect();
271    // A label is named as its field is written, without the `r#` of a raw one.
272    let names = idents.iter().map(|ident| ident.unraw().to_string());
273    // A `&'static str` is borrowed as it is, not copied.
274    let values = fields.iter().zip(&idents).map(|(field, ident)| {
275        if is_static_str(&field.ty) {
276            quote! { ::encore::opentelemetry::Value::from(self.#ident) }
277        } else {
278            quote! { ::encore::metrics::LabelValue::label_value(&self.#ident) }
279        }
280    });
281
282    let name = &input.ident;
283    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
284    Ok(quote! {
285        impl #impl_generics ::encore::metrics::Labels for #name #type_generics #where_clause {
286            fn attributes(&self) -> ::std::vec::Vec<::encore::opentelemetry::KeyValue> {
287                ::std::vec![#(::encore::opentelemetry::KeyValue::new(#names, #values)),*]
288            }
289        }
290    })
291}
292
293/// See `encore::config::ConfigType`.
294#[proc_macro_derive(ConfigType, attributes(config))]
295pub fn derive_config_type(input: TokenStream) -> TokenStream {
296    let input = syn::parse_macro_input!(input as syn::DeriveInput);
297    expand_config_type(input)
298        .unwrap_or_else(syn::Error::into_compile_error)
299        .into()
300}
301
302/// The keys `#[config(...)]` takes on a field. What they mean — and whether
303/// they fit the field's type — is the parser's to check, which reads them to
304/// build the config's schema.
305const CONFIG_KEYS: &[&str] = &[
306    "min",
307    "max",
308    "min_len",
309    "max_len",
310    "pattern",
311    "min_items",
312    "max_items",
313    "secret",
314];
315
316fn expand_config_type(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
317    let mut errors: Vec<syn::Error> = Vec::new();
318    let misplaced = |attrs: &[syn::Attribute], errors: &mut Vec<syn::Error>| {
319        for attr in attrs.iter().filter(|a| a.path().is_ident("config")) {
320            errors.push(syn::Error::new_spanned(
321                attr,
322                "`#[config(...)]` goes on a field: it constrains that field's value",
323            ));
324        }
325    };
326    misplaced(&input.attrs, &mut errors);
327    let fields: Vec<&syn::Field> = match &input.data {
328        syn::Data::Struct(s) => s.fields.iter().collect(),
329        syn::Data::Enum(e) => e
330            .variants
331            .iter()
332            .flat_map(|v| {
333                misplaced(&v.attrs, &mut errors);
334                v.fields.iter()
335            })
336            .collect(),
337        syn::Data::Union(u) => {
338            return Err(syn::Error::new_spanned(
339                u.union_token,
340                "a config type is a struct or an enum",
341            ));
342        }
343    };
344    for field in fields {
345        for attr in field.attrs.iter().filter(|a| a.path().is_ident("config")) {
346            let parsed =
347                attr.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated);
348            match parsed {
349                Ok(args) => {
350                    for arg in args {
351                        if !CONFIG_KEYS.iter().any(|k| arg.path.is_ident(k)) {
352                            errors.push(syn::Error::new_spanned(
353                                &arg.path,
354                                format!(
355                                    "unknown config attribute: expected one of {}",
356                                    CONFIG_KEYS
357                                        .iter()
358                                        .map(|k| format!("`{k}`"))
359                                        .collect::<Vec<_>>()
360                                        .join(", ")
361                                ),
362                            ));
363                        }
364                    }
365                }
366                Err(err) => errors.push(err),
367            }
368        }
369    }
370    if let Some(mut first) = errors.pop() {
371        for err in errors {
372            first.combine(err);
373        }
374        return Err(first);
375    }
376
377    let name = &input.ident;
378    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
379    // The trait's supertraits, stated for the type itself, so a generic type
380    // is a config type exactly when its arguments make it one.
381    let mut predicates: Vec<proc_macro2::TokenStream> = where_clause
382        .map(|w| w.predicates.iter().map(|p| quote!(#p)).collect())
383        .unwrap_or_default();
384    predicates.push(quote! {
385        #name #type_generics: ::encore::config::__private::DeserializeOwned
386            + ::core::marker::Send
387            + ::core::marker::Sync
388            + 'static
389    });
390    Ok(quote! {
391        impl #impl_generics ::encore::config::ConfigType for #name #type_generics
392        where
393            #(#predicates),*
394        {
395        }
396    })
397}
398
399/// Whether `ty` is written `&'static str`.
400fn is_static_str(ty: &syn::Type) -> bool {
401    let syn::Type::Reference(r) = ty else {
402        return false;
403    };
404    let syn::Type::Path(elem) = &*r.elem else {
405        return false;
406    };
407    r.mutability.is_none()
408        && r.lifetime.as_ref().is_some_and(|l| l.ident == "static")
409        && elem.qself.is_none()
410        && elem.path.is_ident("str")
411}
412
413#[cfg(test)]
414mod config_type_tests {
415    // Not a glob: this crate's own `test` would shadow the prelude's.
416    use super::expand_config_type;
417    use quote::quote;
418
419    fn expand(input: proc_macro2::TokenStream) -> Result<String, String> {
420        let input: syn::DeriveInput = syn::parse2(input).unwrap();
421        expand_config_type(input)
422            .map(|t| t.to_string())
423            .map_err(|e| e.to_string())
424    }
425
426    #[test]
427    fn implements_the_trait_and_takes_the_known_keys() {
428        let out = expand(quote! {
429            struct Checkout<T> {
430                #[config(min = 1, max = 500)]
431                max_items: u32,
432                #[config(min_len = 1, max_len = 8, pattern = "^[A-Z]+$")]
433                code: String,
434                #[config(min_items = 1, max_items = 3)]
435                tags: Vec<T>,
436                #[config(secret = "StripeKey")]
437                key: ::encore::secrets::Secret,
438            }
439        })
440        .unwrap();
441        assert!(
442            out.contains("impl < T > :: encore :: config :: ConfigType for Checkout < T >"),
443            "{out}"
444        );
445        assert!(
446            out.contains("Checkout < T > : :: encore :: config :: __private :: DeserializeOwned"),
447            "{out}"
448        );
449    }
450
451    #[test]
452    fn refuses_unknown_keys_and_misplaced_attributes() {
453        let err = expand(quote! {
454            struct Checkout {
455                #[config(minimum = 1)]
456                max_items: u32,
457            }
458        })
459        .unwrap_err();
460        assert!(err.contains("unknown config attribute"), "{err}");
461
462        let err = expand(quote! {
463            #[config(min = 1)]
464            enum Mode { Off, On }
465        })
466        .unwrap_err();
467        assert!(err.contains("goes on a field"), "{err}");
468
469        // Enum variants' fields take them.
470        assert!(expand(quote! {
471            enum Limit { Percent(#[config(max = 100)] u8), Off }
472        })
473        .is_ok());
474    }
475}