Do Macros work inside traits?


#1

Before I log an issue I would first ask around to see if I am doing something obviously wrong. I can build up structs and impls using a TT mucher style macro but dont seem to be able to do the same with a trait. Here is a simple example of code that doesn’t work:


macro_rules! fun{
  () => { fn hello(); }
}

macro_rules! full_fun{
  () => { fn hello(){} }
}

// Fails with:
// <anon>:13:8: 13:11 error: expected one of `const`, `extern`, `fn`, `type`, or `unsafe`, found `fun`
// <anon>:13        fun!();
macro_rules! trait_macro{
  ($name:ident) => {
     pub trait $name {
       fun!();
     }
 };
}

macro_rules! struct_macro{
  ($name:ident) => {
     pub struct $name;
     
     impl $name {
       full_fun!();
     }
 };
}

// I can add functions to a Impl
struct_macro!{Monster}
// But I cannot add functions to a trait
trait_macro!{Monster}


fn main() {
    
}

I’ve spent the evening looking at this so either its not possible or its a bug I think. I can work inside enums, and structs and impls but not traits it seems.


#2

Seems like it not currently supported. The AST doesnt expect macros in the place of trait items:

pub enum TraitItemKind {
    Const(P<Ty>, Option<P<Expr>>),
    Method(MethodSig, Option<P<Block>>),
    Type(TyParamBounds, Option<P<Ty>>),
}

Compare to ImplItem:

pub enum ImplItemKind {
    Const(P<Ty>, P<Expr>),
    Method(MethodSig, P<Block>),
    Type(P<Ty>),
    Macro(Mac),
}