這是一個簡化的示例,但問題依然存在。斯卡拉宏:將樹轉換/解析爲名稱
我想要實現這個使用宏(斯卡拉基於僞代碼):
(a: Int) => {
val z = "toShort"
a.z
}
如果我具體化,我會獲得類似這樣:
Function(
List(
ValDef(
Modifiers(Flag.PARAM),
newTermName("a"),
Ident(scala.Int),
EmptyTree
)
),
Block(
List(
ValDef(
Modifiers(),
newTermName("z"),
TypeTree(),
Literal(Constant("toShort"))
)
),
Apply(
Select(
Ident(newTermName("a")),
newTermName("toShort")
),
List()
)
)
)
我不知道如何訪問爲一個值,然後將其用作TermName。
我試圖取代newTermName("toShort")
與newTermName(c.Expr[String](Select(Ident(newTermName("z")))).splice)
但是編譯器似乎並不喜歡:
exception during macro expansion: java.lang.UnsupportedOperationException: the function you're calling has not been spliced by > the compiler. this means there is a cross-stage evaluation involved, and it needs to be invoked explicitly. if you're sure this is not an oversight, add scala-compiler.jar to the classpath, import
scala.tools.reflect.Eval
and call<your expr>.eval
instead.
我也試過「EVAL」的建議由編譯器:newTermName(c.eval(c.Expr[String](...))
但既不工作。
我怎麼能轉換像Select(Ident(newTermName("z")))
樹(這是一個本地的val值的訪問)
一個名稱
一個字符串,它可以被用來作爲newTermName
參數?可能嗎?
UPDATE:
帶到這裏你作爲一個gist真正的問題!
由於提前,
'newTermName(「z」)''已經返回一個'Name'。我不明白那個有什麼問題。 – sschaef
你的意思是你想從現有的樹中提取它嗎?像'val Select(Ident(name))= tree'? – sschaef
我想使用'val z'的值作爲'newTermName'方法的參數。 'Select(Ident(newTermName(「z」)))'是對該值的訪問,然後是:'newTermName(「」)''。所以可以這樣做:'a.toShort'。 –