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