clang-tools 22.0.0git
VirtualNearMissCheck.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/CXXInheritance.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Lex/Lexer.h"
14
15using namespace clang::ast_matchers;
16
17namespace clang::tidy::bugprone {
18
19namespace {
20AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }
21
22AST_MATCHER(CXXMethodDecl, isOverloadedOperator) {
23 return Node.isOverloadedOperator();
24}
25} // namespace
26
27/// Finds out if the given method overrides some method.
28static bool isOverrideMethod(const CXXMethodDecl *MD) {
29 return MD->size_overridden_methods() > 0 || MD->hasAttr<OverrideAttr>();
30}
31
32/// Checks whether the return types are covariant, according to
33/// C++[class.virtual]p7.
34///
35/// Similar with clang::Sema::CheckOverridingFunctionReturnType.
36/// \returns true if the return types of BaseMD and DerivedMD are covariant.
37static bool checkOverridingFunctionReturnType(const ASTContext *Context,
38 const CXXMethodDecl *BaseMD,
39 const CXXMethodDecl *DerivedMD) {
40 const QualType BaseReturnTy = BaseMD->getType()
41 ->castAs<FunctionType>()
42 ->getReturnType()
43 .getCanonicalType();
44 const QualType DerivedReturnTy = DerivedMD->getType()
45 ->castAs<FunctionType>()
46 ->getReturnType()
47 .getCanonicalType();
48
49 if (DerivedReturnTy->isDependentType() || BaseReturnTy->isDependentType())
50 return false;
51
52 // Check if return types are identical.
53 if (ASTContext::hasSameType(DerivedReturnTy, BaseReturnTy))
54 return true;
55
56 /// Check if the return types are covariant.
57
58 // Both types must be pointers or references to classes.
59 if (!(BaseReturnTy->isPointerType() && DerivedReturnTy->isPointerType()) &&
60 !(BaseReturnTy->isReferenceType() && DerivedReturnTy->isReferenceType()))
61 return false;
62
63 /// BTy is the class type in return type of BaseMD. For example,
64 /// B* Base::md()
65 /// While BRD is the declaration of B.
66 const QualType DTy = DerivedReturnTy->getPointeeType().getCanonicalType();
67 const QualType BTy = BaseReturnTy->getPointeeType().getCanonicalType();
68
69 const CXXRecordDecl *DRD = DTy->getAsCXXRecordDecl();
70 const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();
71 if (DRD == nullptr || BRD == nullptr)
72 return false;
73
74 if (!DRD->hasDefinition() || !BRD->hasDefinition())
75 return false;
76
77 if (DRD == BRD)
78 return true;
79
80 if (!ASTContext::hasSameUnqualifiedType(DTy, BTy)) {
81 // Begin checking whether the conversion from D to B is valid.
82 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
83 /*DetectVirtual=*/false);
84
85 // Check whether D is derived from B, and fill in a CXXBasePaths object.
86 if (!DRD->isDerivedFrom(BRD, Paths))
87 return false;
88
89 // Check ambiguity.
90 if (Paths.isAmbiguous(
91 ASTContext::getCanonicalType(BTy).getUnqualifiedType()))
92 return false;
93
94 // Check accessibility.
95 // FIXME: We currently only support checking if B is accessible base class
96 // of D, or D is the same class which DerivedMD is in.
97 const bool IsItself =
98 DRD->getCanonicalDecl() == DerivedMD->getParent()->getCanonicalDecl();
99 bool HasPublicAccess = false;
100 for (const auto &Path : Paths)
101 if (Path.Access == AS_public)
102 HasPublicAccess = true;
103 if (!HasPublicAccess && !IsItself)
104 return false;
105 // End checking conversion from D to B.
106 }
107
108 // Both pointers or references should have the same cv-qualification.
109 if (DerivedReturnTy.getLocalCVRQualifiers() !=
110 BaseReturnTy.getLocalCVRQualifiers())
111 return false;
112
113 // The class type D should have the same cv-qualification as or less
114 // cv-qualification than the class type B.
115 if (DTy.isMoreQualifiedThan(BTy, *Context))
116 return false;
117
118 return true;
119}
120
121/// \returns decayed type for arrays and functions.
122static QualType getDecayedType(QualType Type) {
123 if (const auto *Decayed = Type->getAs<DecayedType>())
124 return Decayed->getDecayedType();
125 return Type;
126}
127
128/// \returns true if the param types are the same.
129static bool checkParamTypes(const CXXMethodDecl *BaseMD,
130 const CXXMethodDecl *DerivedMD) {
131 const unsigned NumParamA = BaseMD->getNumParams();
132 const unsigned NumParamB = DerivedMD->getNumParams();
133 if (NumParamA != NumParamB)
134 return false;
135
136 for (unsigned I = 0; I < NumParamA; I++)
137 if (getDecayedType(BaseMD->getParamDecl(I)->getType().getCanonicalType()) !=
139 DerivedMD->getParamDecl(I)->getType().getCanonicalType()))
140 return false;
141 return true;
142}
143
144/// \returns true if derived method can override base method except for the
145/// name.
146static bool checkOverrideWithoutName(const ASTContext *Context,
147 const CXXMethodDecl *BaseMD,
148 const CXXMethodDecl *DerivedMD) {
149 if (BaseMD->isStatic() != DerivedMD->isStatic())
150 return false;
151
152 if (BaseMD->getType() == DerivedMD->getType())
153 return true;
154
155 // Now the function types are not identical. Then check if the return types
156 // are covariant and if the param types are the same.
157 if (!checkOverridingFunctionReturnType(Context, BaseMD, DerivedMD))
158 return false;
159 return checkParamTypes(BaseMD, DerivedMD);
160}
161
162/// Check whether BaseMD overrides DerivedMD.
163///
164/// Prerequisite: the class which BaseMD is in should be a base class of that
165/// DerivedMD is in.
166static bool checkOverrideByDerivedMethod(const CXXMethodDecl *BaseMD,
167 const CXXMethodDecl *DerivedMD) {
168 for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),
169 E = DerivedMD->end_overridden_methods();
170 I != E; ++I) {
171 const CXXMethodDecl *OverriddenMD = *I;
172 if (BaseMD->getCanonicalDecl() == OverriddenMD->getCanonicalDecl())
173 return true;
174 }
175
176 return false;
177}
178
179bool VirtualNearMissCheck::isPossibleToBeOverridden(
180 const CXXMethodDecl *BaseMD) {
181 auto [Iter, Inserted] = PossibleMap.try_emplace(BaseMD);
182 if (!Inserted)
183 return Iter->second;
184
185 const bool IsPossible =
186 !BaseMD->isImplicit() && !isa<CXXConstructorDecl>(BaseMD) &&
187 !isa<CXXDestructorDecl>(BaseMD) && BaseMD->isVirtual() &&
188 !BaseMD->isOverloadedOperator() && !isa<CXXConversionDecl>(BaseMD);
189 Iter->second = IsPossible;
190 return IsPossible;
191}
192
193bool VirtualNearMissCheck::isOverriddenByDerivedClass(
194 const CXXMethodDecl *BaseMD, const CXXRecordDecl *DerivedRD) {
195 auto Key = std::make_pair(BaseMD, DerivedRD);
196 auto Iter = OverriddenMap.find(Key);
197 if (Iter != OverriddenMap.end())
198 return Iter->second;
199
200 bool IsOverridden = false;
201 for (const CXXMethodDecl *DerivedMD : DerivedRD->methods()) {
202 if (!isOverrideMethod(DerivedMD))
203 continue;
204
205 if (checkOverrideByDerivedMethod(BaseMD, DerivedMD)) {
206 IsOverridden = true;
207 break;
208 }
209 }
210 OverriddenMap[Key] = IsOverridden;
211 return IsOverridden;
212}
213
214void VirtualNearMissCheck::registerMatchers(MatchFinder *Finder) {
215 Finder->addMatcher(
216 cxxMethodDecl(
217 unless(anyOf(isOverride(), isImplicit(), cxxConstructorDecl(),
218 cxxDestructorDecl(), cxxConversionDecl(), isStatic(),
219 isOverloadedOperator())))
220 .bind("method"),
221 this);
222}
223
224void VirtualNearMissCheck::check(const MatchFinder::MatchResult &Result) {
225 const auto *DerivedMD = Result.Nodes.getNodeAs<CXXMethodDecl>("method");
226 assert(DerivedMD);
227
228 const ASTContext *Context = Result.Context;
229
230 const auto *DerivedRD = DerivedMD->getParent()->getDefinition();
231 assert(DerivedRD);
232
233 for (const auto &BaseSpec : DerivedRD->bases()) {
234 if (const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl()) {
235 for (const auto *BaseMD : BaseRD->methods()) {
236 if (!isPossibleToBeOverridden(BaseMD))
237 continue;
238
239 if (isOverriddenByDerivedClass(BaseMD, DerivedRD))
240 continue;
241
242 const unsigned EditDistance = BaseMD->getName().edit_distance(
243 DerivedMD->getName(), EditDistanceThreshold);
244 if (EditDistance > 0 && EditDistance <= EditDistanceThreshold) {
245 if (checkOverrideWithoutName(Context, BaseMD, DerivedMD)) {
246 // A "virtual near miss" is found.
247 auto Range = CharSourceRange::getTokenRange(
248 SourceRange(DerivedMD->getLocation()));
249
250 const bool ApplyFix = !BaseMD->isTemplateInstantiation() &&
251 !DerivedMD->isTemplateInstantiation();
252 auto Diag =
253 diag(DerivedMD->getBeginLoc(),
254 "method '%0' has a similar name and the same signature as "
255 "virtual method '%1'; did you mean to override it?")
256 << DerivedMD->getQualifiedNameAsString()
257 << BaseMD->getQualifiedNameAsString();
258 if (ApplyFix)
259 Diag << FixItHint::CreateReplacement(Range, BaseMD->getName());
260 }
261 }
262 }
263 }
264 }
265}
266
267} // namespace clang::tidy::bugprone
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static bool checkOverrideByDerivedMethod(const CXXMethodDecl *BaseMD, const CXXMethodDecl *DerivedMD)
Check whether BaseMD overrides DerivedMD.
static bool checkOverrideWithoutName(const ASTContext *Context, const CXXMethodDecl *BaseMD, const CXXMethodDecl *DerivedMD)
static bool isOverrideMethod(const CXXMethodDecl *MD)
Finds out if the given method overrides some method.
static bool checkParamTypes(const CXXMethodDecl *BaseMD, const CXXMethodDecl *DerivedMD)
static QualType getDecayedType(QualType Type)
static bool checkOverridingFunctionReturnType(const ASTContext *Context, const CXXMethodDecl *BaseMD, const CXXMethodDecl *DerivedMD)
Checks whether the return types are covariant, according to C++[class.virtual]p7.
AST_MATCHER(BinaryOperator, isRelationalOperator)