1#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
2#![deny(missing_debug_implementations, nonstandard_style)]
3
4use proc_macro::TokenStream;
5use quote::quote;
6use syn::{Error, Lit, Meta, NestedMeta, ReturnType};
7
8#[proc_macro_attribute]
9pub fn root(attr: TokenStream, item: TokenStream) -> TokenStream {
10 let input = syn::parse_macro_input!(item as syn::ItemFn);
11 let args = syn::parse_macro_input!(attr as syn::AttributeArgs);
12
13 let body = &input.block;
14 let attrs = &input.attrs;
15 let inputs = &input.sig.inputs;
16 let ret = &input.sig.output;
17
18 if input.sig.asyncness.is_none() {
19 let msg = "functions tagged with '#[fort::root]' should be declared as 'async'";
20 return Error::new_spanned(input.sig.fn_token, msg)
21 .to_compile_error()
22 .into();
23 } else if input.sig.ident != "main" {
24 let msg = "only the main function can be tagged with '#[fort::root]'";
25 return Error::new_spanned(input.sig.ident, msg)
26 .to_compile_error()
27 .into();
28 } else if inputs.len() != 1 {
29 let msg = "functions tagged with '#[fort::root]' should have one argument of type 'BastionContext'";
30 return Error::new_spanned(inputs, msg).to_compile_error().into();
31 } else if let ReturnType::Default = ret {
32 let msg = "functions tagged with '#[fort::root]' should return 'Result<(), ()>'";
33 return Error::new_spanned(ret, msg).to_compile_error().into();
34 }
35
36 let mut redundancy = 1;
40 for arg in args {
41 if let NestedMeta::Meta(Meta::NameValue(meta)) = arg {
42 let ident = meta.path.get_ident();
43 if ident.is_none() {
44 let msg = "must specify an ident";
45 return Error::new_spanned(meta, msg).to_compile_error().into();
46 }
47
48 let ident = ident.unwrap();
49 match ident.to_string().as_str() {
50 "redundancy" => {
51 if let Lit::Int(n) = meta.lit {
52 redundancy = n.base10_parse::<usize>().unwrap();
53 } else {
54 let msg = "'redundancy' should be a number";
55 return Error::new_spanned(meta.lit, msg).to_compile_error().into();
56 }
57 }
58 _ => {
59 let msg = "unknown attribute";
60 return Error::new_spanned(ident, msg).to_compile_error().into();
61 }
62 }
63 }
64 }
65
66 (quote! {
67 fn main() {
68 #(#attrs)*
69 async fn main(#inputs) #ret {
70 #body
71 }
72
73 bastion::Bastion::init();
74 bastion::Bastion::children(|children| {
75 children
76 .with_exec(|ctx| main(ctx))
77 .with_redundancy(#redundancy)
78 }).expect("Couldn't create the main children group.");
79
80 bastion::Bastion::start();
81 bastion::Bastion::block_until_stopped();
82 }
83 })
84 .into()
85}