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::Schema`.
244#[proc_macro_derive(Schema, attributes(encore))]
245pub fn derive_schema(input: TokenStream) -> TokenStream {
246    let input = syn::parse_macro_input!(input as syn::DeriveInput);
247    validate_schema(&input)
248        .err()
249        .map_or_else(TokenStream::new, |err| err.into_compile_error().into())
250}
251
252fn validate_schema(input: &syn::DeriveInput) -> syn::Result<()> {
253    fn field_only(attrs: &[syn::Attribute]) -> syn::Result<()> {
254        if let Some(attr) = attrs.iter().find(|a| a.path().is_ident("encore")) {
255            return Err(syn::Error::new_spanned(
256                attr,
257                "`#[encore(sensitive)]` goes on a field",
258            ));
259        }
260        Ok(())
261    }
262
263    fn check_fields(fields: &syn::Fields) -> syn::Result<()> {
264        for field in fields {
265            for attr in field.attrs.iter().filter(|a| a.path().is_ident("encore")) {
266                let mark = attr.parse_args::<syn::Ident>()?;
267                if mark != "sensitive" {
268                    return Err(syn::Error::new_spanned(
269                        mark,
270                        "expected `encore(sensitive)`",
271                    ));
272                }
273            }
274        }
275        Ok(())
276    }
277
278    field_only(&input.attrs)?;
279    match &input.data {
280        syn::Data::Struct(s) => check_fields(&s.fields),
281        syn::Data::Enum(e) => {
282            for v in &e.variants {
283                field_only(&v.attrs)?;
284                check_fields(&v.fields)?;
285            }
286            Ok(())
287        }
288        syn::Data::Union(u) => Err(syn::Error::new_spanned(
289            u.union_token,
290            "a message is a struct or an enum",
291        )),
292    }
293}
294
295/// See `encore::metrics::Labels`.
296#[proc_macro_derive(Labels)]
297pub fn derive_labels(input: TokenStream) -> TokenStream {
298    let input = syn::parse_macro_input!(input as syn::DeriveInput);
299    expand_labels(input)
300        .unwrap_or_else(syn::Error::into_compile_error)
301        .into()
302}
303
304fn expand_labels(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
305    use syn::ext::IdentExt;
306
307    let fields = match &input.data {
308        syn::Data::Struct(syn::DataStruct {
309            fields: syn::Fields::Named(fields),
310            ..
311        }) if !fields.named.is_empty() => &fields.named,
312        _ => {
313            return Err(syn::Error::new_spanned(
314                &input.ident,
315                "`Labels` is derived for a struct with named fields: each field is a label",
316            ));
317        }
318    };
319    let idents: Vec<&syn::Ident> = fields
320        .iter()
321        .map(|field| field.ident.as_ref().expect("named"))
322        .collect();
323    // A label is named as its field is written, without the `r#` of a raw one.
324    let names = idents.iter().map(|ident| ident.unraw().to_string());
325    // A `&'static str` is borrowed as it is, not copied.
326    let values = fields.iter().zip(&idents).map(|(field, ident)| {
327        if is_static_str(&field.ty) {
328            quote! { ::encore::opentelemetry::Value::from(self.#ident) }
329        } else {
330            quote! { ::encore::metrics::LabelValue::label_value(&self.#ident) }
331        }
332    });
333
334    let name = &input.ident;
335    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
336    Ok(quote! {
337        impl #impl_generics ::encore::metrics::Labels for #name #type_generics #where_clause {
338            fn attributes(&self) -> ::std::vec::Vec<::encore::opentelemetry::KeyValue> {
339                ::std::vec![#(::encore::opentelemetry::KeyValue::new(#names, #values)),*]
340            }
341        }
342    })
343}
344
345/// See `encore::config::ConfigType`.
346#[proc_macro_derive(ConfigType, attributes(config))]
347pub fn derive_config_type(input: TokenStream) -> TokenStream {
348    let input = syn::parse_macro_input!(input as syn::DeriveInput);
349    expand_config_type(input)
350        .unwrap_or_else(syn::Error::into_compile_error)
351        .into()
352}
353
354/// The keys `#[config(...)]` takes on a field. What they mean — and whether
355/// they fit the field's type — is the parser's to check, which reads them to
356/// build the config's schema.
357const CONFIG_KEYS: &[&str] = &[
358    "min",
359    "max",
360    "min_len",
361    "max_len",
362    "pattern",
363    "min_items",
364    "max_items",
365    "secret",
366];
367
368fn expand_config_type(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
369    let mut errors: Vec<syn::Error> = Vec::new();
370    let misplaced = |attrs: &[syn::Attribute], errors: &mut Vec<syn::Error>| {
371        for attr in attrs.iter().filter(|a| a.path().is_ident("config")) {
372            errors.push(syn::Error::new_spanned(
373                attr,
374                "`#[config(...)]` goes on a field: it constrains that field's value",
375            ));
376        }
377    };
378    misplaced(&input.attrs, &mut errors);
379    let fields: Vec<&syn::Field> = match &input.data {
380        syn::Data::Struct(s) => s.fields.iter().collect(),
381        syn::Data::Enum(e) => e
382            .variants
383            .iter()
384            .flat_map(|v| {
385                misplaced(&v.attrs, &mut errors);
386                v.fields.iter()
387            })
388            .collect(),
389        syn::Data::Union(u) => {
390            return Err(syn::Error::new_spanned(
391                u.union_token,
392                "a config type is a struct or an enum",
393            ));
394        }
395    };
396    for field in fields {
397        for attr in field.attrs.iter().filter(|a| a.path().is_ident("config")) {
398            let parsed =
399                attr.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated);
400            match parsed {
401                Ok(args) => {
402                    for arg in args {
403                        if !CONFIG_KEYS.iter().any(|k| arg.path.is_ident(k)) {
404                            errors.push(syn::Error::new_spanned(
405                                &arg.path,
406                                format!(
407                                    "unknown config attribute: expected one of {}",
408                                    CONFIG_KEYS
409                                        .iter()
410                                        .map(|k| format!("`{k}`"))
411                                        .collect::<Vec<_>>()
412                                        .join(", ")
413                                ),
414                            ));
415                        }
416                    }
417                }
418                Err(err) => errors.push(err),
419            }
420        }
421    }
422    if let Some(mut first) = errors.pop() {
423        for err in errors {
424            first.combine(err);
425        }
426        return Err(first);
427    }
428
429    let name = &input.ident;
430    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
431    // The trait's supertraits, stated for the type itself, so a generic type
432    // is a config type exactly when its arguments make it one.
433    let mut predicates: Vec<proc_macro2::TokenStream> = where_clause
434        .map(|w| w.predicates.iter().map(|p| quote!(#p)).collect())
435        .unwrap_or_default();
436    predicates.push(quote! {
437        #name #type_generics: ::encore::config::__private::DeserializeOwned
438            + ::core::marker::Send
439            + ::core::marker::Sync
440            + 'static
441    });
442    Ok(quote! {
443        impl #impl_generics ::encore::config::ConfigType for #name #type_generics
444        where
445            #(#predicates),*
446        {
447        }
448    })
449}
450
451/// Whether `ty` is written `&'static str`.
452fn is_static_str(ty: &syn::Type) -> bool {
453    let syn::Type::Reference(r) = ty else {
454        return false;
455    };
456    let syn::Type::Path(elem) = &*r.elem else {
457        return false;
458    };
459    r.mutability.is_none()
460        && r.lifetime.as_ref().is_some_and(|l| l.ident == "static")
461        && elem.qself.is_none()
462        && elem.path.is_ident("str")
463}
464
465#[cfg(test)]
466mod config_type_tests {
467    // Not a glob: this crate's own `test` would shadow the prelude's.
468    use super::expand_config_type;
469    use quote::quote;
470
471    fn expand(input: proc_macro2::TokenStream) -> Result<String, String> {
472        let input: syn::DeriveInput = syn::parse2(input).unwrap();
473        expand_config_type(input)
474            .map(|t| t.to_string())
475            .map_err(|e| e.to_string())
476    }
477
478    #[test]
479    fn implements_the_trait_and_takes_the_known_keys() {
480        let out = expand(quote! {
481            struct Checkout<T> {
482                #[config(min = 1, max = 500)]
483                max_items: u32,
484                #[config(min_len = 1, max_len = 8, pattern = "^[A-Z]+$")]
485                code: String,
486                #[config(min_items = 1, max_items = 3)]
487                tags: Vec<T>,
488                #[config(secret = "StripeKey")]
489                key: ::encore::secrets::Secret,
490            }
491        })
492        .unwrap();
493        assert!(
494            out.contains("impl < T > :: encore :: config :: ConfigType for Checkout < T >"),
495            "{out}"
496        );
497        assert!(
498            out.contains("Checkout < T > : :: encore :: config :: __private :: DeserializeOwned"),
499            "{out}"
500        );
501    }
502
503    #[test]
504    fn refuses_unknown_keys_and_misplaced_attributes() {
505        let err = expand(quote! {
506            struct Checkout {
507                #[config(minimum = 1)]
508                max_items: u32,
509            }
510        })
511        .unwrap_err();
512        assert!(err.contains("unknown config attribute"), "{err}");
513
514        let err = expand(quote! {
515            #[config(min = 1)]
516            enum Mode { Off, On }
517        })
518        .unwrap_err();
519        assert!(err.contains("goes on a field"), "{err}");
520
521        // Enum variants' fields take them.
522        assert!(expand(quote! {
523            enum Limit { Percent(#[config(max = 100)] u8), Off }
524        })
525        .is_ok());
526    }
527}