1

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

4

1 回答 1

1

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

来自 Alien-Factory 的库Plastic就是这样做的。例子:

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编译器库,并基于Fansh中的代码 - Fantom shell,Fantom 发行版的一部分。

于 2014-01-13T07:17:05.977 回答