bitfields-impl 2.0.0

Macro for generating flexible bitfields. Useful for low-level code (embedded or emulators).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::cmp::Ordering;
use std::collections::HashSet;

use proc_macro2::TokenStream;
use syn::spanned::Spanned;
use syn::{Fields, ItemStruct, Meta};

use crate::parsing::bitfields::bitfield::{Bitfield, Field};
use crate::parsing::bitfields::bitfield_attribute::bitfield_arguments::BitOrder;
use crate::parsing::bitfields::bitfield_attribute::bitfield_attribute_parser::BitfieldAttribute;
use crate::parsing::bitfields::bits_attribute::bits_arguments::FieldAccess;
use crate::parsing::bitfields::bits_attribute::bits_attribute_parser::BitsAttribute;
use crate::parsing::common::compiler_error::create_user_parsing_compiler_error;
use crate::parsing::common::const_expr::ConstExpr;
use crate::parsing::common::spanned_data_type::{DataType, SpannedDataTypeToken};
use crate::parsing::common::type_parse_error::TypeParsingError;
use crate::parsing::common::visibility::Visibility;

/// Parses a bitfield struct annotated with `#[bitfield(..)]`.
pub fn parse_bitfield_struct(args: TokenStream, input: TokenStream) -> syn::Result<Bitfield> {
    let struct_tokens = parse_struct_tokens(&input)?;
    let user_attributes_tokens =
        struct_tokens.attrs.iter().map(quote::ToTokens::into_token_stream).collect();
    let visibility = Visibility::new(&struct_tokens.vis);
    let bitfield_attribute = parse_bitfield_attribute(args)?;
    let parsed_fields = parse_fields(&bitfield_attribute, &visibility, &struct_tokens)?;
    let name = struct_tokens.ident.to_string();

    check_fields_fit_in_bitfield_type(&bitfield_attribute, &parsed_fields.non_ignored)?;

    Ok(Bitfield::new(
        user_attributes_tokens,
        visibility,
        name,
        bitfield_attribute.spanned_data_type_token(),
        parsed_fields.non_ignored,
        parsed_fields.ignored,
        bitfield_attribute.arguments(),
    ))
}

fn parse_struct_tokens(input: &TokenStream) -> syn::Result<ItemStruct> {
    syn::parse2::<ItemStruct>(input.clone())
}

fn parse_bitfield_attribute(args: TokenStream) -> syn::Result<BitfieldAttribute> {
    syn::parse2(args)
}

/// Represents parsed fields.
struct ParsedFields {
    non_ignored: Vec<Field>,
    ignored: Vec<Field>,
}

fn parse_fields(
    bitfield_attribute: &BitfieldAttribute,
    bitfield_visibility: &Visibility,
    struct_tokens: &ItemStruct,
) -> syn::Result<ParsedFields> {
    let Fields::Named(field_tokens) = &struct_tokens.fields else {
        return Err(create_user_parsing_compiler_error(
            struct_tokens.span(),
            "Non-named fields are not supported.",
        ));
    };

    let mut non_ignored_parsed_fields: Vec<Field> = Vec::new();
    let mut ignored_fields: Vec<Field> = Vec::new();
    let mut seen_field_names: HashSet<String> = HashSet::new();

    for field in &field_tokens.named {
        let field_name = field.ident.as_ref().expect("Expected field to have a name").to_string();
        if seen_field_names.contains(&field_name) {
            return Err(create_user_parsing_compiler_error(
                field.span(),
                format!(
                    "Duplicate field name '{}' found, all fields must have unique names.",
                    field.ident.as_ref().expect("Expected field to have a name")
                ),
            ));
        }

        let parsed_field = parse_field_helper(
            bitfield_attribute,
            bitfield_visibility,
            field,
            &non_ignored_parsed_fields,
        )?;

        if !parsed_field.reserved() {
            seen_field_names.insert(field_name);
        }
        if parsed_field.ignored() {
            ignored_fields.push(parsed_field);
        } else {
            non_ignored_parsed_fields.push(parsed_field);
        }
    }

    Ok(ParsedFields {
        non_ignored: non_ignored_parsed_fields,
        ignored: ignored_fields,
    })
}

fn parse_field_helper(
    bitfield_attribute: &BitfieldAttribute,
    bitfield_visibility: &Visibility,
    field_tokens: &syn::Field,
    prev_fields: &[Field],
) -> syn::Result<Field> {
    let bits_attribute = get_bits_attribute(field_tokens)?;
    if is_ignored_field(bits_attribute.as_ref()) {
        return Ok(parse_ignored_field(field_tokens));
    }

    let visibility = get_field_visibility(bitfield_visibility, field_tokens);
    let reserved = is_reserved_field(field_tokens);
    let spanned_data_type_token = get_field_data_type_spanned_token(field_tokens)?;
    let bits = get_field_bits(bits_attribute.as_ref(), &spanned_data_type_token)?;

    check_bits(bits_attribute.as_ref(), bits)?;

    if matches!(spanned_data_type_token.data_type(), DataType::Integer(..)) {
        check_default_value_fit_in_field(bits_attribute.as_ref(), bits, &spanned_data_type_token)?;
        check_field_data_type_can_hold_bits(
            bits_attribute.as_ref(),
            bits,
            &spanned_data_type_token,
        )?;
    }

    let offset = calculate_field_offset(bitfield_attribute, field_tokens, bits, prev_fields)?;
    let access = get_field_access(bits_attribute.as_ref(), reserved)?;
    let name = field_tokens.ident.as_ref().expect("Expected field identifier").to_string();
    let arguments = bits_attribute.map(|attr| attr.arguments());
    Ok(Field::new(
        visibility,
        name,
        spanned_data_type_token,
        bits,
        offset,
        reserved,
        access,
        arguments,
        /* ignored= */ false,
    ))
}

fn parse_ignored_field(field_tokens: &syn::Field) -> Field {
    let spanned_data_type_token = SpannedDataTypeToken::new(&field_tokens.ty)
        .expect("Expected field type kind for ignored field");
    Field::new(
        Visibility::new(&field_tokens.vis),
        field_tokens.ident.as_ref().expect("Expected field identifier").to_string(),
        spanned_data_type_token,
        0,
        0,
        false,
        FieldAccess::NoAccess,
        /* arguments= */ None,
        /* ignored= */ true,
    )
}

/// Returns the bits attribute if the field is attributed.
fn get_bits_attribute(field_tokens: &syn::Field) -> syn::Result<Option<BitsAttribute>> {
    let bits_attribute = field_tokens
        .attrs
        .iter()
        .find(|attr| attr.path().is_ident("bits") && attr.style == syn::AttrStyle::Outer);

    let Some(attr) = bits_attribute else { return Ok(None) };

    let Meta::List(bits_attribute_tokens) = &attr.meta else {
        return Err(create_user_parsing_compiler_error(
            field_tokens.span(),
            "The '#[bits]' attribute must be a list.",
        ));
    };

    Ok(Some(syn::parse2::<BitsAttribute>(bits_attribute_tokens.tokens.clone())?))
}

/// Returns true when the parsed `#[bits]` attribute marks the field as ignored.
fn is_ignored_field(bits_attribute: Option<&BitsAttribute>) -> bool {
    bits_attribute.is_some_and(|attr| attr.arguments().ignored())
}

fn is_reserved_field(field_tokens: &syn::Field) -> bool {
    field_tokens.ident.as_ref().is_some_and(|ident| ident.to_string().starts_with('_'))
}

fn get_field_data_type_spanned_token(
    field_tokens: &syn::Field,
) -> syn::Result<SpannedDataTypeToken> {
    let spanned_data_type_token = match SpannedDataTypeToken::new(&field_tokens.ty) {
        Ok(tk) => tk,
        Err(err) => {
            return match err {
                TypeParsingError::SizeTypeNotSupported => Err(create_user_parsing_compiler_error(
                    field_tokens.ty.span(),
                    "The `isize` and `usize` types are not supported, we cannot guarantee their \
                     size at runtime. Switch to a sized integer type like `u8`, `i16`, etc.,"
                        .to_string(),
                )),
                TypeParsingError::UnexpectedFloat => Err(create_user_parsing_compiler_error(
                    field_tokens.ty.span(),
                    "Floats are not supported as a field type.".to_string(),
                )),
                TypeParsingError::ZeroArrayLength => Err(create_user_parsing_compiler_error(
                    field_tokens.ty.span(),
                    "Array fields must have a length greater than 0.".to_string(),
                )),
                TypeParsingError::NonIntegerArrayType => Err(create_user_parsing_compiler_error(
                    field_tokens.ty.span(),
                    "Array fields can only have `u8` as their element type.".to_string(),
                )),
                _ => Err(create_user_parsing_compiler_error(
                    field_tokens.ty.span(),
                    "A field can only have `#[bits]` attributed custom or integers type."
                        .to_string(),
                )),
            };
        },
    };

    Ok(spanned_data_type_token)
}

/// Returns the field bits, inferring from the data type if not explicitly set.
fn get_field_bits(
    bits_attribute: Option<&BitsAttribute>,
    spanned_data_type_token: &SpannedDataTypeToken,
) -> syn::Result<u32> {
    if let Some(bits_attr) = bits_attribute {
        if let Some(bits) = bits_attr.bits() {
            return Ok(bits);
        }
    }

    if matches!(spanned_data_type_token.data_type(), DataType::Custom) {
        return Err(create_user_parsing_compiler_error(
            spanned_data_type_token.span(),
            "Custom and nested field types require a defined bit size, otherwise we can't \
             determine the size of the field."
                .to_string(),
        ));
    }

    // Get field bits from data type if bits attribute doesn't provide any.
    Ok(spanned_data_type_token.data_type().bit_size())
}

/// Validates the bits argument of a field.
fn check_bits(bits_attribute: Option<&BitsAttribute>, bits: u32) -> syn::Result<()> {
    // The user passed 0 for bits
    if bits == 0 {
        return Err(create_user_parsing_compiler_error(
            bits_attribute
                .expect("Expected bits attribute for bit checking")
                .span()
                .expect("Expected span for bit checking"),
            "The field bits must be greater than 0.".to_string(),
        ));
    }

    Ok(())
}

/// Validate that a provided default value (if any) fits within the field's
/// bit width and type constraints. Returns an error when the default is
/// incompatible.
fn check_default_value_fit_in_field(
    bits_attribute: Option<&BitsAttribute>,
    bits: u32,
    spanned_data_type_token: &SpannedDataTypeToken,
) -> syn::Result<()> {
    let Some(bits_attr) = bits_attribute else {
        return Ok(());
    };
    let Some(default_value_expr) = bits_attr.arguments().default_value_expr() else {
        return Ok(());
    };

    // Check if the user is trying to use a const variable or const
    // function or something as a default, leave this to the compiler
    // there's nothing we can do.
    if !matches!(default_value_expr, ConstExpr::Literal { .. }) {
        return Ok(());
    }

    let ConstExpr::Literal {
        number,
        negative_sign,
        spanned_token,
        ..
    } = &default_value_expr
    else {
        unreachable!("Expected a const expr literal");
    };

    if spanned_data_type_token.data_type().unsigned() && *negative_sign {
        return Err(create_user_parsing_compiler_error(
            spanned_token.span(),
            "Unsigned fields cannot have negative default values.".to_string(),
        ));
    }

    // If checked_shl returns None, bits == 128 and no field type can exceed the
    // bit range.
    let (negative_bits_min_value, positive_bits_max_value) = min_max_for_bits(bits);

    if *negative_sign {
        let negative_default_value = (*number as i128)
            .checked_neg()
            .ok_or_else(|| unreachable!("The compiler won't allow a number less than -i128 exist"))
            .expect("Expected a negative default value for negative default value checking");

        if negative_default_value < negative_bits_min_value {
            return Err(create_user_parsing_compiler_error(
                default_value_expr.span(),
                format!(
                    "The negative default value '-{number}' is below the minimum value for the \
                     specified '{bits} bits ({negative_bits_min_value})'.",
                ),
            ));
        }
    } else if *number > positive_bits_max_value {
        return Err(create_user_parsing_compiler_error(
            default_value_expr.span(),
            format!(
                "The default value '{number}' exceeds the maximum value for the specified '{bits} \
                 bits ({positive_bits_max_value})'.",
            ),
        ));
    }

    Ok(())
}

/// Checks if the field can contain the defined bits.
fn check_field_data_type_can_hold_bits(
    bits_attribute: Option<&BitsAttribute>,
    bits: u32,
    spanned_data_type_token: &SpannedDataTypeToken,
) -> syn::Result<()> {
    let Some(bits_attr) = bits_attribute else {
        return Ok(());
    };

    let field_max_bits = spanned_data_type_token.data_type().bit_size();
    let spanned_data_type_tokens = spanned_data_type_token.get_data_type_tokens();
    if bits > field_max_bits {
        return Err(create_user_parsing_compiler_error(
            bits_attr.span().expect("Expected bits attribute for bits checking"),
            format!(
                "The field type '{spanned_data_type_tokens}' is too small to hold the specified \
                 '{bits} bits'."
            ),
        ));
    }

    Ok(())
}

/// Compute the minimum and maximum representable signed/unsigned values for
/// a given number of bits.
const fn min_max_for_bits(bits: u32) -> (i128, u128) {
    let max: u128 = if bits == 128 { u128::MAX } else { (1u128 << bits) - 1 };
    let min: i128 = if bits == 128 { i128::MIN } else { -(1i128 << (bits - 1)) };
    (min, max)
}

fn calculate_field_offset(
    bitfield_attribute: &BitfieldAttribute,
    field_tokens: &syn::Field,
    bits: u32,
    prev_fields: &[Field],
) -> syn::Result<u32> {
    let offset = prev_fields.iter().map(Field::bits).sum::<u32>();

    match bitfield_attribute.arguments().order() {
        BitOrder::Lsb => Ok(offset),
        BitOrder::Msb => {
            let bitfield_bit_size =
                bitfield_attribute.spanned_data_type_token().data_type().bit_size();
            // We calculate offset starting from the left. There's a chance that
            // the total bits of all fields is greater than the number of bits
            // of the bitfield type. We will catch it later so
            // we can ignore for now.
            let total_bits = offset + bits;
            if total_bits <= bitfield_bit_size {
                Ok(bitfield_bit_size - bits - offset)
            } else {
                // We've overflown the bitfield type.
                Err(create_user_parsing_compiler_error(
                    field_tokens.span(),
                    format!(
                        "The total bits of the fields ({total_bits} bits) exceeds the bit size of \
                         the bitfield type ({bitfield_bit_size} bits)."
                    ),
                ))
            }
        },
    }
}

/// Determine the effective access level for a field based on its
/// `#[bits]` arguments and whether it is reserved.
fn get_field_access(
    bits_attribute: Option<&BitsAttribute>,
    reserved: bool,
) -> syn::Result<FieldAccess> {
    if bits_attribute.is_none() && reserved {
        return Ok(FieldAccess::NoAccess);
    }

    if let Some(bits_attribute) = bits_attribute {
        if bits_attribute.arguments().user_set_access() && reserved {
            return Err(create_user_parsing_compiler_error(
                bits_attribute.arguments().access_span().expect("Expected span for access"),
                "Reserved fields cannot have a defined access.".to_string(),
            ));
        }

        if bits_attribute.arguments().default_value_expr().is_some() && reserved {
            return Ok(FieldAccess::ReadOnly);
        }
    }

    if bits_attribute.is_none() {
        return Ok(FieldAccess::ReadWrite);
    }

    Ok(bits_attribute
        .expect("Expected bits attribute for getting field access")
        .arguments()
        .access())
}

/// Get the visibility that should be applied to a field: if the field is
/// private, inherit the bitfield's visibility; otherwise use the field's.
fn get_field_visibility(bitfield_visibility: &Visibility, field_tokens: &syn::Field) -> Visibility {
    let visibility = Visibility::new(&field_tokens.vis);

    if visibility == Visibility::Private {
        return bitfield_visibility.clone();
    }

    visibility
}

/// Ensure the total bits occupied by fields exactly match the bitfield type
/// size. Returns an error if too many or few bits are used.
fn check_fields_fit_in_bitfield_type(
    bitfield_attribute: &BitfieldAttribute,
    fields: &[Field],
) -> syn::Result<()> {
    let total_field_bits = fields.iter().map(Field::bits).sum::<u32>();
    let bitfield_bit_size = bitfield_attribute.spanned_data_type_token().data_type().bit_size();

    match total_field_bits.cmp(&bitfield_bit_size) {
        Ordering::Greater => Err(create_user_parsing_compiler_error(
            bitfield_attribute.spanned_data_type_token().span(),
            format!(
                "The total number of bits of the fields '{} bits' is greater than the number of \
                 bits of the bitfield '{} ({} bits)'.",
                total_field_bits,
                bitfield_attribute.spanned_data_type_token(),
                bitfield_bit_size
            ),
        )),
        Ordering::Less => {
            let remaining_bits = bitfield_bit_size - total_field_bits;

            Err(create_user_parsing_compiler_error(
                bitfield_attribute.spanned_data_type_token().span(),
                format!(
                    "The total number of bits of the fields '{} bits' is less than the number of \
                     bits of the bitfield '{} ({} bits)', you can add a reserved field (prefixed \
                     with '_') to fill the remaining '{} bits'.",
                    total_field_bits,
                    bitfield_attribute.spanned_data_type_token(),
                    bitfield_bit_size,
                    remaining_bits,
                ),
            ))
        },
        Ordering::Equal => {
            // The total number of bits of all fields is equal to the number of
            // bits, we're good.
            Ok(())
        },
    }
}