Literal types
Nick Treleaven
nick at geany.org
Sat Jul 5 10:50:13 UTC 2025
On Friday, 4 July 2025 at 16:16:05 UTC, IchorDev wrote:
> auto a = [1,2];
> ubyte[] b = a.dup(); //ERR: `[1,2]` is an `int[]`… ugh
How can that work? `dup` is a template function that uses the
type of `a`. `dup` doesn't know anything about `b` being
`ubyte[]`. That would need backwards type inference.
> ```
> ubyte[] c = [1,2]; //OK: on second thought, `[1,2]` can totally
> be a `ubyte[]`…
> ```
> One thing that could mitigate this is having explicit suffixes
> for char, byte, and short.
You can write `cast(ubyte) [1, 2]`:
https://dlang.org/spec/expression.html#cast_array_literal
> But what would be really nice is if the language could keep
> track of when a variable’s type was inferred from nothing but a
> literal, and then allow the usual type conversion restrictions
> to be bent a little based on how the literal could’ve been
> interpreted as a different type.
> It’s a similar idea to https://dlang.org/spec/type.html#vrp
> which never accounts for variables that have just been
> unconditionally assigned a literal value.
VRP works for expressions, it doesn't work across statements
(except for const variable declarations). To do that in the
general case requires a lot of analysis, slowing compilation.
> Oddly, the idea that I described already exists for enums:
> ```d
> enum int[] x = [1,2];
> ushort[] y = x; //no error?!
> ushort[2] z = x; //still no error!!?!
> ```
There's no memory allocated for `x`, it is a symbol representing
an array literal. The type of the enum is not a problem because
the element values are still known, similar to:
```d
enum int i = 1;
ushort s = i;
```
More information about the dip.ideas
mailing list