Rust, wasm32, dynamic code generation

Is there a way to do dynamic code generation in Rust ?

Here is the problem I am facing:

  1. The user types in a simple math equation (like in a graphing calculator).

  2. My program parses the expression into an abstract syntax tree.

  3. I need to evaluate the function on a 1000x1000 grid -- 1,000,000 points.

Now, in a dumb implementation, we do something like:

for x in 0..1000
  for y in 0..1000
    let z = eval_ast(parsed_formula, x, y)

the problem here is that every evaluation of every point requires traversing the entire parsed formula -- which contains lots of Rc/Box ... and jumping around in memory.

Now, what I would like to do is to do some type of dynamic code generation, to compile "parsed formula" down to a C function that we can call, something like:

let c_func = do_magic_dynamic_code_generation(parsed_formula);
for x in 0..1000
  for y in 0..1000
    let z = c_func(x, y)

Is there a way to do this in Rust? (perferably with wasm32 support -- but even if not, I would like to hear about it).

maybe have a look at cranelift, it is a dynamic code generator written in rust that can be used for JIT, it has its own IR but also has a webassembly frontend

1 Like