bitbash-macros 0.5.1

proc-macro crate for bitbash
Documentation
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use std::ops::Range;

use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};
use syn::parse_quote;
use syn::{Expr, Fields, Ident, ItemStruct, Path, Token, Type, Visibility};

use super::{is_uint, self_repr_ty, value_repr_ty};
use crate::constness;

#[derive(Clone)]
pub struct Bitfield {
    pub use_const: bool,
    pub strukt: ItemStruct,
    pub new: Option<New>,
    pub derive_debug: bool,
    pub fields: Vec<Field>,
}

#[derive(Clone)]
pub struct New {
    pub attrs: Vec<NewAttribute>,
    pub vis: Visibility,
    pub init_field_names: Vec<Ident>,
    pub init_field_tys: Vec<Type>,
}

#[derive(Clone)]
pub enum NewAttribute {
    DisableCheck,
}

#[derive(Clone)]
pub struct Field {
    pub attrs: Vec<FieldAttribute>,
    pub vis: Visibility,
    pub name: Ident,
    pub value_ty: Type,
    pub rels: Vec<Relationship>,
}

#[derive(Clone)]
pub enum FieldAttribute {
    ReadOnly,
    PrivateWrite,
}

#[derive(Clone)]
pub struct Relationship {
    pub from: Range<Expr>,
    pub to_src: Option<Expr>,
    pub to: Range<Expr>,
}

impl ToTokens for Bitfield {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Bitfield {
            use_const,
            strukt,
            new,
            derive_debug,
            fields,
        } = self;
        let constness = constness(*use_const);

        let strukt_name = &strukt.ident;
        let (impl_generics, ty_generics, where_clause) = strukt.generics.split_for_impl();

        fn mask(ty: &Type, bits: &Ident) -> Expr {
            parse_quote! {{
                let one: #ty = 1;
                let (shifted_bit, overflowed) = one.overflowing_shl(#bits.end - #bits.start);
                let (mask, _) = shifted_bit.overflowing_sub(1);
                ((overflowed as #ty * !0) | ((!overflowed as #ty) * mask)) << #bits.start
            }}
        }

        fn field_rels<'a>(field: &'a Field) -> Vec<Ident> {
            field
                .rels
                .iter()
                .enumerate()
                .map(|(i, _)| format_ident!("rel_{}", i))
                .collect()
        }

        let mut fields_tokens = quote! {};
        for field in fields {
            let value_ty = &field.value_ty;
            let value_repr_ty = value_repr_ty(value_ty);

            let rels = field_rels(field);

            let mut rels_tokens = quote! {};
            for (rel, rel_name) in field.rels.iter().zip(&rels) {
                let self_repr = match &strukt.fields {
                    Fields::Unnamed(_) => match &rel.to_src {
                        Some(i) => quote! { this.0[#i] },
                        None => quote! { this.0 },
                    },
                    Fields::Named(_) => match &rel.to_src {
                        Some(p) => quote! { this.#p },
                        _ => unreachable!(),
                    },
                    _ => unreachable!(),
                };

                let (rel_to_start, rel_to_end) = (&rel.to.start, &rel.to.end);
                let (rel_from_start, rel_from_end) = (&rel.from.start, &rel.from.end);
                let self_repr_ty = self_repr_ty(strukt, &rel.to_src);
                let self_bits = quote! { #rel_to_start..#rel_to_end };
                let value_bits = quote! { #rel_from_start..#rel_from_end };

                let self_mask = mask(&self_repr_ty, &format_ident!("SELF_BITS"));
                let value_mask = mask(&value_repr_ty, &format_ident!("VALUE_BITS"));

                let inbounds_assertion = match &strukt.fields {
                    Fields::Unnamed(fields) => match &fields.unnamed[0].ty {
                        Type::Array(t) => match &rel.to_src {
                            Some(i) => {
                                let len = &t.len;
                                Some(quote! { assert!(#i < #len); })
                            }
                            _ => unreachable!(),
                        },
                        _ => None,
                    },
                    _ => None,
                };
                let assert_inbounds = inbounds_assertion.map(|assertion| match use_const {
                    true => quote! { pub const _ASSERT_INBOUNDS: () = #assertion; },
                    false => assertion,
                });
                let assertions = match use_const {
                    true => quote! {
                        pub const _ASSERT0: () = assert!(SELF_BITS.start <= SELF_BITS.end);
                        pub const _ASSERT1: () = assert!(VALUE_BITS.start <= VALUE_BITS.end);
                        pub const _ASSERT2: () = assert!(SELF_BITS_LEN == VALUE_BITS_LEN);
                        pub const _ASSERT3: () = assert!(SELF_BITS.end as usize <= core::mem::size_of::<SelfRepr>() * 8);
                        pub const _ASSERT4: () = assert!(VALUE_BITS.end as usize <= core::mem::size_of::<ValueRepr>() * 8);
                        #assert_inbounds
                    },
                    false => quote! {{
                        assert!(SELF_BITS.start <= SELF_BITS.end);
                        assert!(VALUE_BITS.start <= VALUE_BITS.end);
                        assert!(SELF_BITS_LEN == VALUE_BITS_LEN);
                        assert!(SELF_BITS.end as usize <= core::mem::size_of::<SelfRepr>() * 8);
                        assert!(VALUE_BITS.end as usize <= core::mem::size_of::<ValueRepr>() * 8);
                        #assert_inbounds
                    }},
                };

                rels_tokens.extend(quote! {
                    #[allow(non_snake_case)]
                    pub mod #rel_name {
                        use super::*;

                        pub(in super::super::super) type SelfRepr = #self_repr_ty;

                        pub const SELF_BITS: core::ops::Range<u32> = #self_bits;
                        pub const SELF_BITS_LEN: usize = (SELF_BITS.end - SELF_BITS.start) as usize;
                        pub(in super::super::super) const SELF_MASK: SelfRepr = #self_mask;
                        pub const VALUE_BITS: core::ops::Range<u32> = #value_bits;
                        pub const VALUE_BITS_LEN: usize = (VALUE_BITS.end - VALUE_BITS.start) as usize;
                        pub(in super::super::super) const VALUE_MASK: ValueRepr = #value_mask;

                        pub(in super::super::super) #constness fn self_repr #impl_generics(this: &#strukt_name #ty_generics) -> SelfRepr #where_clause {
                            #assertions
                            #self_repr
                        }

                        pub(in super::super::super) #constness fn self_repr_mut #impl_generics(this: &mut #strukt_name #ty_generics) -> &mut SelfRepr #where_clause {
                            &mut #self_repr
                        }
                    }
                });
            }

            let value_into_from_repr = match use_const {
                false => quote! {
                    pub(in super::super) fn value_into_repr(value: #value_ty) -> #value_repr_ty {
                        <#value_ty as bitbash::ConvertRepr>::into_repr(value)
                    }
                    pub(in super::super) fn value_from_repr(value_repr: #value_repr_ty) -> #value_ty {
                        <#value_ty as bitbash::ConvertRepr>::try_from_repr(value_repr).expect("invalid representation for value")
                    }
                },
                true => match value_ty {
                    Type::Path(p) if is_uint(&p.path) => quote! {
                        pub(in super::super) const fn value_into_repr(value: #value_ty) -> #value_repr_ty {
                            value
                        }
                        pub(in super::super) const fn value_from_repr(value_repr: #value_repr_ty) -> #value_ty {
                            value_repr
                        }
                    },
                    Type::Path(p) if p.path.is_ident("bool") => quote! {
                        pub(in super::super) const fn value_into_repr(value: #value_ty) -> #value_repr_ty {
                            value as #value_repr_ty
                        }
                        pub(in super::super) const fn value_from_repr(value_repr: #value_repr_ty) -> #value_ty {
                            match value_repr {
                                0 => false,
                                1 => true,
                                _ => panic!("invalid representation for value"),
                            }
                        }
                    },
                    value_ty => quote! {
                        pub(in super::super) const fn value_into_repr(value: #value_ty) -> #value_repr_ty {
                            <#value_ty>::const_into_repr(value)
                        }
                        pub(in super::super) const fn value_from_repr(value_repr: #value_repr_ty) -> #value_ty {
                            match <#value_ty>::const_try_from_repr(value_repr) {
                                Some(value) => value,
                                None => panic!("invalid representation for value"),
                            }
                        }
                    },
                },
            };

            let rels = field_rels(field);
            let field_name = &field.name;
            fields_tokens.extend(quote! {
                #[allow(non_snake_case)]
                pub mod #field_name {
                    use super::*;

                    pub(in super::super) type Value = #value_ty;
                    pub(in super::super) type ValueRepr = #value_repr_ty;

                    #value_into_from_repr

                    #rels_tokens

                    pub(in super::super) const VALUE_REPR_MASK: #value_repr_ty = 0 #(| #rels::VALUE_MASK)*;
                }
            });
        }

        let mod_name = format_ident!("__bitfield_{}", strukt.ident);
        tokens.extend(quote! {
            #strukt

            #[allow(non_snake_case)]
            pub mod #mod_name {
                use super::*;
                #fields_tokens
            }
        });

        if let Some(new) = new {
            let mut disable_check = false;
            for attr in &new.attrs {
                match attr {
                    NewAttribute::DisableCheck => disable_check = true,
                }
            }

            let all_field_names: Vec<_> = fields.iter().map(|f| f.name.clone()).collect();
            let new_f = NewF {
                disable_check,
                vis: &new.vis,
                constness: &constness,
                strukt,
                all_field_names: &all_field_names,
                init_field_names: &new.init_field_names,
                init_field_tys: &new.init_field_tys,
            };
            tokens.extend(quote! {
                impl #impl_generics #strukt_name #ty_generics #where_clause {
                    #new_f
                }
            });
        }

        for field in fields {
            let value_ty = &field.value_ty;
            let rels = field_rels(field);

            let mut ro = false;
            let mut private_write = false;
            for attr in &field.attrs {
                match attr {
                    FieldAttribute::ReadOnly => ro = true,
                    FieldAttribute::PrivateWrite => private_write = true,
                }
            }
            let emit_setter = !ro || private_write;

            let field_name = &field.name;
            let field_mod: Path = parse_quote! { #mod_name::#field_name };

            let get_name = field.name.clone();
            let get = Get {
                vis: &field.vis,
                constness: &constness,
                get_name,
                value_ty,
                field_mod: &field_mod,
                rel: &*rels,
            };
            let set = match emit_setter {
                false => None,
                true => Some(Set {
                    vis: match private_write {
                        false => &field.vis,
                        true => &Visibility::Inherited,
                    },
                    constness: &constness,
                    field_name: &field.name,
                    set_name: format_ident!("set_{}", field.name),
                    with_name: format_ident!("with_{}", field.name),
                    value_ty,
                    field_mod: &field_mod,
                    rel: &*rels,
                }),
            };

            tokens.extend(quote! {
                impl #impl_generics #strukt_name #ty_generics #where_clause {
                    #get
                    #set
                }
            });
        }

        if *derive_debug {
            let mut debug_fields = quote! {};
            for field in fields {
                let field_name = &field.name;
                debug_fields.extend(quote! {
                    s.field(stringify!(#field_name), &self.#field_name());
                });
            }
            tokens.extend(quote! {
                impl #impl_generics core::fmt::Debug for #strukt_name #ty_generics #where_clause {
                    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                        let mut s = f.debug_struct(stringify!(#strukt_name));
                        #debug_fields
                        s.finish()
                    }
                }
            })
        }
    }
}

pub struct Get<'a> {
    vis: &'a Visibility,
    constness: &'a Option<Token![const]>,
    get_name: Ident,
    value_ty: &'a Type,
    field_mod: &'a Path,
    rel: &'a [Ident],
}

impl<'a> ToTokens for Get<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Get {
            vis,
            constness,
            get_name,
            value_ty,
            field_mod,
            rel,
        } = self;
        tokens.extend(quote! {
            #vis #constness fn #get_name(&self) -> #value_ty {
                let mut value_repr: #field_mod::ValueRepr = 0;
                #(value_repr |= (((#field_mod::#rel::self_repr(self) & #field_mod::#rel::SELF_MASK) >> #field_mod::#rel::SELF_BITS.start) as #field_mod::ValueRepr) << #field_mod::#rel::VALUE_BITS.start;)*
                #field_mod::value_from_repr(value_repr)
            }
        });
    }
}

pub struct Set<'a> {
    vis: &'a Visibility,
    constness: &'a Option<Token![const]>,
    field_name: &'a Ident,
    set_name: Ident,
    with_name: Ident,
    value_ty: &'a Type,
    field_mod: &'a Path,
    rel: &'a [Ident],
}

impl<'a> ToTokens for Set<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Set {
            vis,
            constness,
            field_name,
            set_name,
            with_name,
            value_ty,
            field_mod,
            rel,
        } = self;
        tokens.extend(quote! {
            #vis #constness fn #set_name(&mut self, value: #value_ty) {
                let value_repr: #field_mod::ValueRepr = #field_mod::value_into_repr(value);
                assert!((value_repr & !#field_mod::VALUE_REPR_MASK) == 0, concat!("invalid value for ", stringify!(#field_name)));
                #(*#field_mod::#rel::self_repr_mut(self) =
                    (#field_mod::#rel::self_repr(self) & !#field_mod::#rel::SELF_MASK)
                  | ((((value_repr & #field_mod::#rel::VALUE_MASK) >> #field_mod::#rel::VALUE_BITS.start) as #field_mod::#rel::SelfRepr) << #field_mod::#rel::SELF_BITS.start);
                )*
            }

            #vis #constness fn #with_name(mut self, value: #value_ty) -> Self {
                self.#set_name(value);
                self
            }
        });
    }
}

pub struct NewF<'a> {
    disable_check: bool,
    vis: &'a Visibility,
    constness: &'a Option<Token![const]>,
    strukt: &'a ItemStruct,
    all_field_names: &'a [Ident],
    init_field_names: &'a [Ident],
    init_field_tys: &'a [Type],
}

impl<'a> ToTokens for NewF<'a> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let NewF {
            disable_check,
            vis,
            constness,
            strukt,
            all_field_names,
            init_field_names,
            init_field_tys,
        } = self;

        let strukt_name = &strukt.ident;
        let (_, ty_generics, _) = strukt.generics.split_for_impl();

        let with_init_field = init_field_names
            .iter()
            .map(|name| format_ident!("with_{}", name));

        fn initializer(ty: &Type) -> Expr {
            match ty {
                Type::Array(t) => {
                    let len = &t.len;
                    parse_quote! { [0; #len] }
                }
                _ => parse_quote! { 0 },
            }
        }
        let zero_initializer = match &strukt.fields {
            Fields::Unnamed(fields) => {
                let initializer = initializer(&fields.unnamed[0].ty);
                quote! { #strukt_name(#initializer) }
            }
            Fields::Named(fields) => {
                let field_name = fields.named.iter().map(|f| &f.ident);
                let initializer = fields.named.iter().map(|f| initializer(&f.ty));
                quote! { #strukt_name {
                    #(#field_name: #initializer,)*
                }}
            }
            Fields::Unit => unreachable!(),
        };
        let check = match disable_check {
            true => None,
            false => Some(quote! { #(let _ = this.#all_field_names();)* }),
        };
        tokens.extend(quote! {
            #vis #constness fn new(#(#init_field_names: #init_field_tys),*) -> #strukt_name #ty_generics {
                let this = #zero_initializer #(.#with_init_field(#init_field_names))*;
                #check
                this
            }
        })
    }
}