chiark / gitweb /
test: run-*: allow overriding the command
[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 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   for field in &fields.named {
83     //dbg!(field);
84     let fname = &field.ident.as_ref().unwrap();
85     let ty = &field.ty;
86     let fname_span = fname.span();
87     let skl = RefCell::new(None);
88     let set_skl = |new| {
89       let mut skl = skl.borrow_mut();
90       if let Some(old) = &*skl { panic!("dup SKL {} and {} for field {}",
91                                         old, new, &fname); }
92       *skl = Some(new);
93     };
94     let mut method = quote_spanned!{fname_span=> ordinary };
95     for attr in &field.attrs {
96       let atspan = attr.path.segments.last().unwrap().ident.span();
97       if attr.tokens.is_empty() {
98         if &attr.path == &parse_quote!{ per_client } {
99           set_skl(quote_spanned!{fname_span=> SectionKindList::PerClient });
100           continue;
101         } else if &attr.path == &parse_quote!{ global } {
102           set_skl(quote_spanned!{fname_span=> SectionKindList::Global });
103           global_fields.push(syn::Field {
104             attrs: vec![],
105             ..field.clone()
106           });
107           global_assignments.push(quote_spanned!(fname_span=>
108             #fname: <#ty as ResolveGlobal>::resolve
109                     (l.iter().map(|e| &e.#fname)),
110           ));
111           continue;
112         }
113         method = attr.path.to_token_stream();
114         if &attr.path == &parse_quote!{ limited } {
115           set_skl(quote_spanned!{atspan=> SectionKindList::Limited });
116         } else if &attr.path == &parse_quote!{ client } {
117           set_skl(quote_spanned!{atspan=> SectionKindList::PerClient });
118         } else if &attr.path == &parse_quote!{ computed } {
119           set_skl(quote_spanned!{atspan=> SectionKindList::None });
120         }
121       } else if &attr.path == &parse_quote!{ special } {
122         let meta = match attr.parse_meta().unwrap() {
123           Meta::List(list) => list,
124           _ => panic!(),
125         };
126         let (tmethod, tskl) = meta.nested.iter().collect_tuple().unwrap();
127         fn get_path(meta: &NestedMeta) -> TokenStream {
128           match meta {
129             NestedMeta::Meta(Meta::Path(ref path)) => path.to_token_stream(),
130             _ => panic!(),
131           }
132         }
133         method = get_path(tmethod);
134         *skl.borrow_mut() = Some(get_path(tskl));
135       }
136     }
137     let fname_string = fname.to_string();
138     let fname_lit = Literal::string( &fname_string );
139     let skl = skl.into_inner()
140       .expect(&format!("SKL not specified! (field {})!", fname));
141
142     names.push(quote!{
143       (#fname_lit, #skl),
144     });
145     //dbg!(&method);
146     output.push(quote!{
147       #fname: rctx. #method ( #fname_lit, #skl )?,
148     });
149     //eprintln!("{:?} method={:?} skl={:?}", field.ident, method, skl);
150   }
151   //dbg!(&output);
152
153   let global = syn::Ident::new(&format!("{}Global", top_ident),
154                                top_ident.span());
155
156   let output = quote! {
157     impl #target {
158       const FIELDS: &'static [(&'static str, SectionKindList)]
159         = &[ #( #names )* ];
160
161       fn resolve_instance(rctx: &ResolveContext)
162           -> ::std::result::Result<#target, anyhow::Error>
163       {
164         ::std::result::Result::Ok(#target {
165           #( #output )*
166         })
167       }
168     }
169
170     #[derive(Debug)]
171     pub struct #global {
172       #( #global_fields ),*
173     }
174
175     impl #global {
176       pub fn from(l: &[#top_ident]) -> #global { #global {
177         #( #global_assignments )*
178       } }
179     }
180   };
181
182   //eprintln!("{}", &output);
183   output.into()
184 }
185
186 #[proc_macro]
187 pub fn into_crlfs(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
188   let input: proc_macro2::TokenStream = input.into();
189   let token: LitStr = syn::parse2(input).expect("expected literal");
190   let input = token.value();
191   let output = input.split_inclusive('\n')
192     .map(|s| s.trim_start_matches(&[' ','\t'][..]))
193     .map(|s| match s.strip_suffix("\n") {
194       None => [s, ""],
195       Some(l) => [l, "\r\n"],
196     })
197     .flatten()
198     .collect::<String>();
199   //dbg!(&output);
200   let output = LitStr::new(&output, token.span());
201   let output = quote!(#output);
202   output.into()
203 }