From c3acd2e9c048d5e63436cf775760beab21579801 Mon Sep 17 00:00:00 2001 From: Alexander Kornienko Date: Thu, 23 Mar 2017 15:13:54 +0000 Subject: [PATCH] [clang-tidy] Catch trivially true statements like a != 1 || a != 3 Catch trivially true statements of the form a != 1 || a != 3. Statements like these are likely errors. They are particularly easy to miss when handling enums: enum State { RUNNING, STOPPED, STARTING, ENDING } ... if (state != RUNNING || state != STARTING) ... Patch by Blaise Watson! Differential revision: https://reviews.llvm.org/D29858 llvm-svn: 298607 --- clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp | 5 +++++ clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp index aeaeb63c..901b54c 100644 --- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp @@ -239,6 +239,11 @@ static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS, (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE)) return true; + // Handle cases where constants are different but both ops are !=, like: + // x != 5 || x != 10 + if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE) + return true; + return false; } diff --git a/clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp b/clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp index 8c5e3a4..e865ba0 100644 --- a/clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp +++ b/clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp @@ -321,6 +321,8 @@ int TestRelational(int X, int Y) { // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always true if (X <= 10 || X >= 11) return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always true + if (X != 7 || X != 14) return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always true if (X < 7 && X < 6) return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant @@ -422,6 +424,8 @@ int TestRelatiopnalWithEnum(enum Color C) { // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: logical expression is always false if (C == Red && C != Red) return 1; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: logical expression is always false + if (C != Red || C != Yellow) return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: logical expression is always true // Should not match. if (C == Red || C == Yellow) return 1; -- 2.7.4