2012-09-18 36 views
9

下面的宏,從一個更大的示例中提取,應該建立什麼也沒有,但參考一棵樹this我如何在Scala宏中引用「this」?

def echoThisImpl(c:Context): c.Expr[Any] = { 
    import c.universe._ 

    val selfTree = This(c.enclosingClass.symbol) 
    c.Expr[AnyRef](selfTree) 
} 

def echoThis: Any = macro CallMacro.echoThisImpl 

但要echoThis

object Testing extends App { 
    val thisValue = CallMacro.echoThis 
    println(thisValue) 
} 

調用編譯失敗,與消息

[error] /home/rafael/dev/scala/goose/goose-macros/src/test/scala/Testing.scala:8: type mismatch; 
[error] found : <noprefix> 
[error] required: Any 
[error] val thisValue = CallMacro.echoThis 

如果我設置-Ymacro調試,精簡版標記生成的樹是This(newTermName("<local Testing>"))

回答

10

有實現你想要的東西的兩個選項:

1)使用This(tpnme.EMPTY)。目前這不能編譯,所以你必須改用This(newTypeName("")),但是在RC1中這個問題會被修復。 2)使用This(c.enclosingClass.symbol.asModule.moduleClass)。目前這不起作用,因爲https://issues.scala-lang.org/browse/SI-6394,但在RC1中這將被修復。

+0

感謝您回覆尤金。這不足以讓我度過難關。 IIUC'c.prefix'是樹的表達式,引用宏定義的'object'。 –

+0

(繼續) 'This()'帶有一個符號,我相信我正在尋找引用宏調用的封閉類的符號。 我希望能在通話 '高清echoThis:任何=宏MacroImpl.echoThis' 是一樣 '高清echoThis:任何= this' –

+0

好吧,我看到的。讓我想想 –