Search code examples
scalamacrosscala-macrosscala-macro-paradise

How to pass parameters to annotation with macro expansions


I'm using macros annotation for generating code. I would like to change its behaviour based on additional string parameters. So it would produce different results for same code. I closely followed the guide for macro annotations that covers only the simplest use.

@myMacros
class MyClass {
}

That is how I'm using macroses now. And what I'd like to achieve:

@myMacros(name : String)
class MyClass {
}

Solution

  • you can use macroApplication

    class AnnotationPassVal(val name: String) extends StaticAnnotation {
      def macroTransform(annottees: Any*): Any = macro AnnotationPassValImpl.apply
    }
    
    class AnnotationPassValImpl(val c: Context) {
    
      import c.universe._
    
      def showInfo(s: String) =
        c.info(c.enclosingPosition, s.split("\n").mkString("\n |---macro info---\n |", "\n |", ""), true)
    
      def apply(annottees: c.Expr[Any]*) = {
        val a = c.macroApplication
    
        //look macroApplication is what 
        showInfo(show(a))
    
    
        val AnnotationName: Tree = a match {
          case q"new AnnotationPassVal(name = $name).macroTransform(..$a)" =>
            name: Tree
        }
    
        showInfo(show(AnnotationName))
        q"""{..$annottees}"""
      }
    }
    

    test

    @AnnotationPassVal(name = "hello")
    class AnnotationPassValTest //when show info "hello"