4

正如标题所示,我正在尝试创建一个生成类定义的 Scala 宏。基本上我想最终做到以下几点:

classify("StandardEvent", Map("name" -> String, "id" -> Int))
// should at compile-time expand to
case class StandardEvent(name: String, id: Int) extends Event

这甚至可能吗?如果是这样,谁能指出我如何做到这一点的正确方向?实际上,我什至无法让以下简单的宏工作:

// Macro definition:
def classify(): Unit =
  macro classifyImpl

def classifyImpl(c: Context)(): c.Tree = {
  import c.universe._
  q"class SomeClass"
}

// Macro usage in seperate compilation unit
classify()
val s = new SomeClass

这让我收到以下错误消息:

[error] ClassifyTest.scala:6: not found: type SomeClass
[error]   val s = new SomeClass
[error]               ^
[trace] Stack trace suppressed: run last app/compile:compileIncremental for the full output.
[error] (app/compile:compileIncremental) java.lang.AssertionError: assertion failed: 
[error]   class SomeClass extends scala.AnyRef {
[error]   def <init>() = {
[error]     super.<init>();
[error]     ()
[error]   }
[error] }
[error]      while compiling: ClassifyTest.scala
[error]         during phase: typer
[error]      library version: version 2.11.8
[error]     compiler version: version 2.11.8
[error]   reconstructed args: -bootclasspath // ...
[error] 
[error]   last tree to typer: type SomeClass
[error]        tree position: line 5 of ClassifyTest.scala
[error]               symbol: <none>
[error]    symbol definition: <none> (a NoSymbol)
[error]       symbol package: <none>
[error]        symbol owners: 
[error]            call site: <none> in <none>
[error] 
[error] == Source file context for tree position ==
[error] 
[error]      2 object ClassifyTest extends App {
[error]      3 
[error]      4   classify()
[error]      5   val s = new SomeClass
[error]      6 
[error]      7 }

任何人都可以理解这一点吗?非常感谢您的帮助。

4

0 回答 0