Scala 宏 : Getting a List of TypeSymbols to be used at runtime

标签 scala macros scala-macros

有没有办法返回 ListTypeSymbol s 对于使用宏的包下的每个类?

我想要实现的是编写一个宏,给出与此列表等效的内容:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> case class MyClass1()
defined class MyClass1

scala> case class MyClass2()
defined class MyClass2

scala> val typeSymbols = List(typeOf[MyClass1].typeSymbol, typeOf[MyClass2].typeSymbol)
typeSymbols: List[reflect.runtime.universe.Symbol] = List(class MyClass1, class MyClass2)

这是我的设置:

我有一个名为 foo 的包,根据这些定义:
trait FooTrait

case class Bar() extends FooTrait 

case class Bar() extends FooTrait

这是我的宏,它获取 foo 下扩展 FooTrait 的类的所有类型符号:
def allTypeSymbols_impl[T: c.WeakTypeTag](c: Context)(packageName: c.Expr[String]) = {
  import c.universe._

  // Get package name from the expression tree
  val Literal(Constant(name: String)) = packageName.tree

  // Get all classes under given package name
  val pkg = c.mirror.staticPackage(name)

  // Obtain type symbols for the classes - implementation omitted
  val types = getTypeSymbols(c.universe)(List(pkg))

  // Apply method for List. For easy readability in later applications
  val listApply = Select(reify(List).tree, newTermName("apply"))

  val result = types.map {
    t =>
      val typeName = c.Expr[TypeSymbol](Ident(t))
      println(s"Typename: $typeName, $t, ${t.toType}")

      reify(typeName.splice).tree
  }

  println(s"RESULT: ${showRaw(result)}")

  c.Expr[List[reflect.runtime.universe.TypeSymbol]](Apply(listApply, result.toList))
}

第一println打印:
Typename: Expr[c.universe.TypeSymbol](Bar), class Bar, foo.Bar
Typename: Expr[c.universe.TypeSymbol](Baz), class Baz, foo.Baz

第二个打印:
RESULT: List(Ident(foo.Bar), Ident(foo.Baz))

但我收到此错误消息:
[error] no type parameters for method any2ArrowAssoc: (x: A)ArrowAssoc[A] exist so that it can be applied to arguments (<notype>)
[error]  --- because ---
[error] argument expression's type is not compatible with formal parameter type;
[error]  found   : <notype>
[error]  required: ?A
[error] Note that <none> extends Any, not AnyRef.
[error] Such types can participate in value classes, but instances
[error] cannot appear in singleton types or in reference comparisons.

我应该怎么做才能使这项工作?我怀疑我必须写其他东西而不是 Ident ,但我无法弄清楚是什么。

使用 Scala 2.10.2。

提前致谢!

最佳答案

您必须使用 reifyType 在运行时 Universe 中创建反射工件:

import scala.language.experimental.macros
import scala.reflect.macros.Context

object PackageMacros {
  def allTypeSymbols[T](packageName: String) = macro allTypeSymbols_impl[T]

  def allTypeSymbols_impl[T: c.WeakTypeTag](c: Context)(
    packageName: c.Expr[String]
  ) = {
    import c.universe._

    val pkg = packageName.tree match {
      case Literal(Constant(name: String)) => c.mirror.staticPackage(name)
    }

    val types = pkg.typeSignature.members.collect {
      case sym: ClassSymbol =>
        c.reifyType(treeBuild.mkRuntimeUniverseRef, EmptyTree, sym.toType)
    }.toList

    val listApply = Select(reify(List).tree, newTermName("apply"))

    c.Expr[List[Any]](Apply(listApply, types))
  }
}

这将为您提供类型标签列表,而不是符号,但您可以很容易地获取符号,如下所示:
scala> PackageMacros.allTypeSymbols("foo").map(_.tpe.typeSymbol) foreach println
class Baz$
class Bar
class Baz
trait FooTrait
class Bar$

或者在宏本身中。

关于Scala 宏 : Getting a List of TypeSymbols to be used at runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17653447/

相关文章:

scala - 不同的字节码生成问题

mysql - Squeryl:插入时未更新 KeyedEntity.id

scala - Scala 中编译时对象创建的语法糖

clojure 生成向量与映射文字表达式

c - 学习C#define语句(MACROS)

scala - 在 Scala 宏中对来自 ValDef 的 TypeTree 值进行模式匹配的正确方法?

Scala 3 宏 - 在运行时保留泛型

scala - 使用sbt run或sbt控制台的BufferedReader.readLine问题

macros - Clojure defmacro 丢失元数据

Scala 宏 : What is the difference between typed (aka typechecked) and untyped Trees