RFR: 8261669: Add lint warning for widening primitive conversions that lose information

Aggelos Biboudis abimpoudis at openjdk.org
Fri Feb 21 09:59:55 UTC 2025


On Thu, 20 Feb 2025 22:24:01 GMT, Archie Cobbs <acobbs at openjdk.org> wrote:

>> This PR is a prototype to stimulate discussion of [JDK-8261669](https://bugs.openjdk.org/browse/JDK-8261669), which seeks to add more warnings when an implicit cast of a primitive value might lose information. This can possibly happen when converting an `int` to `float`, or when converting a `long` to `float` or `double`. Java does not require an explicit cast for such assignments, even though they may result in information loss.
>> 
>> I'm interested in feedback both on whether this is a good idea and also the approach taken - thanks!
>> 
>> Currently, we generate this warning, but only for assignment operators, e.g.:
>> 
>> int x = 0;
>> x += 1.0f;   // warning here
>> 
>> 
>> This PR would add warnings for two additional cases, (a) regular assignments and (b) method parameters, e.g.:
>> 
>> void method(float f) { }
>> ...
>> float a = 0x10000001;   // warning here
>> method(0x10000001);     // warning here
>> 
>> 
>> It would _not_ generate a warning in cases (a) and (b) when the value is a constant value and we can determine that no information would be lost, e.g.:
>> 
>> float f1 = 0x10000000;     // no warning here
>> 
>> The definition of "no information would be lost" is that a round trip results in the same value, e.g., `(int)(float)x == x`. In the examples above, `0x10000000` survives the round trip but `0x10000001` does not.
>> 
>> As usual, warnings can be suppressed via `@SuppressWarnings` or by adding an explicit cast:
>> 
>> 
>> float a = (float)0x10000001;   // no warning here
>
> Sorry for the mailing list spam - this PR discussion really only belongs on `compiler-dev`, but the bot added the others due to the changes to the corresponding makefile (which add `-Xlint:-lossy-conversions` to suppress the new warnings).
> 
> I'll remove `client`, `core-libs`, `hotspot-jfr` and `serviceability` but feel free to add them back if needed/desired.

@archiecobbs this is excellent work! Thank you for the initiative and the patch which was on the right direction to address this issue.

There are several reasons that it would be ideal to hold this PR off, for now. There is an ongoing effort to study conversions and contexts holistically in Java and possibly regularizing various contexts across the board.

That study will build upon the implementation (and terminology) realised by JEP 488 regarding exact and lossy conversions which might well include the warnings contained in your PR. 

I am re-assigning this to me on JBS and I will link back to it when the new JBS ticket is created.

-------------

PR Comment: https://git.openjdk.org/jdk/pull/23718#issuecomment-2674096146


More information about the build-dev mailing list