forked from rust-osdev/volatile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvolatile.rs
252 lines (220 loc) · 6.76 KB
/
volatile.rs
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
244
245
246
247
248
249
250
251
252
use quote::format_ident;
use syn::punctuated::Punctuated;
use syn::{
parse_quote, Attribute, Fields, Ident, Item, ItemImpl, ItemStruct, ItemTrait, Meta, Path,
Result, Signature, Token, Visibility,
};
fn validate_input(input: &ItemStruct) -> Result<()> {
if !matches!(&input.fields, Fields::Named(_)) {
bail!(
&input.fields,
"#[derive(VolatileFieldAccess)] can only be used on structs with named fields"
);
}
if !input.generics.params.is_empty() {
bail!(
&input.generics,
"#[derive(VolatileFieldAccess)] cannot be used with generic structs"
);
}
let mut valid_repr = false;
for attr in &input.attrs {
if attr.path().is_ident("repr") {
let nested = attr.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?;
for meta in nested {
if let Meta::Path(path) = meta {
if path.is_ident("C") || path.is_ident("transparent") {
valid_repr = true;
}
}
}
}
}
if !valid_repr {
bail!(
&input.ident,
"#[derive(VolatileFieldAccess)] structs must be `#[repr(C)]` or `#[repr(transparent)]`"
);
}
Ok(())
}
struct ParsedInput {
attrs: Vec<Attribute>,
vis: Visibility,
trait_ident: Ident,
struct_ident: Ident,
method_attrs: Vec<Vec<Attribute>>,
sigs: Vec<Signature>,
}
fn parse_input(input: &ItemStruct) -> Result<ParsedInput> {
let mut attrs = vec![];
for attr in &input.attrs {
if attr.path().is_ident("doc") {
attrs.push(attr.clone());
}
}
let mut method_attrs = vec![];
for field in &input.fields {
let mut attrs = vec![];
for attr in &field.attrs {
if attr.path().is_ident("doc") {
attrs.push(attr.clone());
}
}
method_attrs.push(attrs);
}
let mut sigs = vec![];
for field in &input.fields {
let ident = field.ident.as_ref().unwrap();
let ty = &field.ty;
let mut access: Path = parse_quote! { ::volatile::access::ReadWrite };
for attr in &field.attrs {
if attr.path().is_ident("access") {
access = attr.parse_args()?;
}
}
let sig = parse_quote! {
fn #ident(self) -> ::volatile::VolatilePtr<'a, #ty, #access>
};
sigs.push(sig);
}
Ok(ParsedInput {
attrs,
vis: input.vis.clone(),
trait_ident: format_ident!("{}VolatileFieldAccess", input.ident),
struct_ident: input.ident.clone(),
method_attrs,
sigs,
})
}
fn emit_trait(
ParsedInput {
attrs,
vis,
trait_ident,
method_attrs,
sigs,
..
}: &ParsedInput,
) -> ItemTrait {
parse_quote! {
#(#attrs)*
#[allow(non_camel_case_types)]
#vis trait #trait_ident <'a> {
#(
#(#method_attrs)*
#sigs;
)*
}
}
}
fn emit_impl(
ParsedInput {
trait_ident,
struct_ident,
sigs,
..
}: &ParsedInput,
) -> ItemImpl {
let fields = sigs.iter().map(|sig| &sig.ident);
parse_quote! {
#[automatically_derived]
impl<'a> #trait_ident<'a> for ::volatile::VolatilePtr<'a, #struct_ident, ::volatile::access::ReadWrite> {
#(
#sigs {
::volatile::map_field!(self.#fields).restrict()
}
)*
}
}
}
pub fn derive_volatile(input: ItemStruct) -> Result<Vec<Item>> {
validate_input(&input)?;
let parsed_input = parse_input(&input)?;
let item_trait = emit_trait(&parsed_input);
let item_impl = emit_impl(&parsed_input);
Ok(vec![Item::Trait(item_trait), Item::Impl(item_impl)])
}
#[cfg(test)]
mod tests {
use quote::{quote, ToTokens};
use super::*;
#[test]
fn test_derive() -> Result<()> {
let input = parse_quote! {
/// Struct documentation.
///
/// This is a wonderful struct.
#[repr(C)]
#[derive(VolatileFieldAccess, Default)]
pub struct DeviceConfig {
feature_select: u32,
/// Feature.
///
/// This is a good field.
#[access(ReadOnly)]
feature: u32,
}
};
let result = derive_volatile(input)?;
let expected_trait = quote! {
/// Struct documentation.
///
/// This is a wonderful struct.
#[allow(non_camel_case_types)]
pub trait DeviceConfigVolatileFieldAccess<'a> {
fn feature_select(self) -> ::volatile::VolatilePtr<'a, u32, ::volatile::access::ReadWrite>;
/// Feature.
///
/// This is a good field.
fn feature(self) -> ::volatile::VolatilePtr<'a, u32, ReadOnly>;
}
};
let expected_impl = quote! {
#[automatically_derived]
impl<'a> DeviceConfigVolatileFieldAccess<'a> for ::volatile::VolatilePtr<'a, DeviceConfig, ::volatile::access::ReadWrite> {
fn feature_select(self) -> ::volatile::VolatilePtr<'a, u32, ::volatile::access::ReadWrite> {
::volatile::map_field!(self.feature_select).restrict()
}
fn feature(self) -> ::volatile::VolatilePtr<'a, u32, ReadOnly> {
::volatile::map_field!(self.feature).restrict()
}
}
};
assert_eq!(
expected_trait.to_string(),
result[0].to_token_stream().to_string()
);
assert_eq!(
expected_impl.to_string(),
result[1].to_token_stream().to_string()
);
Ok(())
}
#[test]
fn test_align() -> Result<()> {
let input = parse_quote! {
#[repr(C, align(8))]
#[derive(VolatileFieldAccess)]
pub struct DeviceConfig {}
};
let result = derive_volatile(input)?;
let expected_trait = quote! {
#[allow(non_camel_case_types)]
pub trait DeviceConfigVolatileFieldAccess<'a> {}
};
let expected_impl = quote! {
#[automatically_derived]
impl<'a> DeviceConfigVolatileFieldAccess<'a> for ::volatile::VolatilePtr<'a, DeviceConfig, ::volatile::access::ReadWrite> {}
};
assert_eq!(
expected_trait.to_string(),
result[0].to_token_stream().to_string()
);
assert_eq!(
expected_impl.to_string(),
result[1].to_token_stream().to_string()
);
Ok(())
}
}