将类型标识符传递给静态宏注释

Pass type identifier to static macro annotation

有没有办法将类型标识符传递给宏注释?这就是我的意思:

@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 fooSomeTrait).

例如,您可以将 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"
  }
}

用法:

trait SomeTrait

@mymacro("SomeTrait")
class Test 

// scalac: SomeTrait

如果你更喜欢@user在评论中提出的companion-object方法,那么你可以

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"
  }
}

用法:

trait SomeTrait
object SomeTrait

@mymacro(SomeTrait)
class Test

//scalac: trait SomeTrait