Skip to content

Commit be7d633

Browse files
bruntibAaronBallman
authored andcommitted
Magic number checker shouldn't warn on user defined string literals
Fixes a false positive brought up by PR40633.
1 parent 29f0a65 commit be7d633

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -122,10 +122,21 @@ bool MagicNumbersCheck::isConstant(const MatchFinder::MatchResult &Result,
122122
return llvm::any_of(
123123
Result.Context->getParents(ExprResult),
124124
[&Result](const DynTypedNode &Parent) {
125-
return isUsedToInitializeAConstant(Result, Parent) ||
126-
// Ignore this instance, because this match reports the location
127-
// where the template is defined, not where it is instantiated.
128-
Parent.get<SubstNonTypeTemplateParmExpr>();
125+
if (isUsedToInitializeAConstant(Result, Parent))
126+
return true;
127+
128+
// Ignore this instance, because this match reports the location
129+
// where the template is defined, not where it is instantiated.
130+
if (Parent.get<SubstNonTypeTemplateParmExpr>())
131+
return true;
132+
133+
// Don't warn on string user defined literals:
134+
// std::string s = "Hello World"s;
135+
if (const auto *UDL = Parent.get<UserDefinedLiteral>())
136+
if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String)
137+
return true;
138+
139+
return false;
129140
});
130141
}
131142

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// RUN: %check_clang_tidy -std=c++14-or-later %s readability-magic-numbers %t --
2+
3+
namespace std {
4+
class string {};
5+
using size_t = decltype(sizeof(int));
6+
string operator ""s(const char *, std::size_t);
7+
int operator "" s(unsigned long long);
8+
}
9+
10+
void UserDefinedLiteral() {
11+
using std::operator ""s;
12+
"Hello World"s;
13+
const int i = 3600s;
14+
int j = 3600s;
15+
// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3600s is a magic number; consider replacing it with a named constant [readability-magic-numbers]
16+
}

0 commit comments

Comments
 (0)