bitfields_impl/lib.rs
1mod generation;
2mod parsing;
3
4use std::cmp::Ordering;
5use std::fmt;
6
7use proc_macro2::TokenStream;
8use quote::{ToTokens, quote};
9use syn::spanned::Spanned;
10use syn::{Expr, ExprLit, ExprUnary, Fields, Lit, LitInt, Meta, Type, Visibility};
11
12use crate::generation::bit_operations::{generate_get_bit_tokens, generate_set_bit_tokens};
13use crate::generation::builder_struct::{generate_builder_tokens, generate_to_builder_tokens};
14use crate::generation::common::PANIC_ERROR_MESSAGE;
15use crate::generation::debug_impl::generate_debug_implementation;
16use crate::generation::default_impl::generate_default_implementation_tokens;
17use crate::generation::field_const_getter_setter::{
18 generate_field_constants_tokens, generate_field_getters_functions_tokens,
19 generate_field_setters_functions_tokens,
20};
21use crate::generation::from_into_bits_conversions::{
22 generate_from_bits_function_tokens, generate_from_bits_with_defaults_function_tokens,
23 generate_into_bits_function_tokens,
24};
25use crate::generation::from_types_impl::{
26 generate_from_bitfield_for_bitfield_type_implementation_tokens,
27 generate_from_bitfield_type_for_bitfield_implementation_tokens,
28};
29use crate::generation::new_impl::{
30 generate_new_function_tokens, generate_new_without_defaults_function_tokens,
31};
32use crate::generation::set_clear_bits_impl::generate_set_bits_function_tokens;
33use crate::generation::set_clear_bits_impl::{
34 generate_clear_bits_function_tokens, generate_clear_bits_preserve_defaults_function_tokens,
35 generate_set_bits_with_defaults_function_tokens,
36};
37use crate::generation::tuple_struct::{
38 generate_struct_with_fields_tokens, generate_tuple_struct_tokens,
39};
40use crate::parsing::bitfield_attribute::{BitOrder, BitfieldAttribute};
41use crate::parsing::bitfield_field::{BitfieldField, BitsAttribute, FieldAccess, FieldType};
42use crate::parsing::number_parser::{NumberParseError, ParsedNumber, parse_number_string};
43use crate::parsing::types::{
44 IntegerType, get_bits_from_type, get_integer_suffix_from_integer_type,
45 get_integer_type_from_type, get_type_ident, is_custom_field_type, is_size_type,
46 is_supported_field_type, is_unsigned_integer_type,
47};
48
49/// The `#[bit]` attribute name.
50pub(crate) const BIT_ATTRIBUTE_NAME: &str = "bits";
51
52/// The ident prefix for padding fields.
53pub(crate) const PADDING_FIELD_NAME_PREFIX: &str = "_";
54
55#[rustfmt::skip]
56/// Creates a bitfield for the attributed struct.
57///
58/// ## Example
59///
60/// ```ignore
61/// use bitfields::bitfield;
62///
63/// /// All fields in the bitfield must sum up to the number of bits of the bitfield type.
64/// #[bitfield(u64)]
65/// #[derive(Clone)] // Attributes are passed to the struct.
66/// pub struct Bitfield {
67/// /// Fields without bits specified default to the size of the field type.
68/// /// 8 bits.
69/// u8int: u8,
70/// /// A field can have specified bits, but the bits must be greater than zero
71/// /// and fit in the field type.
72/// #[bitfield(4)] // u8 is 8 bits, so 4 bits is valid.
73/// small_u8int: u8,
74/// /// A field that is signed, will be sign-extended by the most significant
75/// /// bit of its type.
76/// signed_int: i8,
77/// /// If you specify bits, the field will be sign-extended by the most significant
78/// /// bit of the specified bits. In this case, the most significant bit of 4 bits.
79/// #[bits(4)]
80/// small_signed_int: i8,
81/// /// A field can be a bool type.
82/// bool_field: bool,
83/// /// A field can have a default value, which must fit in the field type.
84/// #[bits(default = 0x1F)]
85/// field_with_default: u8,
86/// /// A field can have a default value and specified bits. The default value
87/// /// must fit in the specified bits or a compile error will occur.
88/// #[bits(4, default = 0xF)] // Default fits in 4 bits.
89/// field_with_bits_default: u8,
90/// /// By default, all functions share the same visibility as the bitfield struct.
91/// /// Fields can have their getters and setters visibility overridden by specifying
92/// /// the visibility of the field.
93/// pub pub_field: u8, // Getter and setter are public.
94/// /// Nested bitfields are supported, but must have their bits specified.
95/// #[bits(3)]
96/// nested_field: NestedBitfield,
97/// /// Custom types are supported, but must have their bits specified and
98/// /// implement the `from_bits` and `into_bits` functions.
99/// #[bits(3)]
100/// custom_type: CustomType,
101/// /// Fields can have their access restricted. `ro` means read-only, meaning
102/// /// the field can be read but not written.
103/// #[bits(5, access = ro)] // Read-only field, no setter.
104/// read_only: u8,
105/// /// Fields prefixed with "_" are padding fields, which are inaccessible.
106/// #[bits(4, default = 0x3)]
107/// _padding: u8,
108/// /// Fields with the ignore attribute are ignored.
109/// #[bits(99, ignore = true)]
110/// ignore_me: u128,
111/// }
112///
113/// #[bitfield(u8)]
114/// struct NestedBitfield {
115/// field: u8
116/// }
117///
118/// /// Custom types must have 2 const functions, `from_bits` and `into_bits` to convert
119/// /// the type to and from bits functions.
120/// #[derive(Default)]
121/// struct CustomType {
122/// a: u8,
123/// }
124///
125/// impl CustomType {
126/// /// Make sure the parameter type can fit the specified number of bits. Also,
127/// /// must be const, we need that extra compile time safety.
128/// const fn from_bits(bits: u8) -> Self {
129/// Self {
130/// a: bits,
131/// }
132/// }
133///
134/// /// Make sure the return type can fit the specified number of bits. Also,
135/// /// must be const, we need that extra compile time safety.
136/// const fn into_bits(self) -> u8 {
137/// self.a
138/// }
139/// }
140///
141/// // Usage:
142/// // Creates a new bitfield using a builder pattern, unset fields default to 0
143/// // or their provided default value.
144/// let mut bitfield = BitfieldBuilder::new()
145/// .with_u8int(5)
146/// .with_small_u8int(0xF)
147/// .with_custom_type(CustomType::from_bits(0x3))
148/// // .with_custom_type(CustomType::default()) // Can pass a [`CustomType`] instance.
149/// .with_read_only(0x3) // Read-only field can only be set during construction.
150/// // .with__padding(0x3) // Compile error, padding fields are inaccessible.
151/// .with_signed_int(-5)
152/// .with_small_signed_int(0xF)
153/// .build();
154///
155/// // let bitfield = Bitfield::new(); // Bitfield with default values.
156/// // let bitfield = Bitfield::new_without_defaults(); // Bitfield without default values.
157/// // let bitfield = BitfieldBuilder::new_without_defaults(); // Builder without defaults.
158///
159/// // let builder = bitfield.to_builder(); // Convert a bitfield back to builder, requires
160/// // `#[bitfield(to_builder = true)]` and `#[derive(Clone)]` on the bitfield.
161///
162/// // Accessing fields:
163/// let u8int = bitfield.u8int(); // Getters
164/// let small_u8int = bitfield.small_u8int(); // Signed-types are sign-extended.
165/// bitfield.ignore_me; // Ignored fields can be accessed directly.
166/// // bitfield.set_read_only(0x3); // Compile error, read-only fields can't be set.
167///
168/// // Setting fields:
169/// bitfield.set_u8int(0x3); // Setters
170/// bitfield.checked_set_small_u8int(0xF); // Checked setter, error if value overflow bits.
171///
172/// // Converting to bits:
173/// let bits = bitfield.into_bits();
174///
175/// // Converting from bits:
176/// let mut bitfield = Bitfield::from_bits(0x3); // Converts from bits
177/// // let bitfield = Bitfield::from_bits_with_defaults(0x3); // Converts, respects defaults.
178///
179/// // Set and clear bitfield:
180/// bitfield.set_bits(0x12345678); // Sets the bitfield.
181/// bitfield.set_bits_with_defaults(0x12345678); // Sets the bitfield, respects
182/// defaults.
183///
184/// bitfield.clear_bits(); // Clears the bitfield.
185/// bitfield.clear_bits_with_defaults(); // Clears the bitfield, respects
186/// defaults.
187///
188/// // Constants:
189/// assert_eq!(Bitfield::U8INT_BITS, 8); // Number of bits of the field.
190/// assert_eq!(Bitfield::U8INT_OFFSET, 0); // The offset of the field in the
191/// bitfield.
192/// ```
193///
194/// ## Features
195///
196/// ### Bitfield Types
197///
198/// A bitfield can represent unsigned types (`u8`, `u16`, `u32`, `u64`, `u128`)
199/// up to 128-bits, because Rust was weak and stopped at `u128`. The field bits
200/// of a bitfield must add up to the number of bits of the bitfield type.
201///
202/// ```ignore
203/// use bitfields::bitfield;
204///
205/// #[bitfield(u8)]
206/// struct BitFieldU8 {
207/// a: u8,
208/// }
209///
210/// #[bitfield(u32)]
211/// struct BitFieldU32 {
212/// a: u32,
213/// }
214///
215/// #[bitfield(u128)]
216/// struct BitFieldU128 {
217/// a: u128,
218/// }
219/// ```
220///
221/// ### Bitfield Field Types
222///
223/// A bitfield field can be any unsigned (`u8`, `u16`, `u32`, `u64`, `u128`),
224/// signed type (`i8`, `i16`, `i32`, `i64`, `i128`), or a custom type that
225/// implements the const functions `from_bits` and `into_bits`. A default value
226/// can also be a const variable or a const function. Just be aware that const
227/// function and variables defaults lose their compile-time field bits checking.
228///
229/// Signed types are treated as 2's complement data types, meaning the most
230/// significant represents the sign bit. For example, if you had a field with 5
231/// bits, the value range would be `-16` to `15`. The more bits you include, the
232/// larger the value range.
233///
234/// ```ignore
235/// use bitfields::bitfield;
236///
237/// const CONST_VAR: u8 = 0x2;
238///
239/// const fn provide_val() -> u8 {
240/// 0x1
241/// }
242///
243/// #[bitfield(u32)]
244/// struct Bitfield {
245/// #[bits(default = 0xFF)]
246/// a: u8,
247/// #[bits(default = -127)]
248/// b: i8,
249/// /// Sign-extended by the most significant bit of 4 bits. Also treated as 2's
250/// /// complement, meaning this field with 4 bits has the value range of `-8` to `7`.
251/// /// You can add more bits to increase this range!
252/// #[bits(4, default = 9)]
253/// c_sign_extended: i8,
254/// #[bits(2, default = CONST_VAR)] // No compile time checks for const variables.
255/// const_var_default: u8,
256/// #[bits(2, default = provide_val())] // No compile time checks for const functions.
257/// const_fn_default: u8, // No compile time checks for const functions.
258/// #[bits(8, default = CustomType::C)]
259/// custom_type: CustomType
260/// }
261///
262/// #[derive(Debug, PartialEq)]
263/// enum CustomType {
264/// A = 0,
265/// B = 1,
266/// C = 2,
267/// }
268///
269/// impl CustomType {
270/// const fn from_bits(bits: u8) -> Self {
271/// match bits {
272/// 0 => Self::A,
273/// 1 => Self::B,
274/// 2 => Self::C,
275/// _ => unreachable!(),
276/// }
277/// }
278///
279/// const fn into_bits(self) -> u8 {
280/// self as u8
281/// }
282/// }
283///
284/// let bitfield = Bitfield::new();
285/// assert_eq!(bitfield.a(), 0xFF);
286/// assert_eq!(bitfield.b(), -127);
287/// assert_eq!(bitfield.c_sign_extended(), -7);
288/// assert_eq!(bitfield.const_var_default(), 0x2);
289/// assert_eq!(bitfield.const_fn_default(), 0x1);
290/// assert_eq!(bitfield.custom_type(), CustomType::C);
291/// ```
292///
293/// ### Constructing a Bitfield
294///
295/// A bitfield can be constructed using the `new` and `new_without_defaults`
296/// constructors. The former initializes the bitfield with default values, while
297/// the latter initializes the bitfield without default values, except for
298/// padding fields which always keep their default value or 0.
299///
300/// A bitfield can also be constructed using a fluent builder pattern using the
301/// `<Bitfield>Builder::new` and `<Bitfield>Builder::new_without_defaults`
302/// constructors. They operate the same as the `new` and `new_without_defaults`
303/// constructors.
304///
305/// ```ignore
306/// use bitfields::bitfield;
307///
308/// #[bitfield(u32)]
309/// struct Bitfield {
310/// #[bits(default = 0x12)]
311/// a: u8,
312/// #[bits(default = 0x34)]
313/// b: u8,
314/// #[bits(default = 0x56)]
315/// c: u8,
316/// #[bits(default = 0x78)]
317/// _d: u8,
318/// }
319///
320/// let bitfield = Bitfield::new();
321/// assert_eq!(bitfield.a(), 0x12);
322/// assert_eq!(bitfield.b(), 0x34);
323/// assert_eq!(bitfield.c(), 0x56);
324/// assert_eq!(bitfield.into_bits(), 0x78563412);
325///
326/// let bitfield_without_defaults = Bitfield::new_without_defaults();
327/// assert_eq!(bitfield_without_defaults.a(), 0);
328/// assert_eq!(bitfield_without_defaults.b(), 0);
329/// assert_eq!(bitfield_without_defaults.c(), 0);
330/// assert_eq!(bitfield_without_defaults.into_bits(), 0x78000000);
331///
332/// let bitfield = BitfieldBuilder::new()
333/// .with_a(0x12)
334/// .with_b(0x34)
335/// .with_c(0x56)
336/// .build();
337/// assert_eq!(bitfield.a(), 0x12);
338/// assert_eq!(bitfield.b(), 0x34);
339/// assert_eq!(bitfield.c(), 0x56);
340/// assert_eq!(bitfield.into_bits(), 0x78563412);
341/// ```
342///
343/// ### To Builder
344///
345/// A constructed bitfield can be converted back to a builder using the
346/// `to_builder` function which is enabled using the `#[bitfield(to_builder =
347/// true)]` attribute arg. The bitfield must also derive `Clone` to support this
348/// feature.
349///
350/// ```ignore
351/// use bitfields::bitfield;
352///
353/// #[bitfield(u32, to_builder = true)]
354/// #[derive(Clone)]
355/// struct Bitfield {
356/// #[bits(default = 0x12)]
357/// a: u8,
358/// #[bits(default = 0x34)]
359/// b: u8,
360/// #[bits(default = 0x56)]
361/// c: u8,
362/// #[bits(default = 0x78)]
363/// _d: u8,
364/// }
365///
366/// let bitfield = Bitfield::new();
367///
368/// let bitfield_builder = bitfield.to_builder();
369/// ```
370///
371/// ### Setting and Clearing a Bitfield
372///
373/// You are able to set and clear a bitfield using the `set_bits` and
374/// `clear_bits` functions.
375///
376/// ```ignore
377/// use bitfields::bitfield;
378///
379/// #[bitfield(u32)]
380/// struct Bitfield {
381/// #[bits(default = 0x12)]
382/// a: u8,
383/// #[bits(default = 0x34)]
384/// b: u8,
385/// c: u8,
386/// #[bits(default = 0x78)]
387/// _d: u8, // Padding fields are respected.
388/// }
389///
390/// let mut bitfield = Bitfield::new();
391/// bitfield.set_bits(0x11223344);
392/// assert_eq!(bitfield.into_bits(), 0x78223344);
393///
394/// let mut bitfield = Bitfield::new();
395/// bitfield.set_bits_with_defaults(0x11223344);
396/// assert_eq!(bitfield.into_bits(), 0x78223412);
397///
398/// let mut bitfield = Bitfield::new();
399/// bitfield.clear_bits();
400/// assert_eq!(bitfield.into_bits(), 0x78000000);
401///
402/// let mut bitfield = Bitfield::new();
403/// bitfield.clear_bits_with_defaults();
404/// assert_eq!(bitfield.into_bits(), 0x78003412);
405/// ```
406///
407/// ### Bitfield Conversions
408///
409/// A bitfield can be converted from bits using the `from_bits` or
410/// `from_bits_with_defaults` functions. The former ignores default values,
411/// while the latter respects them. Padding fields are always 0 or their default
412/// value. The bitfield can also be converted to bits using the `into_bits`
413/// function. The `From` trait is also implemented between the bitfield and the
414/// bitfield type and operates the same as `from_bits`.
415///
416/// ```ignore
417/// use bitfields::bitfield;
418///
419/// #[bitfield(u32)]
420/// #[derive(Copy, Clone)]
421/// struct Bitfield {
422/// #[bits(default = 0x12)]
423/// a: u8,
424/// #[bits(8)]
425/// b: CustomType,
426/// c: u8,
427/// #[bits(default = 0x78)]
428/// _d: u8,
429/// }
430///
431/// #[derive(Debug, PartialEq)]
432/// enum CustomType {
433/// A = 0,
434/// B = 1,
435/// C = 2,
436/// }
437///
438/// impl CustomType {
439/// const fn from_bits(bits: u8) -> Self {
440/// match bits {
441/// 1 => Self::A,
442/// 2 => Self::B,
443/// 3 => Self::C,
444/// _ => Self::A,
445/// }
446/// }
447///
448/// const fn into_bits(self) -> u8 {
449/// self as u8
450/// }
451/// }
452///
453/// let bitfield = Bitfield::from_bits(0x11223344);
454/// assert_eq!(bitfield.a(), 0x44);
455/// assert_eq!(bitfield.b(), CustomType::A);
456/// assert_eq!(bitfield.c(), 0x22);
457/// let val = bitfield.into_bits();
458/// assert_eq!(val, 0x78220044);
459///
460/// let bitfield_respect_defaults =
461/// Bitfield::from_bits_with_defaults(0x11223344);
462/// assert_eq!(bitfield_respect_defaults.a(), 0x12); // Default value respected
463/// assert_eq!(bitfield_respect_defaults.b(), CustomType::A);
464/// assert_eq!(bitfield_respect_defaults.c(), 0x22);
465/// let val = bitfield_respect_defaults.into_bits();
466/// assert_eq!(val, 0x78220012);
467///
468/// // From trait
469/// let val: u32 = bitfield.into();
470/// assert_eq!(val, 0x78220044);
471/// let bitfield: Bitfield = val.into();
472/// assert_eq!(bitfield.into_bits(), 0x78220044);
473/// ```
474///
475/// ### Conversion Endianess
476///
477/// Sometimes the outside world is outside our control, like how systems store
478/// or expect data endian. Luckily, the endian of the bitfield conversions can
479/// be controlled by specifying the `#[bitfield(from_endian = x, into_endian =
480/// x)]` args. The possible endians are `little` or `big`. By default, the
481/// endian of both is `big`.
482///
483/// ````ignore
484/// use bitfields::bitfield;
485///
486/// // We are working with a system that stores data in little-endian, we
487/// // set the from_endian to little for the proper representation.
488/// //
489/// // The system expects the data it stores in big-endian, we set the
490/// // into_endian to big-endian for converting into the proper representation.
491/// #[bitfield(u32, from_endian = little, into_endian = big)]
492/// pub struct Bitfield {
493/// a: u8,
494/// b: u8,
495/// c: u8,
496/// d: u8,
497/// }
498///
499/// // The host device stored the data 0x12345678 in little-endian memory
500/// // as [0x78, 0x56, 0x34, 0x12].
501/// let bitfield = Bitfield::from_bits(0x78563412);
502///
503/// assert_eq!(bitfield.a(), 0x78);
504/// assert_eq!(bitfield.b(), 0x56);
505/// assert_eq!(bitfield.c(), 0x34);
506/// assert_eq!(bitfield.d(), 0x12);
507/// assert_eq!(bitfield.into_bits(), 0x12345678);
508/// ````
509///
510/// ### Field Order
511///
512/// By default, fields are ordered from the least significant bit (lsb) to the
513/// most significant bit (msb). The order can be changed by specifying the
514/// `#[bitfield(order = x)]` arg on the bitfield struct. There are two field
515/// orderings, `lsb` and `msb`.
516///
517/// ```ignore
518/// use bitfields::bitfield;
519///
520/// #[bitfield(u32, order = msb)]
521/// struct Bitfield {
522/// #[bits(default = 0x12)]
523/// a: u8,
524/// #[bits(default = 0x34)]
525/// b: u8,
526/// #[bits(default = 0x56)]
527/// c: u8,
528/// #[bits(default = 0x78)]
529/// d: u8,
530/// }
531///
532/// let bitfield = Bitfield::new();
533/// assert_eq!(bitfield.a(), 0x12);
534/// assert_eq!(bitfield.b(), 0x34);
535/// assert_eq!(bitfield.c(), 0x56);
536/// assert_eq!(bitfield.d(), 0x78);
537/// let val = bitfield.into_bits();
538///
539/// // .- a
540/// // | .- b
541/// // | | .- c
542/// // | | | .- d
543/// assert_eq!(val, 0x12_34_56_78);
544/// assert_eq!(Bitfield::A_OFFSET, 24); // Offset of the a field in the
545/// bitfield.
546/// ```
547///
548/// ### Field Access
549///
550/// Field access can be controlled by specifying the `#[bits(access = x)]` arg
551/// on a field. There are four accesses:
552/// - `rw` - Read and write access (default)
553/// - `ro` - Read-only access, only set during construction or from bits.
554/// - `wo` - Write-only access.
555/// - `none` - No access.
556///
557/// ```ignore
558/// use bitfields::bitfield;
559///
560/// #[bitfield(u32)]
561/// struct Bitfield {
562/// read_write: u8,
563/// #[bits(access = ro)]
564/// read_only: u8,
565/// #[bits(access = wo)]
566/// write_only: u8,
567/// #[bits(default = 0xFF, access = none)]
568/// none: u8,
569/// }
570///
571/// let mut bitfield = BitfieldBuilder::new()
572/// .with_read_write(0x12)
573/// .with_read_only(0x34) // Read-only fields only set during construction or from bits.
574/// .with_write_only(0x56)
575/// // .with_none(0x78) // Compile error, none field can't be set.
576/// .build();
577/// bitfield.set_read_write(0x12);
578/// // bitfield.set_read_only(1); // Compile error, read-only field can't be set, after construction.
579/// bitfield.set_write_only(0x56);
580/// // bitfield.set_none(0x78); // Compile error, none field can't be set.
581///
582/// assert_eq!(bitfield.read_write(), 0x12);
583/// assert_eq!(bitfield.read_only(), 0x34);
584/// // assert_eq!(bitfield.write_only(), 0x56); // Compile error, write-only can't be read.
585/// // assert_eq!(bitfield.none(), 0xFF); // Compile error, none field can't be accessed.
586/// assert_eq!(bitfield.into_bits(), 0xFF563412); // All fields exposed when converted to bits.
587/// ```
588///
589/// ### Checked Setters
590///
591/// Normally, when a field is set, the value is truncated to the number of bits
592/// of the field. Fields also have checked setters that returns an error if the
593/// value overflows the number of bits of the field.
594///
595/// ```ignore
596/// use bitfields::bitfield;
597///
598/// #[bitfield(u16)]
599/// struct Bitfield {
600/// a: u8,
601/// #[bits(4)]
602/// b: u8,
603/// #[bits(4)]
604/// _padding: u8,
605/// }
606///
607/// let mut bitfield = Bitfield::new();
608/// bitfield.set_a(0xFF);
609/// bitfield.set_b(0x12); // Truncated to 4 bits.
610/// assert_eq!(bitfield.a(), 0xFF);
611/// assert_eq!(bitfield.b(), 0x2);
612///
613/// let res = bitfield.checked_set_b(0x12); // Error, value overflows bits.
614/// assert!(res.is_err());
615/// ```
616///
617/// ### Bit Operations
618///
619/// Individual bits can be get or set using the `get_bit` and `set_bit`
620/// functions. They can be enabled using the bitfield attribute arg
621/// `#[bitfield(bit_ops = true)]` When calling `get_bit`, if the bit is
622/// out-of-bounds or the field doesn't have write access, `false` is returned.
623/// There is a checked version `checked_get_bit` that return an error instead.
624/// Similarly, for `set_bit`, if the bit is out-of-bounds or the field doesn't
625/// have write access, the operation is no-op. There is a checked version
626/// `checked_set_bit` that returns an error instead.
627///
628/// ```ignore
629/// use bitfields::bitfield;
630///
631/// #[bitfield(u8, bit_ops = true)]
632/// #[derive(Copy, Clone)]
633/// pub struct Bitfield {
634/// #[bits(2, default = 0b11)]
635/// a: u8,
636/// #[bits(2, default = 0b00)]
637/// b: u8,
638/// #[bits(2, default = 0b10, access = wo)]
639/// c: u8,
640/// #[bits(2, default = 0b01)]
641/// _d: u8,
642/// }
643///
644/// let bitfield = Bitfield::new();
645///
646/// assert!(bitfield.get_bit(0));
647/// assert!(bitfield.get_bit(1));
648/// assert!(!bitfield.get_bit(2));
649/// assert!(!bitfield.get_bit(3));
650/// assert!(bitfield.get_bit(4)); // No write access, false is returned.
651/// assert!(bitfield.get_bit(5)); // No write access, false is returned.
652/// assert!(bitfield.checked_get_bit(4).is_err()); // No write access, err.
653/// assert!(bitfield.checked_get_bit(5).is_err()); // No write access, err.
654/// assert!(bitfield.get_bit(6));
655/// assert!(!bitfield.get_bit(7));
656/// assert!(bitfield.get_bit(50)); // Out-of-bounds, false is returned.
657/// assert!(bitfield.checked_get_bit(50).is_err()); // Out-of-bounds, err.
658/// ```
659///
660/// ```ignore
661/// #[bitfield(u8, bit_ops = true)]
662/// #[derive(Copy, Clone)]
663/// pub struct Bitfield {
664/// #[bits(2)]
665/// a: u8,
666/// #[bits(2, default = 0b11)]
667/// b: u8,
668/// #[bits(2, default = 0b11, access = ro)]
669/// c: u8,
670/// #[bits(2, default = 0b00)]
671/// _d: u8,
672/// }
673///
674/// let mut bitfield = Bitfield::new();
675///
676/// bitfield.set_bit(0, true);
677/// bitfield.set_bit(1, true);
678/// bitfield.set_bit(2, false);
679/// bitfield.set_bit(3, false);
680/// bitfield.set_bit(4, false); // No-op, no write access.
681/// bitfield.set_bit(5, false); // No-op, no write access.
682/// assert!(bitfield.checked_set_bit(4, false).is_err()); // Error, no write access.
683/// assert!(bitfield.checked_set_bit(5, false).is_err()); // Error, no write access.
684/// bitfield.set_bit(6, true); // No-op, padding.
685/// bitfield.set_bit(7, true); // No-op, padding.
686/// assert!(bitfield.checked_set_bit(4, false).is_err()); // Error, padding.
687/// assert!(bitfield.checked_set_bit(5, false).is_err()); // Error, padding.
688/// assert_eq!(bitfield.into_bits(), 0b110011);
689/// ```
690///
691/// ### Padding Fields
692///
693/// Fields prefixed with an underscore `_` are padding fields, which are
694/// inaccessible. Meaning the field is always 0/false or a default value. They
695/// are useful for padding the bits of the bitfield.
696///
697/// ```ignore
698/// use bitfields::bitfield;
699///
700/// #[bitfield(u16)]
701/// struct Bitfield {
702/// a: u8,
703/// #[bits(default = 0xFF)]
704/// _padding: u8, // Fills the remaining bits of the u16.
705/// }
706///
707/// let bitfield = Bitfield::new();
708/// assert_eq!(bitfield.a(), 0);
709/// // assert_eq!(bitfield._padding(), 0xFF00); // Compile error, padding inaccessible.
710/// // bitfield.set__padding(0xFF); // Compile error, padding fields are inaccessible.
711/// assert_eq!(bitfield.into_bits(), 0xFF00); // All fields exposed when converted to bits.
712/// ```
713///
714/// ### Ignored Fields
715///
716/// Fields with the `#[bits(ignore = true)` attribute are ignored and not
717/// included in the bitfield. This is useful for when you are building a custom
718/// bitfield, but want to include certain fields that aren't a part of the
719/// bitfield without wrapping having to wrap bitfield is a parent struct. All
720/// ignored fields must implement the `Default` trait. Ignored fields
721/// are accessible directly like normal struct fields.
722///
723/// ```ignore
724/// use bitfields::bitfield;
725///
726/// #[bitfield(u16)]
727/// struct Bitfield {
728/// a: u8,
729/// b: u8,
730/// #[bits(ignore = true)] // Ignored field.
731/// field_id: u8,
732/// #[bits(ignore = true)] // Ignored field.
733/// field_custom: CustomType,
734/// }
735///
736/// #[derive(Debug, Default, PartialEq)]
737/// enum CustomType {
738/// #[default]
739/// A,
740/// B,
741/// }
742///
743/// let bitfield = Bitfield::new();
744///
745/// assert_eq!(bitfield.field_id, 0); // Ignored fields can be accessed
746/// directly. assert_eq!(bitfield.field_custom, CustomType::A); // Ignored
747/// fields can be accessed directly.
748/// ```
749///
750/// ### Field Constants
751///
752/// Fields with read or write access have constants generated for their number
753/// of bits and offset in the bitfield.
754///
755/// ```ignore
756/// use bitfields::bitfield;
757///
758/// #[bitfield(u32)]
759/// struct Bitfield {
760/// #[bits(default = 0x12)]
761/// a: u8,
762/// #[bits(default = 0x34)]
763/// b: u8,
764/// #[bits(default = 0x56)]
765/// c: u8,
766/// #[bits(default = 0x78)]
767/// d: u8,
768/// }
769///
770/// assert_eq!(Bitfield::A_BITS, 8); // Number of bits of the afield.
771/// assert_eq!(Bitfield::A_OFFSET, 0); // The offset of the a field in the
772/// bitfield. assert_eq!(Bitfield::B_BITS, 8); // Number of bits of the b field.
773/// assert_eq!(Bitfield::B_OFFSET, 8); // The offset of the b field in the
774/// bitfield. assert_eq!(Bitfield::C_BITS, 8); // Number of bits of c the field.
775/// assert_eq!(Bitfield::C_OFFSET, 16); // The offset of the c field in the
776/// bitfield. assert_eq!(Bitfield::D_BITS, 8); // Number of bits of the d field.
777/// assert_eq!(Bitfield::D_OFFSET, 24); // The offset of the d field in the
778/// bitfield.
779/// ```
780///
781/// ### Debug Implementation
782///
783/// A debug implementation is generated for the bitfield, which prints the
784/// fields and their values.
785///
786/// ```ignore
787/// use bitfields::bitfield;
788///
789/// #[bitfield(u32)]
790/// struct Bitfield {
791/// #[bits(default = 0x12)]
792/// a: u8,
793/// #[bits(default = 0x34)]
794/// b: u8,
795/// #[bits(default = 0x56)]
796/// c: u8,
797/// #[bits(default = 0x78)]
798/// d: u8,
799/// }
800///
801/// let bitfield = Bitfield::new();
802///
803/// assert_eq!(format!("{:?}", bitfield), "Bitfield { d: 120, c: 86, b: 52, a: 18 }"); ```
804///
805/// ### Passing Attributes
806///
807/// Attributes below the `#[bitfield]` attribute are passed to the generated
808/// struct.
809/// ```ignore
810/// use bitfields::bitfield;
811///
812/// #[bitfield(u32)]
813/// #[derive(Copy, Clone)]
814/// struct Bitfield {
815/// a: u32,
816/// }
817/// ```
818///
819/// ### Complete Generation Control
820///
821/// You have complete control over what gets generated by the bitfield macro.
822/// When your deploying to a resource-constrained environment, you can generate
823/// only the necessary functions or implementations. You can disable generation
824/// by passing `false` to its attribute arg.
825///
826/// The `#[bitfield]` args that control generation are:
827///
828/// - `#[bitfield(new = true)]` - Generates the `new` and `new_without_defaults`
829/// constructor.
830/// - `#[bitfield(from_bits = true)]` - Generates the `from_bits` and
831/// `from_bits_with_defaults` functions.
832/// - `#[bitfield(into_bits = true)]` - Generates the `into_bits` function.
833/// - `#[bitfield(from = true)]` - Generates the `From` trait implementation.
834/// - `#[bitfield(debug = true)]` - Generates the `Debug` trait implementation.
835/// - `#[bitfield(default = true)]` - Generates the `Default` trait
836/// implementation
837/// - `#[bitfield(builder = true)]` - Generates the builder implementation.
838/// - `#[bitfield(set_bits = true)]` - Generates the `set_bits` function.
839/// - `#[bitfield(clear_bits = true)]` - Generates the `clear_bits` function.
840/// - `#[bitfield(bit_ops = true)]` - Generates the bit operations
841/// implementation.
842/// - `#[bitfield(to_builder = true)]` - Generates the `to_builder` function.
843#[proc_macro_attribute]
844pub fn bitfield(
845 args: proc_macro::TokenStream,
846 input: proc_macro::TokenStream,
847) -> proc_macro::TokenStream {
848 match parse_bitfield(args.into(), input.into()) {
849 Ok(res) => res.into(),
850 Err(err) => err.into_compile_error().into(),
851 }
852}
853
854/// Parses the bitfield attribute, struct, and fields.
855fn parse_bitfield(args: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
856 // Parse the struct tokens
857 let struct_tokens = syn::parse2::<syn::ItemStruct>(input.clone())?;
858
859 // Parse the arguments of the '#[bitfield(arg, arg)]' attribute
860 let bitfield_attribute: BitfieldAttribute = match syn::parse2(args) {
861 Ok(bitfield_attribute) => bitfield_attribute,
862 Err(err) => {
863 return Err(create_syn_error(input.span(), err.to_string()));
864 }
865 };
866
867 // Check if the bitfield type can contain the fields.
868 let all_fields = parse_fields(&bitfield_attribute, &struct_tokens)?;
869 let fields = all_fields.0;
870 let ignored_fields = all_fields.1;
871 check_bitfield_type_contain_field_bits(&bitfield_attribute, &fields)?;
872 check_bitfield_names_unique(&fields)?;
873
874 // Generate the bitfield functions.
875 generate_functions(&bitfield_attribute, &fields, &ignored_fields, &struct_tokens)
876}
877
878/// Check if the bitfield type can contain the field bits.
879fn check_bitfield_type_contain_field_bits(
880 bitfield_attribute: &BitfieldAttribute,
881 fields: &[BitfieldField],
882) -> syn::Result<()> {
883 let total_field_bits = fields.iter().map(|field| field.bits).sum::<u8>();
884
885 match total_field_bits.cmp(&bitfield_attribute.bits) {
886 Ordering::Greater => Err(create_syn_error(
887 bitfield_attribute.ty.span(),
888 format!(
889 "The total number of bits of the fields ({} bits) is greater than the number of bits of the bitfield type '{}' ({} bits).",
890 total_field_bits,
891 get_type_ident(&bitfield_attribute.ty).unwrap(),
892 bitfield_attribute.bits
893 ),
894 )),
895 Ordering::Less => {
896 let remaining_bits = bitfield_attribute.bits - total_field_bits;
897 Err(create_syn_error(
898 bitfield_attribute.ty.span(),
899 format!(
900 "The total number of bits of the fields ({} bits) is less than the number of bits of the bitfield type '{}' ({} bits), you can add a padding field (prefixed with '_') to fill the remaining '{} bits'.",
901 total_field_bits,
902 get_type_ident(&bitfield_attribute.ty).unwrap(),
903 bitfield_attribute.bits,
904 remaining_bits,
905 ),
906 ))
907 }
908 Ordering::Equal => {
909 // The total number of bits of all fields is equal to the number of bits, we're
910 // good.
911 Ok(())
912 }
913 }
914}
915
916fn check_bitfield_names_unique(fields: &[BitfieldField]) -> syn::Result<()> {
917 let mut field_names = Vec::new();
918 for field in fields {
919 if field_names.contains(&field.name) {
920 return Err(create_syn_error(
921 field.name.span(),
922 format!(
923 "The field name '{}' is duplicated, each field must have a unique name.",
924 field.name
925 ),
926 ));
927 }
928 if !field.padding {
929 field_names.push(field.name.clone());
930 }
931 }
932
933 Ok(())
934}
935
936/// Parses all the fields into a list of [`BitfieldField`]s.
937fn parse_fields(
938 bitfield_attribute: &BitfieldAttribute,
939 struct_tokens: &syn::ItemStruct,
940) -> syn::Result<(Vec<BitfieldField>, Vec<BitfieldField>)> {
941 let fields_tokens = match &struct_tokens.fields {
942 Fields::Named(named_files) => named_files,
943 _ => {
944 return Err(create_syn_error(
945 struct_tokens.span(),
946 "Non-named fields are not supported.",
947 ));
948 }
949 };
950
951 let mut fields = Vec::new();
952 let mut ignored_fields = Vec::new();
953 for field_token in fields_tokens.named.clone() {
954 let field = do_parse_field(bitfield_attribute, field_token, &fields)?;
955 if field.ignore {
956 ignored_fields.push(field);
957 } else {
958 fields.push(field);
959 }
960 }
961
962 Ok((fields, ignored_fields))
963}
964
965/// Internal implementation of [`parse_fields`] to parse a single field.
966fn do_parse_field(
967 bitfield_attribute: &BitfieldAttribute,
968 field_tokens: syn::Field,
969 prev_fields: &[BitfieldField],
970) -> syn::Result<BitfieldField> {
971 // Parse field attribute, a field could have multiple attributes, but we only
972 // care about our 'bits' attribute.
973 let field_bit_attribute = field_tokens.attrs.iter().find(|attr| {
974 attr.path().is_ident(BIT_ATTRIBUTE_NAME) && attr.style == syn::AttrStyle::Outer
975 });
976
977 let visibility = match field_tokens.vis {
978 // Pass the visibility to the field.
979 Visibility::Public(_) | Visibility::Restricted(_) => Some(field_tokens.vis.clone()),
980 // Use the visibility of the struct
981 Visibility::Inherited => None,
982 };
983
984 let field_type = if is_custom_field_type(&field_tokens.ty) {
985 FieldType::CustomFieldType
986 } else {
987 FieldType::IntegerFieldType
988 };
989
990 let padding =
991 field_tokens.ident.clone().unwrap().to_string().starts_with(PADDING_FIELD_NAME_PREFIX);
992
993 let bitfield = if field_bit_attribute.is_none() {
994 if !is_supported_field_type(&field_tokens.ty) {
995 return Err(create_syn_error(
996 field_tokens.span(),
997 format!(
998 "The field type {:?} is not supported.",
999 get_type_ident(&field_tokens.ty).unwrap()
1000 ),
1001 ));
1002 }
1003
1004 // We have to determine the number of bits from the field type since there's no
1005 // '#[bits]' attribute.
1006 if is_size_type(&field_tokens.ty) {
1007 return Err(create_syn_error(
1008 field_tokens.span(),
1009 "The types isize and usize require a bit size, otherwise we can't determine the size of the field.",
1010 ));
1011 }
1012
1013 if field_type != FieldType::IntegerFieldType {
1014 return Err(create_syn_error(
1015 field_tokens.span(),
1016 "Custom and nested field types require a defined bit size, otherwise we can't determine the size of the field.",
1017 ));
1018 }
1019
1020 let bits = get_bits_from_type(&field_tokens.ty)?;
1021 let offset = calculate_field_offset(bits, bitfield_attribute, prev_fields)?;
1022 let access = if padding { FieldAccess::None } else { FieldAccess::ReadWrite };
1023
1024 // Create a bitfield field with default values since we don't have one to
1025 // parse.
1026 BitfieldField {
1027 name: field_tokens.ident.unwrap(),
1028 ty: field_tokens.ty.clone(),
1029 vis: visibility,
1030 bits,
1031 offset,
1032 default_value_tokens: None,
1033 unsigned: true,
1034 padding,
1035 access,
1036 field_type: FieldType::IntegerFieldType,
1037 ignore: false,
1038 }
1039 } else {
1040 let bit_attribute_tokens = match &field_bit_attribute.unwrap().meta {
1041 Meta::List(list) => list,
1042 _ => {
1043 return Err(create_syn_error(
1044 field_tokens.span(),
1045 "The '#[bits]' attribute must be a list.",
1046 ));
1047 }
1048 };
1049
1050 let bits_attribute: BitsAttribute = syn::parse2(bit_attribute_tokens.tokens.clone())?;
1051
1052 if bits_attribute.ignore {
1053 return Ok(BitfieldField {
1054 ty: field_tokens.ty.clone(),
1055 vis: Some(field_tokens.vis),
1056 bits: 0,
1057 offset: 0,
1058 default_value_tokens: None,
1059 unsigned: false,
1060 padding,
1061 access: FieldAccess::ReadOnly,
1062 name: field_tokens.ident.unwrap(),
1063 ignore: true,
1064 field_type,
1065 });
1066 }
1067
1068 if !is_supported_field_type(&field_tokens.ty) {
1069 return Err(create_syn_error(
1070 field_tokens.span(),
1071 format!(
1072 "The field type {:?} is not supported.",
1073 get_type_ident(&field_tokens.ty).unwrap()
1074 ),
1075 ));
1076 }
1077
1078 let bits = match bits_attribute.bits {
1079 Some(bits) => {
1080 // Make sure the type of the field can contain the specified number of bits if
1081 // not a custom type.
1082 if field_type == FieldType::IntegerFieldType
1083 && bits > get_bits_from_type(&field_tokens.ty)?
1084 {
1085 return Err(create_syn_error(
1086 bit_attribute_tokens.span(),
1087 format!(
1088 "The field type {:?} ({} bits) is too small to hold the specified '{} bits'.",
1089 get_type_ident(&field_tokens.ty).unwrap(),
1090 get_bits_from_type(&field_tokens.ty)?,
1091 bits
1092 ),
1093 ));
1094 }
1095
1096 bits
1097 }
1098 None => {
1099 if field_type != FieldType::IntegerFieldType {
1100 return Err(create_syn_error(
1101 field_tokens.span(),
1102 "Custom and nested field types require a defined bit size, otherwise we can't determine the size of the field.",
1103 ));
1104 }
1105
1106 get_bits_from_type(&field_tokens.ty)?
1107 }
1108 };
1109
1110 // Make sure the field bits are greater than 0.
1111 if bits == 0 {
1112 return Err(create_syn_error(
1113 bit_attribute_tokens.span(),
1114 "The field bits must be greater than 0.",
1115 ));
1116 }
1117
1118 // Make sure the default value is within the field bits. If a number was unable
1119 // to be parsed, let's take a chance and see if the user is trying to
1120 // use a const variable or a const function.
1121 let parsed_number = if field_type == FieldType::IntegerFieldType
1122 && bits_attribute.clone().default_value_expr.is_some()
1123 {
1124 check_default_value_fit_in_field(
1125 &bits_attribute.clone().default_value_expr.unwrap(),
1126 bits,
1127 field_tokens.ty.clone(),
1128 )?
1129 } else {
1130 None
1131 };
1132
1133 let unsigned =
1134 field_type != FieldType::IntegerFieldType || is_unsigned_integer_type(&field_tokens.ty);
1135 let access = if padding {
1136 if bits_attribute.access.is_some() {
1137 return Err(create_syn_error(
1138 bit_attribute_tokens.span(),
1139 "Padding fields can't have a specified access.",
1140 ));
1141 }
1142
1143 FieldAccess::None
1144 } else {
1145 bits_attribute.access.unwrap_or(FieldAccess::ReadWrite)
1146 };
1147 let offset = calculate_field_offset(bits, bitfield_attribute, prev_fields)?;
1148
1149 let default_value_tokens = match bits_attribute.default_value_expr {
1150 None => None,
1151 Some(ref expr) => {
1152 // We want to add integer literals to default values expressions if the
1153 // expression is a negative number without a suffix. We do alot of casting
1154 // so what happens is, if there is the default value expr `-125`, when we
1155 // try to cast later like `-125 as u8`, Rust will complain that the number
1156 // is too large for the type. Adding the integer suffix will fix this since
1157 // Rust will know the type of the number and will cast it.
1158 if unsigned
1159 || field_type != FieldType::IntegerFieldType
1160 || parsed_number.is_none()
1161 || parsed_number.unwrap().has_integer_suffix
1162 {
1163 Some(quote! {
1164 #expr
1165 })
1166 } else {
1167 let tokens =
1168 add_integer_literals_to_expr(&expr.clone(), field_tokens.ty.clone())?;
1169
1170 Some(quote! {
1171 #tokens
1172 })
1173 }
1174 }
1175 };
1176
1177 BitfieldField {
1178 name: field_tokens.ident.unwrap(),
1179 ty: field_tokens.ty.clone(),
1180 vis: visibility,
1181 bits,
1182 offset,
1183 default_value_tokens,
1184 unsigned,
1185 padding,
1186 access,
1187 field_type,
1188 ignore: false,
1189 }
1190 };
1191
1192 Ok(bitfield)
1193}
1194
1195/// Checks if the default value can fit in the field bits.
1196fn check_default_value_fit_in_field(
1197 default_value_expr: &Expr,
1198 bits: u8,
1199 field_type: Type,
1200) -> syn::Result<Option<ParsedNumber>> {
1201 let default_value_str = "e!(#default_value_expr).to_string();
1202
1203 let parsed_number = match parse_number_string(default_value_str) {
1204 Ok(number) => number,
1205 Err(err) => {
1206 return match err {
1207 NumberParseError::FloatNotSupported => Err(create_syn_error(
1208 default_value_expr.span(),
1209 "Floats are not supported as default values.".to_string(),
1210 )),
1211 // Maybe the user is trying to use a const variable or a const
1212 // function call as a default.
1213 NumberParseError::InvalidNumberString => Ok(None),
1214 };
1215 }
1216 };
1217
1218 let bits_max_value = 1 << bits as u128;
1219 if parsed_number.number >= bits_max_value {
1220 if parsed_number.negative {
1221 return Err(create_syn_error(
1222 default_value_expr.span(),
1223 format!(
1224 "The default value -'{}' is too large to fit into the specified '{} bits'.",
1225 parsed_number.number, bits,
1226 ),
1227 ));
1228 }
1229 return Err(create_syn_error(
1230 default_value_expr.span(),
1231 format!(
1232 "The default value '{}' is too large to fit into the specified '{} bits'.",
1233 parsed_number.number, bits,
1234 ),
1235 ));
1236 }
1237
1238 let default_value_too_big_for_type = match get_integer_type_from_type(&field_type) {
1239 IntegerType::Bool => parsed_number.number > 1,
1240 IntegerType::U8 => parsed_number.number > u8::MAX as u128,
1241 IntegerType::U16 => parsed_number.number > u16::MAX as u128,
1242 IntegerType::U32 => parsed_number.number > u32::MAX as u128,
1243 IntegerType::U64 => parsed_number.number > u64::MAX as u128,
1244 IntegerType::U128 => {
1245 // Unable to happen, this is Rust's max unsigned type value.
1246 false
1247 }
1248 IntegerType::Usize => parsed_number.number > usize::MAX as u128,
1249 IntegerType::Isize => {
1250 if parsed_number.negative {
1251 parsed_number.number > isize::MIN.unsigned_abs() as u128
1252 } else {
1253 parsed_number.number > isize::MAX as u128
1254 }
1255 }
1256 IntegerType::I8 => {
1257 if parsed_number.negative {
1258 parsed_number.number > i8::MIN.unsigned_abs() as u128
1259 } else {
1260 parsed_number.number > i8::MAX as u128
1261 }
1262 }
1263 IntegerType::I16 => {
1264 if parsed_number.negative {
1265 parsed_number.number > i16::MIN.unsigned_abs() as u128
1266 } else {
1267 parsed_number.number > i16::MAX as u128
1268 }
1269 }
1270 IntegerType::I32 => {
1271 if parsed_number.negative {
1272 parsed_number.number > i32::MIN.unsigned_abs() as u128
1273 } else {
1274 parsed_number.number > i32::MAX as u128
1275 }
1276 }
1277 IntegerType::I64 => {
1278 if parsed_number.negative {
1279 parsed_number.number > i64::MIN.unsigned_abs() as u128
1280 } else {
1281 parsed_number.number > i64::MAX as u128
1282 }
1283 }
1284 IntegerType::I128 => {
1285 if parsed_number.negative {
1286 parsed_number.number > i128::MIN.unsigned_abs()
1287 } else {
1288 parsed_number.number > i128::MAX as u128
1289 }
1290 }
1291 _ => Err(create_syn_error(default_value_expr.span(), PANIC_ERROR_MESSAGE))?,
1292 };
1293
1294 if default_value_too_big_for_type {
1295 let negative_str = if parsed_number.negative { "-" } else { "" };
1296 return Err(create_syn_error(
1297 default_value_expr.span(),
1298 format!(
1299 "The default value '{}{}' is too large to fit into the field type '{}'.",
1300 negative_str,
1301 parsed_number.number,
1302 get_type_ident(&field_type).unwrap()
1303 ),
1304 ));
1305 }
1306
1307 Ok(Some(parsed_number))
1308}
1309
1310/// Calculate the offset of a field based on previous fields.
1311fn calculate_field_offset(
1312 bits: u8,
1313 bitfield_attribute: &BitfieldAttribute,
1314 prev_fields: &[BitfieldField],
1315) -> syn::Result<u8> {
1316 let offset = prev_fields.iter().map(|field| field.bits).sum::<u8>();
1317
1318 match bitfield_attribute.bit_order {
1319 BitOrder::Lsb => Ok(offset),
1320 BitOrder::Msb => {
1321 let bitfield_type_bits = get_bits_from_type(&bitfield_attribute.ty)?;
1322 // We calculate offset starting from the left. There's a chance that
1323 // the total bits of all fields is greater than the number of bits
1324 // of the bitfield type. We will catch it later so
1325 // we can ignore for now.
1326 if offset + bits < bitfield_type_bits {
1327 Ok(bitfield_type_bits - bits - offset)
1328 } else {
1329 // We've underflow the bitfield type, this will be caught later.
1330 Ok(0)
1331 }
1332 }
1333 }
1334}
1335
1336/// Adds the field type integer literal suffix to the expression.
1337///
1338/// For example, if the expression is '-1' and the field type is 'i8', the
1339/// expression will be updated to '1i8'.
1340fn add_integer_literals_to_expr(expr: &Expr, field_type: Type) -> syn::Result<TokenStream> {
1341 let updated_expr = if let Expr::Unary(unary) = expr {
1342 let attrs = unary.attrs.clone();
1343 let op = unary.op;
1344
1345 let updated_expr = if let Expr::Lit(expr_lit) = *unary.expr.clone() {
1346 let new_lit = create_expr_lit_with_integer_suffix(&expr_lit, field_type)?;
1347
1348 Expr::Lit(ExprLit { attrs: expr_lit.attrs, lit: new_lit.lit })
1349 } else {
1350 Err(create_syn_error(expr.span(), PANIC_ERROR_MESSAGE))?
1351 };
1352
1353 Expr::Unary(ExprUnary { attrs, op, expr: Box::new(updated_expr) })
1354 } else if let Expr::Lit(expr_lit) = expr {
1355 let new_lit = create_expr_lit_with_integer_suffix(expr_lit, field_type)?;
1356
1357 Expr::Lit(ExprLit { attrs: expr_lit.clone().attrs, lit: new_lit.lit })
1358 } else {
1359 Err(create_syn_error(expr.span(), PANIC_ERROR_MESSAGE))?
1360 };
1361
1362 Ok(quote! {
1363 #updated_expr
1364 })
1365}
1366
1367/// Helper for creating an integer literal with the integer suffix.
1368fn create_expr_lit_with_integer_suffix(lit: &ExprLit, field_type: Type) -> syn::Result<ExprLit> {
1369 let integer_type = get_integer_type_from_type(&field_type);
1370 let integer_suffix = get_integer_suffix_from_integer_type(integer_type)?;
1371
1372 let new_lit = match lit.lit.clone() {
1373 Lit::Int(lit_int) => {
1374 let new_lit_int =
1375 LitInt::new(&format!("{}{}", lit_int.token(), integer_suffix), lit_int.span());
1376 ExprLit { attrs: lit.attrs.clone(), lit: Lit::Int(new_lit_int) }
1377 }
1378 _ => Err(create_syn_error(lit.span(), PANIC_ERROR_MESSAGE))?,
1379 };
1380
1381 Ok(new_lit)
1382}
1383
1384/// Generate the bitfield functions.
1385fn generate_functions(
1386 bitfield_attribute: &BitfieldAttribute,
1387 fields: &[BitfieldField],
1388 ignored_fields: &[BitfieldField],
1389 struct_tokens: &syn::ItemStruct,
1390) -> syn::Result<TokenStream> {
1391 let struct_attributes: TokenStream =
1392 struct_tokens.attrs.iter().map(ToTokens::to_token_stream).collect();
1393 let struct_name = &struct_tokens.ident;
1394
1395 let bitfield_struct = if !ignored_fields.is_empty() {
1396 generate_struct_with_fields_tokens(
1397 struct_name.clone(),
1398 struct_tokens.vis.clone(),
1399 bitfield_attribute.ty.clone(),
1400 ignored_fields,
1401 )
1402 } else {
1403 generate_tuple_struct_tokens(
1404 struct_name.clone(),
1405 struct_tokens.vis.clone(),
1406 bitfield_attribute.ty.clone(),
1407 )
1408 };
1409 let new_function = bitfield_attribute.generate_new_func.then(|| {
1410 generate_new_function_tokens(
1411 struct_tokens.vis.clone(),
1412 fields,
1413 ignored_fields,
1414 &bitfield_attribute.ty,
1415 )
1416 });
1417 let new_without_defaults_function = bitfield_attribute.generate_new_func.then(|| {
1418 generate_new_without_defaults_function_tokens(
1419 struct_tokens.vis.clone(),
1420 fields,
1421 ignored_fields,
1422 &bitfield_attribute.ty,
1423 )
1424 });
1425 let from_bits_function = bitfield_attribute.generate_from_bits_func.then(|| {
1426 generate_from_bits_function_tokens(
1427 struct_tokens.vis.clone(),
1428 fields,
1429 ignored_fields,
1430 &bitfield_attribute.ty,
1431 bitfield_attribute,
1432 )
1433 });
1434 let from_bits_with_defaults_function = bitfield_attribute.generate_from_bits_func.then(|| {
1435 generate_from_bits_with_defaults_function_tokens(
1436 struct_tokens.vis.clone(),
1437 fields,
1438 &bitfield_attribute.ty,
1439 bitfield_attribute,
1440 !ignored_fields.is_empty(),
1441 )
1442 });
1443 let generate_into_bits_function = bitfield_attribute.generate_into_bits_func.then(|| {
1444 generate_into_bits_function_tokens(
1445 struct_tokens.vis.clone(),
1446 bitfield_attribute,
1447 !ignored_fields.is_empty(),
1448 )
1449 });
1450 let field_consts_tokens = generate_field_constants_tokens(struct_tokens.vis.clone(), fields);
1451 let field_getters_tokens = generate_field_getters_functions_tokens(
1452 struct_tokens.vis.clone(),
1453 bitfield_attribute,
1454 fields,
1455 !ignored_fields.is_empty(),
1456 )?;
1457 let field_setters_tokens = generate_field_setters_functions_tokens(
1458 struct_tokens.vis.clone(),
1459 bitfield_attribute,
1460 fields,
1461 !ignored_fields.is_empty(),
1462 );
1463 let default_function = bitfield_attribute.generate_default_impl.then(|| {
1464 generate_default_implementation_tokens(
1465 struct_name.clone(),
1466 &bitfield_attribute.ty,
1467 fields,
1468 ignored_fields,
1469 )
1470 });
1471 let builder_tokens = bitfield_attribute.generate_builder.then(|| {
1472 generate_builder_tokens(
1473 struct_tokens.vis.clone(),
1474 &bitfield_attribute.ty,
1475 struct_name.clone(),
1476 fields,
1477 ignored_fields,
1478 )
1479 });
1480
1481 let from_bitfield_type_for_bitfield_function_tokens =
1482 bitfield_attribute.generate_from_trait_funcs.then(|| {
1483 generate_from_bitfield_type_for_bitfield_implementation_tokens(
1484 struct_name.clone(),
1485 fields,
1486 ignored_fields,
1487 &bitfield_attribute.ty,
1488 )
1489 });
1490 let from_bitfield_for_bitfield_type_function_tokens =
1491 bitfield_attribute.generate_from_trait_funcs.then(|| {
1492 generate_from_bitfield_for_bitfield_type_implementation_tokens(
1493 struct_name.clone(),
1494 bitfield_attribute,
1495 !ignored_fields.is_empty(),
1496 )
1497 });
1498 let debug_impl = bitfield_attribute.generate_debug_impl.then(|| {
1499 generate_debug_implementation(
1500 struct_name.clone(),
1501 bitfield_attribute,
1502 fields,
1503 !ignored_fields.is_empty(),
1504 )
1505 });
1506 let get_bit_operations = bitfield_attribute.generate_bit_ops.then(|| {
1507 generate_get_bit_tokens(
1508 struct_tokens.vis.clone(),
1509 &bitfield_attribute.ty,
1510 fields,
1511 !ignored_fields.is_empty(),
1512 )
1513 });
1514 let set_bit_operations = bitfield_attribute.generate_bit_ops.then(|| {
1515 generate_set_bit_tokens(
1516 struct_tokens.vis.clone(),
1517 &bitfield_attribute.ty,
1518 fields,
1519 !ignored_fields.is_empty(),
1520 )
1521 });
1522 let to_builder_tokens = (bitfield_attribute.generate_builder
1523 && bitfield_attribute.generate_to_builder)
1524 .then(|| generate_to_builder_tokens(struct_tokens.vis.clone(), struct_name.clone()));
1525 let set_bits_operations = bitfield_attribute.generate_set_bits_impl.then(|| {
1526 generate_set_bits_function_tokens(
1527 struct_tokens.vis.clone(),
1528 fields,
1529 &bitfield_attribute.ty,
1530 !ignored_fields.is_empty(),
1531 )
1532 });
1533 let set_bits_with_defaults_operations = bitfield_attribute.generate_set_bits_impl.then(|| {
1534 generate_set_bits_with_defaults_function_tokens(
1535 struct_tokens.vis.clone(),
1536 fields,
1537 &bitfield_attribute.ty,
1538 !ignored_fields.is_empty(),
1539 )
1540 });
1541 let clear_bits_operations = bitfield_attribute.generate_clear_bits_impl.then(|| {
1542 generate_clear_bits_function_tokens(
1543 struct_tokens.vis.clone(),
1544 fields,
1545 &bitfield_attribute.ty,
1546 !ignored_fields.is_empty(),
1547 )
1548 });
1549 let clear_bits_preserve_defaults_operations =
1550 bitfield_attribute.generate_clear_bits_impl.then(|| {
1551 generate_clear_bits_preserve_defaults_function_tokens(
1552 struct_tokens.vis.clone(),
1553 fields,
1554 &bitfield_attribute.ty,
1555 !ignored_fields.is_empty(),
1556 )
1557 });
1558 let default_attrs = if ignored_fields.is_empty() {
1559 quote! {
1560 #[repr(transparent)]
1561 }
1562 } else {
1563 quote! {
1564 #[repr(C)]
1565 }
1566 };
1567
1568 Ok(quote! {
1569 #struct_attributes
1570 #default_attrs
1571 #bitfield_struct
1572
1573 impl #struct_name {
1574 #new_function
1575 #new_without_defaults_function
1576
1577 #from_bits_function
1578 #from_bits_with_defaults_function
1579
1580 #generate_into_bits_function
1581
1582 #field_consts_tokens
1583 #field_getters_tokens
1584 #field_setters_tokens
1585
1586 #set_bits_operations
1587 #set_bits_with_defaults_operations
1588 #clear_bits_operations
1589 #clear_bits_preserve_defaults_operations
1590
1591 #get_bit_operations
1592 #set_bit_operations
1593
1594 #to_builder_tokens
1595 }
1596
1597 #default_function
1598
1599 #builder_tokens
1600
1601 #from_bitfield_type_for_bitfield_function_tokens
1602 #from_bitfield_for_bitfield_type_function_tokens
1603
1604 #debug_impl
1605 })
1606}
1607
1608/// Creates a syn error with the specified message that occurred at the
1609/// specified span.
1610pub(crate) fn create_syn_error(span: proc_macro2::Span, msg: impl fmt::Display) -> syn::Error {
1611 syn::Error::new(span, msg)
1612}