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
mod struct_field;
mod struct_impl;
extern crate proc_macro as pm;
use crate::struct_field::{FieldFormatting, FieldMenuInit};
use proc_macro2::TokenStream;
use proc_macro_error::{abort, abort_call_site, proc_macro_error};
use quote::{quote, ToTokens};
use syn::{
parse_macro_input, Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, FieldsNamed,
Ident, Meta, Path,
};
macro_rules! run {
(nested: $id:ident, $var:ident, $nested:expr, $s:expr) => {
if let NestedMeta::Lit(Lit::$var(lit)) = $nested {
$id = Some(lit.clone());
} else {
abort_invalid_type($nested, $s);
}
};
($id:ident, $var:ident, $lit:expr, $s:expr) => {
if let Lit::$var(lit) = $lit {
$id = Some(lit.clone());
} else {
abort_invalid_type($lit, $s);
}
};
}
use crate::struct_impl::MenuInit;
pub(crate) use run;
#[proc_macro_attribute]
#[proc_macro_error]
pub fn parser(_attr: pm::TokenStream, _ts: pm::TokenStream) -> pm::TokenStream {
pm::TokenStream::new()
}
#[proc_macro_attribute]
#[proc_macro_error]
pub fn parsed(_attr: pm::TokenStream, ts: pm::TokenStream) -> pm::TokenStream {
let input = parse_macro_input!(ts as DeriveInput);
if let Data::Enum(e) = &input.data {
build_parsed_enum(&input, e)
} else {
abort!(
input,
"ezmenu::parsed macro attribute only works on unit-like enums."
)
}
.into()
}
fn build_parsed_enum(input: &DeriveInput, data: &DataEnum) -> TokenStream {
let ident = &input.ident;
let inputs = data.variants.iter().map(|var| {
let val = var.ident.to_string().to_lowercase();
quote!(#val)
});
let outputs = data.variants.iter().map(|var| &var.ident);
quote! {
#input
impl ::std::str::FromStr for #ident {
type Err = ::ezmenu::MenuError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
#(#inputs => Ok(Self::#outputs),)*
_ => Err(::ezmenu::MenuError::Custom(
Box::new(format!("unrecognized input for `{}`", s))))
}
}
}
}
}
#[proc_macro_derive(Menu, attributes(menu))]
#[proc_macro_error]
pub fn build_menu(ts: pm::TokenStream) -> pm::TokenStream {
let input = parse_macro_input!(ts as DeriveInput);
match input.data {
Data::Enum(_e) => todo!("derive on enum soon"),
Data::Struct(DataStruct {
fields: Fields::Named(fields),
..
}) => build_struct(input.ident, input.attrs, fields),
_ => abort_call_site!("Menu derive supports only non-tuple structs and unit-like enums."),
}
.into()
}
#[cfg(feature = "custom_io")]
fn def_init<'a>(menu_desc: MenuInit) -> TokenStream {
let fields = menu_desc.fields.iter().map(|field| &field.kind);
quote! {
pub fn from_io<R, W>(reader: R, writer: W) -> ::ezmenu::MenuResult<Self>
where
R: ::std::io::BufRead,
W: ::std::io::Write,
{
let mut menu = ::ezmenu::StructMenu::new(reader, writer)
#menu_desc;
Ok(Self {#(
#fields
)*})
}
}
}
#[cfg(not(any(feature = "custom_io", test)))]
fn def_init<'a>(menu_desc: MenuInit) -> TokenStream {
let fields = menu_desc.fields.iter().map(|field| &field.kind);
quote! {
pub fn from_menu() -> ::ezmenu::MenuResult<Self> {
let mut menu = ::ezmenu::StructMenu::default()
#menu_desc;
Ok(Self {#(
#fields
)*})
}
}
}
#[inline(never)]
fn abort_invalid_type(span: impl ToTokens, s: &str) -> ! {
abort!(
span,
"invalid literal type for `{}` attribute", s;
help = "try surrounding: `{}(\"...\")`", s
)
}
#[inline(never)]
fn abort_invalid_arg_name(span: impl ToTokens, s: &str) -> ! {
abort!(span, "invalid argument name: `{}`", s)
}
#[inline]
fn path_to_string(from: &Path) -> String {
from.get_ident().unwrap().to_string()
}
fn get_meta_attr(attrs: Vec<Attribute>) -> Option<Meta> {
attrs.into_iter().find_map(|attr| {
attr.path.is_ident("menu").then(|| {
attr.parse_meta()
.unwrap_or_else(|e| abort!(attr, "incorrect definition of menu attribute: {}", e))
})
})
}
fn build_struct(name: Ident, attrs: Vec<Attribute>, fields: FieldsNamed) -> TokenStream {
let struct_attr = get_meta_attr(attrs);
let fields = fields
.named
.into_iter()
.map(|field| FieldMenuInit::from(field))
.collect();
let init = def_init(MenuInit::new(struct_attr, fields));
quote! {
impl #name {
#init
}
}
}