llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.52k stars 11.79k forks source link

Clang should warn about chained comparisons like `a > b > c` #60256

Open zmodem opened 1 year ago

zmodem commented 1 year ago

We had this = vs. == bug in Chromium recently:

int f(int);
int g(int a) {
  a == f(a) > 1 ? 1 : f(a);
  // stuff
}

In most cases, Clang would catch a = vs == bug with -Wunused-comparison, but in this case the unintentional comparison became an operand to the ternary operator, and no warning fired.

Perhaps there should be warning for the general case of "chained comparisons" that would catch the above as well as code like:

void h(int a, int b, int c) {
  if (a > b > c) {
    // stuff...
  }
}
hazohelet commented 1 year ago

Let me work on this issue. I guess the change for this would be to add a new warning flag within -Wparentheses that detects comparison operators within comparison operators, just like '&&' within '||'.

tbaederr commented 1 year ago

I can't find the revision in phab, but does this also fix https://github.com/llvm/llvm-project/issues/31470 ?

hazohelet commented 1 year ago

This is the differential I made some time ago. https://reviews.llvm.org/D142800

I intend to fix that issue as well.