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
|
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::Token;
use crate::macro_flag::MacroFlag;
use crate::util::iterator_ext::IteratorExt;
pub const FACTORY_MACRO_FLAGS: &[&str] = &["threadsafe"];
pub struct FactoryMacroArgs
{
pub flags: Punctuated<MacroFlag, Token![,]>,
}
impl Parse for FactoryMacroArgs
{
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self>
{
let flags = Punctuated::<MacroFlag, Token![,]>::parse_terminated(input)?;
for flag in &flags {
let name = flag.name().to_string();
if !FACTORY_MACRO_FLAGS.contains(&name.as_str()) {
return Err(input.error(format!(
"Unknown flag '{}'. Expected one of [ {} ]",
name,
FACTORY_MACRO_FLAGS.join(",")
)));
}
}
let flag_names = flags
.iter()
.map(|flag| flag.name().to_string())
.collect::<Vec<_>>();
if let Some((dupe_flag_name, _)) = flag_names.iter().find_duplicate() {
return Err(input.error(format!("Duplicate flag '{dupe_flag_name}'")));
}
Ok(Self { flags })
}
}
#[cfg(test)]
mod tests
{
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::{parse2, Lit, LitBool};
use super::*;
use crate::macro_flag::MacroFlagValue;
#[test]
fn can_parse_with_single_flag()
{
let input_args = quote! {
threadsafe = true
};
let factory_macro_args = parse2::<FactoryMacroArgs>(input_args).unwrap();
assert_eq!(
factory_macro_args.flags,
Punctuated::from_iter(vec![MacroFlag {
name: format_ident!("threadsafe"),
value: MacroFlagValue::Literal(Lit::Bool(LitBool::new(
true,
Span::call_site()
)))
}])
);
}
#[test]
fn cannot_parse_with_invalid_flag()
{
let input_args = quote! {
threadsafe = false, foo = true
};
assert!(parse2::<FactoryMacroArgs>(input_args).is_err());
}
#[test]
fn cannot_parse_with_duplicate_flag()
{
assert!(
// Formatting is weird without this comment
parse2::<FactoryMacroArgs>(quote! {
threadsafe = true, threadsafe = true
})
.is_err()
);
assert!(
// Formatting is weird without this comment
parse2::<FactoryMacroArgs>(quote! {
threadsafe = true, threadsafe = false
})
.is_err()
);
}
}
|