chiark / gitweb /
1233b4103d5fdd15c3c13a4e9b373192e9191f39
[hippotat.git] / macros / macros.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use syn::{parse_macro_input, parse_quote};
6 use syn::{Data, DataStruct, DeriveInput, LitStr, Meta, NestedMeta};
7 use quote::{quote, quote_spanned, ToTokens};
8 use proc_macro2::{Literal, TokenStream};
9
10 use itertools::Itertools;
11
12 /// Generates config resolver method
13 /// 
14 /// Each field ends up having an SKL and a method.
15 /// The method actually looks up the value in a particular link context.
16 /// SKL is passed to the method, which usually uses it to decide which
17 /// sections to look in.  But it is also used by general validation,
18 /// unconditionally, to reject settings in the wrong section.
19 ///
20 /// Atrributes:
21 ///
22 ///  * `limited`, `server`, `client`: cooked sets of settings;
23 ///    default `SKL` is `PerClient` except for `limited`
24 ///  * `special(method, SKL)`
25 ///
26 /// Generated code
27 ///
28 /// ```no_run
29 /// impl<'c> ResolveContext<'c> {
30 ///
31 ///   // SKL here is used by SectionKindList::contains()
32 ///   const FIELDS: &'static [(&'static str, SectionKindList)] = &[ ... ];
33 ///
34 ///   #[throws(AE)]
35 ///   fn resolve_instance(&self) -> InstanceConfig {
36 ///     InstanceConfig {
37 ///       ...
38 ///        // SKL here is usually passed to first_of, but the method
39 ///        // can do something more special.
40 ///        max_batch_down: self.limited("max_batch_down", SKL::PerClient)?,
41 ///        ...
42 ///      }
43 ///   }
44 /// }
45 /// ```
46 #[proc_macro_derive(ResolveConfig, attributes(
47   limited, server, client, computed, special
48 ))]
49 pub fn resolve(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
50   let input = parse_macro_input!(input as DeriveInput);
51
52   let fields = match input.data {
53     Data::Struct(DataStruct { fields: syn::Fields::Named(ref f),.. }) => f,
54     _ => panic!(),
55   };
56
57   let target = &input.ident;
58
59   let mut names = vec![];
60   let mut output = vec![];
61   for field in &fields.named {
62     //dbg!(field);
63     let fname = &field.ident.as_ref().unwrap();
64     let fname_span = fname.span();
65     let mut skl = Some(quote_spanned!{fname_span=> SectionKindList::PerClient });
66     let mut method = quote_spanned!{fname_span=> ordinary };
67     for attr in &field.attrs {
68       let atspan = attr.path.segments.last().unwrap().ident.span();
69       if attr.tokens.is_empty() {
70         method = attr.path.to_token_stream();
71         if &attr.path == &parse_quote!{ limited } {
72           skl = Some(quote_spanned!{atspan=> SectionKindList::Limited });
73         } else if &attr.path == &parse_quote!{ computed } {
74           skl = Some(quote_spanned!{atspan=> SectionKindList::None });
75         }
76       } else if &attr.path == &parse_quote!{ special } {
77         let meta = match attr.parse_meta().unwrap() {
78           Meta::List(list) => list,
79           _ => panic!(),
80         };
81         let (tmethod, tskl) = meta.nested.iter().collect_tuple().unwrap();
82         fn get_path(meta: &NestedMeta) -> TokenStream {
83           match meta {
84             NestedMeta::Meta(Meta::Path(ref path)) => path.to_token_stream(),
85             _ => panic!(),
86           }
87         }
88         method = get_path(tmethod);
89         skl = Some(get_path(tskl));
90       }
91     }
92     let fname_string = fname.to_string();
93     let fname_lit = Literal::string( &fname_string );
94     let skl = skl.expect(&format!("SKL not specified! (field {:?})!", fname));
95
96     names.push(quote!{
97       (#fname_lit, #skl),
98     });
99     //dbg!(&method);
100     output.push(quote!{
101       #fname: rctx. #method ( #fname_lit, #skl )?,
102     });
103     //eprintln!("{:?} method={:?} skl={:?}", field.ident, method, skl);
104   }
105   //dbg!(&output);
106
107   let output = quote! {
108     impl #target {
109       const FIELDS: &'static [(&'static str, SectionKindList)]
110         = &[ #( #names )* ];
111
112       fn resolve_instance(rctx: &ResolveContext)
113           -> ::std::result::Result<#target, anyhow::Error>
114       {
115         ::std::result::Result::Ok(#target {
116           #( #output )*
117         })
118       }
119     }
120   };
121   //eprintln!("{}", &output);
122   output.into()
123 }
124
125 #[proc_macro]
126 pub fn into_crlfs(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
127   let input: proc_macro2::TokenStream = input.into();
128   let token: LitStr = syn::parse2(input).expect("expected literal");
129   let input = token.value();
130   let output = input.split_inclusive('\n')
131     .map(|s| s.trim_start_matches(&[' ','\t'][..]))
132     .map(|s| match s.strip_suffix("\n") {
133       None => [s, ""],
134       Some(l) => [l, "\r\n"],
135     })
136     .flatten()
137     .collect::<String>();
138   //dbg!(&output);
139   let output = LitStr::new(&output, token.span());
140   let output = quote!(#output);
141   output.into()
142 }