assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Support custom type casts

Open bowenwang1996 opened this issue 5 years ago • 5 comments

It would be nice to support custom type cast. As an example, see https://github.com/MaxGraey/bignum.wasm/issues/19

bowenwang1996 avatar Jun 19 '19 22:06 bowenwang1996

Maybe we could hijack Object.prototype.valueOf, but make it generic? Something like

class MyClass {
  valueOf<T>(): T {
    // statically evaluate `T` and convert `this` -> `T`
    return converted;
  }
}

Might even be possible to implement it in a way that if it does not have a generic parameter, it defaults to i32, for compatibility with JS.

dcodeIO avatar Jun 19 '19 22:06 dcodeIO

I like this. Also need somehow determine implicit & explicit conversion. For example:

class MyClass {
  // implicit conversion
  valueOf<T>(): T {
    ...
  }
  // explicit conversion like `new MyClass() as f64`
  as<T>(): T {
    ...
  }
}

MaxGraey avatar Jun 19 '19 22:06 MaxGraey

Another variant:

class MyClass {
  // implicit conversion
  @operator.implicit("as")
  as<T>(): T { // or valueOf<T>()
    ...
  }
  // explicit conversion
  @operator.explicit("as")
  as_expl<T>(): T {
    ...
  }
}

MaxGraey avatar Jun 19 '19 23:06 MaxGraey

Explicit casting is most interesting feature for math related packages. For example I want to overload linear operators ("+") and ("*") for complex numbers algebra or vector space.

//z3 = z1 * z2;
@operator("*")
static add(a: Complex, b: Complex) {
  return new Complex(a.re + b.re, a.im + b.im);
}

This operators also should works for constants and we need to create explicit casting or 2 operator overloading

//z2 = c * z1;
@explicit @operator.postfix("as")
as_expl<f64>(): Complex {
  return new Complex(this, 0);
}

//another way
@polymorphism @operator("*")
static mul(c: f64, z: Complex) { // left
  return new Complex(c * z.re, c * z.im);
}
@polymorphism @operator("*")
static mul(z: Complex, c: f64) { // right
  return new Complex(c * z.re, c * z.im);
}

This can be the most yummy part of AS and I think we shouldn't stay with TS superset strictness. Since wasm is toy for math I think we need this, just imagine how rich and compact code can be.

munrocket avatar Oct 30 '20 22:10 munrocket

I think we should stay as compatible with TS as possible. The further away we go, the more difficult it becomes to make AS code compile to plain JS not just Wasm, less interoperable, and less compatible with TS tooling.

People could of course choose not to use incompatible features, but maybe there is some library that someone wrote only for AS, and the consumer wants to use it in their compile-to-JS pipeline; if that lib has more incompatible features, the more work it is to port.

I would love to see AS get closer, than further.

trusktr avatar Apr 09 '22 18:04 trusktr