1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use proc_macro_crate::{crate_name, FoundCrate};
use quote::quote;
use syn::parse::{Parse, ParseStream, Result};
mod codec;
mod from_assignment_helpers;
mod index_assignment;
mod single_page;
pub(crate) fn vote_field(n: usize) -> Ident {
quote::format_ident!("votes{}", n)
}
pub(crate) fn syn_err(message: &'static str) -> syn::Error {
syn::Error::new(Span::call_site(), message)
}
#[proc_macro]
pub fn generate_solution_type(item: TokenStream) -> TokenStream {
let solution_def = syn::parse_macro_input!(item as SolutionDef);
let imports = imports().unwrap_or_else(|e| e.to_compile_error());
let def = single_page::generate(solution_def).unwrap_or_else(|e| e.to_compile_error());
quote!(
#imports
#def
)
.into()
}
struct SolutionDef {
vis: syn::Visibility,
ident: syn::Ident,
voter_type: syn::Type,
target_type: syn::Type,
weight_type: syn::Type,
count: usize,
compact_encoding: bool,
}
fn check_attributes(input: ParseStream) -> syn::Result<bool> {
let attrs = input.call(syn::Attribute::parse_outer).unwrap_or_default();
if attrs.len() > 1 {
return Err(syn_err("compact solution can accept only #[compact]"))
}
Ok(attrs.iter().any(|attr| {
if attr.path.segments.len() == 1 {
let segment = attr.path.segments.first().expect("Vec with len 1 can be popped.");
if segment.ident == Ident::new("compact", Span::call_site()) {
return true
}
}
false
}))
}
impl Parse for SolutionDef {
fn parse(input: ParseStream) -> syn::Result<Self> {
let compact_encoding = check_attributes(input)?;
let vis: syn::Visibility = input.parse()?;
let _ = <syn::Token![struct]>::parse(input)?;
let ident: syn::Ident = input.parse()?;
let _ = <syn::Token![::]>::parse(input)?;
let generics: syn::AngleBracketedGenericArguments = input.parse()?;
if generics.args.len() != 3 {
return Err(syn_err("Must provide 3 generic args."))
}
let expected_types = ["VoterIndex", "TargetIndex", "Accuracy"];
let mut types: Vec<syn::Type> = generics
.args
.iter()
.zip(expected_types.iter())
.map(|(t, expected)| match t {
syn::GenericArgument::Type(ty) => {
Err(syn::Error::new_spanned(
ty,
format!("Expected binding: `{} = ...`", expected),
))
},
syn::GenericArgument::Binding(syn::Binding { ident, ty, .. }) => {
if ident == expected {
Ok(ty.clone())
} else {
Err(syn::Error::new_spanned(ident, format!("Expected `{}`", expected)))
}
},
_ => Err(syn_err("Wrong type of generic provided. Must be a `type`.")),
})
.collect::<Result<_>>()?;
let weight_type = types.pop().expect("Vector of length 3 can be popped; qed");
let target_type = types.pop().expect("Vector of length 2 can be popped; qed");
let voter_type = types.pop().expect("Vector of length 1 can be popped; qed");
let count_expr: syn::ExprParen = input.parse()?;
let count = parse_parenthesized_number::<usize>(count_expr)?;
Ok(Self { vis, ident, voter_type, target_type, weight_type, count, compact_encoding })
}
}
fn parse_parenthesized_number<N: std::str::FromStr>(input_expr: syn::ExprParen) -> syn::Result<N>
where
<N as std::str::FromStr>::Err: std::fmt::Display,
{
let expr = input_expr.expr;
let expr_lit = match *expr {
syn::Expr::Lit(count_lit) => count_lit.lit,
_ => return Err(syn_err("Count must be literal.")),
};
let int_lit = match expr_lit {
syn::Lit::Int(int_lit) => int_lit,
_ => return Err(syn_err("Count must be int literal.")),
};
int_lit.base10_parse::<N>()
}
fn imports() -> Result<TokenStream2> {
match crate_name("sp-npos-elections") {
Ok(FoundCrate::Itself) => Ok(quote! { use crate as _npos; }),
Ok(FoundCrate::Name(sp_npos_elections)) => {
let ident = syn::Ident::new(&sp_npos_elections, Span::call_site());
Ok(quote!( extern crate #ident as _npos; ))
},
Err(e) => Err(syn::Error::new(Span::call_site(), e)),
}
}
#[cfg(test)]
mod tests {
#[test]
fn ui_fail() {
let cases = trybuild::TestCases::new();
cases.compile_fail("tests/ui/fail/*.rs");
}
}