[RFC][clang-tidy] misplaced cast that does not prevent loss of precision

Hello!

I am working on a new clang-tidy checker. It will warn when there seems to be a misplaced cast that does not prevent loss of precision.

Example code:

    int SomeInt;
    long x = (long)(SomeInt << 16);

The cast is ineffective and if the developer tried to say that the result needs to be stored in a long there is possible loss of precision.

Code that does not generate warning:

    long x = (long)SomeInt << 16;

I intentionally only warn if the casted value is assigned or returned. Not if it is then used in some calculation.

I try to warn only if it seems that there could be loss of precision in the calculation. Currently I only warn for * << and + results.

I attach a proof of concept patch. Any comments?

The patch generates very few warnings. I have not tested it fully with my scripts yet.. but in ~100 projects analysed so far I only saw these 2 messages:

clang-tidy avfs-1.0.1/src/state.c
state.c:279:16: warning: possible truncation before conversion from 'unsigned int' to 'avino_t' (aka 'unsigned long long') [misc-long-cast]
    buf->ino = (avino_t)((((unsigned int)buf->ino) % (~0U - 1)) + 2);
               ^
state.c:311:16: warning: possible truncation before conversion from 'unsigned int' to 'avino_t' (aka 'unsigned long long') [misc-long-cast]
    buf->ino = (avino_t)((((unsigned int)buf->ino) % (~0U - 1)) + 2);
               ^

These specific warnings are FPs, there can't be loss of precision as far as I see. But I am not sure how I would avoid these FPs.

Best regards,
Daniel Marjamäki

..................................................................................................................
Daniel Marjamäki Senior Engineer
Evidente ES East AB Warfvinges väg 34 SE-112 51 Stockholm Sweden

Mobile: +46 (0)709 12 42 62
E-mail: Daniel.Marjamaki@evidente.se

www.evidente.se