xref: /openbmc/qemu/rust/qemu-api-macros/src/lib.rs (revision 7d87775f)
1 // Copyright 2024, Linaro Limited
2 // Author(s): Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
3 // SPDX-License-Identifier: GPL-2.0-or-later
4 
5 use proc_macro::TokenStream;
6 use proc_macro2::Span;
7 use quote::{quote, quote_spanned};
8 use syn::{
9     parse_macro_input, parse_quote, punctuated::Punctuated, token::Comma, Data, DeriveInput, Field,
10     Fields, Ident, Type, Visibility,
11 };
12 
13 struct CompileError(String, Span);
14 
15 impl From<CompileError> for proc_macro2::TokenStream {
16     fn from(err: CompileError) -> Self {
17         let CompileError(msg, span) = err;
18         quote_spanned! { span => compile_error!(#msg); }
19     }
20 }
21 
22 fn is_c_repr(input: &DeriveInput, msg: &str) -> Result<(), CompileError> {
23     let expected = parse_quote! { #[repr(C)] };
24 
25     if input.attrs.iter().any(|attr| attr == &expected) {
26         Ok(())
27     } else {
28         Err(CompileError(
29             format!("#[repr(C)] required for {}", msg),
30             input.ident.span(),
31         ))
32     }
33 }
34 
35 #[proc_macro_derive(Object)]
36 pub fn derive_object(input: TokenStream) -> TokenStream {
37     let input = parse_macro_input!(input as DeriveInput);
38     let name = input.ident;
39 
40     let expanded = quote! {
41         ::qemu_api::module_init! {
42             MODULE_INIT_QOM => unsafe {
43                 ::qemu_api::bindings::type_register_static(&<#name as ::qemu_api::definitions::ObjectImpl>::TYPE_INFO);
44             }
45         }
46     };
47 
48     TokenStream::from(expanded)
49 }
50 
51 fn get_fields(input: &DeriveInput) -> Result<&Punctuated<Field, Comma>, CompileError> {
52     if let Data::Struct(s) = &input.data {
53         if let Fields::Named(fs) = &s.fields {
54             Ok(&fs.named)
55         } else {
56             Err(CompileError(
57                 "Cannot generate offsets for unnamed fields.".to_string(),
58                 input.ident.span(),
59             ))
60         }
61     } else {
62         Err(CompileError(
63             "Cannot generate offsets for union or enum.".to_string(),
64             input.ident.span(),
65         ))
66     }
67 }
68 
69 #[rustfmt::skip::macros(quote)]
70 fn derive_offsets_or_error(input: DeriveInput) -> Result<proc_macro2::TokenStream, CompileError> {
71     is_c_repr(&input, "#[derive(offsets)]")?;
72 
73     let name = &input.ident;
74     let fields = get_fields(&input)?;
75     let field_names: Vec<&Ident> = fields.iter().map(|f| f.ident.as_ref().unwrap()).collect();
76     let field_types: Vec<&Type> = fields.iter().map(|f| &f.ty).collect();
77     let field_vis: Vec<&Visibility> = fields.iter().map(|f| &f.vis).collect();
78 
79     Ok(quote! {
80 	::qemu_api::with_offsets! {
81 	    struct #name {
82 		#(#field_vis #field_names: #field_types,)*
83 	    }
84 	}
85     })
86 }
87 
88 #[proc_macro_derive(offsets)]
89 pub fn derive_offsets(input: TokenStream) -> TokenStream {
90     let input = parse_macro_input!(input as DeriveInput);
91     let expanded = derive_offsets_or_error(input).unwrap_or_else(Into::into);
92 
93     TokenStream::from(expanded)
94 }
95