sirisian / ecmascript-types

ECMAScript Optional Static Typing Proposal http://sirisian.github.io/ecmascript-types/
454 stars 4 forks source link

Arrays of value type classes vs arrays of references #71

Open sirisian opened 2 years ago

sirisian commented 2 years ago

WIP issue with thoughts.

Currently the value types defined in the spec create logical sequential typed arrays in memory that can have views over them. If I go with the design where all typed classes are frozen then one could write:

class A {
  a:uint8;
  b:uint16;
}
const a:[10]<A>;
a[0] = a[1]; // copy instance at 1 to 0 treating this like a single value type
a[0] == a[1]; // call equality operator
a[0] === a[1]; // always false as these are unique memory locations

Since A is frozen it's memory layout is exactly as written, so it would be 10 * (1 + 2) = 30 bytes. If one used dynamic class A {...} then this would not allow for sequential data. Would it be treated as a reference to 10 instances?

The explicit syntax for creating an array of typed non-dynamic class would then need special syntax. The token is chosen from C++, but it could be almost anything as it's inside of the template syntax.

const a:[10]<A&>;

I'd need to analyze other places this syntax comes up in generic code. Like are there situations where one wants to do:

class A<T> {
  a:[10]<T>;
  b:[]<T&>;
}
let a:A<T&> = [];
let b:A<T> = [];

One might solve this though by throwing an error if it sees T&&. In some cases one might need to pass <T, T&> to support cases where difference fields can behave differently.

class A<T, U> {
  a:[10]<T>;
  b:[]<U>;
}
let a:A<T&, T> = [];
let b:A<T, T> = [];

This might be incredibly rare.

I mention the reference syntax because right now the typed arrays work like that for value types, so if you can define a value type I'd expect it to work identically to the other value types. So it should create sequential memory and views can be mapped over them intuitively. However, unlike say uint8 a custom value type might want to be placed on the heap and referenced, so it needs syntax to treat it like it's dynamic.

Or is this sequential memory so rare it should have its own syntax like a stack keyword? [10]<stack T> where this would only be valid if T was completely frozen.