宏在运行时访问函数的源代码 [英] Macro to access source code of function at runtime
问题描述
使用Scala宏,我想访问功能f的源代码.
Using Scala macros I would like to get access to source code of function f.
这是我的问题的简化示例:
Here is simplified example of my problem:
def logFImplementation(f: => Boolean) {
val sourceCodeOfF: String = ... // <-- how to get source code of f??
println("Scala source of f=" + sourceCodeOfF)
}
如此:
logFImplementation { val i = 5; List(1, 2, 3); true }
它应该打印:
Scala source of f=val i: Int = 5; immutable.this.List.apply[Int](1, 2, 3); true
(目前,我测试了 Macro,以便在运行时访问源代码文本,它对于{ val i = 5; List(1, 2, 3); true }.logValueImpl
非常有用,但对于f.logValueImpl
,它仅显示f
.)
(Right now I tested Macro to access source code text at runtime and it works great for { val i = 5; List(1, 2, 3); true }.logValueImpl
but for f.logValueImpl
it just prints f
.)
谢谢您的建议.
推荐答案
我认真怀疑是否有可能.
首先,宏是编译时.他们所做的只是变换程序组成的抽象语法树.这正是您能够执行{ val i = 5; List(1, 2, 3); true }.logValueImpl
的原因:AST就在这里,因此将其打印为字符串没有困难.但是宏无法解析运行时值,因为在运行时没有 宏.
First, macros are compile-time thing. All they do is transform abstract syntax trees your program consists of. That's exactly the reason why you were able to do { val i = 5; List(1, 2, 3); true }.logValueImpl
: AST is right here, so there is no difficulty printing it as string. But macros just can't resolve runtime values, because there are no macros at runtime.
第二,绝对没有理由相信f
是Scala代码.我可以这样从Java调用您的函数(不确定我的名字正确无误,但想法仍然相同):
Second, there is absolutely no reason to believe that f
is Scala code. I could call your function from Java like this (not sure that I got all names right, but the idea is still the same):
someObject.logFImplementation(new scala.Function0<Boolean>() {
@Override
public Boolean apply() {
// do some things in Java
}
});
(这是可能的,因为内部按名称调用参数被转换为scala.Function0
对象).在这种情况下,您希望函数打印什么?
(and this is possible because internally call-by-name parameters are transformed into scala.Function0
objects). What would you expect your function to print in this case?
这篇关于宏在运行时访问函数的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!