问题描述
是否可以将类型标识符传递给宏注释?这是我的意思:
@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]*) = //...
}
用例:
trait SomeTrait
@mymacro(SomeTrait)
class Test {
//...
}
或者也许还有其他方法可以将任意非通用类型的类型标识符传递给宏注释实现?
背后的动机:我需要生成一些class Test
成员函数def foo
,具体取决于作为参数传递给宏注释(SomeTrait
)的类型。
解决方法
例如,您可以将openCamera
作为字符串传递
typeName
用法:
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"
}
}
Getting Parameters from Scala Macro Annotation
如果您更喜欢 @user 在评论中提出的伴随对象方法,则可以
trait SomeTrait
@mymacro("SomeTrait")
class Test
// scalac: SomeTrait
用法:
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"
}
}