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
use super::super::TraitHandler;
use super::models::{
FieldAttributeBuilder, FieldAttributeName, TypeAttributeBuilder, TypeAttributeName,
};
use crate::Trait;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Generics, Meta};
pub struct DebugUnionHandler;
impl TraitHandler for DebugUnionHandler {
fn trait_meta_handler(
ast: &DeriveInput,
tokens: &mut TokenStream,
traits: &[Trait],
meta: &Meta,
) {
let type_attribute = TypeAttributeBuilder {
enable_flag: true,
name: TypeAttributeName::Default,
enable_name: true,
named_field: false,
enable_named_field: false,
enable_bound: true,
}
.from_debug_meta(meta);
let name = type_attribute.name.into_string_by_ident(&ast.ident);
let bound = type_attribute
.bound
.into_punctuated_where_predicates_by_generic_parameters(&ast.generics.params);
let mut builder_tokens = TokenStream::new();
if let Data::Union(data) = &ast.data {
for field in data.fields.named.iter() {
let _ = FieldAttributeBuilder {
name: FieldAttributeName::Default,
enable_name: false,
enable_ignore: false,
enable_impl: false,
}
.from_attributes(&field.attrs, traits);
}
if name.is_empty() {
builder_tokens.extend(quote!(
let size = core::mem::size_of::<Self>();
let data = unsafe {{ core::slice::from_raw_parts(self as *const Self as *const u8, size) }};
core::fmt::Debug::fmt(data, formatter)
));
} else {
builder_tokens.extend(quote!(
let mut builder = formatter.debug_tuple(#name);
let size = core::mem::size_of::<Self>();
let data = unsafe {{ core::slice::from_raw_parts(self as *const Self as *const u8, size) }};
builder.field(&data);
builder.finish()
));
}
}
let ident = &ast.ident;
let mut generics_cloned: Generics = ast.generics.clone();
let where_clause = generics_cloned.make_where_clause();
where_clause.predicates.extend(bound.iter().cloned());
let (impl_generics, ty_generics, where_clause) = generics_cloned.split_for_impl();
let debug_impl = quote! {
impl #impl_generics core::fmt::Debug for #ident #ty_generics #where_clause {
#[inline]
fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
#builder_tokens
}
}
};
tokens.extend(debug_impl);
}
}