2013-08-30 12 views
7

这是我的previous question的后续处理。在生成的宏方法中使用`this`

我想像下面的代码的工作。我希望能够以产生宏生成的方法:

case class Cat() 

test[Cat].method(1) 

如果本身是使用宏(一"vampire" method)生成的方法的实现:

// 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 
} 
+0

我刚刚写了一个更普遍的回应这个问题[博客文章](http://meta.plasm.us/posts/2013/08/31/feeding-我们 - 吸血鬼/)。如果这是你要找的东西,我可以在这里添加一个精简版本作为答案。 –

回答

2

的“本”是通常可作为c.prefix.tree。所以也许类似

val bodyInstance = 
    q"(p: Int) => ${c.prefix.tree}.otherMethod(p * 2)"