Literal types

Nick Treleaven nick at geany.org
Sun Jul 6 19:14:55 UTC 2025


On Sunday, 6 July 2025 at 13:37:41 UTC, IchorDev wrote:
> 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.

I assumed you were showing that line as something that could be 
made to work. I was asking how you think the language could make 
that work.

>> 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

Because how do you know the variable wasn't mutated after 
initialization but before the value of the variable is needed. 
Detecting that needs complex analysis. You could come up with 
simple cases, but then people will get confused and complain when 
they have a slightly more complex case and it doesn't work.

>, 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.

Not only that, but it would also encourage people to use integer 
types that are slower than optimal for the machine, thus 
producing slow code, as well as making under/overflow more likely.

> 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.

An enum is const, so VRP works exactly the same as a const 
variable.

> 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