rescript-compiler icon indicating copy to clipboard operation
rescript-compiler copied to clipboard

Coercion improvements

Open zth opened this issue 7 months ago • 5 comments

Listing some ideas for improvements to coercion/subtyping.

  • [ ] A variant can be coerced to a polyvariant if the polyvariant is closed and the runtime representation matches
  • [ ] Investigate dicts - what can be coerced?
  • [ ] Handle more coercion + unboxed variants. For example. "hello" :> JSON.t and 1. :> JSON.t works, but not 1 :> JSON.t, true :> JSON.t or dict{"test": "hello"} :> JSON.t

zth avatar May 23 '25 11:05 zth

A variant can be coerced to a polyvariant if the polyvariant is closed and the runtime representation matches

Not sure if this example falls under that, but it would be great if we could do the following:

let f = (v:s) => ()

type t = | Foo | Bar | Meh

let _ = f(Foo) // without writing `Foo :> string`

nojaf avatar May 23 '25 11:05 nojaf

I don't think that example is complete...? What is s?

zth avatar May 23 '25 12:05 zth

Oh, sorry s for string.

nojaf avatar May 23 '25 12:05 nojaf

Ah right. So you essentially mean implicit coercion. No, that's something we've intentionally decided against. We want any type coercion to be explicit. There are many reasons:

  1. You might not actually want a type coercion in various contexts, since types have meaning depending on context
  2. It needs to be clear from the code where coercion is happening
  3. Coercion can come with some perf loss in the type checking if the types are complex, so doing it should be explicit

zth avatar May 23 '25 12:05 zth

Got it, thanks!

nojaf avatar May 23 '25 12:05 nojaf