-
Notifications
You must be signed in to change notification settings - Fork 14.3k
[clang-tidy] Create a check for signed and unsigned integers comparison #113144
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
171 changes: 171 additions & 0 deletions
171
clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy -------------------===// | ||
// | ||
// 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#include "UseIntegerSignComparisonCheck.h" | ||
#include "clang/AST/Expr.h" | ||
#include "clang/ASTMatchers/ASTMatchFinder.h" | ||
#include "clang/Lex/Lexer.h" | ||
|
||
using namespace clang::ast_matchers; | ||
using namespace clang::ast_matchers::internal; | ||
|
||
namespace clang::tidy::modernize { | ||
|
||
/// Find if the passed type is the actual "char" type, | ||
/// not applicable to explicit "signed char" or "unsigned char" types. | ||
static bool isActualCharType(const clang::QualType &Ty) { | ||
using namespace clang; | ||
const Type *DesugaredType = Ty->getUnqualifiedDesugaredType(); | ||
if (const auto *BT = llvm::dyn_cast<BuiltinType>(DesugaredType)) | ||
return (BT->getKind() == BuiltinType::Char_U || | ||
BT->getKind() == BuiltinType::Char_S); | ||
return false; | ||
} | ||
|
||
namespace { | ||
AST_MATCHER(clang::QualType, isActualChar) { | ||
return clang::tidy::modernize::isActualCharType(Node); | ||
} | ||
} // namespace | ||
|
||
static BindableMatcher<clang::Stmt> | ||
intCastExpression(bool IsSigned, | ||
const std::string &CastBindName = std::string()) { | ||
// std::cmp_{} functions trigger a compile-time error if either LHS or RHS | ||
// is a non-integer type, char, enum or bool | ||
// (unsigned char/ signed char are Ok and can be used). | ||
auto IntTypeExpr = expr(hasType(hasCanonicalType(qualType( | ||
isInteger(), IsSigned ? isSignedInteger() : isUnsignedInteger(), | ||
unless(isActualChar()), unless(booleanType()), unless(enumType()))))); | ||
|
||
const auto ImplicitCastExpr = | ||
CastBindName.empty() ? implicitCastExpr(hasSourceExpression(IntTypeExpr)) | ||
: implicitCastExpr(hasSourceExpression(IntTypeExpr)) | ||
.bind(CastBindName); | ||
|
||
const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr)); | ||
const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr)); | ||
const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr)); | ||
|
||
return expr(anyOf(ImplicitCastExpr, CStyleCastExpr, StaticCastExpr, | ||
FunctionalCastExpr)); | ||
} | ||
|
||
static StringRef parseOpCode(BinaryOperator::Opcode Code) { | ||
switch (Code) { | ||
case BO_LT: | ||
return "cmp_less"; | ||
case BO_GT: | ||
return "cmp_greater"; | ||
case BO_LE: | ||
return "cmp_less_equal"; | ||
case BO_GE: | ||
return "cmp_greater_equal"; | ||
case BO_EQ: | ||
return "cmp_equal"; | ||
case BO_NE: | ||
return "cmp_not_equal"; | ||
default: | ||
return ""; | ||
} | ||
} | ||
|
||
UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck( | ||
StringRef Name, ClangTidyContext *Context) | ||
: ClangTidyCheck(Name, Context), | ||
IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", | ||
utils::IncludeSorter::IS_LLVM), | ||
areDiagsSelfContained()) {} | ||
|
||
void UseIntegerSignComparisonCheck::storeOptions( | ||
ClangTidyOptions::OptionMap &Opts) { | ||
Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle()); | ||
} | ||
|
||
void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) { | ||
const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression"); | ||
const auto UnSignedIntCastExpr = intCastExpression(false); | ||
|
||
// Flag all operators "==", "<=", ">=", "<", ">", "!=" | ||
// that are used between signed/unsigned | ||
const auto CompareOperator = | ||
binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="), | ||
hasOperands(SignedIntCastExpr, UnSignedIntCastExpr), | ||
unless(isInTemplateInstantiation())) | ||
.bind("intComparison"); | ||
|
||
Finder->addMatcher(CompareOperator, this); | ||
} | ||
|
||
void UseIntegerSignComparisonCheck::registerPPCallbacks( | ||
const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) { | ||
IncludeInserter.registerPreprocessor(PP); | ||
} | ||
|
||
void UseIntegerSignComparisonCheck::check( | ||
const MatchFinder::MatchResult &Result) { | ||
const auto *SignedCastExpression = | ||
Result.Nodes.getNodeAs<ImplicitCastExpr>("sIntCastExpression"); | ||
assert(SignedCastExpression); | ||
|
||
// Ignore the match if we know that the signed int value is not negative. | ||
Expr::EvalResult EVResult; | ||
if (!SignedCastExpression->isValueDependent() && | ||
SignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult, | ||
*Result.Context)) { | ||
const llvm::APSInt SValue = EVResult.Val.getInt(); | ||
if (SValue.isNonNegative()) | ||
return; | ||
} | ||
|
||
const auto *BinaryOp = | ||
Result.Nodes.getNodeAs<BinaryOperator>("intComparison"); | ||
if (BinaryOp == nullptr) | ||
return; | ||
|
||
const BinaryOperator::Opcode OpCode = BinaryOp->getOpcode(); | ||
|
||
const Expr *LHS = BinaryOp->getLHS()->IgnoreImpCasts(); | ||
const Expr *RHS = BinaryOp->getRHS()->IgnoreImpCasts(); | ||
if (LHS == nullptr || RHS == nullptr) | ||
return; | ||
const Expr *SubExprLHS = nullptr; | ||
const Expr *SubExprRHS = nullptr; | ||
SourceRange R1 = SourceRange(LHS->getBeginLoc()); | ||
SourceRange R2 = SourceRange(BinaryOp->getOperatorLoc()); | ||
SourceRange R3 = SourceRange(Lexer::getLocForEndOfToken( | ||
RHS->getEndLoc(), 0, *Result.SourceManager, getLangOpts())); | ||
if (const auto *LHSCast = llvm::dyn_cast<ExplicitCastExpr>(LHS)) { | ||
SubExprLHS = LHSCast->getSubExpr(); | ||
R1 = SourceRange(LHS->getBeginLoc(), | ||
SubExprLHS->getBeginLoc().getLocWithOffset(-1)); | ||
R2.setBegin(Lexer::getLocForEndOfToken( | ||
SubExprLHS->getEndLoc(), 0, *Result.SourceManager, getLangOpts())); | ||
} | ||
if (const auto *RHSCast = llvm::dyn_cast<ExplicitCastExpr>(RHS)) { | ||
SubExprRHS = RHSCast->getSubExpr(); | ||
R2.setEnd(SubExprRHS->getBeginLoc().getLocWithOffset(-1)); | ||
} | ||
DiagnosticBuilder Diag = | ||
diag(BinaryOp->getBeginLoc(), | ||
"comparison between 'signed' and 'unsigned' integers"); | ||
const std::string CmpNamespace = ("std::" + parseOpCode(OpCode)).str(); | ||
const std::string CmpHeader = "<utility>"; | ||
// Prefer modernize-use-integer-sign-comparison when C++20 is available! | ||
Diag << FixItHint::CreateReplacement( | ||
CharSourceRange(R1, SubExprLHS != nullptr), | ||
llvm::Twine(CmpNamespace + "(").str()); | ||
Diag << FixItHint::CreateReplacement(R2, ","); | ||
Diag << FixItHint::CreateReplacement(CharSourceRange::getCharRange(R3), ")"); | ||
|
||
// If there is no include for cmp_{*} functions, we'll add it. | ||
Diag << IncludeInserter.createIncludeInsertion( | ||
Result.SourceManager->getFileID(BinaryOp->getBeginLoc()), CmpHeader); | ||
} | ||
|
||
} // namespace clang::tidy::modernize |
42 changes: 42 additions & 0 deletions
42
clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.h
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
//===--- 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 { | ||
|
||
/// Replace comparisons between signed and unsigned integers with their safe | ||
/// C++20 ``std::cmp_*`` alternative, if available. | ||
/// | ||
/// 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.CPlusPlus20; | ||
} | ||
|
||
private: | ||
utils::IncludeInserter IncludeInserter; | ||
}; | ||
|
||
} // namespace clang::tidy::modernize | ||
|
||
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USEINTEGERSIGNCOMPARISONCHECK_H |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
clang-tools-extra/docs/clang-tidy/checks/modernize/use-integer-sign-comparison.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
.. title:: clang-tidy - modernize-use-integer-sign-comparison | ||
|
||
modernize-use-integer-sign-comparison | ||
===================================== | ||
|
||
Replace comparisons between signed and unsigned integers with their safe | ||
C++20 ``std::cmp_*`` alternative, if available. | ||
qt-tatiana marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
qt-tatiana marked this conversation as resolved.
Show resolved
Hide resolved
|
||
The check provides a replacement only for C++20 or later, otherwise | ||
it highlights the problem and expects the user to fix it manually. | ||
|
||
Examples of fixes created by the check: | ||
|
||
.. code-block:: c++ | ||
|
||
unsigned int func(int a, unsigned int b) { | ||
return a == b; | ||
} | ||
|
||
becomes | ||
|
||
.. code-block:: c++ | ||
|
||
#include <utility> | ||
|
||
unsigned int func(int a, unsigned int b) { | ||
return std::cmp_equal(a, b); | ||
} | ||
|
||
Options | ||
------- | ||
qt-tatiana marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. option:: IncludeStyle | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (not for this patch) Sounds like it's about time to move this to the top-level configuration instead of duplicated for every check. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I created #113577. |
||
|
||
A string specifying which include-style is used, `llvm` or `google`. | ||
Default is `llvm`. |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.