When I write a derive proc-macro, I need to generates a method for each field of struct, which returns true if the type of the field implements a trait T, else returns false. Is any way to do this?
I treid some ways, but found that I can't specialize code based on whether T impl or not impl trait.
pub trait T {}
pub struct X; // implements T
pub struct Y; // doesn't implement T
impl X for T { }
type Z = X;
#[derive(MySillyDerive)]
struct Foo {
val1: Z, // users can define type aliases, so we can't rely on the name of type
val2: Y,
}
// Want to generates something like this
impl Foo {
fn is_val1_implement_t() -> bool { // TODO: always return true
}
fn is_val2_implement_t() -> bool { // TODO: always return false
}
}
You can make those methods at compile time and hope they optimize away, but I don't know of any stable way to make them const, i.e., callable at compile time. I can't tell if that's sufficient for your use case or not.
The basic idea is using same method name, but one is provided by type itself, while another is provided by a extension trait.
One more question, for ImplType<X>, both methods should be available, is there some document to clarify the rules to tell us which method will be chosen?