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