Skip to content

Commit 4d60b54

Browse files
committed
[clang-tidy] Add new check readability-use-numeric-limits
1 parent 5676478 commit 4d60b54

File tree

8 files changed

+338
-0
lines changed

8 files changed

+338
-0
lines changed

clang-tools-extra/clang-tidy/readability/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ add_clang_library(clangTidyReadabilityModule STATIC
5858
UniqueptrDeleteReleaseCheck.cpp
5959
UppercaseLiteralSuffixCheck.cpp
6060
UseAnyOfAllOfCheck.cpp
61+
UseNumericLimitsCheck.cpp
6162
UseStdMinMaxCheck.cpp
6263

6364
LINK_LIBS

clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
#include "UniqueptrDeleteReleaseCheck.h"
6262
#include "UppercaseLiteralSuffixCheck.h"
6363
#include "UseAnyOfAllOfCheck.h"
64+
#include "UseNumericLimitsCheck.h"
6465
#include "UseStdMinMaxCheck.h"
6566

6667
namespace clang::tidy {
@@ -173,6 +174,8 @@ class ReadabilityModule : public ClangTidyModule {
173174
"readability-uppercase-literal-suffix");
174175
CheckFactories.registerCheck<UseAnyOfAllOfCheck>(
175176
"readability-use-anyofallof");
177+
CheckFactories.registerCheck<UseNumericLimitsCheck>(
178+
"readability-use-numeric-limits");
176179
CheckFactories.registerCheck<UseStdMinMaxCheck>(
177180
"readability-use-std-min-max");
178181
}
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
//===--- UseNumericLimitsCheck.cpp - clang-tidy ---------------------------===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
9+
#include "UseNumericLimitsCheck.h"
10+
#include "clang/AST/ASTContext.h"
11+
#include "clang/ASTMatchers/ASTMatchFinder.h"
12+
#include "clang/Lex/Preprocessor.h"
13+
#include <cmath>
14+
#include <limits>
15+
16+
using namespace clang::ast_matchers;
17+
18+
namespace clang::tidy::readability {
19+
20+
UseNumericLimitsCheck::UseNumericLimitsCheck(StringRef Name,
21+
ClangTidyContext *Context)
22+
: ClangTidyCheck(Name, Context),
23+
SignedConstants{
24+
{std::numeric_limits<int8_t>::min(),
25+
"std::numeric_limits<int8_t>::min()"},
26+
{std::numeric_limits<int8_t>::max(),
27+
"std::numeric_limits<int8_t>::max()"},
28+
{std::numeric_limits<int16_t>::min(),
29+
"std::numeric_limits<int16_t>::min()"},
30+
{std::numeric_limits<int16_t>::max(),
31+
"std::numeric_limits<int16_t>::max()"},
32+
{std::numeric_limits<int32_t>::min(),
33+
"std::numeric_limits<int32_t>::min()"},
34+
{std::numeric_limits<int32_t>::max(),
35+
"std::numeric_limits<int32_t>::max()"},
36+
{std::numeric_limits<int64_t>::min(),
37+
"std::numeric_limits<int64_t>::min()"},
38+
{std::numeric_limits<int64_t>::max(),
39+
"std::numeric_limits<int64_t>::max()"},
40+
},
41+
UnsignedConstants{
42+
{std::numeric_limits<uint8_t>::max(),
43+
"std::numeric_limits<uint8_t>::max()"},
44+
{std::numeric_limits<uint16_t>::max(),
45+
"std::numeric_limits<uint16_t>::max()"},
46+
{std::numeric_limits<uint32_t>::max(),
47+
"std::numeric_limits<uint32_t>::max()"},
48+
{std::numeric_limits<uint64_t>::max(),
49+
"std::numeric_limits<uint64_t>::max()"},
50+
},
51+
Inserter(Options.getLocalOrGlobal("IncludeStyle",
52+
utils::IncludeSorter::IS_LLVM),
53+
areDiagsSelfContained()) {}
54+
55+
void UseNumericLimitsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
56+
Options.store(Opts, "IncludeStyle", Inserter.getStyle());
57+
}
58+
59+
void UseNumericLimitsCheck::registerMatchers(MatchFinder *Finder) {
60+
auto PositiveIntegerMatcher = [](auto Value) {
61+
return unaryOperator(hasOperatorName("+"),
62+
hasUnaryOperand(integerLiteral(equals(Value))
63+
.bind("positive-integer-literal")))
64+
.bind("unary-op");
65+
};
66+
67+
auto NegativeIntegerMatcher = [](auto Value) {
68+
return unaryOperator(hasOperatorName("-"),
69+
hasUnaryOperand(integerLiteral(equals(-Value))
70+
.bind("negative-integer-literal")))
71+
.bind("unary-op");
72+
};
73+
74+
auto BareIntegerMatcher = [](auto Value) {
75+
return integerLiteral(allOf(unless(hasParent(unaryOperator(
76+
hasAnyOperatorName("-", "+")))),
77+
equals(Value)))
78+
.bind("bare-integer-literal");
79+
};
80+
81+
for (const auto &[Value, _] : SignedConstants) {
82+
if (Value < 0) {
83+
Finder->addMatcher(NegativeIntegerMatcher(Value), this);
84+
} else {
85+
Finder->addMatcher(
86+
expr(anyOf(PositiveIntegerMatcher(Value), BareIntegerMatcher(Value))),
87+
this);
88+
}
89+
}
90+
91+
for (const auto &[Value, _] : UnsignedConstants) {
92+
Finder->addMatcher(
93+
expr(anyOf(PositiveIntegerMatcher(Value), BareIntegerMatcher(Value))),
94+
this);
95+
}
96+
}
97+
98+
void UseNumericLimitsCheck::registerPPCallbacks(
99+
const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
100+
Inserter.registerPreprocessor(PP);
101+
}
102+
103+
void UseNumericLimitsCheck::check(const MatchFinder::MatchResult &Result) {
104+
const IntegerLiteral *MatchedDecl = nullptr;
105+
106+
const IntegerLiteral *NegativeMatchedDecl =
107+
Result.Nodes.getNodeAs<IntegerLiteral>("negative-integer-literal");
108+
const IntegerLiteral *PositiveMatchedDecl =
109+
Result.Nodes.getNodeAs<IntegerLiteral>("positive-integer-literal");
110+
const IntegerLiteral *BareMatchedDecl =
111+
Result.Nodes.getNodeAs<IntegerLiteral>("bare-integer-literal");
112+
113+
if (NegativeMatchedDecl != nullptr) {
114+
MatchedDecl = NegativeMatchedDecl;
115+
} else if (PositiveMatchedDecl != nullptr) {
116+
MatchedDecl = PositiveMatchedDecl;
117+
} else if (BareMatchedDecl != nullptr) {
118+
MatchedDecl = BareMatchedDecl;
119+
}
120+
121+
const llvm::APInt MatchedIntegerConstant = MatchedDecl->getValue();
122+
123+
auto Fixer = [&](auto SourceValue, auto Value,
124+
const std::string &Replacement) {
125+
static_assert(std::is_same_v<decltype(SourceValue), decltype(Value)>,
126+
"The types of SourceValue and Value must match");
127+
128+
SourceLocation Location = MatchedDecl->getExprLoc();
129+
SourceRange Range{MatchedDecl->getBeginLoc(), MatchedDecl->getEndLoc()};
130+
131+
// Only valid if unary operator is present
132+
const UnaryOperator *UnaryOpExpr =
133+
Result.Nodes.getNodeAs<UnaryOperator>("unary-op");
134+
135+
if (MatchedDecl == NegativeMatchedDecl && -SourceValue == Value) {
136+
Range = SourceRange(UnaryOpExpr->getBeginLoc(), UnaryOpExpr->getEndLoc());
137+
Location = UnaryOpExpr->getExprLoc();
138+
SourceValue = -SourceValue;
139+
} else if (MatchedDecl == PositiveMatchedDecl && SourceValue == Value) {
140+
Range = SourceRange(UnaryOpExpr->getBeginLoc(), UnaryOpExpr->getEndLoc());
141+
Location = UnaryOpExpr->getExprLoc();
142+
} else if (MatchedDecl != BareMatchedDecl || SourceValue != Value) {
143+
return;
144+
}
145+
146+
diag(Location,
147+
"The constant %0 is being utilized. Consider using %1 instead")
148+
<< std::to_string(SourceValue) << Replacement
149+
<< FixItHint::CreateReplacement(Range, Replacement)
150+
<< Inserter.createIncludeInsertion(
151+
Result.SourceManager->getFileID(Location), "<limits>");
152+
};
153+
154+
for (const auto &[Value, Replacement] : SignedConstants) {
155+
Fixer(MatchedIntegerConstant.getSExtValue(), Value, Replacement);
156+
}
157+
158+
for (const auto &[Value, Replacement] : UnsignedConstants) {
159+
Fixer(MatchedIntegerConstant.getZExtValue(), Value, Replacement);
160+
}
161+
}
162+
163+
} // namespace clang::tidy::readability
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//===--- UseNumericLimitsCheck.h - clang-tidy -------------------*- C++ -*-===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
9+
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_USENUMERICLIMITSCHECK_H
10+
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_USENUMERICLIMITSCHECK_H
11+
12+
#include "../ClangTidyCheck.h"
13+
#include "../utils/IncludeInserter.h"
14+
15+
namespace clang::tidy::readability {
16+
17+
/// Replaces certain integer literals with equivalent calls to
18+
/// ``std::numeric_limits``.
19+
/// For the user-facing documentation see:
20+
/// http://clang.llvm.org/extra/clang-tidy/checks/readability/use-numeric-limits.html
21+
class UseNumericLimitsCheck : public ClangTidyCheck {
22+
public:
23+
UseNumericLimitsCheck(StringRef Name, ClangTidyContext *Context);
24+
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
25+
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
26+
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
27+
Preprocessor *ModuleExpanderPP) override;
28+
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
29+
30+
private:
31+
const llvm::SmallVector<std::pair<int64_t, std::string>> SignedConstants;
32+
const llvm::SmallVector<std::pair<uint64_t, std::string>> UnsignedConstants;
33+
utils::IncludeInserter Inserter;
34+
};
35+
36+
} // namespace clang::tidy::readability
37+
38+
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_USENUMERICLIMITSCHECK_H

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,13 @@ Improvements to clang-tidy
117117
New checks
118118
^^^^^^^^^^
119119

120+
- New :doc:`readability-use-numeric-limits
121+
<clang-tidy/checks/readability/use-numeric-limits>` check.
122+
123+
Replaces certain integer literals with equivalent calls to
124+
``std::numeric_limits<T>::min()`` or ``std::numeric_limits<T>::max()``.
125+
126+
120127
- New :doc:`bugprone-capturing-this-in-member-variable
121128
<clang-tidy/checks/bugprone/capturing-this-in-member-variable>` check.
122129

@@ -148,6 +155,10 @@ New checks
148155
Finds potentially erroneous calls to ``reset`` method on smart pointers when
149156
the pointee type also has a ``reset`` method.
150157

158+
- New :doc:`readability-use-numeric-limits
159+
<clang-tidy/checks/readability/use-numeric-limits>` check to replace certain
160+
integer literals with ``std::numeric_limits`` calls.
161+
151162
New check aliases
152163
^^^^^^^^^^^^^^^^^
153164

clang-tools-extra/docs/clang-tidy/checks/list.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,7 @@ Clang-Tidy Checks
408408
:doc:`readability-uniqueptr-delete-release <readability/uniqueptr-delete-release>`, "Yes"
409409
:doc:`readability-uppercase-literal-suffix <readability/uppercase-literal-suffix>`, "Yes"
410410
:doc:`readability-use-anyofallof <readability/use-anyofallof>`,
411+
:doc:`readability-use-numeric-limits <readability/use-numeric-limits>`, "Yes"
411412
:doc:`readability-use-std-min-max <readability/use-std-min-max>`, "Yes"
412413
:doc:`zircon-temporary-objects <zircon/temporary-objects>`,
413414

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
.. title:: clang-tidy - readability-use-numeric-limits
2+
3+
readability-use-numeric-limits
4+
==============================
5+
6+
Replaces certain integer literals with equivalent calls to
7+
``std::numeric_limits<T>::min()`` or ``std::numeric_limits<T>::max()``.
8+
9+
Before:
10+
11+
.. code-block:: c++
12+
13+
void foo() {
14+
int32_t a = 2147483647;
15+
}
16+
17+
After:
18+
19+
.. code-block:: c++
20+
21+
void foo() {
22+
int32_t a = std::numeric_limits<int32_t>::max();
23+
}
24+
25+
Options
26+
-------
27+
28+
.. option:: IncludeStyle
29+
30+
A string specifying which include-style is used, `llvm` or `google`. Default
31+
is `llvm`.
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// RUN: %check_clang_tidy %s readability-use-numeric-limits %t
2+
#include <stdint.h>
3+
4+
void Invalid() {
5+
// CHECK-MESSAGES: :[[@LINE+2]]:14: warning: The constant -128 is being utilized. Consider using std::numeric_limits<int8_t>::min() instead [readability-use-numeric-limits]
6+
// CHECK-FIXES: int8_t a = std::numeric_limits<int8_t>::min();
7+
int8_t a = -128;
8+
9+
// CHECK-MESSAGES: :[[@LINE+2]]:14: warning: The constant 127 is being utilized. Consider using std::numeric_limits<int8_t>::max() instead [readability-use-numeric-limits]
10+
// CHECK-FIXES: int8_t b = std::numeric_limits<int8_t>::max();
11+
int8_t b = +127;
12+
13+
// CHECK-MESSAGES: :[[@LINE+2]]:14: warning: The constant 127 is being utilized. Consider using std::numeric_limits<int8_t>::max() instead [readability-use-numeric-limits]
14+
// CHECK-FIXES: int8_t c = std::numeric_limits<int8_t>::max();
15+
int8_t c = 127;
16+
17+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant -32768 is being utilized. Consider using std::numeric_limits<int16_t>::min() instead [readability-use-numeric-limits]
18+
// CHECK-FIXES: int16_t d = std::numeric_limits<int16_t>::min();
19+
int16_t d = -32768;
20+
21+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 32767 is being utilized. Consider using std::numeric_limits<int16_t>::max() instead [readability-use-numeric-limits]
22+
// CHECK-FIXES: int16_t e = std::numeric_limits<int16_t>::max();
23+
int16_t e = +32767;
24+
25+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 32767 is being utilized. Consider using std::numeric_limits<int16_t>::max() instead [readability-use-numeric-limits]
26+
// CHECK-FIXES: int16_t f = std::numeric_limits<int16_t>::max();
27+
int16_t f = 32767;
28+
29+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant -2147483648 is being utilized. Consider using std::numeric_limits<int32_t>::min() instead [readability-use-numeric-limits]
30+
// CHECK-FIXES: int32_t g = std::numeric_limits<int32_t>::min();
31+
int32_t g = -2147483648;
32+
33+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 2147483647 is being utilized. Consider using std::numeric_limits<int32_t>::max() instead [readability-use-numeric-limits]
34+
// CHECK-FIXES: int32_t h = std::numeric_limits<int32_t>::max();
35+
int32_t h = +2147483647;
36+
37+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 2147483647 is being utilized. Consider using std::numeric_limits<int32_t>::max() instead [readability-use-numeric-limits]
38+
// CHECK-FIXES: int32_t i = std::numeric_limits<int32_t>::max();
39+
int32_t i = 2147483647;
40+
41+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant -9223372036854775808 is being utilized. Consider using std::numeric_limits<int64_t>::min() instead [readability-use-numeric-limits]
42+
// CHECK-FIXES: int64_t j = std::numeric_limits<int64_t>::min();
43+
int64_t j = -9223372036854775808;
44+
45+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 9223372036854775807 is being utilized. Consider using std::numeric_limits<int64_t>::max() instead [readability-use-numeric-limits]
46+
// CHECK-FIXES: int64_t k = std::numeric_limits<int64_t>::max();
47+
int64_t k = +9223372036854775807;
48+
49+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 9223372036854775807 is being utilized. Consider using std::numeric_limits<int64_t>::max() instead [readability-use-numeric-limits]
50+
// CHECK-FIXES: int64_t l = std::numeric_limits<int64_t>::max();
51+
int64_t l = 9223372036854775807;
52+
53+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 255 is being utilized. Consider using std::numeric_limits<uint8_t>::max() instead [readability-use-numeric-limits]
54+
// CHECK-FIXES: uint8_t m = std::numeric_limits<uint8_t>::max();
55+
uint8_t m = 255;
56+
57+
// CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 255 is being utilized. Consider using std::numeric_limits<uint8_t>::max() instead [readability-use-numeric-limits]
58+
// CHECK-FIXES: uint8_t n = std::numeric_limits<uint8_t>::max();
59+
uint8_t n = +255;
60+
61+
// CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 65535 is being utilized. Consider using std::numeric_limits<uint16_t>::max() instead [readability-use-numeric-limits]
62+
// CHECK-FIXES: uint16_t o = std::numeric_limits<uint16_t>::max();
63+
uint16_t o = 65535;
64+
65+
// CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 65535 is being utilized. Consider using std::numeric_limits<uint16_t>::max() instead [readability-use-numeric-limits]
66+
// CHECK-FIXES: uint16_t p = std::numeric_limits<uint16_t>::max();
67+
uint16_t p = +65535;
68+
69+
// CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 4294967295 is being utilized. Consider using std::numeric_limits<uint32_t>::max() instead [readability-use-numeric-limits]
70+
// CHECK-FIXES: uint32_t q = std::numeric_limits<uint32_t>::max();
71+
uint32_t q = 4294967295;
72+
73+
// CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 4294967295 is being utilized. Consider using std::numeric_limits<uint32_t>::max() instead [readability-use-numeric-limits]
74+
// CHECK-FIXES: uint32_t r = std::numeric_limits<uint32_t>::max();
75+
uint32_t r = +4294967295;
76+
77+
// CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 18446744073709551615 is being utilized. Consider using std::numeric_limits<uint64_t>::max() instead [readability-use-numeric-limits]
78+
// CHECK-FIXES: uint64_t s = std::numeric_limits<uint64_t>::max();
79+
uint64_t s = 18446744073709551615;
80+
81+
// CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 18446744073709551615 is being utilized. Consider using std::numeric_limits<uint64_t>::max() instead [readability-use-numeric-limits]
82+
// CHECK-FIXES: uint64_t t = std::numeric_limits<uint64_t>::max();
83+
uint64_t t = +18446744073709551615;
84+
}
85+
86+
void Valid(){
87+
int16_t a = +128;
88+
89+
int16_t b = -127;
90+
}

0 commit comments

Comments
 (0)