2014-01-13 82 views
1

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

+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 compiler库,它基于Fansh中的代码 - Fantom外壳,属于Fantom发行版的一部分。