1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
|
//===--- MakeMemberFunctionConstCheck.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 "MakeMemberFunctionConstCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ParentMapContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace readability {
AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }
AST_MATCHER(CXXMethodDecl, hasTrivialBody) { return Node.hasTrivialBody(); }
AST_MATCHER(CXXRecordDecl, hasAnyDependentBases) {
return Node.hasAnyDependentBases();
}
AST_MATCHER(CXXMethodDecl, isTemplate) {
return Node.getTemplatedKind() != FunctionDecl::TK_NonTemplate;
}
AST_MATCHER(CXXMethodDecl, isDependentContext) {
return Node.isDependentContext();
}
AST_MATCHER(CXXMethodDecl, isInsideMacroDefinition) {
const ASTContext &Ctxt = Finder->getASTContext();
return clang::Lexer::makeFileCharRange(
clang::CharSourceRange::getCharRange(
Node.getTypeSourceInfo()->getTypeLoc().getSourceRange()),
Ctxt.getSourceManager(), Ctxt.getLangOpts())
.isInvalid();
}
AST_MATCHER_P(CXXMethodDecl, hasCanonicalDecl,
ast_matchers::internal::Matcher<CXXMethodDecl>, InnerMatcher) {
return InnerMatcher.matches(*Node.getCanonicalDecl(), Finder, Builder);
}
enum UsageKind { Unused, Const, NonConst };
class FindUsageOfThis : public RecursiveASTVisitor<FindUsageOfThis> {
ASTContext &Ctxt;
public:
FindUsageOfThis(ASTContext &Ctxt) : Ctxt(Ctxt) {}
UsageKind Usage = Unused;
template <class T> const T *getParent(const Expr *E) {
DynTypedNodeList Parents = Ctxt.getParents(*E);
if (Parents.size() != 1)
return nullptr;
return Parents.begin()->get<T>();
}
bool VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *) {
// An UnresolvedMemberExpr might resolve to a non-const non-static
// member function.
Usage = NonConst;
return false; // Stop traversal.
}
bool VisitCXXConstCastExpr(const CXXConstCastExpr *) {
// Workaround to support the pattern
// class C {
// const S *get() const;
// S* get() {
// return const_cast<S*>(const_cast<const C*>(this)->get());
// }
// };
// Here, we don't want to make the second 'get' const even though
// it only calls a const member function on this.
Usage = NonConst;
return false; // Stop traversal.
}
// Our AST is
// `-ImplicitCastExpr
// (possibly `-UnaryOperator Deref)
// `-CXXThisExpr 'S *' this
bool visitUser(const ImplicitCastExpr *Cast) {
if (Cast->getCastKind() != CK_NoOp)
return false; // Stop traversal.
// Only allow NoOp cast to 'const S' or 'const S *'.
QualType QT = Cast->getType();
if (QT->isPointerType())
QT = QT->getPointeeType();
if (!QT.isConstQualified())
return false; // Stop traversal.
const auto *Parent = getParent<Stmt>(Cast);
if (!Parent)
return false; // Stop traversal.
if (isa<ReturnStmt>(Parent))
return true; // return (const S*)this;
if (isa<CallExpr>(Parent))
return true; // use((const S*)this);
// ((const S*)this)->Member
if (const auto *Member = dyn_cast<MemberExpr>(Parent))
return visitUser(Member, /*OnConstObject=*/true);
return false; // Stop traversal.
}
// If OnConstObject is true, then this is a MemberExpr using
// a constant this, i.e. 'const S' or 'const S *'.
bool visitUser(const MemberExpr *Member, bool OnConstObject) {
if (Member->isBoundMemberFunction(Ctxt)) {
if (!OnConstObject || Member->getFoundDecl().getAccess() != AS_public) {
// Non-public non-static member functions might not preserve the
// logical constness. E.g. in
// class C {
// int &data() const;
// public:
// int &get() { return data(); }
// };
// get() uses a private const method, but must not be made const
// itself.
return false; // Stop traversal.
}
// Using a public non-static const member function.
return true;
}
const auto *Parent = getParent<Expr>(Member);
if (const auto *Cast = dyn_cast_or_null<ImplicitCastExpr>(Parent)) {
// A read access to a member is safe when the member either
// 1) has builtin type (a 'const int' cannot be modified),
// 2) or it's a public member (the pointee of a public 'int * const' can
// can be modified by any user of the class).
if (Member->getFoundDecl().getAccess() != AS_public &&
!Cast->getType()->isBuiltinType())
return false;
if (Cast->getCastKind() == CK_LValueToRValue)
return true;
if (Cast->getCastKind() == CK_NoOp && Cast->getType().isConstQualified())
return true;
}
if (const auto *M = dyn_cast_or_null<MemberExpr>(Parent))
return visitUser(M, /*OnConstObject=*/false);
return false; // Stop traversal.
}
bool VisitCXXThisExpr(const CXXThisExpr *E) {
Usage = Const;
const auto *Parent = getParent<Expr>(E);
// Look through deref of this.
if (const auto *UnOp = dyn_cast_or_null<UnaryOperator>(Parent)) {
if (UnOp->getOpcode() == UO_Deref) {
Parent = getParent<Expr>(UnOp);
}
}
// It's okay to
// return (const S*)this;
// use((const S*)this);
// ((const S*)this)->f()
// when 'f' is a public member function.
if (const auto *Cast = dyn_cast_or_null<ImplicitCastExpr>(Parent)) {
if (visitUser(Cast))
return true;
// And it's also okay to
// (const T)(S->t)
// (LValueToRValue)(S->t)
// when 't' is either of builtin type or a public member.
} else if (const auto *Member = dyn_cast_or_null<MemberExpr>(Parent)) {
if (visitUser(Member, /*OnConstObject=*/false))
return true;
}
// Unknown user of this.
Usage = NonConst;
return false; // Stop traversal.
}
};
AST_MATCHER(CXXMethodDecl, usesThisAsConst) {
FindUsageOfThis UsageOfThis(Finder->getASTContext());
// TraverseStmt does not modify its argument.
UsageOfThis.TraverseStmt(const_cast<Stmt *>(Node.getBody()));
return UsageOfThis.Usage == Const;
}
void MakeMemberFunctionConstCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(
traverse(
TK_AsIs,
cxxMethodDecl(
isDefinition(), isUserProvided(),
unless(anyOf(
isExpansionInSystemHeader(), isVirtual(), isConst(),
isStatic(), hasTrivialBody(), cxxConstructorDecl(),
cxxDestructorDecl(), isTemplate(), isDependentContext(),
ofClass(anyOf(isLambda(),
hasAnyDependentBases()) // Method might become
// virtual depending on
// template base class.
),
isInsideMacroDefinition(),
hasCanonicalDecl(isInsideMacroDefinition()))),
usesThisAsConst())
.bind("x")),
this);
}
static SourceLocation getConstInsertionPoint(const CXXMethodDecl *M) {
TypeSourceInfo *TSI = M->getTypeSourceInfo();
if (!TSI)
return {};
FunctionTypeLoc FTL =
TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
if (!FTL)
return {};
return FTL.getRParenLoc().getLocWithOffset(1);
}
void MakeMemberFunctionConstCheck::check(
const MatchFinder::MatchResult &Result) {
const auto *Definition = Result.Nodes.getNodeAs<CXXMethodDecl>("x");
const auto *Declaration = Definition->getCanonicalDecl();
auto Diag = diag(Definition->getLocation(), "method %0 can be made const")
<< Definition
<< FixItHint::CreateInsertion(getConstInsertionPoint(Definition),
" const");
if (Declaration != Definition) {
Diag << FixItHint::CreateInsertion(getConstInsertionPoint(Declaration),
" const");
}
}
} // namespace readability
} // namespace tidy
} // namespace clang
|