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/// ### Inverting Bits
715///
716/// Bitfields with the `#[bitfield(neg = true)` attribute, generates a `neg_<field>` getter function for each field
717/// that inverts the field's bits.
718///
719/// ```ignore
720/// #[bitfield(u8, neg = true)]
721/// struct Bitfield {
722///   #[bits(5, default = 0xC)]
723///   a: u8,
724///   #[bits(1, default = true)]
725///   b: bool,
726///   #[bits(2)]
727///   _padding: u8,
728/// }
729///
730/// let builder = Bitfield::new();
731///
732/// assert_eq!(builder.a(), 0xC);
733/// assert!(builder.b());
734///
735/// // Inverted bits
736/// assert_eq!(builder.neg_a(), 0x13);
737/// assert!(!builder.neg_b());
738/// ```
739///
740/// ### Ignored Fields
741///
742/// Fields with the `#[bits(ignore = true)` attribute are ignored and not
743/// included in the bitfield. This is useful for when you are building a custom
744/// bitfield, but want to include certain fields that aren't a part of the
745/// bitfield without wrapping having to wrap bitfield is a parent struct. All
746/// ignored fields must implement the `Default` trait. Ignored fields
747/// are accessible directly like normal struct fields.
748///
749/// ```ignore
750/// use bitfields::bitfield;
751///
752/// #[bitfield(u16)]
753/// struct Bitfield {
754///    a: u8,
755///    b: u8,
756///    #[bits(ignore = true)] // Ignored field.
757///    field_id: u8,
758///    #[bits(ignore = true)] // Ignored field.
759///    field_custom: CustomType,
760/// }
761///
762/// #[derive(Debug, Default, PartialEq)]
763/// enum CustomType {
764///    #[default]
765///    A,
766///    B,
767/// }
768///
769/// let bitfield = Bitfield::new();
770///
771/// assert_eq!(bitfield.field_id, 0); // Ignored fields can be accessed
772/// directly. assert_eq!(bitfield.field_custom, CustomType::A); // Ignored
773/// fields can be accessed directly.
774/// ```
775///
776/// ### Field Constants
777///
778/// Fields with read or write access have constants generated for their number
779/// of bits and offset in the bitfield.
780///
781/// ```ignore
782/// use bitfields::bitfield;
783///
784/// #[bitfield(u32)]
785/// struct Bitfield {
786///     #[bits(default = 0x12)]
787///     a: u8,
788///     #[bits(default = 0x34)]
789///     b: u8,
790///     #[bits(default = 0x56)]
791///     c: u8,
792///     #[bits(default = 0x78)]
793///     d: u8,
794/// }
795///
796/// assert_eq!(Bitfield::A_BITS, 8); // Number of bits of the  afield.
797/// assert_eq!(Bitfield::A_OFFSET, 0); // The offset of the a field in the
798/// bitfield. assert_eq!(Bitfield::B_BITS, 8); // Number of bits of the b field.
799/// assert_eq!(Bitfield::B_OFFSET, 8); // The offset of the b field in the
800/// bitfield. assert_eq!(Bitfield::C_BITS, 8); // Number of bits of c the field.
801/// assert_eq!(Bitfield::C_OFFSET, 16); // The offset of the c field in the
802/// bitfield. assert_eq!(Bitfield::D_BITS, 8); // Number of bits of the d field.
803/// assert_eq!(Bitfield::D_OFFSET, 24); // The offset of the d field in the
804/// bitfield.
805/// ```
806///
807/// ### Debug Implementation
808///
809/// A debug implementation is generated for the bitfield, which prints the
810/// fields and their values.
811///
812/// ```ignore
813/// use bitfields::bitfield;
814///
815/// #[bitfield(u32)]
816/// struct Bitfield {
817///     #[bits(default = 0x12)]
818///     a: u8,
819///     #[bits(default = 0x34)]
820///     b: u8,
821///     #[bits(default = 0x56)]
822///     c: u8,
823///     #[bits(default = 0x78)]
824///     d: u8,
825/// }
826///
827/// let bitfield = Bitfield::new();
828///
829/// assert_eq!(format!("{:?}", bitfield), "Bitfield { d: 120, c: 86, b: 52, a: 18 }");
830/// ```
831///
832/// ### Passing Attributes
833///
834/// Attributes below the `#[bitfield]` attribute are passed to the generated
835/// struct.
836/// ```ignore
837/// use bitfields::bitfield;
838///
839/// #[bitfield(u32)]
840/// #[derive(Copy, Clone)]
841/// struct Bitfield {
842///     a: u32,
843/// }
844/// ```
845///
846/// ### Complete Generation Control
847///
848/// You have complete control over what gets generated by the bitfield macro.
849/// When your deploying to a resource-constrained environment, you can generate
850/// only the necessary functions or implementations. You can disable generation
851/// by passing `false` to its attribute arg.
852///
853/// The `#[bitfield]` args that control generation are:
854///
855/// - `#[bitfield(new = true)]` - Generates the `new` and `new_without_defaults`
856///   constructor.
857/// - `#[bitfield(from_bits = true)]` - Generates the `from_bits` and
858///   `from_bits_with_defaults` functions.
859/// - `#[bitfield(into_bits = true)]` - Generates the `into_bits` function.
860/// - `#[bitfield(from = true)]` - Generates the `From` trait implementation.
861/// - `#[bitfield(debug = true)]` - Generates the `Debug` trait implementation.
862/// - `#[bitfield(default = true)]` - Generates the `Default` trait
863///   implementation
864/// - `#[bitfield(builder = true)]` - Generates the builder implementation.
865/// - `#[bitfield(set_bits = true)]` - Generates the `set_bits` function.
866/// - `#[bitfield(clear_bits = true)]` - Generates the `clear_bits` function.
867/// - `#[bitfield(bit_ops = true)]` - Generates the bit operations
868///   implementation.
869/// - `#[bitfield(to_builder = true)]` - Generates the `to_builder` function.
870/// - `#[bitfield(neg = true)]` - Generates `neg_<field>` getter functions for each field.
871#[proc_macro_attribute]
872pub fn bitfield(
873    args: proc_macro::TokenStream,
874    input: proc_macro::TokenStream,
875) -> proc_macro::TokenStream {
876    match parse_bitfield(args.into(), input.into()) {
877        Ok(res) => res.into(),
878        Err(err) => err.into_compile_error().into(),
879    }
880}
881
882/// Parses the bitfield attribute, struct, and fields.
883fn parse_bitfield(args: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
884    // Parse the struct tokens
885    let struct_tokens = syn::parse2::<syn::ItemStruct>(input.clone())?;
886
887    // Parse the arguments of the '#[bitfield(arg, arg)]' attribute
888    let bitfield_attribute: BitfieldAttribute = match syn::parse2(args) {
889        Ok(bitfield_attribute) => bitfield_attribute,
890        Err(err) => {
891            return Err(create_syn_error(input.span(), err.to_string()));
892        }
893    };
894
895    // Check if the bitfield type can contain the fields.
896    let all_fields = parse_fields(&bitfield_attribute, &struct_tokens)?;
897    let fields = all_fields.0;
898    let ignored_fields = all_fields.1;
899    check_bitfield_type_contain_field_bits(&bitfield_attribute, &fields)?;
900    check_bitfield_names_unique(&fields)?;
901
902    // Generate the bitfield functions.
903    generate_functions(&bitfield_attribute, &fields, &ignored_fields, &struct_tokens)
904}
905
906/// Check if the bitfield type can contain the field bits.
907fn check_bitfield_type_contain_field_bits(
908    bitfield_attribute: &BitfieldAttribute,
909    fields: &[BitfieldField],
910) -> syn::Result<()> {
911    let total_field_bits = fields.iter().map(|field| field.bits).sum::<u8>();
912
913    match total_field_bits.cmp(&bitfield_attribute.bits) {
914        Ordering::Greater => Err(create_syn_error(
915            bitfield_attribute.ty.span(),
916            format!(
917                "The total number of bits of the fields ({} bits) is greater than the number of bits of the bitfield type '{}' ({} bits).",
918                total_field_bits,
919                get_type_ident(&bitfield_attribute.ty).unwrap(),
920                bitfield_attribute.bits
921            ),
922        )),
923        Ordering::Less => {
924            let remaining_bits = bitfield_attribute.bits - total_field_bits;
925            Err(create_syn_error(
926                bitfield_attribute.ty.span(),
927                format!(
928                    "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'.",
929                    total_field_bits,
930                    get_type_ident(&bitfield_attribute.ty).unwrap(),
931                    bitfield_attribute.bits,
932                    remaining_bits,
933                ),
934            ))
935        }
936        Ordering::Equal => {
937            // The total number of bits of all fields is equal to the number of bits, we're
938            // good.
939            Ok(())
940        }
941    }
942}
943
944fn check_bitfield_names_unique(fields: &[BitfieldField]) -> syn::Result<()> {
945    let mut field_names = Vec::new();
946    for field in fields {
947        if field_names.contains(&field.name) {
948            return Err(create_syn_error(
949                field.name.span(),
950                format!(
951                    "The field name '{}' is duplicated, each field must have a unique name.",
952                    field.name
953                ),
954            ));
955        }
956        if !field.padding {
957            field_names.push(field.name.clone());
958        }
959    }
960
961    Ok(())
962}
963
964/// Parses all the fields into a list of [`BitfieldField`]s.
965fn parse_fields(
966    bitfield_attribute: &BitfieldAttribute,
967    struct_tokens: &syn::ItemStruct,
968) -> syn::Result<(Vec<BitfieldField>, Vec<BitfieldField>)> {
969    let fields_tokens = match &struct_tokens.fields {
970        Fields::Named(named_files) => named_files,
971        _ => {
972            return Err(create_syn_error(
973                struct_tokens.span(),
974                "Non-named fields are not supported.",
975            ));
976        }
977    };
978
979    let mut fields = Vec::new();
980    let mut ignored_fields = Vec::new();
981    for field_token in fields_tokens.named.clone() {
982        let field = do_parse_field(bitfield_attribute, field_token, &fields)?;
983        if field.ignore {
984            ignored_fields.push(field);
985        } else {
986            fields.push(field);
987        }
988    }
989
990    Ok((fields, ignored_fields))
991}
992
993/// Internal implementation of [`parse_fields`] to parse a single field.
994fn do_parse_field(
995    bitfield_attribute: &BitfieldAttribute,
996    field_tokens: syn::Field,
997    prev_fields: &[BitfieldField],
998) -> syn::Result<BitfieldField> {
999    // Parse field attribute, a field could have multiple attributes, but we only
1000    // care about our 'bits' attribute.
1001    let field_bit_attribute = field_tokens.attrs.iter().find(|attr| {
1002        attr.path().is_ident(BIT_ATTRIBUTE_NAME) && attr.style == syn::AttrStyle::Outer
1003    });
1004
1005    let visibility = match field_tokens.vis {
1006        // Pass the visibility to the field.
1007        Visibility::Public(_) | Visibility::Restricted(_) => Some(field_tokens.vis.clone()),
1008        // Use the visibility of the struct
1009        Visibility::Inherited => None,
1010    };
1011
1012    let field_type = if is_custom_field_type(&field_tokens.ty) {
1013        FieldType::CustomFieldType
1014    } else {
1015        FieldType::IntegerFieldType
1016    };
1017
1018    let padding =
1019        field_tokens.ident.clone().unwrap().to_string().starts_with(PADDING_FIELD_NAME_PREFIX);
1020
1021    let bitfield = if field_bit_attribute.is_none() {
1022        if !is_supported_field_type(&field_tokens.ty) {
1023            return Err(create_syn_error(
1024                field_tokens.span(),
1025                format!(
1026                    "The field type {:?} is not supported.",
1027                    get_type_ident(&field_tokens.ty).unwrap()
1028                ),
1029            ));
1030        }
1031
1032        // We have to determine the number of bits from the field type since there's no
1033        // '#[bits]' attribute.
1034        if is_size_type(&field_tokens.ty) {
1035            return Err(create_syn_error(
1036                field_tokens.span(),
1037                "The types isize and usize require a bit size, otherwise we can't determine the size of the field.",
1038            ));
1039        }
1040
1041        if field_type != FieldType::IntegerFieldType {
1042            return Err(create_syn_error(
1043                field_tokens.span(),
1044                "Custom and nested field types require a defined bit size, otherwise we can't determine the size of the field.",
1045            ));
1046        }
1047
1048        let bits = get_bits_from_type(&field_tokens.ty)?;
1049        let offset = calculate_field_offset(bits, bitfield_attribute, prev_fields)?;
1050        let access = if padding { FieldAccess::None } else { FieldAccess::ReadWrite };
1051
1052        // Create a bitfield field with default values since we don't have one to
1053        // parse.
1054        BitfieldField {
1055            name: field_tokens.ident.unwrap(),
1056            ty: field_tokens.ty.clone(),
1057            vis: visibility,
1058            bits,
1059            offset,
1060            default_value_tokens: None,
1061            unsigned: true,
1062            padding,
1063            access,
1064            field_type: FieldType::IntegerFieldType,
1065            ignore: false,
1066        }
1067    } else {
1068        let bit_attribute_tokens = match &field_bit_attribute.unwrap().meta {
1069            Meta::List(list) => list,
1070            _ => {
1071                return Err(create_syn_error(
1072                    field_tokens.span(),
1073                    "The '#[bits]' attribute must be a list.",
1074                ));
1075            }
1076        };
1077
1078        let bits_attribute: BitsAttribute = syn::parse2(bit_attribute_tokens.tokens.clone())?;
1079
1080        if bits_attribute.ignore {
1081            return Ok(BitfieldField {
1082                ty: field_tokens.ty.clone(),
1083                vis: Some(field_tokens.vis),
1084                bits: 0,
1085                offset: 0,
1086                default_value_tokens: None,
1087                unsigned: false,
1088                padding,
1089                access: FieldAccess::ReadOnly,
1090                name: field_tokens.ident.unwrap(),
1091                ignore: true,
1092                field_type,
1093            });
1094        }
1095
1096        if !is_supported_field_type(&field_tokens.ty) {
1097            return Err(create_syn_error(
1098                field_tokens.span(),
1099                format!(
1100                    "The field type {:?} is not supported.",
1101                    get_type_ident(&field_tokens.ty).unwrap()
1102                ),
1103            ));
1104        }
1105
1106        let bits = match bits_attribute.bits {
1107            Some(bits) => {
1108                // Make sure the type of the field can contain the specified number of bits if
1109                // not a custom type.
1110                if field_type == FieldType::IntegerFieldType
1111                    && bits > get_bits_from_type(&field_tokens.ty)?
1112                {
1113                    return Err(create_syn_error(
1114                        bit_attribute_tokens.span(),
1115                        format!(
1116                            "The field type {:?} ({} bits) is too small to hold the specified '{} bits'.",
1117                            get_type_ident(&field_tokens.ty).unwrap(),
1118                            get_bits_from_type(&field_tokens.ty)?,
1119                            bits
1120                        ),
1121                    ));
1122                }
1123
1124                bits
1125            }
1126            None => {
1127                if field_type != FieldType::IntegerFieldType {
1128                    return Err(create_syn_error(
1129                        field_tokens.span(),
1130                        "Custom and nested field types require a defined bit size, otherwise we can't determine the size of the field.",
1131                    ));
1132                }
1133
1134                get_bits_from_type(&field_tokens.ty)?
1135            }
1136        };
1137
1138        // Make sure the field bits are greater than 0.
1139        if bits == 0 {
1140            return Err(create_syn_error(
1141                bit_attribute_tokens.span(),
1142                "The field bits must be greater than 0.",
1143            ));
1144        }
1145
1146        // Make sure the default value is within the field bits. If a number was unable
1147        // to be parsed, let's take a chance and see if the user is trying to
1148        // use a const variable or a const function.
1149        let parsed_number = if field_type == FieldType::IntegerFieldType
1150            && bits_attribute.clone().default_value_expr.is_some()
1151        {
1152            check_default_value_fit_in_field(
1153                &bits_attribute.clone().default_value_expr.unwrap(),
1154                bits,
1155                field_tokens.ty.clone(),
1156            )?
1157        } else {
1158            None
1159        };
1160
1161        let unsigned =
1162            field_type != FieldType::IntegerFieldType || is_unsigned_integer_type(&field_tokens.ty);
1163        let access = if padding {
1164            if bits_attribute.access.is_some() {
1165                return Err(create_syn_error(
1166                    bit_attribute_tokens.span(),
1167                    "Padding fields can't have a specified access.",
1168                ));
1169            }
1170
1171            FieldAccess::None
1172        } else {
1173            bits_attribute.access.unwrap_or(FieldAccess::ReadWrite)
1174        };
1175        let offset = calculate_field_offset(bits, bitfield_attribute, prev_fields)?;
1176
1177        let default_value_tokens = match bits_attribute.default_value_expr {
1178            None => None,
1179            Some(ref expr) => {
1180                // We want to add integer literals to default values expressions if the
1181                // expression is a negative number without a suffix. We do alot of casting
1182                // so what happens is, if there is the default value expr `-125`, when we
1183                // try to cast later like `-125 as u8`, Rust will complain that the number
1184                // is too large for the type. Adding the integer suffix will fix this since
1185                // Rust will know the type of the number and will cast it.
1186                if unsigned
1187                    || field_type != FieldType::IntegerFieldType
1188                    || parsed_number.is_none()
1189                    || parsed_number.unwrap().has_integer_suffix
1190                {
1191                    Some(quote! {
1192                        #expr
1193                    })
1194                } else {
1195                    let tokens =
1196                        add_integer_literals_to_expr(&expr.clone(), field_tokens.ty.clone())?;
1197
1198                    Some(quote! {
1199                        #tokens
1200                    })
1201                }
1202            }
1203        };
1204
1205        BitfieldField {
1206            name: field_tokens.ident.unwrap(),
1207            ty: field_tokens.ty.clone(),
1208            vis: visibility,
1209            bits,
1210            offset,
1211            default_value_tokens,
1212            unsigned,
1213            padding,
1214            access,
1215            field_type,
1216            ignore: false,
1217        }
1218    };
1219
1220    Ok(bitfield)
1221}
1222
1223/// Checks if the default value can fit in the field bits.
1224fn check_default_value_fit_in_field(
1225    default_value_expr: &Expr,
1226    bits: u8,
1227    field_type: Type,
1228) -> syn::Result<Option<ParsedNumber>> {
1229    let default_value_str = &quote!(#default_value_expr).to_string();
1230
1231    let parsed_number = match parse_number_string(default_value_str) {
1232        Ok(number) => number,
1233        Err(err) => {
1234            return match err {
1235                NumberParseError::FloatNotSupported => Err(create_syn_error(
1236                    default_value_expr.span(),
1237                    "Floats are not supported as default values.".to_string(),
1238                )),
1239                // Maybe the user is trying to use a const variable or a const
1240                // function call as a default.
1241                NumberParseError::InvalidNumberString => Ok(None),
1242            };
1243        }
1244    };
1245
1246    let bits_max_value = 1 << bits as u128;
1247    if parsed_number.number >= bits_max_value {
1248        if parsed_number.negative {
1249            return Err(create_syn_error(
1250                default_value_expr.span(),
1251                format!(
1252                    "The default value -'{}' is too large to fit into the specified '{} bits'.",
1253                    parsed_number.number, bits,
1254                ),
1255            ));
1256        }
1257        return Err(create_syn_error(
1258            default_value_expr.span(),
1259            format!(
1260                "The default value '{}' is too large to fit into the specified '{} bits'.",
1261                parsed_number.number, bits,
1262            ),
1263        ));
1264    }
1265
1266    let default_value_too_big_for_type = match get_integer_type_from_type(&field_type) {
1267        IntegerType::Bool => parsed_number.number > 1,
1268        IntegerType::U8 => parsed_number.number > u8::MAX as u128,
1269        IntegerType::U16 => parsed_number.number > u16::MAX as u128,
1270        IntegerType::U32 => parsed_number.number > u32::MAX as u128,
1271        IntegerType::U64 => parsed_number.number > u64::MAX as u128,
1272        IntegerType::U128 => {
1273            // Unable to happen, this is Rust's max unsigned type value.
1274            false
1275        }
1276        IntegerType::Usize => parsed_number.number > usize::MAX as u128,
1277        IntegerType::Isize => {
1278            if parsed_number.negative {
1279                parsed_number.number > isize::MIN.unsigned_abs() as u128
1280            } else {
1281                parsed_number.number > isize::MAX as u128
1282            }
1283        }
1284        IntegerType::I8 => {
1285            if parsed_number.negative {
1286                parsed_number.number > i8::MIN.unsigned_abs() as u128
1287            } else {
1288                parsed_number.number > i8::MAX as u128
1289            }
1290        }
1291        IntegerType::I16 => {
1292            if parsed_number.negative {
1293                parsed_number.number > i16::MIN.unsigned_abs() as u128
1294            } else {
1295                parsed_number.number > i16::MAX as u128
1296            }
1297        }
1298        IntegerType::I32 => {
1299            if parsed_number.negative {
1300                parsed_number.number > i32::MIN.unsigned_abs() as u128
1301            } else {
1302                parsed_number.number > i32::MAX as u128
1303            }
1304        }
1305        IntegerType::I64 => {
1306            if parsed_number.negative {
1307                parsed_number.number > i64::MIN.unsigned_abs() as u128
1308            } else {
1309                parsed_number.number > i64::MAX as u128
1310            }
1311        }
1312        IntegerType::I128 => {
1313            if parsed_number.negative {
1314                parsed_number.number > i128::MIN.unsigned_abs()
1315            } else {
1316                parsed_number.number > i128::MAX as u128
1317            }
1318        }
1319        _ => Err(create_syn_error(default_value_expr.span(), PANIC_ERROR_MESSAGE))?,
1320    };
1321
1322    if default_value_too_big_for_type {
1323        let negative_str = if parsed_number.negative { "-" } else { "" };
1324        return Err(create_syn_error(
1325            default_value_expr.span(),
1326            format!(
1327                "The default value '{}{}' is too large to fit into the field type '{}'.",
1328                negative_str,
1329                parsed_number.number,
1330                get_type_ident(&field_type).unwrap()
1331            ),
1332        ));
1333    }
1334
1335    Ok(Some(parsed_number))
1336}
1337
1338/// Calculate the offset of a field based on previous fields.
1339fn calculate_field_offset(
1340    bits: u8,
1341    bitfield_attribute: &BitfieldAttribute,
1342    prev_fields: &[BitfieldField],
1343) -> syn::Result<u8> {
1344    let offset = prev_fields.iter().map(|field| field.bits).sum::<u8>();
1345
1346    match bitfield_attribute.bit_order {
1347        BitOrder::Lsb => Ok(offset),
1348        BitOrder::Msb => {
1349            let bitfield_type_bits = get_bits_from_type(&bitfield_attribute.ty)?;
1350            // We calculate offset starting from the left. There's a chance that
1351            // the total bits of all fields is greater than the number of bits
1352            // of the bitfield type. We will catch it later so
1353            // we can ignore for now.
1354            if offset + bits < bitfield_type_bits {
1355                Ok(bitfield_type_bits - bits - offset)
1356            } else {
1357                // We've underflow the bitfield type, this will be caught later.
1358                Ok(0)
1359            }
1360        }
1361    }
1362}
1363
1364/// Adds the field type integer literal suffix to the expression.
1365///
1366/// For example, if the expression is '-1' and the field type is 'i8', the
1367/// expression will be updated to '1i8'.
1368fn add_integer_literals_to_expr(expr: &Expr, field_type: Type) -> syn::Result<TokenStream> {
1369    let updated_expr = if let Expr::Unary(unary) = expr {
1370        let attrs = unary.attrs.clone();
1371        let op = unary.op;
1372
1373        let updated_expr = if let Expr::Lit(expr_lit) = *unary.expr.clone() {
1374            let new_lit = create_expr_lit_with_integer_suffix(&expr_lit, field_type)?;
1375
1376            Expr::Lit(ExprLit { attrs: expr_lit.attrs, lit: new_lit.lit })
1377        } else {
1378            Err(create_syn_error(expr.span(), PANIC_ERROR_MESSAGE))?
1379        };
1380
1381        Expr::Unary(ExprUnary { attrs, op, expr: Box::new(updated_expr) })
1382    } else if let Expr::Lit(expr_lit) = expr {
1383        let new_lit = create_expr_lit_with_integer_suffix(expr_lit, field_type)?;
1384
1385        Expr::Lit(ExprLit { attrs: expr_lit.clone().attrs, lit: new_lit.lit })
1386    } else {
1387        Err(create_syn_error(expr.span(), PANIC_ERROR_MESSAGE))?
1388    };
1389
1390    Ok(quote! {
1391        #updated_expr
1392    })
1393}
1394
1395/// Helper for creating an integer literal with the integer suffix.
1396fn create_expr_lit_with_integer_suffix(lit: &ExprLit, field_type: Type) -> syn::Result<ExprLit> {
1397    let integer_type = get_integer_type_from_type(&field_type);
1398    let integer_suffix = get_integer_suffix_from_integer_type(integer_type)?;
1399
1400    let new_lit = match lit.lit.clone() {
1401        Lit::Int(lit_int) => {
1402            let new_lit_int =
1403                LitInt::new(&format!("{}{}", lit_int.token(), integer_suffix), lit_int.span());
1404            ExprLit { attrs: lit.attrs.clone(), lit: Lit::Int(new_lit_int) }
1405        }
1406        _ => Err(create_syn_error(lit.span(), PANIC_ERROR_MESSAGE))?,
1407    };
1408
1409    Ok(new_lit)
1410}
1411
1412/// Generate the bitfield functions.
1413fn generate_functions(
1414    bitfield_attribute: &BitfieldAttribute,
1415    fields: &[BitfieldField],
1416    ignored_fields: &[BitfieldField],
1417    struct_tokens: &syn::ItemStruct,
1418) -> syn::Result<TokenStream> {
1419    let struct_attributes: TokenStream =
1420        struct_tokens.attrs.iter().map(ToTokens::to_token_stream).collect();
1421    let struct_name = &struct_tokens.ident;
1422
1423    let bitfield_struct = if !ignored_fields.is_empty() {
1424        generate_struct_with_fields_tokens(
1425            struct_name.clone(),
1426            struct_tokens.vis.clone(),
1427            bitfield_attribute.ty.clone(),
1428            ignored_fields,
1429        )
1430    } else {
1431        generate_tuple_struct_tokens(
1432            struct_name.clone(),
1433            struct_tokens.vis.clone(),
1434            bitfield_attribute.ty.clone(),
1435        )
1436    };
1437    let new_function = bitfield_attribute.generate_new_func.then(|| {
1438        generate_new_function_tokens(
1439            struct_tokens.vis.clone(),
1440            fields,
1441            ignored_fields,
1442            &bitfield_attribute.ty,
1443        )
1444    });
1445    let new_without_defaults_function = bitfield_attribute.generate_new_func.then(|| {
1446        generate_new_without_defaults_function_tokens(
1447            struct_tokens.vis.clone(),
1448            fields,
1449            ignored_fields,
1450            &bitfield_attribute.ty,
1451        )
1452    });
1453    let from_bits_function = bitfield_attribute.generate_from_bits_func.then(|| {
1454        generate_from_bits_function_tokens(
1455            struct_tokens.vis.clone(),
1456            fields,
1457            ignored_fields,
1458            &bitfield_attribute.ty,
1459            bitfield_attribute,
1460        )
1461    });
1462    let from_bits_with_defaults_function = bitfield_attribute.generate_from_bits_func.then(|| {
1463        generate_from_bits_with_defaults_function_tokens(
1464            struct_tokens.vis.clone(),
1465            fields,
1466            &bitfield_attribute.ty,
1467            bitfield_attribute,
1468            !ignored_fields.is_empty(),
1469        )
1470    });
1471    let generate_into_bits_function = bitfield_attribute.generate_into_bits_func.then(|| {
1472        generate_into_bits_function_tokens(
1473            struct_tokens.vis.clone(),
1474            bitfield_attribute,
1475            !ignored_fields.is_empty(),
1476        )
1477    });
1478    let field_consts_tokens = generate_field_constants_tokens(struct_tokens.vis.clone(), fields);
1479    let field_getters_tokens = generate_field_getters_functions_tokens(
1480        struct_tokens.vis.clone(),
1481        bitfield_attribute,
1482        fields,
1483        !ignored_fields.is_empty(),
1484        bitfield_attribute.generate_neg_func,
1485    )?;
1486    let field_setters_tokens = generate_field_setters_functions_tokens(
1487        struct_tokens.vis.clone(),
1488        bitfield_attribute,
1489        fields,
1490        !ignored_fields.is_empty(),
1491    );
1492    let default_function = bitfield_attribute.generate_default_impl.then(|| {
1493        generate_default_implementation_tokens(
1494            struct_name.clone(),
1495            &bitfield_attribute.ty,
1496            fields,
1497            ignored_fields,
1498        )
1499    });
1500    let builder_tokens = bitfield_attribute.generate_builder.then(|| {
1501        generate_builder_tokens(
1502            struct_tokens.vis.clone(),
1503            &bitfield_attribute.ty,
1504            struct_name.clone(),
1505            fields,
1506            ignored_fields,
1507        )
1508    });
1509
1510    let from_bitfield_type_for_bitfield_function_tokens =
1511        bitfield_attribute.generate_from_trait_funcs.then(|| {
1512            generate_from_bitfield_type_for_bitfield_implementation_tokens(
1513                struct_name.clone(),
1514                fields,
1515                ignored_fields,
1516                &bitfield_attribute.ty,
1517            )
1518        });
1519    let from_bitfield_for_bitfield_type_function_tokens =
1520        bitfield_attribute.generate_from_trait_funcs.then(|| {
1521            generate_from_bitfield_for_bitfield_type_implementation_tokens(
1522                struct_name.clone(),
1523                bitfield_attribute,
1524                !ignored_fields.is_empty(),
1525            )
1526        });
1527    let debug_impl = bitfield_attribute.generate_debug_impl.then(|| {
1528        generate_debug_implementation(
1529            struct_name.clone(),
1530            bitfield_attribute,
1531            fields,
1532            !ignored_fields.is_empty(),
1533        )
1534    });
1535    let get_bit_operations = bitfield_attribute.generate_bit_ops.then(|| {
1536        generate_get_bit_tokens(
1537            struct_tokens.vis.clone(),
1538            &bitfield_attribute.ty,
1539            fields,
1540            !ignored_fields.is_empty(),
1541        )
1542    });
1543    let set_bit_operations = bitfield_attribute.generate_bit_ops.then(|| {
1544        generate_set_bit_tokens(
1545            struct_tokens.vis.clone(),
1546            &bitfield_attribute.ty,
1547            fields,
1548            !ignored_fields.is_empty(),
1549        )
1550    });
1551    let to_builder_tokens = (bitfield_attribute.generate_builder
1552        && bitfield_attribute.generate_to_builder)
1553        .then(|| generate_to_builder_tokens(struct_tokens.vis.clone(), struct_name.clone()));
1554    let set_bits_operations = bitfield_attribute.generate_set_bits_impl.then(|| {
1555        generate_set_bits_function_tokens(
1556            struct_tokens.vis.clone(),
1557            fields,
1558            &bitfield_attribute.ty,
1559            !ignored_fields.is_empty(),
1560        )
1561    });
1562    let set_bits_with_defaults_operations = bitfield_attribute.generate_set_bits_impl.then(|| {
1563        generate_set_bits_with_defaults_function_tokens(
1564            struct_tokens.vis.clone(),
1565            fields,
1566            &bitfield_attribute.ty,
1567            !ignored_fields.is_empty(),
1568        )
1569    });
1570    let clear_bits_operations = bitfield_attribute.generate_clear_bits_impl.then(|| {
1571        generate_clear_bits_function_tokens(
1572            struct_tokens.vis.clone(),
1573            fields,
1574            &bitfield_attribute.ty,
1575            !ignored_fields.is_empty(),
1576        )
1577    });
1578    let clear_bits_preserve_defaults_operations =
1579        bitfield_attribute.generate_clear_bits_impl.then(|| {
1580            generate_clear_bits_preserve_defaults_function_tokens(
1581                struct_tokens.vis.clone(),
1582                fields,
1583                &bitfield_attribute.ty,
1584                !ignored_fields.is_empty(),
1585            )
1586        });
1587    let default_attrs = if ignored_fields.is_empty() {
1588        quote! {
1589            #[repr(transparent)]
1590        }
1591    } else {
1592        quote! {
1593            #[repr(C)]
1594        }
1595    };
1596
1597    Ok(quote! {
1598        #struct_attributes
1599        #default_attrs
1600        #bitfield_struct
1601
1602        impl #struct_name {
1603            #new_function
1604            #new_without_defaults_function
1605
1606            #from_bits_function
1607            #from_bits_with_defaults_function
1608
1609            #generate_into_bits_function
1610
1611            #field_consts_tokens
1612            #field_getters_tokens
1613            #field_setters_tokens
1614
1615            #set_bits_operations
1616            #set_bits_with_defaults_operations
1617            #clear_bits_operations
1618            #clear_bits_preserve_defaults_operations
1619
1620            #get_bit_operations
1621            #set_bit_operations
1622
1623            #to_builder_tokens
1624        }
1625
1626        #default_function
1627
1628        #builder_tokens
1629
1630        #from_bitfield_type_for_bitfield_function_tokens
1631        #from_bitfield_for_bitfield_type_function_tokens
1632
1633        #debug_impl
1634    })
1635}
1636
1637/// Creates a syn error with the specified message that occurred at the
1638/// specified span.
1639pub(crate) fn create_syn_error(span: proc_macro2::Span, msg: impl fmt::Display) -> syn::Error {
1640    syn::Error::new(span, msg)
1641}