« | Main | »

JewelScript 1.4: dynamic compilation during execution

By Jewe | February 27, 2016

JewelScript’s runtime overhaul has reached a new milestone. I have literally torn the virtual machine apart, in order to make the management of byte code more flexible.

Previously, the JewelScript virtual machine used a single block of memory, the “code segment”, where all byte code of all compiled classes was stored in one big, happy chunk. This had some advantages, like making it quite easy to save the compiled program to disk and reload it. It also allowed simpler “jmp” and “jsr” instructions, because all classes could call into other classes without the overhead of adding another native call recursion.

The big downside to the design was, that it’s rather static. When I tried to add some cooler, dynamic stuff to JewelScript, the static design of the code segment created too many problems. So, I decided this would be the time to redesign this.

Every class (more exactly every type) is now compiled and stored in it’s own private code segment. Once stored in the VM, a class is made read-only, so the compiler can’t affect it anymore. This allows users to dynamically compile and add new classes and functions, without affecting existing code, even while the VM is currently running. It would also allow – in theory – to unload classes dynamically, if the class is no longer needed, to free up memory.

Basically, what this all means is: You can now write a program that creates code from the program’s data, and then executes it.

Here’s a demo script. The code already works, but there may be still a few bugs in the new VM to iron out.

 * evaluate.jc
 * Demonstrates how to dynamically compile and run additional functions and classes.
import stdlib;
import runtime;

using stdlib;

// declare a delegate
delegate int Foo(int a, int b);

function test1()
    // compile a string that implements this delegate
    Foo fn = runtime::evaluate(typeof(Foo), "return a + b * 2;");
    // execute it
    int v = fn(23, 11);

// declare an interface
interface Bar
    method string get();

function test2()
    // compile a string that implements this interface
    Bar b = runtime::evaluate(typeof(Bar),
        "method constructor() {}"
        "method string get() { return \"Hello!\"; }"

    // execute it

function string main(const string[] args)
    return null;

Topics: code examples, docs, news | Comments Off on JewelScript 1.4: dynamic compilation during execution

Comments are closed.