2013-08-30 14 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)"