I would like to write a syntax extension that combines information from a related type when generating a new function. As a nonsense example, pretend I have this code:
struct Monster {
health: u8,
}
impl Monster {
fn health(&self) { self.health }
}
#[attack(Monster)]
struct Player {
has_weapon: true,
}
I'd like the attack
attribute to be expanded to a function that knows about the methods of Monster
. A simple example would be
impl Player {
fn attack_monster(m: &Monster) {
println!("{}", m.health());
}
}
Specifically, I'd like to be able to get the function signatures of the inherent methods of a type. I'd also be OK with being able to the function signatures of a trait. The important distinction is that my extension does not know ahead of time which type or trait to look up - it would be provided by the user as an argument to the annotation.
I currently have a syntax extension that decorates a type, as I want to add methods. To that end, I have implemented a MultiItemDecorator
. After looking at the parameters to the expand
function, I've been unable to figure out any way of looking up a type or a trait, only ways of generating brand-new types or traits:
trait MultiItemDecorator {
fn expand(&self,
ctx: &mut ExtCtxt,
sp: Span,
meta_item: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable));
}