Why does intpromote spew warnings for ~ operator?

Steven Schveighoffer schveiguy at gmail.com
Mon Sep 13 21:47:03 UTC 2021


On 9/13/21 5:03 PM, Guillaume Piolat wrote:
> On Sunday, 12 September 2021 at 14:14:03 UTC, Steven Schveighoffer wrote:
>> With the -preview=intpromote switch, the uncasted negation compiles 
>> and runs as expected.
>>
>> Right now, the deprecation is telling users under penalty of not 
>> compiling to do something that will achieve nothing when intpromote is 
>> enabled.
> 
> What is achieve is that people can review the place where -x and ~x were 
> used, and see if there was bug there ; because it is a real possibility 
> that C code was ported and then it has a different semantics.

Why should I review all uses, when the compiler can trivially prove it's 
fine for most of them, and warn on the cases that will need attention? 
It already doesn't warn for ~int or -int, so it's not just usage of that 
operator that is problematic, but specific uses.

Note that D already does the right thing for all the code I've pointed 
out here.

> 
> The end game of it is:
> 
>     A. "when you paste C code and it builds then it's the same"
> 
> instead of:
> 
>     B. "when you paste C code and it builds then it's the same, EXCEPT 
> -x and ~x who don't promote their operand to int"

C allows assigning ints to shorts. When you have:

```d
short x = -y;
```

It's exactly the same as C. There's no reason to deprecate this. When 
you build without using intpromote, it does what C does. When you build 
using intpromote, you have to cast to a short, which.... does what C does.

> when people of the future come to D in 2030 they will enjoy the 
> proposition A instead of B.

It all depends on if your opinion is that when you paste C code, it 
shouldn't compile. Because basically that's what's happening here.

D gets away with requiring a cast here or there without being annoying, 
because VRP takes care of many cases, and op= cases work even though the 
written out form would not. But that won't be true here, and I can say 
there's probably a decent chunk of bit manipulation with ushorts.

I'd propose that:

1. In cases where the behavior is already the same as C, and would not 
require casts after intpromote is enabled, do not warn.
2. In cases where a type is being assigned to the negation of the same 
type, do not require a cast, and do not warn.
3. In cases where the behavior is NOT the same as C, issue a warning and 
corrective action recommendation (i.e. either `~cast(int)(val)` to get 
rid of the warning and accept new behavior, or `cast(ushort)~(val)` to 
keep existing behavior).

I honestly don't think casts should be necessary anywhere they aren't 
already required after intpromote is enabled.

This would achieve your goal (warn people so they can inspect 
problematic cases) without ruining most valid code.

-Steve


More information about the Digitalmars-d mailing list