Search code examples
fantom

Dynamically evaluating code at runtime


Is it possible to take a string/AST of source code and evaluate it (like eval()) at runtime in Fantom? I found some suggesting features in the documentation but not obvious evidence.


Solution

  • It's not as easy as calling an eval() function, but it is possible. You need to first compile your Fantom code into a class before you can execute it.

    Plastic, a library from Alien-Factory, does just that. Example:

    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()
        }
    }
    

    The PlasticCompiler class does the job of compiling Fantom code into a usable Type.

    It uses the Fantom compiler library and is based on code found in Fansh - a Fantom shell, part of the Fantom distribution.