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
use darling::FromMeta;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
parse_macro_input, spanned::Spanned, AttributeArgs, Error, Expr, ItemConst, Type,
Type::Reference,
};
type TokenStream2 = proc_macro2::TokenStream;
#[derive(Debug, FromMeta)]
struct Metadata {
#[darling(default)]
min: Option<f64>,
#[darling(default)]
max: Option<f64>,
#[darling(default)]
step: Option<f64>,
}
impl Metadata {
pub fn from_attributes(args: AttributeArgs) -> Result<Self, TokenStream> {
match Metadata::from_list(&args) {
Ok(v) => Ok(v),
Err(e) => Err(TokenStream::from(e.write_errors())),
}
}
}
fn field_init(
ty: &Type,
metadata: Metadata,
default_value: Expr,
) -> Result<TokenStream2, TokenStream> {
if let Type::Path(type_path) = &*ty {
match type_path.path.get_ident() {
Some(type_ident) => {
let min = metadata.min.unwrap_or(-1.0);
let max = metadata.max.unwrap_or(1.0);
let step = metadata.step.unwrap_or(0.1);
match &*(type_ident.to_string()) {
"f32" => Ok(quote! {
const_tweaker::Field::F32 {
value: #default_value as f32,
min: #min,
max: #max,
step: #step,
module: module_path!().to_string(),
file: file!().to_string(),
line: line!(),
}
}),
"f64" => Ok(quote! {
const_tweaker::Field::F64 {
value: #default_value,
min: #min,
max: #max,
step: #step,
module: module_path!().to_string(),
file: file!().to_string(),
line: line!(),
}
}),
"bool" => Ok(quote! {
const_tweaker::Field::Bool {
value: #default_value,
module: module_path!().to_string(),
file: file!().to_string(),
line: line!(),
}
}),
"str" => Ok(quote! {
const_tweaker::Field::String {
value: #default_value.to_string(),
module: module_path!().to_string(),
file: file!().to_string(),
line: line!(),
}
}),
_ => mismatching_type_error(&ty),
}
}
None => mismatching_type_error(&ty),
}
} else {
mismatching_type_error(&ty)
}
}
fn field_name(ty: &Type) -> Result<TokenStream2, TokenStream> {
if let Type::Path(type_path) = &*ty {
match type_path.path.get_ident() {
Some(type_ident) => match &*(type_ident.to_string()) {
"f32" => Ok(quote! { const_tweaker::Field::F32 }),
"f64" => Ok(quote! { const_tweaker::Field::F64 }),
"bool" => Ok(quote! { const_tweaker::Field::Bool }),
"str" => Ok(quote! { const_tweaker::Field::String }),
_ => mismatching_type_error(&ty),
},
None => mismatching_type_error(&ty),
}
} else {
mismatching_type_error(&ty)
}
}
fn mismatching_type_error<T>(ty: &Type) -> Result<T, TokenStream> {
Err(TokenStream::from(
Error::new(
ty.span(),
"expected bool, &str, f32 or f64, other types are not supported in const_tweaker (yet)",
)
.to_compile_error(),
))
}
fn tweak_impl(args: AttributeArgs, input: ItemConst) -> Result<TokenStream, TokenStream> {
let name = input.ident;
let init_name = format_ident!("{}_INIT", name);
let ty = if let Reference(type_ref) = *input.ty {
type_ref.elem
} else {
input.ty
};
let field_init = field_init(&*ty, Metadata::from_attributes(args)?, *input.expr)?;
let field_name = field_name(&*ty)?;
let result = quote! {
#[allow(non_camel_case_types)]
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct #name {
__private_field: ()
}
impl #name {
pub fn get(&self) -> &'static #ty {
#init_name.call_once(|| {
const_tweaker::DATA.insert(concat!(module_path!(), "::", stringify!(#name)), #field_init);
});
match const_tweaker::DATA.get(concat!(module_path!(), "::", stringify!(#name))).expect("Value should have been added already").value() {
#field_name { ref value, .. } => unsafe {
std::mem::transmute::<&#ty, &'static #ty>(value as &#ty)
},
_ => panic!("Type mismatch, this probably means there's a duplicate value in the map, please report an issue")
}
}
}
impl std::ops::Deref for #name {
type Target = #ty;
fn deref(&self) -> &'static #ty {
self.get()
}
}
impl std::fmt::Debug for #name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self.get())
}
}
impl std::fmt::Display for #name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self.get())
}
}
static #init_name: std::sync::Once = std::sync::Once::new();
static #name: #name = #name { __private_field: () };
};
Ok(result.into())
}
#[proc_macro_attribute]
pub fn tweak(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as AttributeArgs);
let input = parse_macro_input!(input as ItemConst);
match tweak_impl(args, input) {
Ok(result) => result,
Err(err) => err,
}
}