1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
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};
10 use std::cell::RefCell;
12 use itertools::Itertools;
14 /// Generates config resolver method
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.
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)`
32 /// impl<'c> ResolveContext<'c> {
34 /// // SKL here is used by SectionKindList::contains()
35 /// const FIELDS: &'static [(&'static str, SectionKindList)] = &[ ... ];
38 /// fn resolve_instance(&self) -> InstanceConfig {
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)?,
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)),
57 #[proc_macro_derive(ResolveConfig, attributes(
58 limited, server, client, computed, special,
61 pub fn resolve(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
62 let input = parse_macro_input!(input as DeriveInput);
64 let (fields, top_ident) = match input {
67 data: Data::Struct(DataStruct {
68 fields: syn::Fields::Named(ref f),
76 let target = &input.ident;
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 {
84 let fname = &field.ident.as_ref().unwrap();
86 let fname_span = fname.span();
87 let skl = RefCell::new(None);
89 let mut skl = skl.borrow_mut();
90 if let Some(old) = &*skl { panic!("dup SKL {} and {} for field {}",
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 });
101 } else if &attr.path == &parse_quote!{ global } {
102 set_skl(quote_spanned!{fname_span=> SectionKindList::Global });
103 global_fields.push(syn::Field {
107 global_assignments.push(quote_spanned!(fname_span=>
108 #fname: <#ty as ResolveGlobal>::resolve
109 (l.iter().map(|e| &e.#fname)),
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 });
121 } else if &attr.path == &parse_quote!{ special } {
122 let meta = match attr.parse_meta().unwrap() {
123 Meta::List(list) => list,
126 let (tmethod, tskl) = meta.nested.iter().collect_tuple().unwrap();
127 fn get_path(meta: &NestedMeta) -> TokenStream {
129 NestedMeta::Meta(Meta::Path(ref path)) => path.to_token_stream(),
133 method = get_path(tmethod);
134 *skl.borrow_mut() = Some(get_path(tskl));
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));
147 #fname: rctx. #method ( #fname_lit, #skl )?,
149 //eprintln!("{:?} method={:?} skl={:?}", field.ident, method, skl);
153 let global = syn::Ident::new(&format!("{}Global", top_ident),
156 let output = quote! {
158 const FIELDS: &'static [(&'static str, SectionKindList)]
161 fn resolve_instance(rctx: &ResolveContext)
162 -> ::std::result::Result<#target, anyhow::Error>
164 ::std::result::Result::Ok(#target {
172 #( #global_fields ),*
176 pub fn from(l: &[#top_ident]) -> #global { #global {
177 #( #global_assignments )*
182 //eprintln!("{}", &output);
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") {
195 Some(l) => [l, "\r\n"],
198 .collect::<String>();
200 let output = LitStr::new(&output, token.span());
201 let output = quote!(#output);