Debian Codegraph @

src/generation/debug_impl.rs

raw symbols SCIP
1 use proc_macro2::{Ident, TokenStream};
2 use quote::quote;
3
4 use crate::parsing::bitfield_attribute::{BitOrder, BitfieldAttribute};
5 use crate::parsing::bitfield_field::BitfieldField;
6
7 /// Generates the debug implementation.
8 pub(crate) fn generate_debug_implementation(
9 bitfield_struct_name: Ident,
10 bitfield_attribute: &BitfieldAttribute,
11 fields: &[BitfieldField],
12 ignored_fields_struct: bool,
13 ) -> TokenStream {
14 let mut fields_msb_to_lsb = fields.to_owned();
15 if bitfield_attribute.bit_order == BitOrder::Lsb {
16 fields_msb_to_lsb.reverse()
17 }
18 let bitfield_struct_name_str = bitfield_struct_name.to_string();
19 let mut debug_impl = Vec::new();
20 debug_impl.push(quote! {
21 let mut debug = f.debug_struct(#bitfield_struct_name_str);
22 });
23 let struct_val_ident = if ignored_fields_struct {
24 quote! { self.val }
25 } else {
26 quote! { self.0 }
27 };
28
29 fields_msb_to_lsb.iter().for_each(|field| {
30 let field_name = &field.name;
31 let field_bits = field.bits as u32;
32 let field_offset = field.offset as u32;
33 let bitfield_type = &bitfield_attribute.ty;
34
35 debug_impl.push(quote! {
36 let mask = #bitfield_type::MAX >> (#bitfield_type::BITS - #field_bits);
37 let this = ((#struct_val_ident >> #field_offset) & mask) as #bitfield_type;
38 debug.field(stringify!(#field_name), &((#struct_val_ident >> #field_offset) & mask));
39 });
40 });
41
42 debug_impl.push(quote! {
43 debug.finish()
44 });
45
46 quote! {
47 impl core::fmt::Debug for #bitfield_struct_name {
48 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
49 #( #debug_impl )*
50 }
51 }
52 }
53 }