clang-tools 22.0.0git
RedundantSmartptrGetCheck.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/ASTMatchers/ASTMatchFinder.h"
11#include "clang/Lex/Lexer.h"
12
13using namespace clang::ast_matchers;
14
16
17namespace {
18internal::Matcher<Expr> callToGet(const internal::Matcher<Decl> &OnClass) {
19 return expr(
20 anyOf(cxxMemberCallExpr(
21 on(expr(anyOf(hasType(OnClass),
22 hasType(qualType(pointsTo(
23 decl(OnClass).bind("ptr_to_ptr"))))))
24 .bind("smart_pointer")),
25 unless(callee(
26 memberExpr(hasObjectExpression(cxxThisExpr())))),
27 callee(cxxMethodDecl(hasName("get"),
28 returns(qualType(pointsTo(
29 type().bind("getType"))))))),
30 cxxDependentScopeMemberExpr(
31 hasMemberName("get"),
32 hasObjectExpression(
33 expr(hasType(qualType(hasCanonicalType(
34 templateSpecializationType(hasDeclaration(
35 classTemplateDecl(has(cxxRecordDecl(
36 OnClass,
37 hasMethod(cxxMethodDecl(
38 hasName("get"),
39 returns(qualType(
40 pointsTo(type().bind(
41 "getType")))))))))))))))
42 .bind("smart_pointer")))))
43 .bind("redundant_get");
44}
45
46internal::Matcher<Decl> knownSmartptr() {
47 return recordDecl(hasAnyName("::std::unique_ptr", "::std::shared_ptr"));
48}
49
50void registerMatchersForGetArrowStart(MatchFinder *Finder,
51 MatchFinder::MatchCallback *Callback) {
52 const auto MatchesOpArrow =
53 allOf(hasName("operator->"),
54 returns(qualType(pointsTo(type().bind("op->Type")))));
55 const auto MatchesOpStar =
56 allOf(hasName("operator*"),
57 returns(qualType(references(type().bind("op*Type")))));
58 const auto HasRelevantOps =
59 allOf(anyOf(hasMethod(MatchesOpArrow),
60 has(functionTemplateDecl(has(functionDecl(MatchesOpArrow))))),
61 anyOf(hasMethod(MatchesOpStar),
62 has(functionTemplateDecl(has(functionDecl(MatchesOpStar))))));
63
64 const auto QuacksLikeASmartptr =
65 cxxRecordDecl(cxxRecordDecl().bind("duck_typing"), HasRelevantOps);
66
67 // Make sure we are not missing the known standard types.
68 const auto SmartptrAny = anyOf(knownSmartptr(), QuacksLikeASmartptr);
69 const auto SmartptrWithDeref = anyOf(
70 cxxRecordDecl(knownSmartptr(), HasRelevantOps), QuacksLikeASmartptr);
71
72 // Catch 'ptr.get()->Foo()'
73 Finder->addMatcher(
74 memberExpr(expr().bind("memberExpr"), isArrow(),
75 hasObjectExpression(callToGet(SmartptrWithDeref))),
76 Callback);
77
78 // Catch '*ptr.get()' or '*ptr->get()'
79 Finder->addMatcher(
80 unaryOperator(hasOperatorName("*"),
81 hasUnaryOperand(callToGet(SmartptrWithDeref))),
82 Callback);
83
84 // Catch '!ptr.get()'
85 const auto CallToGetAsBool = callToGet(
86 recordDecl(SmartptrAny, has(cxxConversionDecl(returns(booleanType())))));
87 Finder->addMatcher(
88 unaryOperator(hasOperatorName("!"), hasUnaryOperand(CallToGetAsBool)),
89 Callback);
90
91 // Catch 'if(ptr.get())'
92 Finder->addMatcher(ifStmt(hasCondition(CallToGetAsBool)), Callback);
93
94 // Catch 'ptr.get() ? X : Y'
95 Finder->addMatcher(conditionalOperator(hasCondition(CallToGetAsBool)),
96 Callback);
97
98 Finder->addMatcher(cxxDependentScopeMemberExpr(hasObjectExpression(
99 callExpr(has(callToGet(SmartptrAny))))),
100 Callback);
101}
102
103void registerMatchersForGetEquals(MatchFinder *Finder,
104 MatchFinder::MatchCallback *Callback) {
105 // This one is harder to do with duck typing.
106 // The operator==/!= that we are looking for might be member or non-member,
107 // might be on global namespace or found by ADL, might be a template, etc.
108 // For now, lets keep it to the known standard types.
109
110 // Matches against nullptr.
111 Finder->addMatcher(
112 binaryOperator(hasAnyOperatorName("==", "!="),
113 hasOperands(anyOf(cxxNullPtrLiteralExpr(), gnuNullExpr(),
114 integerLiteral(equals(0))),
115 callToGet(knownSmartptr()))),
116 Callback);
117
118 // FIXME: Match and fix if (l.get() == r.get()).
119}
120
121} // namespace
122
125 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
126}
127
129 registerMatchersForGetArrowStart(Finder, this);
130 registerMatchersForGetEquals(Finder, this);
131}
132
133namespace {
134bool allReturnTypesMatch(const MatchFinder::MatchResult &Result) {
135 if (Result.Nodes.getNodeAs<Decl>("duck_typing") == nullptr)
136 return true;
137 // Verify that the types match.
138 // We can't do this on the matcher because the type nodes can be different,
139 // even though they represent the same type. This difference comes from how
140 // the type is referenced (eg. through a typedef, a type trait, etc).
141 const Type *OpArrowType =
142 Result.Nodes.getNodeAs<Type>("op->Type")->getUnqualifiedDesugaredType();
143 const Type *OpStarType =
144 Result.Nodes.getNodeAs<Type>("op*Type")->getUnqualifiedDesugaredType();
145 const Type *GetType =
146 Result.Nodes.getNodeAs<Type>("getType")->getUnqualifiedDesugaredType();
147 return OpArrowType == OpStarType && OpArrowType == GetType;
148}
149} // namespace
150
151void RedundantSmartptrGetCheck::check(const MatchFinder::MatchResult &Result) {
152 if (!allReturnTypesMatch(Result))
153 return;
154
155 bool IsPtrToPtr = Result.Nodes.getNodeAs<Decl>("ptr_to_ptr") != nullptr;
156 bool IsMemberExpr = Result.Nodes.getNodeAs<Expr>("memberExpr") != nullptr;
157 const auto *GetCall = Result.Nodes.getNodeAs<Expr>("redundant_get");
158 if (GetCall->getBeginLoc().isMacroID() && IgnoreMacros)
159 return;
160
161 const auto *Smartptr = Result.Nodes.getNodeAs<Expr>("smart_pointer");
162
163 if (IsPtrToPtr && IsMemberExpr) {
164 // Ignore this case (eg. Foo->get()->DoSomething());
165 return;
166 }
167
168 auto SR = GetCall->getSourceRange();
169 // CXXDependentScopeMemberExpr source range does not include parens
170 // Extend the source range of the get call to account for them.
171 if (isa<CXXDependentScopeMemberExpr>(GetCall))
172 SR.setEnd(Lexer::getLocForEndOfToken(SR.getEnd(), 0, *Result.SourceManager,
173 getLangOpts())
174 .getLocWithOffset(1));
175
176 StringRef SmartptrText = Lexer::getSourceText(
177 CharSourceRange::getTokenRange(Smartptr->getSourceRange()),
178 *Result.SourceManager, getLangOpts());
179 // Check if the last two characters are "->" and remove them
180 if (SmartptrText.ends_with("->")) {
181 SmartptrText = SmartptrText.drop_back(2);
182 }
183 // Replace foo->get() with *foo, and foo.get() with foo.
184 std::string Replacement = Twine(IsPtrToPtr ? "*" : "", SmartptrText).str();
185 diag(GetCall->getBeginLoc(), "redundant get() call on smart pointer")
186 << FixItHint::CreateReplacement(SR, Replacement);
187}
188
189} // namespace clang::tidy::readability
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
llvm::StringMap< ClangTidyValue > OptionMap