I'd like to better handle errors within my custom macros.
In my program, there are some structs that must implement a certain trait otherwise certain methods won't be available and the compiler will fail.
#[derive(Foo)]
struct ValidStruct { ... }
impl X for ValidStruct {
fn foo() { ... }
}
#[derive(Foo)]
struct InvalidStruct { ... }
// no X trait implemented
I would like for my macro to show an error message like "MyStruct does not implement X trait." when a macro is used on an invalid struct.
At first, I tried to get information about the implemented traits from syn::Type - with no success. My last try was using the syn::parse2(quote!{ invalidstruct::foo() }) trying to get an error, based on which I could then throw my own error message - also without success.
A pattern I've used before is to generate something some sort of no-op function that uses generics to
assert a particular trait is implemented.
Here is an example where we assert Normalize implements Transform<Tensor<f32>, Output = Tensor<f32>> and Transform<Tensor<u64>, Output = Tensor<f32>> (i.e. normalizing tensors of f32's or u64's always results in a f32 tensor).