hkust-taco / mlscript

The MLscript programming language. Functional and object-oriented; structurally typed and sound; with powerful type inference. Soon to have full interop with TypeScript!
https://hkust-taco.github.io/mlscript
MIT License
147 stars 24 forks source link

Support explicit and inferred self types #21

Open LPTK opened 2 years ago

LPTK commented 2 years ago

Example:

class A
  this: { x: int }
  method Foo = this.x  // ok

class B: A  // fine, transfers the `this`-type requirement

B{} // error: does not satisfy `this`-type

class C: A { x: 0 | 1 }

C{x = 0}   // ok

class A2
  // self inferred
  method Foo = this.x  // ok

A2{}  // illegal

class B2: A2

B2{}  // illegal

class C2: A2 { x: 0 | 1 }

C2{x = 0}  // ok
LPTK commented 2 years ago

I no longer think it's a good idea to infer self types (or receiver refinements, for that matter), but we could still use partially-specified self types with class-level type variables to achieve simple extensible programming as in @andongfan's project:

class Base {
  self: { eval: 'a -> int }  // used when typing methods below
  // Note that 'a is quantified at the level of the class instance
  ...
  fun eval: (Lit | Add('a, 'a)) -> int
    = ...
}

I think this actually helps to clarify the approach, and could be presented as the desugaring of the syntax we show in the SRC extended abstract.

To avoid confusion, we may want to capitalize class-level type variables, as in fun eval: (Lit | Add('A, 'A)) -> int, otherwise one could think the function is polymorphic in it.