在运行时动态评估代码

时间:2014-01-13 03:18:04

标签: fantom

是否有可能在Fantom的运行时获取源代码的字符串/ AST并对其进行评估(如eval())?我在文档中发现了一些建议的功能,但没有明显的证据。

1 个答案:

答案 0 :(得分:1)

这不像调用eval()函数那么容易,但它是可能的。您需要先将Fantom代码编译成一个类,然后才能执行它。

Plastic,来自Alien-Factory的图书馆就是这样做的。例如:

using afPlastic

class Example {
    Void main() {
        eval("2 + 2")  // --> 4
    }

    Obj? eval(Str code) {
        model := PlasticClassModel("MyClass", true)
        model.addMethod(Obj?#, "eval", "", code)
        myType := PlasticCompiler().compileModel(model.toFantomCode)
        return myType.make->eval()
    }
}

PlasticCompiler类完成将Fantom代码编译为可用类型的工作。

它使用了Fantom compiler库,它基于Fansh中的代码 - Fantom shell,Fantom发行版的一部分。

相关问题