dlang-community / D-Scanner

Swiss-army knife for D source code
Boost Software License 1.0
242 stars 80 forks source link

Warn about negating unsigned (uint/ulong etc) #891

Open HuskyNator opened 1 year ago

HuskyNator commented 1 year ago

Warn when an unsigned value is negated. Example from a bug I had:

uint size = 5u;
uint offset = -size // 4294967291
int offset = -size; // -5
float offset = -size; // 4.29497e+09
float offset = -5u; // Error: cannot implicitly convert expression `4294967291u` of type `uint` to `float`

Unsigned arithmetic is full of pitfalls. Even checked casts seem inconsistent.

uint(-5u); // 4294967291;
int(-5u); // -5;
int(4294967291) // Error: cannot implicitly convert expression `4294967291L` of type `long` to `int`
int(4294967291u) // -5;

I'm not even sure why this happens when using this way of casting:

uint a = -5u; // 4294967291
float(-a); // 4.29497e+09
float(-5u); // Error: cannot implicitly convert expression `4294967291u` of type `uint` to `float`
cast(float) -5u // 4.29497e+09