encore-macros 0.1.0

Procedural macros for the Encore Rust SDK. Use them through the `encore` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Procedural macros for the Encore Rust SDK. They are re-exported by the
//! `encore` crate, which documents them and is what their output refers to:
//! use them from there.

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Expr, ExprLit, ItemFn, Lit, MetaNameValue, ReturnType, Token};

/// The arguments of `#[encore::test]`: those of `#[tokio::test]` that choose
/// the runtime.
struct TestArgs {
    multi_thread: bool,
    worker_threads: Option<usize>,
    /// `fixture = PATH`, or `fixture = none`.
    fixture: Option<syn::Path>,
}

impl Parse for TestArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut args = TestArgs {
            multi_thread: false,
            worker_threads: None,
            fixture: None,
        };
        let mut flavor = None;
        for arg in Punctuated::<MetaNameValue, Token![,]>::parse_terminated(input)? {
            if arg.path.is_ident("fixture") {
                let Expr::Path(path) = &arg.value else {
                    return Err(syn::Error::new_spanned(
                        &arg.value,
                        "`fixture` is a fixture's path, or `none`",
                    ));
                };
                args.fixture = Some(path.path.clone());
                continue;
            }
            let lit = match &arg.value {
                Expr::Lit(ExprLit { lit, .. }) => lit,
                other => {
                    return Err(syn::Error::new_spanned(other, "expected a literal"));
                }
            };
            if arg.path.is_ident("flavor") {
                let Lit::Str(value) = lit else {
                    return Err(syn::Error::new_spanned(lit, "`flavor` is a string"));
                };
                args.multi_thread = match value.value().as_str() {
                    "current_thread" => false,
                    "multi_thread" => true,
                    _ => {
                        return Err(syn::Error::new_spanned(
                            value,
                            "the flavor is \"current_thread\" (the default) or \"multi_thread\"",
                        ));
                    }
                };
                flavor = Some(value.span());
            } else if arg.path.is_ident("worker_threads") {
                let Lit::Int(value) = lit else {
                    return Err(syn::Error::new_spanned(lit, "`worker_threads` is a number"));
                };
                args.worker_threads = Some(value.base10_parse()?);
            } else {
                return Err(syn::Error::new_spanned(
                    &arg.path,
                    "unknown argument: expected `flavor`, `worker_threads` or `fixture`",
                ));
            }
        }
        if args.worker_threads.is_some() && !args.multi_thread {
            return Err(syn::Error::new(
                flavor.unwrap_or_else(Span::call_site),
                "`worker_threads` needs `flavor = \"multi_thread\"`",
            ));
        }
        Ok(args)
    }
}

/// See `encore::test`.
#[proc_macro_attribute]
pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
    let args = syn::parse_macro_input!(args as TestArgs);
    let function = syn::parse_macro_input!(item as ItemFn);
    expand_test(args, function)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

fn expand_test(args: TestArgs, function: ItemFn) -> syn::Result<proc_macro2::TokenStream> {
    let ItemFn {
        attrs,
        vis,
        sig,
        block,
    } = function;
    if !sig.inputs.is_empty() {
        return Err(syn::Error::new_spanned(
            &sig.inputs,
            "a test function takes no arguments",
        ));
    }
    if !sig.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &sig.generics,
            "a test function cannot be generic",
        ));
    }
    let name = &sig.ident;
    let output = &sig.output;
    let returns = match output {
        ReturnType::Default => quote!(()),
        ReturnType::Type(_, ty) => quote!(#ty),
    };
    let info = quote! {
        ::encore::testing::__private::TestInfo {
            module: ::core::module_path!(),
            name: ::core::stringify!(#name),
            file: ::core::file!(),
            line: ::core::line!(),
        }
    };

    let fixture = match &args.fixture {
        None => quote!(::encore::testing::__private::FixtureArg::Module),
        Some(path) if path.is_ident("none") => {
            quote!(::encore::testing::__private::FixtureArg::None)
        }
        Some(path) => quote!(::encore::testing::__private::FixtureArg::Named(&#path)),
    };

    let body = if sig.asyncness.is_some() {
        let multi_thread = args.multi_thread;
        let worker_threads = match args.worker_threads {
            Some(n) => quote!(::core::option::Option::Some(#n)),
            None => quote!(::core::option::Option::None),
        };
        quote! {
            ::encore::testing::__private::run::<#returns, _>(
                #info,
                ::encore::testing::__private::RuntimeConfig {
                    multi_thread: #multi_thread,
                    worker_threads: #worker_threads,
                },
                #fixture,
                async move #block,
            )
        }
    } else {
        if args.multi_thread {
            return Err(syn::Error::new_spanned(
                sig.fn_token,
                "a runtime flavor is for an `async fn` test",
            ));
        }
        quote! {
            ::encore::testing::__private::run_sync::<#returns, _>(#info, #fixture, move || #block)
        }
    };

    Ok(quote! {
        #[::core::prelude::v1::test]
        #(#attrs)*
        #vis fn #name() #output {
            #body
        }
    })
}

/// See `encore::pubsub::register`.
#[proc_macro_attribute]
pub fn register(args: TokenStream, item: TokenStream) -> TokenStream {
    if !args.is_empty() {
        return syn::Error::new(
            Span::call_site(),
            "`register` takes no arguments: what it registers is the `static` it is on",
        )
        .into_compile_error()
        .into();
    }
    let item = syn::parse_macro_input!(item as syn::ItemStatic);
    expand_subscription(item)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

fn expand_subscription(mut item: syn::ItemStatic) -> syn::Result<proc_macro2::TokenStream> {
    // The declaration: `Subscription::new(topic, name, handler)`, with its
    // options chained on.
    let mut expr = item.expr.as_mut();
    while let Expr::MethodCall(call) = expr {
        expr = call.receiver.as_mut();
    }
    let declaration = match expr {
        Expr::Call(call) if call.args.len() == 3 => call,
        other => {
            return Err(syn::Error::new_spanned(
                other,
                "expected `Subscription::new(&TOPIC, \"name\", handler)`, optionally followed \
                 by its options",
            ));
        }
    };
    // A handler given by name is boxed, as `Subscription::new` takes it.
    let handler = declaration.args.last_mut().expect("three arguments");
    if !matches!(handler, Expr::Closure(_)) {
        *handler = syn::parse_quote!(|message| ::std::boxed::Box::pin((#handler)(message)));
    }

    let name = &item.ident;
    Ok(quote! {
        #item

        const _: () = {
            #[::encore::pubsub::__private::linkme::distributed_slice(
                ::encore::pubsub::__private::SUBSCRIPTIONS
            )]
            #[linkme(crate = ::encore::pubsub::__private::linkme)]
            static REGISTER: &'static dyn ::encore::pubsub::__private::AnySubscription = &#name;
        };
    })
}

/// See `encore::metrics::Labels`.
#[proc_macro_derive(Labels)]
pub fn derive_labels(input: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(input as syn::DeriveInput);
    expand_labels(input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

fn expand_labels(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    use syn::ext::IdentExt;

    let fields = match &input.data {
        syn::Data::Struct(syn::DataStruct {
            fields: syn::Fields::Named(fields),
            ..
        }) if !fields.named.is_empty() => &fields.named,
        _ => {
            return Err(syn::Error::new_spanned(
                &input.ident,
                "`Labels` is derived for a struct with named fields: each field is a label",
            ));
        }
    };
    let idents: Vec<&syn::Ident> = fields
        .iter()
        .map(|field| field.ident.as_ref().expect("named"))
        .collect();
    // A label is named as its field is written, without the `r#` of a raw one.
    let names = idents.iter().map(|ident| ident.unraw().to_string());
    // A `&'static str` is borrowed as it is, not copied.
    let values = fields.iter().zip(&idents).map(|(field, ident)| {
        if is_static_str(&field.ty) {
            quote! { ::encore::opentelemetry::Value::from(self.#ident) }
        } else {
            quote! { ::encore::metrics::LabelValue::label_value(&self.#ident) }
        }
    });

    let name = &input.ident;
    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
    Ok(quote! {
        impl #impl_generics ::encore::metrics::Labels for #name #type_generics #where_clause {
            fn attributes(&self) -> ::std::vec::Vec<::encore::opentelemetry::KeyValue> {
                ::std::vec![#(::encore::opentelemetry::KeyValue::new(#names, #values)),*]
            }
        }
    })
}

/// See `encore::config::ConfigType`.
#[proc_macro_derive(ConfigType, attributes(config))]
pub fn derive_config_type(input: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(input as syn::DeriveInput);
    expand_config_type(input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// The keys `#[config(...)]` takes on a field. What they mean — and whether
/// they fit the field's type — is the parser's to check, which reads them to
/// build the config's schema.
const CONFIG_KEYS: &[&str] = &[
    "min",
    "max",
    "min_len",
    "max_len",
    "pattern",
    "min_items",
    "max_items",
    "secret",
];

fn expand_config_type(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let mut errors: Vec<syn::Error> = Vec::new();
    let misplaced = |attrs: &[syn::Attribute], errors: &mut Vec<syn::Error>| {
        for attr in attrs.iter().filter(|a| a.path().is_ident("config")) {
            errors.push(syn::Error::new_spanned(
                attr,
                "`#[config(...)]` goes on a field: it constrains that field's value",
            ));
        }
    };
    misplaced(&input.attrs, &mut errors);
    let fields: Vec<&syn::Field> = match &input.data {
        syn::Data::Struct(s) => s.fields.iter().collect(),
        syn::Data::Enum(e) => e
            .variants
            .iter()
            .flat_map(|v| {
                misplaced(&v.attrs, &mut errors);
                v.fields.iter()
            })
            .collect(),
        syn::Data::Union(u) => {
            return Err(syn::Error::new_spanned(
                u.union_token,
                "a config type is a struct or an enum",
            ));
        }
    };
    for field in fields {
        for attr in field.attrs.iter().filter(|a| a.path().is_ident("config")) {
            let parsed =
                attr.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated);
            match parsed {
                Ok(args) => {
                    for arg in args {
                        if !CONFIG_KEYS.iter().any(|k| arg.path.is_ident(k)) {
                            errors.push(syn::Error::new_spanned(
                                &arg.path,
                                format!(
                                    "unknown config attribute: expected one of {}",
                                    CONFIG_KEYS
                                        .iter()
                                        .map(|k| format!("`{k}`"))
                                        .collect::<Vec<_>>()
                                        .join(", ")
                                ),
                            ));
                        }
                    }
                }
                Err(err) => errors.push(err),
            }
        }
    }
    if let Some(mut first) = errors.pop() {
        for err in errors {
            first.combine(err);
        }
        return Err(first);
    }

    let name = &input.ident;
    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
    // The trait's supertraits, stated for the type itself, so a generic type
    // is a config type exactly when its arguments make it one.
    let mut predicates: Vec<proc_macro2::TokenStream> = where_clause
        .map(|w| w.predicates.iter().map(|p| quote!(#p)).collect())
        .unwrap_or_default();
    predicates.push(quote! {
        #name #type_generics: ::encore::config::__private::DeserializeOwned
            + ::core::marker::Send
            + ::core::marker::Sync
            + 'static
    });
    Ok(quote! {
        impl #impl_generics ::encore::config::ConfigType for #name #type_generics
        where
            #(#predicates),*
        {
        }
    })
}

/// Whether `ty` is written `&'static str`.
fn is_static_str(ty: &syn::Type) -> bool {
    let syn::Type::Reference(r) = ty else {
        return false;
    };
    let syn::Type::Path(elem) = &*r.elem else {
        return false;
    };
    r.mutability.is_none()
        && r.lifetime.as_ref().is_some_and(|l| l.ident == "static")
        && elem.qself.is_none()
        && elem.path.is_ident("str")
}

#[cfg(test)]
mod config_type_tests {
    // Not a glob: this crate's own `test` would shadow the prelude's.
    use super::expand_config_type;
    use quote::quote;

    fn expand(input: proc_macro2::TokenStream) -> Result<String, String> {
        let input: syn::DeriveInput = syn::parse2(input).unwrap();
        expand_config_type(input)
            .map(|t| t.to_string())
            .map_err(|e| e.to_string())
    }

    #[test]
    fn implements_the_trait_and_takes_the_known_keys() {
        let out = expand(quote! {
            struct Checkout<T> {
                #[config(min = 1, max = 500)]
                max_items: u32,
                #[config(min_len = 1, max_len = 8, pattern = "^[A-Z]+$")]
                code: String,
                #[config(min_items = 1, max_items = 3)]
                tags: Vec<T>,
                #[config(secret = "StripeKey")]
                key: ::encore::secrets::Secret,
            }
        })
        .unwrap();
        assert!(
            out.contains("impl < T > :: encore :: config :: ConfigType for Checkout < T >"),
            "{out}"
        );
        assert!(
            out.contains("Checkout < T > : :: encore :: config :: __private :: DeserializeOwned"),
            "{out}"
        );
    }

    #[test]
    fn refuses_unknown_keys_and_misplaced_attributes() {
        let err = expand(quote! {
            struct Checkout {
                #[config(minimum = 1)]
                max_items: u32,
            }
        })
        .unwrap_err();
        assert!(err.contains("unknown config attribute"), "{err}");

        let err = expand(quote! {
            #[config(min = 1)]
            enum Mode { Off, On }
        })
        .unwrap_err();
        assert!(err.contains("goes on a field"), "{err}");

        // Enum variants' fields take them.
        assert!(expand(quote! {
            enum Limit { Percent(#[config(max = 100)] u8), Off }
        })
        .is_ok());
    }
}