Draco-lang / Language-suggestions

Collecting ideas for a new .NET language that could replace C#
75 stars 5 forks source link

Type hinting #74

Open LPeter1997 opened 2 years ago

LPeter1997 commented 2 years ago

There are a couple of ugly edges that our language already needs to solve/fix. Particularly, I believe there are three very related things we could solve with this proposed feature. Namely:

Many languages solve these by introducing some syntactical differentiator:

Personally, I find some of these solutions ugly. For example, why can't 1 be a floating point number?

Type hints

Since Fresh uses : meaning "has type", I think there is no reason not to allow its use in arbitrary expressions. For example, (1 + 2): int + 3 would be equivalent to 1 + 2 + 3, but in the former case, the compiler would explicitly type-check the type of the subexpressions. This is already allowed by some ML languages to do coercions or aid type inference.

We could make these type hints denote the exact type for our literals, and default to something, when none is provided:

var x = 4; // x: int32
var y = 4: uint32; // y: uint32
// var z = x: uint32; // ERROR: only literals can be casted/coerced implicitly like this

var s1 = "a"; // s1: string
var ch = "a": char; // ch: char
// var ch2 = "ab": char; // ERROR: non-single-character string literals can't be coerced to char
var s2 = "hello UTF8 encoding!": u8string; // s2: u8string

Note, that this colon syntax could be used on literals in more complex expressions too. For example:

var x = 3; // x: int32
var a = x * 2: float32; // Equivalent to x * 2.0f in C#, a: float32

Important: These are not runtime casts, purely compile-time hints for the compiler.

Open questions