これは私の前の質問のフォローアップです。
以下のコードのようなものが機能することを望みます。マクロ生成メソッドを生成できるようにしたい:
case class Cat()
test[Cat].method(1)
生成されたメソッド自体の実装がマクロを使用している場合 ( 「吸血鬼」メソッド):
// macro call
def test[T] = macro testImpl[T]
// macro implementation
def testImpl[T : c.WeakTypeTag](c: Context): c.Expr[Any] = {
import c.universe._
val className = newTypeName("Test")
// IS IT POSSIBLE TO CALL `otherMethod` HERE?
val bodyInstance = q"(p: Int) => otherMethod(p * 2)"
c.Expr { q"""
class $className {
protected val aValue = 1
@body($bodyInstance)
def method(p: Int): Int = macro methodImpl[Int]
def otherMethod(p: Int): Int = p
}
new $className {}
"""}
}
// method implementation
def methodImpl[F](c: Context)(p: c.Expr[F]): c.Expr[F] = {
import c.universe._
val field = c.macroApplication.symbol
val bodyAnnotation = field.annotations.filter(_.tpe <:< typeOf[body]).head
c.Expr(q"${bodyAnnotation.scalaArgs.head}.apply(${p.tree.duplicate})")
}
このコードは、次の場合にコンパイルに失敗します:
[error] no-symbol does not have an owner
last tree to typer: This(anonymous class $anonfun)
[error] symbol: anonymous class $anonfun (flags: final <synthetic>)
[error] symbol definition: final class $anonfun extends AbstractFunction1$mcII$sp with Serializable
[error] tpe: examples.MacroMatcherSpec.Test.$anonfun.type
[error] symbol owners: anonymous class $anonfun -> value <local Test> -> class Test -> method e1 -> class MacroMatcherSpec -> package examples
[error] context owners: value $outer -> anonymous class $anonfun -> value <local Test> -> class Test -> method e1 -> class MacroMatcherSpec -> package examples
[error]
[error] == Enclosing template or block ==
[error]
[error] DefDef( // val $outer(): Test.this.type
[error] <method> <synthetic> <stable> <expandedname>
[error] "examples$MacroMatcherSpec$Test$$anonfun$$$outer"
[error] []
[error] List(Nil)
[error] <tpt> // tree.tpe=Any
[error] $anonfun.this."$outer " // private[this] val $outer: Test.this.type, tree.tpe=Test.this.type
[error] )
this.otherMethod
私はこれが何を意味するのかを解読するのが本当に苦手ですが、吸血鬼メソッドの本体で参照できないという事実に関連していると思われます. それを行う方法はありますか?
これが機能する場合、次のステップは、次のような実装を行うことですotherMethod
。
def otherMethod(p: Int) = new $className {
override protected val aValue = p
}