Literal types
IchorDev
zxinsworld at gmail.com
Sun Jul 6 13:37:41 UTC 2025
On Saturday, 5 July 2025 at 10:50:13 UTC, Nick Treleaven wrote:
> 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?
It doesn’t, that’s the point.
> 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.
The problem is that in practice VRP only really cares about type.
I don’t see why it would be non-trivial to add a piece of
metadata that specifies the literal that a variable was
initialised with, but I haven’t worked on dmd much so maybe it’s
not flexible like that.
A simpler solution is just remove integer promotion. Yes, ha-ha
very funny. More realistically, a future edition could make it so
that the compiler never assumes that a number that could fit into
a `byte`/`short` is an `int`, but this would break a lot of
declarations like `auto n=1;`, so I can see it being unpopular.
I think this idea is in the same category as wanting `float`
arithmetic to use `float`s: it would be so useful but it’s
unlikely to happen.
> 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;
> ```
Uhh, yeah obviously? I pointed this out because it illustrates
how D already breaks the usual implicit cast rules in the same
way as in my idea. The only difference between enums and
variables here is that variables are less statically predictable.
Nothing requires the compiler to actually allocate a variable
either if that variable can be optimised away.
More information about the dip.ideas
mailing list