这是一个简化的示例,但问题依然存在。斯卡拉宏:将树转换/解析为名称
我想要实现这个使用宏(斯卡拉基于伪代码):
(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'。 –