chiark / gitweb /
print config value
[hippotat.git] / macros / macros.rs
1 // Copyright 2021-2022 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 std::cell::RefCell;
11
12 use itertools::Itertools;
13
14 /// Generates config resolver method
15 /// 
16 /// Each field ends up having an SKL and a method.
17 /// The method actually looks up the value in a particular link context.
18 /// SKL is passed to the method, which usually uses it to decide which
19 /// sections to look in.  But it is also used by general validation,
20 /// unconditionally, to reject settings in the wrong section.
21 ///
22 /// Atrributes:
23 ///
24 ///  * `limited`, `server`, `client`: cooked sets of settings;
25 ///    default `SKL` is `PerClient` except for `limited`
26 ///  * `global` and `per_client`: set the SKL.
27 ///  * `special(method, SKL)`
28 ///
29 /// Generated code
30 ///
31 /// ```no_run
32 /// impl<'c> ResolveContext<'c> {
33 ///
34 ///   // SKL here is used by SectionKindList::contains()
35 ///   const FIELDS: &'static [(&'static str, SectionKindList)] = &[ ... ];
36 ///
37 ///   #[throws(AE)]
38 ///   fn resolve_instance(&self) -> InstanceConfig {
39 ///     InstanceConfig {
40 ///       ...
41 ///        // SKL here is usually passed to first_of, but the method
42 ///        // can do something more special.
43 ///        max_batch_down: self.limited("max_batch_down", SKL::PerClient)?,
44 ///        ...
45 ///      }
46 ///   }
47 /// }
48 ///
49 /// pub struct InstanceConfigCommon { ... }
50 /// impl InstanceConfigCommon {
51 ///   pub fn from(l: &[InstanceConfig]) { InstanceConfigCommon {
52 ///     field: <Type as ResolveGlobal>::resolve(l.iter().map(|e| &e.field)),
53 ///     ...
54 ///   } }
55 /// }
56 /// ```
57 #[proc_macro_derive(ResolveConfig, attributes(
58   limited, server, client, computed, special,
59   per_client, global,
60 ))]
61 pub fn resolve(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
62   let input = parse_macro_input!(input as DeriveInput);
63
64   let (fields, top_ident) = match input {
65     DeriveInput {
66       ref ident,
67       data: Data::Struct(DataStruct {
68         fields: syn::Fields::Named(ref f),
69         ..
70       }),
71       ..
72     } => (f, ident),
73     _ => panic!(),
74   };
75
76   let target = &input.ident;
77
78   let mut names = vec![];
79   let mut output = vec![];
80   let mut global_fields = vec![];
81   let mut global_assignments = vec![];
82   let mut inspects = vec![];
83   for field in &fields.named {
84     //dbg!(field);
85     let fname = &field.ident.as_ref().unwrap();
86     let fname_string = fname.to_string();
87     let fname_lit = Literal::string( &fname_string );
88     let ty = &field.ty;
89     let fname_span = fname.span();
90     let skl = RefCell::new(None);
91     let set_skl = |new| {
92       let mut skl = skl.borrow_mut();
93       if let Some(old) = &*skl { panic!("dup SKL {} and {} for field {}",
94                                         old, new, &fname); }
95       *skl = Some(new);
96     };
97     let mut method = quote_spanned!{fname_span=> ordinary };
98     for attr in &field.attrs {
99       let atspan = attr.path.segments.last().unwrap().ident.span();
100       if attr.tokens.is_empty() {
101         if &attr.path == &parse_quote!{ per_client } {
102           set_skl(quote_spanned!{fname_span=> SectionKindList::PerClient });
103           continue;
104         } else if &attr.path == &parse_quote!{ global } {
105           set_skl(quote_spanned!{fname_span=> SectionKindList::Global });
106           global_fields.push(syn::Field {
107             attrs: vec![],
108             ..field.clone()
109           });
110           global_assignments.push(quote_spanned!(fname_span=>
111             #fname: <#ty as ResolveGlobal>::resolve
112                     (l.iter().map(|e| &e.#fname)),
113           ));
114           inspects.push(quote!{
115             #fname_lit => &self.#fname,
116           });
117           continue;
118         }
119         method = attr.path.to_token_stream();
120         if &attr.path == &parse_quote!{ limited } {
121           set_skl(quote_spanned!{atspan=> SectionKindList::Limited });
122         } else if &attr.path == &parse_quote!{ client } {
123           set_skl(quote_spanned!{atspan=> SectionKindList::PerClient });
124         } else if &attr.path == &parse_quote!{ computed } {
125           set_skl(quote_spanned!{atspan=> SectionKindList::None });
126         }
127       } else if &attr.path == &parse_quote!{ special } {
128         let meta = match attr.parse_meta().unwrap() {
129           Meta::List(list) => list,
130           _ => panic!(),
131         };
132         let (tmethod, tskl) = meta.nested.iter().collect_tuple().unwrap();
133         fn get_path(meta: &NestedMeta) -> TokenStream {
134           match meta {
135             NestedMeta::Meta(Meta::Path(ref path)) => path.to_token_stream(),
136             _ => panic!(),
137           }
138         }
139         method = get_path(tmethod);
140         *skl.borrow_mut() = Some(get_path(tskl));
141       }
142     }
143     let skl = skl.into_inner()
144       .expect(&format!("SKL not specified! (field {})!", fname));
145
146     names.push(quote!{
147       (#fname_lit, #skl),
148     });
149     //dbg!(&method);
150     output.push(quote!{
151       #fname: rctx. #method ( #fname_lit, #skl )?,
152     });
153     //eprintln!("{:?} method={:?} skl={:?}", field.ident, method, skl);
154   }
155   //dbg!(&output);
156
157   let global = syn::Ident::new(&format!("{}Global", top_ident),
158                                top_ident.span());
159
160   let output = quote! {
161     impl #target {
162       const FIELDS: &'static [(&'static str, SectionKindList)]
163         = &[ #( #names )* ];
164
165       fn resolve_instance(rctx: &ResolveContext)
166           -> ::std::result::Result<#target, anyhow::Error>
167       {
168         ::std::result::Result::Ok(#target {
169           #( #output )*
170         })
171       }
172     }
173
174     #[derive(Debug)]
175     pub struct #global {
176       #( #global_fields ),*
177     }
178
179     impl #global {
180       pub fn from(l: &[#top_ident]) -> #global { #global {
181         #( #global_assignments )*
182       } }
183
184       pub fn inspect_key(&self, field: &'_ str)
185                          -> Option<&dyn InspectableConfigValue> {
186         Some(match field {
187           #( #inspects )*
188           _ => return None,
189         })
190       }
191     }
192   };
193
194   //eprintln!("{}", &output);
195   output.into()
196 }
197
198 #[proc_macro]
199 pub fn into_crlfs(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
200   let input: proc_macro2::TokenStream = input.into();
201   let token: LitStr = syn::parse2(input).expect("expected literal");
202   let input = token.value();
203   let output = input.split_inclusive('\n')
204     .map(|s| s.trim_start_matches(&[' ','\t'][..]))
205     .map(|s| match s.strip_suffix("\n") {
206       None => [s, ""],
207       Some(l) => [l, "\r\n"],
208     })
209     .flatten()
210     .collect::<String>();
211   //dbg!(&output);
212   let output = LitStr::new(&output, token.span());
213   let output = quote!(#output);
214   output.into()
215 }