[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

Carlos Galvez via cfe-commits cfe-commits at lists.llvm.org
Mon Dec 9 11:14:05 PST 2024


================
@@ -0,0 +1,47 @@
+//===--- UseIntegerSignComparisonCheck.h - clang-tidy -----------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USEINTEGERSIGNCOMPARISONCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USEINTEGERSIGNCOMPARISONCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "../utils/IncludeInserter.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+namespace clang::tidy::modernize {
+
+/// Class detects comparisons between signed and unsigned integers
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-integer-sign-comparison.html
+class UseIntegerSignComparisonCheck : public ClangTidyCheck {
+public:
+  UseIntegerSignComparisonCheck(StringRef Name, ClangTidyContext *Context);
+
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+  void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
+                           Preprocessor *ModuleExpanderPP) override;
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+    return LangOpts.CPlusPlus;
+  }
----------------
carlosgalvezp wrote:

The purpose of `modernize` checks is typically to transform the codebase into a new feature that is more modern (or it's "best practice") and makes the code simpler (that's why all except one have automatic fixes).

If we don't provide a fix, users will do "whatever they can" in pre C++20 to get rid of the warning. The quickest fix is to litter the code with `static_casts`, which is pretty bad because then the problem is silenced and they can't truly modernize their codebase automatically when they do move to C++20 (let alone introduce bugs).

Also, I expect this check to be very noisy in a real-world codebase, not quite fixable manually. 

Besides, "warning on integer comparison" already exists as a warning in Clang (`-Wsign-compare`), so this check would be redundant pre-C++20.


https://github.com/llvm/llvm-project/pull/113144


More information about the cfe-commits mailing list