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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
|
// Copyright 2024, Linaro Limited
// Author(s): Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
// SPDX-License-Identifier: GPL-2.0-or-later
use proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, parse_quote,
punctuated::Punctuated,
spanned::Spanned,
token::Comma,
Attribute, Data, DeriveInput, Error, Field, Fields, FieldsUnnamed, Ident, Meta, Path, Token,
Variant,
};
mod bits;
use bits::BitsConstInternal;
#[cfg(test)]
mod tests;
fn get_fields<'a>(
input: &'a DeriveInput,
msg: &str,
) -> Result<&'a Punctuated<Field, Comma>, Error> {
let Data::Struct(ref s) = &input.data else {
return Err(Error::new(
input.ident.span(),
format!("Struct required for {msg}"),
));
};
let Fields::Named(ref fs) = &s.fields else {
return Err(Error::new(
input.ident.span(),
format!("Named fields required for {msg}"),
));
};
Ok(&fs.named)
}
fn get_unnamed_field<'a>(input: &'a DeriveInput, msg: &str) -> Result<&'a Field, Error> {
let Data::Struct(ref s) = &input.data else {
return Err(Error::new(
input.ident.span(),
format!("Struct required for {msg}"),
));
};
let Fields::Unnamed(FieldsUnnamed { ref unnamed, .. }) = &s.fields else {
return Err(Error::new(
s.fields.span(),
format!("Tuple struct required for {msg}"),
));
};
if unnamed.len() != 1 {
return Err(Error::new(
s.fields.span(),
format!("A single field is required for {msg}"),
));
}
Ok(&unnamed[0])
}
fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), Error> {
let expected = parse_quote! { #[repr(C)] };
if input.attrs.iter().any(|attr| attr == &expected) {
Ok(())
} else {
Err(Error::new(
input.ident.span(),
format!("#[repr(C)] required for {msg}"),
))
}
}
fn is_transparent_repr(input: &DeriveInput, msg: &str) -> Result<(), Error> {
let expected = parse_quote! { #[repr(transparent)] };
if input.attrs.iter().any(|attr| attr == &expected) {
Ok(())
} else {
Err(Error::new(
input.ident.span(),
format!("#[repr(transparent)] required for {msg}"),
))
}
}
fn derive_object_or_error(input: DeriveInput) -> Result<proc_macro2::TokenStream, Error> {
is_c_repr(&input, "#[derive(Object)]")?;
let name = &input.ident;
let parent = &get_fields(&input, "#[derive(Object)]")?
.get(0)
.ok_or_else(|| {
Error::new(
input.ident.span(),
"#[derive(Object)] requires a parent field",
)
})?
.ident;
Ok(quote! {
::common::assert_field_type!(#name, #parent,
::qom::ParentField<<#name as ::qom::ObjectImpl>::ParentType>);
::util::module_init! {
MODULE_INIT_QOM => unsafe {
::qom::type_register_static(&<#name as ::qom::ObjectImpl>::TYPE_INFO);
}
}
})
}
#[proc_macro_derive(Object)]
pub fn derive_object(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
derive_object_or_error(input)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
fn derive_opaque_or_error(input: DeriveInput) -> Result<proc_macro2::TokenStream, Error> {
is_transparent_repr(&input, "#[derive(Wrapper)]")?;
let name = &input.ident;
let field = &get_unnamed_field(&input, "#[derive(Wrapper)]")?;
let typ = &field.ty;
Ok(quote! {
unsafe impl ::common::opaque::Wrapper for #name {
type Wrapped = <#typ as ::common::opaque::Wrapper>::Wrapped;
}
impl #name {
pub unsafe fn from_raw<'a>(ptr: *mut <Self as ::common::opaque::Wrapper>::Wrapped) -> &'a Self {
let ptr = ::std::ptr::NonNull::new(ptr).unwrap().cast::<Self>();
unsafe { ptr.as_ref() }
}
pub const fn as_mut_ptr(&self) -> *mut <Self as ::common::opaque::Wrapper>::Wrapped {
self.0.as_mut_ptr()
}
pub const fn as_ptr(&self) -> *const <Self as ::common::opaque::Wrapper>::Wrapped {
self.0.as_ptr()
}
pub const fn as_void_ptr(&self) -> *mut ::core::ffi::c_void {
self.0.as_void_ptr()
}
pub const fn raw_get(slot: *mut Self) -> *mut <Self as ::common::opaque::Wrapper>::Wrapped {
slot.cast()
}
}
})
}
#[derive(Debug)]
enum DevicePropertyName {
CStr(syn::LitCStr),
Str(syn::LitStr),
}
impl Parse for DevicePropertyName {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let lo = input.lookahead1();
if lo.peek(syn::LitStr) {
Ok(Self::Str(input.parse()?))
} else if lo.peek(syn::LitCStr) {
Ok(Self::CStr(input.parse()?))
} else {
Err(lo.error())
}
}
}
#[derive(Default, Debug)]
struct DeviceProperty {
rename: Option<DevicePropertyName>,
bitnr: Option<syn::Expr>,
defval: Option<syn::Expr>,
}
impl DeviceProperty {
fn parse_from(&mut self, a: &Attribute) -> syn::Result<()> {
use attrs::{set, with, Attrs};
let mut parser = Attrs::new();
parser.once("rename", with::eq(set::parse(&mut self.rename)));
parser.once("bit", with::eq(set::parse(&mut self.bitnr)));
parser.once("default", with::eq(set::parse(&mut self.defval)));
a.parse_args_with(&mut parser)
}
fn parse(a: &Attribute) -> syn::Result<Self> {
let mut retval = Self::default();
retval.parse_from(a)?;
Ok(retval)
}
}
#[proc_macro_derive(Device, attributes(property))]
pub fn derive_device(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
derive_device_or_error(input)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
fn derive_device_or_error(input: DeriveInput) -> Result<proc_macro2::TokenStream, Error> {
is_c_repr(&input, "#[derive(Device)]")?;
let properties: Vec<(syn::Field, DeviceProperty)> = get_fields(&input, "#[derive(Device)]")?
.iter()
.flat_map(|f| {
f.attrs
.iter()
.filter(|a| a.path().is_ident("property"))
.map(|a| Ok((f.clone(), DeviceProperty::parse(a)?)))
})
.collect::<Result<Vec<_>, Error>>()?;
let name = &input.ident;
let mut properties_expanded = vec![];
for (field, prop) in properties {
let DeviceProperty {
rename,
bitnr,
defval,
} = prop;
let field_name = field.ident.unwrap();
macro_rules! str_to_c_str {
($value:expr, $span:expr) => {{
let (value, span) = ($value, $span);
let cstr = std::ffi::CString::new(value.as_str()).map_err(|err| {
Error::new(
span,
format!(
"Property name `{value}` cannot be represented as a C string: {err}"
),
)
})?;
let cstr_lit = syn::LitCStr::new(&cstr, span);
Ok(quote! { #cstr_lit })
}};
}
let prop_name = rename.map_or_else(
|| str_to_c_str!(field_name.to_string(), field_name.span()),
|prop_rename| -> Result<proc_macro2::TokenStream, Error> {
match prop_rename {
DevicePropertyName::CStr(cstr_lit) => Ok(quote! { #cstr_lit }),
DevicePropertyName::Str(str_lit) => {
str_to_c_str!(str_lit.value(), str_lit.span())
}
}
},
)?;
let field_ty = field.ty.clone();
let qdev_prop = if bitnr.is_none() {
quote! { <#field_ty as ::hwcore::QDevProp>::BASE_INFO }
} else {
quote! { <#field_ty as ::hwcore::QDevProp>::BIT_INFO }
};
let bitnr = bitnr.unwrap_or(syn::Expr::Verbatim(quote! { 0 }));
let set_default = defval.is_some();
let defval = defval.unwrap_or(syn::Expr::Verbatim(quote! { 0 }));
properties_expanded.push(quote! {
::hwcore::bindings::Property {
name: ::std::ffi::CStr::as_ptr(#prop_name),
info: #qdev_prop,
offset: ::core::mem::offset_of!(#name, #field_name) as isize,
bitnr: #bitnr,
set_default: #set_default,
defval: ::hwcore::bindings::Property__bindgen_ty_1 { u: #defval as u64 },
..::common::Zeroable::ZERO
}
});
}
Ok(quote_spanned! {input.span() =>
unsafe impl ::hwcore::DevicePropertiesImpl for #name {
const PROPERTIES: &'static [::hwcore::bindings::Property] = &[
#(#properties_expanded),*
];
}
})
}
#[proc_macro_derive(Wrapper)]
pub fn derive_opaque(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
derive_opaque_or_error(input)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
#[allow(non_snake_case)]
fn get_repr_uN(input: &DeriveInput, msg: &str) -> Result<Path, Error> {
let repr = input.attrs.iter().find(|attr| attr.path().is_ident("repr"));
if let Some(repr) = repr {
let nested = repr.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?;
for meta in nested {
match meta {
Meta::Path(path) if path.is_ident("u8") => return Ok(path),
Meta::Path(path) if path.is_ident("u16") => return Ok(path),
Meta::Path(path) if path.is_ident("u32") => return Ok(path),
Meta::Path(path) if path.is_ident("u64") => return Ok(path),
_ => {}
}
}
}
Err(Error::new(
input.ident.span(),
format!("#[repr(u8/u16/u32/u64) required for {msg}"),
))
}
fn get_variants(input: &DeriveInput) -> Result<&Punctuated<Variant, Comma>, Error> {
let Data::Enum(ref e) = &input.data else {
return Err(Error::new(
input.ident.span(),
"Cannot derive TryInto for union or struct.",
));
};
if let Some(v) = e.variants.iter().find(|v| v.fields != Fields::Unit) {
return Err(Error::new(
v.fields.span(),
"Cannot derive TryInto for enum with non-unit variants.",
));
}
Ok(&e.variants)
}
#[rustfmt::skip::macros(quote)]
fn derive_tryinto_body(
name: &Ident,
variants: &Punctuated<Variant, Comma>,
repr: &Path,
) -> Result<proc_macro2::TokenStream, Error> {
let discriminants: Vec<&Ident> = variants.iter().map(|f| &f.ident).collect();
Ok(quote! {
#(const #discriminants: #repr = #name::#discriminants as #repr;)*
match value {
#(#discriminants => core::result::Result::Ok(#name::#discriminants),)*
_ => core::result::Result::Err(value),
}
})
}
#[rustfmt::skip::macros(quote)]
fn derive_tryinto_or_error(input: DeriveInput) -> Result<proc_macro2::TokenStream, Error> {
let repr = get_repr_uN(&input, "#[derive(TryInto)]")?;
let name = &input.ident;
let body = derive_tryinto_body(name, get_variants(&input)?, &repr)?;
let errmsg = format!("invalid value for {name}");
Ok(quote! {
impl #name {
#[allow(dead_code)]
pub const fn into_bits(self) -> #repr {
self as #repr
}
#[allow(dead_code)]
pub const fn from_bits(value: #repr) -> Self {
match ({
#body
}) {
Ok(x) => x,
Err(_) => panic!(#errmsg),
}
}
}
impl core::convert::TryFrom<#repr> for #name {
type Error = #repr;
#[allow(ambiguous_associated_items)]
fn try_from(value: #repr) -> Result<Self, #repr> {
#body
}
}
})
}
#[proc_macro_derive(TryInto)]
pub fn derive_tryinto(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
derive_tryinto_or_error(input)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
#[proc_macro]
pub fn bits_const_internal(ts: TokenStream) -> TokenStream {
let ts = proc_macro2::TokenStream::from(ts);
let mut it = ts.into_iter();
BitsConstInternal::parse(&mut it)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
|