MikeInnes/Charlotte.jl

Allow function merging

Opened this issue · 1 comments

This is more of a proof of concept or idea, but I think it would be nice to allow merging multiple compiled versions of the same function into a single function on the js side. A library could provide both the merged version and the regular versions of functions (just leave that decision up to the user). If you want to be as fast as possible you stick to the regular ones.

function wtype(i) {
  if (typeof(i) == "number") {
    return Number.isInteger(i) ? 'i32' : 'f32'
  } else if (typeof(i) == "bigint") {
    return 'i64';
  }
  error()
}

function addTwo_i32_i32(x, y) { return x + y; }
function addTwo_i32_f32(x, y) { return x + y; }
function addTwo_f32_i32(x, y) { return x + y; }
function addTwo_f32_f32(x, y) { return x + y; }
function addTwo_i64_i64(x, y) { return x + y; }

function addTwo(x, y) {
  var call = "addTwo_" + wtype(x) + "_" + wtype(y) + "(" + x + ", " + y + ")";
  console.log(call)
  return eval(call);
}

I think a good way to specify doing this would be to allow calling @wasm with sets of types. For example:

@wasm addTwo((Int32, Float32), (Int32, Float32))

Would become:

@wasm addTwo(Int32, Int32) addTwo(Int32, Float32) addTwo(Float32, Int32)...

And then they would be merged into one function again on the js side.

Good idea. If there's just one method for a given function, I'd prefer to just use the shorter name without type annotations on the JS side. That'll be quite common.