Reputation: 9521
Is there a way to pass a type identifier to a macro annotation? Here is what I mean:
@compileTimeOnly("Compile-time only annotation")
class mymacro(val typeName: universe.TypeName) extends StaticAnnotation { // <-- does not work
def macroTransform(annottees: Any*): Any = macro impl
}
object mymacro {
def impl(c: whitebox.Context)(annottees: c.Expr[Any]*) = //...
}
use-case:
trait SomeTrait
@mymacro(SomeTrait)
class Test {
//...
}
Or maybe there is any other way to pass Type identifier of an arbitrary non-generic type to a macro annotation implementation?
Motivation behind this: I need to generate some class Test
member function def foo
depending on the type passed as an argument to the macro annotation (SomeTrait
).
Upvotes: 0
Views: 83
Reputation: 51683
For example you can pass typeName
as a string
import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
@compileTimeOnly("Compile-time only annotation")
class mymacro(typeName: String) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro mymacro.impl
}
object mymacro {
def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
val typeName = TypeName(c.prefix.tree match {
case q"new mymacro(${str: String})" => str
})
println(typeName)
q"..$annottees"
}
}
Usage:
trait SomeTrait
@mymacro("SomeTrait")
class Test
// scalac: SomeTrait
Getting Parameters from Scala Macro Annotation
If you prefer the companion-object approach proposed by @user in comments then you can do
import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
@compileTimeOnly("Compile-time only annotation")
class mymacro(companionObject: Any) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro mymacro.impl
}
object mymacro {
def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
val companionTrait = c.typecheck(c.prefix.tree) match {
case q"new mymacro($arg)" => arg.symbol.companion
}
println(companionTrait)
q"..$annottees"
}
}
Usage:
trait SomeTrait
object SomeTrait
@mymacro(SomeTrait)
class Test
//scalac: trait SomeTrait
Upvotes: 3