Skip to main content

actix_macros/
lib.rs

1//! Macros for Actix system and runtime.
2//!
3//! The [`actix-rt`](https://docs.rs/actix-rt) crate must be available for macro output to compile.
4//!
5//! # Entry-point
6//! See docs for the [`#[main]`](macro@main) macro.
7//!
8//! # Tests
9//! See docs for the [`#[test]`](macro@test) macro.
10
11#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
12#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
13
14use proc_macro::TokenStream;
15use quote::quote;
16use syn::parse::Parser as _;
17
18type AttributeArgs = syn::punctuated::Punctuated<syn::Meta, syn::Token![,]>;
19
20/// Marks async entry-point function to be executed by Actix system.
21///
22/// # Examples
23/// ```
24/// #[actix_rt::main]
25/// async fn main() {
26///     println!("Hello world");
27/// }
28/// ```
29#[proc_macro_attribute]
30pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
31    let mut input = match syn::parse::<syn::ItemFn>(item.clone()) {
32        Ok(input) => input,
33        // on parse err, make IDEs happy; see fn docs
34        Err(err) => return input_and_compile_error(item, err),
35    };
36
37    let parser = AttributeArgs::parse_terminated;
38    let args = match parser.parse(args.clone()) {
39        Ok(args) => args,
40        Err(err) => return input_and_compile_error(args, err),
41    };
42
43    let attrs = &input.attrs;
44    let vis = &input.vis;
45    let sig = &mut input.sig;
46    let body = &input.block;
47
48    if sig.asyncness.is_none() {
49        return syn::Error::new_spanned(
50            sig.fn_token,
51            "the async keyword is missing from the function declaration",
52        )
53        .to_compile_error()
54        .into();
55    }
56
57    let mut system = syn::parse_str::<syn::Path>("::actix_rt::System").unwrap();
58
59    for arg in &args {
60        match arg {
61            syn::Meta::NameValue(syn::MetaNameValue {
62                path,
63                value:
64                    syn::Expr::Lit(syn::ExprLit {
65                        lit: syn::Lit::Str(lit),
66                        ..
67                    }),
68                ..
69            }) => match path
70                .get_ident()
71                .map(|i| i.to_string().to_lowercase())
72                .as_deref()
73            {
74                Some("system") => match lit.parse() {
75                    Ok(path) => system = path,
76                    Err(_) => {
77                        return syn::Error::new_spanned(lit, "Expected path")
78                            .to_compile_error()
79                            .into();
80                    }
81                },
82                _ => {
83                    return syn::Error::new_spanned(arg, "Unknown attribute specified")
84                        .to_compile_error()
85                        .into();
86                }
87            },
88
89            _ => {
90                return syn::Error::new_spanned(arg, "Unknown attribute specified")
91                    .to_compile_error()
92                    .into();
93            }
94        }
95    }
96
97    sig.asyncness = None;
98
99    (quote! {
100        #(#attrs)*
101        #vis #sig {
102            <#system>::new().block_on(async move { #body })
103        }
104    })
105    .into()
106}
107
108/// Marks async test function to be executed in an Actix system.
109///
110/// # Examples
111/// ```
112/// #[actix_rt::test]
113/// async fn my_test() {
114///     assert!(true);
115/// }
116/// ```
117#[proc_macro_attribute]
118pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
119    let mut input = match syn::parse::<syn::ItemFn>(item.clone()) {
120        Ok(input) => input,
121        // on parse err, make IDEs happy; see fn docs
122        Err(err) => return input_and_compile_error(item, err),
123    };
124
125    let parser = AttributeArgs::parse_terminated;
126    let args = match parser.parse(args.clone()) {
127        Ok(args) => args,
128        Err(err) => return input_and_compile_error(args, err),
129    };
130
131    let attrs = &input.attrs;
132    let vis = &input.vis;
133    let sig = &mut input.sig;
134    let body = &input.block;
135    let mut has_test_attr = false;
136
137    for attr in attrs {
138        if attr.path().is_ident("test") {
139            has_test_attr = true;
140        }
141    }
142
143    if sig.asyncness.is_none() {
144        return syn::Error::new_spanned(
145            input.sig.fn_token,
146            "the async keyword is missing from the function declaration",
147        )
148        .to_compile_error()
149        .into();
150    }
151
152    sig.asyncness = None;
153
154    let missing_test_attr = if has_test_attr {
155        quote! {}
156    } else {
157        quote! { #[::core::prelude::v1::test] }
158    };
159
160    let mut system = syn::parse_str::<syn::Path>("::actix_rt::System").unwrap();
161
162    for arg in &args {
163        match arg {
164            syn::Meta::NameValue(syn::MetaNameValue {
165                path,
166                value:
167                    syn::Expr::Lit(syn::ExprLit {
168                        lit: syn::Lit::Str(lit),
169                        ..
170                    }),
171                ..
172            }) => match path
173                .get_ident()
174                .map(|i| i.to_string().to_lowercase())
175                .as_deref()
176            {
177                Some("system") => match lit.parse() {
178                    Ok(path) => system = path,
179                    Err(_) => {
180                        return syn::Error::new_spanned(lit, "Expected path")
181                            .to_compile_error()
182                            .into();
183                    }
184                },
185                _ => {
186                    return syn::Error::new_spanned(arg, "Unknown attribute specified")
187                        .to_compile_error()
188                        .into();
189                }
190            },
191            _ => {
192                return syn::Error::new_spanned(arg, "Unknown attribute specified")
193                    .to_compile_error()
194                    .into();
195            }
196        }
197    }
198
199    (quote! {
200        #missing_test_attr
201        #(#attrs)*
202        #vis #sig {
203            <#system>::new().block_on(async { #body })
204        }
205    })
206    .into()
207}
208
209/// Converts the error to a token stream and appends it to the original input.
210///
211/// Returning the original input in addition to the error is good for IDEs which can gracefully
212/// recover and show more precise errors within the macro body.
213///
214/// See <https://github.com/rust-analyzer/rust-analyzer/issues/10468> for more info.
215fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStream {
216    let compile_err = TokenStream::from(err.to_compile_error());
217    item.extend(compile_err);
218    item
219}