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
|
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", "async"];
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 flag_str = flag.flag.to_string();
if !FACTORY_MACRO_FLAGS.contains(&flag_str.as_str()) {
return Err(input.error(format!(
"Unknown flag '{}'. Expected one of [ {} ]",
flag_str,
FACTORY_MACRO_FLAGS.join(",")
)));
}
}
let flag_names = flags
.iter()
.map(|flag| flag.flag.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 std::error::Error;
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::{parse2, LitBool};
use super::*;
#[test]
fn can_parse_with_single_flag() -> Result<(), Box<dyn Error>>
{
let input_args = quote! {
async = true
};
let factory_macro_args = parse2::<FactoryMacroArgs>(input_args)?;
assert_eq!(
factory_macro_args.flags,
Punctuated::from_iter(vec![MacroFlag {
flag: format_ident!("async"),
is_on: LitBool::new(true, Span::call_site())
}])
);
Ok(())
}
#[test]
fn can_parse_with_multiple_flags() -> Result<(), Box<dyn Error>>
{
let input_args = quote! {
async = true, threadsafe = false
};
let factory_macro_args = parse2::<FactoryMacroArgs>(input_args)?;
assert_eq!(
factory_macro_args.flags,
Punctuated::from_iter(vec![
MacroFlag {
flag: format_ident!("async"),
is_on: LitBool::new(true, Span::call_site())
},
MacroFlag {
flag: format_ident!("threadsafe"),
is_on: LitBool::new(false, Span::call_site())
}
])
);
Ok(())
}
#[test]
fn cannot_parse_with_invalid_flag()
{
let input_args = quote! {
async = true, 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! {
async = true, threadsafe = false, async = true
})
.is_err()
);
assert!(
// Formatting is weird without this comment
parse2::<FactoryMacroArgs>(quote! {
async = true, threadsafe = false, async = false
})
.is_err()
);
}
}
|