1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{parse_macro_input, Data, DeriveInput, Fields, Lit};
4
5
6#[proc_macro_derive(AssertOffsets, attributes(offset))]
7pub fn derive_assert_offsets(input: TokenStream) -> TokenStream {
8 let input = parse_macro_input!(input as DeriveInput);
9
10 let struct_name = &input.ident;
11 let fields = match &input.data {
12 Data::Struct(data_struct) => match &data_struct.fields {
13 Fields::Named(fields) => &fields.named,
14 _ => panic!("AssertOffsets only supports structs with named fields"),
15 },
16 _ => panic!("AssertOffsets can only be used with structs"),
17 };
18
19 let mut assertions = vec![];
20
21 for field in fields {
22 let field_name = field.ident.as_ref().unwrap();
23 let mut expected_offset = None;
24
25 for attr in &field.attrs {
26 if attr.path().is_ident("offset") {
27 if let Ok(Lit::Int(lit_int)) = attr.parse_args() {
28 expected_offset = Some(
29 lit_int
30 .base10_parse::<usize>()
31 .expect("Offset must be an integer"),
32 );
33 }
34 }
35 }
36
37 if let Some(expected_offset) = expected_offset {
38 let expected_offset_hex = format!("0x{:X}", expected_offset);
39 assertions.push(quote! {
40 const _: () = assert!(
41 core::mem::offset_of!(#struct_name, #field_name) == #expected_offset,
42 concat!(
43 "Field `",
44 stringify!(#struct_name),
45 "::",
46 stringify!(#field_name),
47 "` is not at expected offset ",
48 #expected_offset_hex
49 )
50 );
51 });
52 }
53 }
54
55 let expanded = quote! {
56 #(#assertions)*;
57 };
58
59 TokenStream::from(expanded)
60}