clang-tools 24.0.0git
ConvertMemberFunctionsToStaticCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "../utils/Matchers.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/DeclCXX.h"
13#include "clang/AST/RecursiveASTVisitor.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15#include "clang/Basic/SourceLocation.h"
16#include "clang/Lex/Lexer.h"
17
18using namespace clang::ast_matchers;
19using namespace clang::tidy::matchers;
20
22
23namespace {
24
25AST_MATCHER(CXXMethodDecl, hasTrivialBody) { return Node.hasTrivialBody(); }
26
27AST_MATCHER(CXXRecordDecl, hasAnyDependentBases) {
28 return Node.hasAnyDependentBases();
29}
30
31AST_MATCHER(CXXMethodDecl, isTemplate) {
32 return Node.getTemplatedKind() != FunctionDecl::TK_NonTemplate;
33}
34
35AST_MATCHER(CXXMethodDecl, isDependentContext) {
36 return Node.isDependentContext();
37}
38
39AST_MATCHER(CXXMethodDecl, isInsideMacroDefinition) {
40 const ASTContext &Ctxt = Finder->getASTContext();
41 return Lexer::makeFileCharRange(
42 CharSourceRange::getCharRange(
43 Node.getTypeSourceInfo()->getTypeLoc().getSourceRange()),
44 Ctxt.getSourceManager(), Ctxt.getLangOpts())
45 .isInvalid();
46}
47
48AST_MATCHER_P(CXXMethodDecl, hasCanonicalDecl,
49 ast_matchers::internal::Matcher<CXXMethodDecl>, InnerMatcher) {
50 return InnerMatcher.matches(*Node.getCanonicalDecl(), Finder, Builder);
51}
52
53AST_MATCHER(CXXMethodDecl, usesThis) {
54 class FindUsageOfThis : public RecursiveASTVisitor<FindUsageOfThis> {
55 public:
56 bool Used = false;
57
58 bool VisitCXXThisExpr(const CXXThisExpr *E) {
59 Used = true;
60 return false; // Stop traversal.
61 }
62
63 bool VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *E) {
64 if (E->isImplicitAccess()) {
65 Used = true;
66 return false;
67 }
68 return true; // Continue traversal.
69 }
70
71 // If we enter a class declaration, don't traverse into it as any usages of
72 // `this` will correspond to the nested class.
73 bool TraverseCXXRecordDecl(CXXRecordDecl *RD) { return true; }
74
75 } UsageOfThis;
76
77 // TraverseStmt does not modify its argument.
78 UsageOfThis.TraverseStmt(Node.getBody());
79
80 return UsageOfThis.Used;
81}
82
83AST_MATCHER(CXXMethodDecl, hasNonConstOverload) {
84 const auto *Method = &Node;
85 const DeclContext::lookup_result LookupResult =
86 Method->getParent()->lookup(Method->getNameInfo().getName());
87 if (LookupResult.isSingleResult())
88 return false;
89
90 const auto HasSameParameterTypes = [](const CXXMethodDecl &MD1,
91 const CXXMethodDecl &MD2) {
92 if (MD1.getNumParams() != MD2.getNumParams())
93 return false;
94 for (unsigned I = 0, E = MD1.getNumParams(); I < E; ++I)
95 if (MD1.getParamDecl(I)->getType().getCanonicalType() !=
96 MD2.getParamDecl(I)->getType().getCanonicalType())
97 return false;
98 return true;
99 };
100
101 return llvm::any_of(
102 LookupResult, [Method, HasSameParameterTypes](const Decl *D) {
103 const auto *Overload = dyn_cast<CXXMethodDecl>(D);
104 return Overload && Overload != Method && !Overload->isConst() &&
105 HasSameParameterTypes(*Method, *Overload);
106 });
107}
108} // namespace
109
111 MatchFinder *Finder) {
112 Finder->addMatcher(
113 cxxMethodDecl(
114 isDefinition(), isUserProvided(),
115 unless(anyOf(
116 isVirtual(), isStatic(), hasTrivialBody(), isOverloadedOperator(),
117 cxxConstructorDecl(), cxxDestructorDecl(), cxxConversionDecl(),
118 isExplicitObjectMemberFunction(), isTemplate(),
119 isDependentContext(), allOf(isConst(), hasNonConstOverload()),
120 ofClass(anyOf(
121 isLambda(),
122 hasAnyDependentBases()) // Method might become virtual
123 // depending on template base class.
124 ),
125 isInsideMacroDefinition(),
126 hasCanonicalDecl(isInsideMacroDefinition()), usesThis())))
127 .bind("x"),
128 this);
129}
130
131/// Obtain the original source code text from a SourceRange.
132static StringRef getStringFromRange(const SourceManager &SourceMgr,
133 const LangOptions &LangOpts,
134 SourceRange Range) {
135 if (SourceMgr.getFileID(Range.getBegin()) !=
136 SourceMgr.getFileID(Range.getEnd()))
137 return {};
138
139 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr,
140 LangOpts);
141}
142
143static SourceRange getLocationOfConst(const TypeSourceInfo *TSI,
144 const SourceManager &SourceMgr,
145 const LangOptions &LangOpts) {
146 assert(TSI);
147 const auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>();
148 assert(FTL);
149
150 const SourceRange Range{FTL.getRParenLoc().getLocWithOffset(1),
151 FTL.getLocalRangeEnd()};
152 // Inside Range, there might be other keywords and trailing return types.
153 // Find the exact position of "const".
154 const StringRef Text = getStringFromRange(SourceMgr, LangOpts, Range);
155 const size_t Offset = Text.find("const");
156 if (Offset == StringRef::npos)
157 return {};
158
159 const SourceLocation Start = Range.getBegin().getLocWithOffset(Offset);
160 return {Start, Start.getLocWithOffset(strlen("const") - 1)};
161}
162
164 const MatchFinder::MatchResult &Result) {
165 const auto *Definition = Result.Nodes.getNodeAs<CXXMethodDecl>("x");
166
167 // TODO: For out-of-line declarations, don't modify the source if the header
168 // is excluded by the -header-filter option.
169 const DiagnosticBuilder Diag =
170 diag(Definition->getLocation(), "method %0 can be made static")
171 << Definition;
172
173 // TODO: Would need to remove those in a fix-it.
174 if (Definition->getMethodQualifiers().hasVolatile() ||
175 Definition->getMethodQualifiers().hasRestrict() ||
176 Definition->getRefQualifier() != RQ_None)
177 return;
178
179 const CXXMethodDecl *Declaration = Definition->getCanonicalDecl();
180
181 if (Definition->isConst()) {
182 // Make sure that we either remove 'const' on both declaration and
183 // definition or emit no fix-it at all.
184 const SourceRange DefConst = getLocationOfConst(
185 Definition->getTypeSourceInfo(), *Result.SourceManager,
186 Result.Context->getLangOpts());
187
188 if (DefConst.isInvalid())
189 return;
190
191 if (Declaration != Definition) {
192 const SourceRange DeclConst = getLocationOfConst(
193 Declaration->getTypeSourceInfo(), *Result.SourceManager,
194 Result.Context->getLangOpts());
195
196 if (DeclConst.isInvalid())
197 return;
198 Diag << FixItHint::CreateRemoval(DeclConst);
199 }
200
201 // Remove existing 'const' from both declaration and definition.
202 Diag << FixItHint::CreateRemoval(DefConst);
203 }
204 Diag << FixItHint::CreateInsertion(Declaration->getBeginLoc(), "static ");
205}
206
207} // namespace clang::tidy::readability
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)
static SourceRange getLocationOfConst(const TypeSourceInfo *TSI, const SourceManager &SourceMgr, const LangOptions &LangOpts)
static StringRef getStringFromRange(const SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.