1use 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
12struct TestArgs {
15 multi_thread: bool,
16 worker_threads: Option<usize>,
17 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#[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 let body = if sig.asyncness.is_some() {
136 let multi_thread = args.multi_thread;
137 let worker_threads = match args.worker_threads {
138 Some(n) => quote!(::core::option::Option::Some(#n)),
139 None => quote!(::core::option::Option::None),
140 };
141 quote! {
142 ::encore::testing::__private::run::<#returns, _>(
143 #info,
144 ::encore::testing::__private::RuntimeConfig {
145 multi_thread: #multi_thread,
146 worker_threads: #worker_threads,
147 },
148 #fixture,
149 async move #block,
150 )
151 }
152 } else {
153 if args.multi_thread {
154 return Err(syn::Error::new_spanned(
155 sig.fn_token,
156 "a runtime flavor is for an `async fn` test",
157 ));
158 }
159 quote! {
160 ::encore::testing::__private::run_sync::<#returns, _>(#info, #fixture, move || #block)
161 }
162 };
163
164 Ok(quote! {
165 #[::core::prelude::v1::test]
166 #(#attrs)*
167 #vis fn #name() #output {
168 #body
169 }
170 })
171}
172
173#[proc_macro_attribute]
175pub fn register(args: TokenStream, item: TokenStream) -> TokenStream {
176 if !args.is_empty() {
177 return syn::Error::new(
178 Span::call_site(),
179 "`register` takes no arguments: what it registers is the `static` it is on",
180 )
181 .into_compile_error()
182 .into();
183 }
184 let item = syn::parse_macro_input!(item as syn::ItemStatic);
185 expand_subscription(item)
186 .unwrap_or_else(syn::Error::into_compile_error)
187 .into()
188}
189
190fn expand_subscription(mut item: syn::ItemStatic) -> syn::Result<proc_macro2::TokenStream> {
191 let mut expr = item.expr.as_mut();
194 while let Expr::MethodCall(call) = expr {
195 expr = call.receiver.as_mut();
196 }
197 let declaration = match expr {
198 Expr::Call(call) if call.args.len() == 3 => call,
199 other => {
200 return Err(syn::Error::new_spanned(
201 other,
202 "expected `Subscription::new(&TOPIC, \"name\", handler)`, optionally followed \
203 by its options",
204 ));
205 }
206 };
207 let handler = declaration.args.last_mut().expect("three arguments");
209 if !matches!(handler, Expr::Closure(_)) {
210 *handler = syn::parse_quote!(|message| ::std::boxed::Box::pin((#handler)(message)));
211 }
212
213 let name = &item.ident;
214 Ok(quote! {
215 #item
216
217 const _: () = {
218 #[::encore::pubsub::__private::linkme::distributed_slice(
219 ::encore::pubsub::__private::SUBSCRIPTIONS
220 )]
221 #[linkme(crate = ::encore::pubsub::__private::linkme)]
222 static REGISTER: &'static dyn ::encore::pubsub::__private::AnySubscription = &#name;
223 };
224 })
225}
226
227#[proc_macro_derive(Labels)]
229pub fn derive_labels(input: TokenStream) -> TokenStream {
230 let input = syn::parse_macro_input!(input as syn::DeriveInput);
231 expand_labels(input)
232 .unwrap_or_else(syn::Error::into_compile_error)
233 .into()
234}
235
236fn expand_labels(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
237 use syn::ext::IdentExt;
238
239 let fields = match &input.data {
240 syn::Data::Struct(syn::DataStruct {
241 fields: syn::Fields::Named(fields),
242 ..
243 }) if !fields.named.is_empty() => &fields.named,
244 _ => {
245 return Err(syn::Error::new_spanned(
246 &input.ident,
247 "`Labels` is derived for a struct with named fields: each field is a label",
248 ));
249 }
250 };
251 let idents: Vec<&syn::Ident> = fields
252 .iter()
253 .map(|field| field.ident.as_ref().expect("named"))
254 .collect();
255 let names = idents.iter().map(|ident| ident.unraw().to_string());
257 let values = fields.iter().zip(&idents).map(|(field, ident)| {
259 if is_static_str(&field.ty) {
260 quote! { ::encore::opentelemetry::Value::from(self.#ident) }
261 } else {
262 quote! { ::encore::metrics::LabelValue::label_value(&self.#ident) }
263 }
264 });
265
266 let name = &input.ident;
267 let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
268 Ok(quote! {
269 impl #impl_generics ::encore::metrics::Labels for #name #type_generics #where_clause {
270 fn attributes(&self) -> ::std::vec::Vec<::encore::opentelemetry::KeyValue> {
271 ::std::vec![#(::encore::opentelemetry::KeyValue::new(#names, #values)),*]
272 }
273 }
274 })
275}
276
277#[proc_macro_derive(ConfigType, attributes(config))]
279pub fn derive_config_type(input: TokenStream) -> TokenStream {
280 let input = syn::parse_macro_input!(input as syn::DeriveInput);
281 expand_config_type(input)
282 .unwrap_or_else(syn::Error::into_compile_error)
283 .into()
284}
285
286const CONFIG_KEYS: &[&str] = &[
290 "min",
291 "max",
292 "min_len",
293 "max_len",
294 "pattern",
295 "min_items",
296 "max_items",
297 "secret",
298];
299
300fn expand_config_type(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
301 let mut errors: Vec<syn::Error> = Vec::new();
302 let misplaced = |attrs: &[syn::Attribute], errors: &mut Vec<syn::Error>| {
303 for attr in attrs.iter().filter(|a| a.path().is_ident("config")) {
304 errors.push(syn::Error::new_spanned(
305 attr,
306 "`#[config(...)]` goes on a field: it constrains that field's value",
307 ));
308 }
309 };
310 misplaced(&input.attrs, &mut errors);
311 let fields: Vec<&syn::Field> = match &input.data {
312 syn::Data::Struct(s) => s.fields.iter().collect(),
313 syn::Data::Enum(e) => e
314 .variants
315 .iter()
316 .flat_map(|v| {
317 misplaced(&v.attrs, &mut errors);
318 v.fields.iter()
319 })
320 .collect(),
321 syn::Data::Union(u) => {
322 return Err(syn::Error::new_spanned(
323 u.union_token,
324 "a config type is a struct or an enum",
325 ));
326 }
327 };
328 for field in fields {
329 for attr in field.attrs.iter().filter(|a| a.path().is_ident("config")) {
330 let parsed =
331 attr.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated);
332 match parsed {
333 Ok(args) => {
334 for arg in args {
335 if !CONFIG_KEYS.iter().any(|k| arg.path.is_ident(k)) {
336 errors.push(syn::Error::new_spanned(
337 &arg.path,
338 format!(
339 "unknown config attribute: expected one of {}",
340 CONFIG_KEYS
341 .iter()
342 .map(|k| format!("`{k}`"))
343 .collect::<Vec<_>>()
344 .join(", ")
345 ),
346 ));
347 }
348 }
349 }
350 Err(err) => errors.push(err),
351 }
352 }
353 }
354 if let Some(mut first) = errors.pop() {
355 for err in errors {
356 first.combine(err);
357 }
358 return Err(first);
359 }
360
361 let name = &input.ident;
362 let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
363 let mut predicates: Vec<proc_macro2::TokenStream> = where_clause
366 .map(|w| w.predicates.iter().map(|p| quote!(#p)).collect())
367 .unwrap_or_default();
368 predicates.push(quote! {
369 #name #type_generics: ::encore::config::__private::DeserializeOwned
370 + ::core::marker::Send
371 + ::core::marker::Sync
372 + 'static
373 });
374 Ok(quote! {
375 impl #impl_generics ::encore::config::ConfigType for #name #type_generics
376 where
377 #(#predicates),*
378 {
379 }
380 })
381}
382
383fn is_static_str(ty: &syn::Type) -> bool {
385 let syn::Type::Reference(r) = ty else {
386 return false;
387 };
388 let syn::Type::Path(elem) = &*r.elem else {
389 return false;
390 };
391 r.mutability.is_none()
392 && r.lifetime.as_ref().is_some_and(|l| l.ident == "static")
393 && elem.qself.is_none()
394 && elem.path.is_ident("str")
395}
396
397#[cfg(test)]
398mod config_type_tests {
399 use super::expand_config_type;
401 use quote::quote;
402
403 fn expand(input: proc_macro2::TokenStream) -> Result<String, String> {
404 let input: syn::DeriveInput = syn::parse2(input).unwrap();
405 expand_config_type(input)
406 .map(|t| t.to_string())
407 .map_err(|e| e.to_string())
408 }
409
410 #[test]
411 fn implements_the_trait_and_takes_the_known_keys() {
412 let out = expand(quote! {
413 struct Checkout<T> {
414 #[config(min = 1, max = 500)]
415 max_items: u32,
416 #[config(min_len = 1, max_len = 8, pattern = "^[A-Z]+$")]
417 code: String,
418 #[config(min_items = 1, max_items = 3)]
419 tags: Vec<T>,
420 #[config(secret = "StripeKey")]
421 key: ::encore::secrets::Secret,
422 }
423 })
424 .unwrap();
425 assert!(
426 out.contains("impl < T > :: encore :: config :: ConfigType for Checkout < T >"),
427 "{out}"
428 );
429 assert!(
430 out.contains("Checkout < T > : :: encore :: config :: __private :: DeserializeOwned"),
431 "{out}"
432 );
433 }
434
435 #[test]
436 fn refuses_unknown_keys_and_misplaced_attributes() {
437 let err = expand(quote! {
438 struct Checkout {
439 #[config(minimum = 1)]
440 max_items: u32,
441 }
442 })
443 .unwrap_err();
444 assert!(err.contains("unknown config attribute"), "{err}");
445
446 let err = expand(quote! {
447 #[config(min = 1)]
448 enum Mode { Off, On }
449 })
450 .unwrap_err();
451 assert!(err.contains("goes on a field"), "{err}");
452
453 assert!(expand(quote! {
455 enum Limit { Percent(#[config(max = 100)] u8), Off }
456 })
457 .is_ok());
458 }
459}