Reference implementations for bitfield 04-multiple-of-8bits of procmacro workshop

I am stucked at 04-multiple-of-8bits , which I do not know how to emit codes based on #size % 8 , because we can't resolve the actual const value from the expression in proc-macro,

Anyone has a solution?

1 Like

I did this: bitfield 04: pass · zjp-CN/proc-macro-workshop@c596336 · GitHub

let total_bits = {
  let ty = ty.clone();
  quote! { #( <#ty as ::bitfield::Specifier>::BITS )+* }
};
const _ : usize = 0 - (#total_bits) % 8;

Note: it seems dtolnay uses a trait trick to do it, but I use a naive implementation (not in this part) which I'm unsatisfied with. I wrote that a year ago, noticing I was on a wrong way from this 04-test or so, but I insisted on my way.

So take your own risk.

-error[E0277]: the trait bound `bitfield::checks::SevenMod8: bitfield::checks::TotalSizeIsMultipleOfEightBits` is not satisfied
+error: any use of this value will cause an error
   --> tests/04-multiple-of-8bits.rs:53:1
    |
 53 | #[bitfield]
-   | ^^^^^^^^^^^ the trait `bitfield::checks::TotalSizeIsMultipleOfEightBits` is not implemented for `bitfield::checks::SevenMod8`
+   | ^^^^^^^^^^^ attempt to compute `0_usize - 7_usize`, which would overflow

I found simply panicking gives a better info : update(bitfield::04-multiple-of-8bits): user-friendly error report · zjp-CN/proc-macro-workshop@644637f · GitHub

-const _ : usize = 0 - (#total_bits) % 8;
+const _ : () = { if (#total_bits) % 8 != 0 { panic!("should be a multiple of 8 bits") } };
 53 | #[bitfield]
-   | ^^^^^^^^^^^ attempt to compute `0_usize - 7_usize`, which would overflow
+   | ^^^^^^^^^^^ the evaluated program panicked at 'should be a multiple of 8 bits', $DIR/tests/04-multiple-of-8bits.rs:53:1

But unfortunately you can't write panic!("{} should be a multiple of 8 bits", ...), since

error[E0015]: cannot call non-const formatting macro in constants
 --> src/main.rs:6:22
  |
6 |             panic!("{TOTAL_BITS} should be a multiple of 8 bits");
  |                      ^^^^^^^^^^

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.