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 itertools::Itertools;
12 /// Generates config resolver method
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.
22 /// * `limited`, `server`, `client`: cooked sets of settings;
23 /// default `SKL` is `PerClient` except for `limited`
24 /// * `special(method, SKL)`
29 /// impl<'c> ResolveContext<'c> {
31 /// // SKL here is used by SectionKindList::contains()
32 /// const FIELDS: &'static [(&'static str, SectionKindList)] = &[ ... ];
35 /// fn resolve_instance(&self) -> InstanceConfig {
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)?,
46 #[proc_macro_derive(ResolveConfig, attributes(
47 limited, server, client, computed, special
49 pub fn resolve(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
50 let input = parse_macro_input!(input as DeriveInput);
52 let fields = match input.data {
53 Data::Struct(DataStruct { fields: syn::Fields::Named(ref f),.. }) => f,
57 let target = &input.ident;
59 let mut names = vec![];
60 let mut output = vec![];
61 for field in &fields.named {
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 });
76 } else if &attr.path == &parse_quote!{ special } {
77 let meta = match attr.parse_meta().unwrap() {
78 Meta::List(list) => list,
81 let (tmethod, tskl) = meta.nested.iter().collect_tuple().unwrap();
82 fn get_path(meta: &NestedMeta) -> TokenStream {
84 NestedMeta::Meta(Meta::Path(ref path)) => path.to_token_stream(),
88 method = get_path(tmethod);
89 skl = Some(get_path(tskl));
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));
101 #fname: rctx. #method ( #fname_lit, #skl )?,
103 //eprintln!("{:?} method={:?} skl={:?}", field.ident, method, skl);
107 let output = quote! {
109 const FIELDS: &'static [(&'static str, SectionKindList)]
112 fn resolve_instance(rctx: &ResolveContext)
113 -> ::std::result::Result<#target, anyhow::Error>
115 ::std::result::Result::Ok(#target {
121 //eprintln!("{}", &output);
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") {
134 Some(l) => [l, "\r\n"],
137 .collect::<String>();
139 let output = LitStr::new(&output, token.span());
140 let output = quote!(#output);