I have a procmacro deriving whose behavior I'd like to customize based on a caller-provided constant. The standard way is to provide this constant as a literal attribute; for example I can provide the literal array [1, 2, 3, 4, 5]
:
#[derive(MyTrait)]
#[my_trait([1, 2, 3, 4, 5])]
struct SomeStruct { .. }
I'd like to do better than this; I want to be able to use a computed const
value to store this constant. For example, I'd like to write this:
const CONFIG: [u64; 5] = [1, 2, 3, 4, 5];
#[derive(MyMacro)]
#[my_macro(CONFIG)]
struct SomeStruct { .. }
Is it possible to do something like this? From what I understand, I think not, because of phase ordering problems: procmacros are evaluated during an early syntax stage, before this module's semantics are ready. So all the procmacro will get is the token CONFIG
rather than being able to access the value referenced by the constant CONFIG
.
Context of what I'm trying to do: the trait I'm trying to derive is for encoding types in dense bit-packed way. For enum
types, it turns out that the desired encoding is a nontrivial function of the bit widths of all the fields (involves running a dynamic programming algorithm). I'd like to run that dynamic programming algorithm at compile time, during the evaluation of the procmacro, but in order to do so it needs access to the bit widths of all of the fields of the enum
, which I don't think I have access to.