blob: 150b517811b66c51ac72143b6f4027c791b4f908 [file] [log] [blame]
Alexander Kornienko98ba0812016-01-13 14:16:35 +00001//===--- VirtualNearMissCheck.cpp - clang-tidy-----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alexander Kornienko98ba0812016-01-13 14:16:35 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "VirtualNearMissCheck.h"
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 {
18namespace tidy {
Alexander Kornienkod4ac4af2017-11-24 14:16:29 +000019namespace bugprone {
Alexander Kornienko98ba0812016-01-13 14:16:35 +000020
Benjamin Kramerf8c99292018-02-18 19:02:35 +000021namespace {
Alexander Kornienko8ac20a82016-01-29 15:22:10 +000022AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }
23
24AST_MATCHER(CXXMethodDecl, isOverloadedOperator) {
25 return Node.isOverloadedOperator();
26}
Benjamin Kramerf8c99292018-02-18 19:02:35 +000027} // namespace
Alexander Kornienko8ac20a82016-01-29 15:22:10 +000028
Alexander Kornienko98ba0812016-01-13 14:16:35 +000029/// Finds out if the given method overrides some method.
30static bool isOverrideMethod(const CXXMethodDecl *MD) {
31 return MD->size_overridden_methods() > 0 || MD->hasAttr<OverrideAttr>();
32}
33
34/// Checks whether the return types are covariant, according to
35/// C++[class.virtual]p7.
36///
37/// Similar with clang::Sema::CheckOverridingFunctionReturnType.
38/// \returns true if the return types of BaseMD and DerivedMD are covariant.
39static bool checkOverridingFunctionReturnType(const ASTContext *Context,
40 const CXXMethodDecl *BaseMD,
41 const CXXMethodDecl *DerivedMD) {
Alexander Kornienko8ac20a82016-01-29 15:22:10 +000042 QualType BaseReturnTy = BaseMD->getType()
43 ->getAs<FunctionType>()
44 ->getReturnType()
45 .getCanonicalType();
46 QualType DerivedReturnTy = DerivedMD->getType()
47 ->getAs<FunctionType>()
48 ->getReturnType()
49 .getCanonicalType();
Alexander Kornienko98ba0812016-01-13 14:16:35 +000050
51 if (DerivedReturnTy->isDependentType() || BaseReturnTy->isDependentType())
52 return false;
53
54 // Check if return types are identical.
55 if (Context->hasSameType(DerivedReturnTy, BaseReturnTy))
56 return true;
57
58 /// Check if the return types are covariant.
Gabor Horvath93bc5762016-01-22 21:45:51 +000059
60 // Both types must be pointers or references to classes.
61 if (!(BaseReturnTy->isPointerType() && DerivedReturnTy->isPointerType()) &&
62 !(BaseReturnTy->isReferenceType() && DerivedReturnTy->isReferenceType()))
63 return false;
64
Alexander Kornienko98ba0812016-01-13 14:16:35 +000065 /// BTy is the class type in return type of BaseMD. For example,
66 /// B* Base::md()
67 /// While BRD is the declaration of B.
Alexander Kornienko8ac20a82016-01-29 15:22:10 +000068 QualType DTy = DerivedReturnTy->getPointeeType().getCanonicalType();
69 QualType BTy = BaseReturnTy->getPointeeType().getCanonicalType();
Alexander Kornienko98ba0812016-01-13 14:16:35 +000070
Gabor Horvath93bc5762016-01-22 21:45:51 +000071 const CXXRecordDecl *DRD = DTy->getAsCXXRecordDecl();
72 const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();
Alexander Kornienko98ba0812016-01-13 14:16:35 +000073 if (DRD == nullptr || BRD == nullptr)
74 return false;
75
Haojian Wubbff5382016-02-03 17:21:44 +000076 if (!DRD->hasDefinition() || !BRD->hasDefinition())
77 return false;
78
Alexander Kornienko98ba0812016-01-13 14:16:35 +000079 if (DRD == BRD)
80 return true;
81
82 if (!Context->hasSameUnqualifiedType(DTy, BTy)) {
83 // Begin checking whether the conversion from D to B is valid.
84 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
85 /*DetectVirtual=*/false);
86
87 // Check whether D is derived from B, and fill in a CXXBasePaths object.
88 if (!DRD->isDerivedFrom(BRD, Paths))
89 return false;
90
91 // Check ambiguity.
92 if (Paths.isAmbiguous(Context->getCanonicalType(BTy).getUnqualifiedType()))
93 return false;
94
95 // Check accessibility.
96 // FIXME: We currently only support checking if B is accessible base class
97 // of D, or D is the same class which DerivedMD is in.
Alexander Kornienko8ac20a82016-01-29 15:22:10 +000098 bool IsItself =
99 DRD->getCanonicalDecl() == DerivedMD->getParent()->getCanonicalDecl();
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000100 bool HasPublicAccess = false;
101 for (const auto &Path : Paths) {
102 if (Path.Access == AS_public)
103 HasPublicAccess = true;
104 }
105 if (!HasPublicAccess && !IsItself)
106 return false;
107 // End checking conversion from D to B.
108 }
109
110 // Both pointers or references should have the same cv-qualification.
111 if (DerivedReturnTy.getLocalCVRQualifiers() !=
112 BaseReturnTy.getLocalCVRQualifiers())
113 return false;
114
115 // The class type D should have the same cv-qualification as or less
116 // cv-qualification than the class type B.
117 if (DTy.isMoreQualifiedThan(BTy))
118 return false;
119
120 return true;
121}
122
Gabor Horvath93bc5762016-01-22 21:45:51 +0000123/// \returns decayed type for arrays and functions.
124static QualType getDecayedType(QualType Type) {
125 if (const auto *Decayed = Type->getAs<DecayedType>())
126 return Decayed->getDecayedType();
127 return Type;
128}
129
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000130/// \returns true if the param types are the same.
131static bool checkParamTypes(const CXXMethodDecl *BaseMD,
132 const CXXMethodDecl *DerivedMD) {
133 unsigned NumParamA = BaseMD->getNumParams();
134 unsigned NumParamB = DerivedMD->getNumParams();
135 if (NumParamA != NumParamB)
136 return false;
137
138 for (unsigned I = 0; I < NumParamA; I++) {
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000139 if (getDecayedType(BaseMD->getParamDecl(I)->getType().getCanonicalType()) !=
140 getDecayedType(
141 DerivedMD->getParamDecl(I)->getType().getCanonicalType()))
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000142 return false;
143 }
144 return true;
145}
146
147/// \returns true if derived method can override base method except for the
148/// name.
149static bool checkOverrideWithoutName(const ASTContext *Context,
150 const CXXMethodDecl *BaseMD,
151 const CXXMethodDecl *DerivedMD) {
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000152 if (BaseMD->isStatic() != DerivedMD->isStatic())
153 return false;
154
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000155 if (BaseMD->getType() == DerivedMD->getType())
156 return true;
157
158 // Now the function types are not identical. Then check if the return types
159 // are covariant and if the param types are the same.
160 if (!checkOverridingFunctionReturnType(Context, BaseMD, DerivedMD))
161 return false;
162 return checkParamTypes(BaseMD, DerivedMD);
163}
164
165/// Check whether BaseMD overrides DerivedMD.
166///
167/// Prerequisite: the class which BaseMD is in should be a base class of that
168/// DerivedMD is in.
169static bool checkOverrideByDerivedMethod(const CXXMethodDecl *BaseMD,
170 const CXXMethodDecl *DerivedMD) {
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000171 for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),
172 E = DerivedMD->end_overridden_methods();
173 I != E; ++I) {
174 const CXXMethodDecl *OverriddenMD = *I;
Alexander Kornienkobfee5f72016-01-29 15:22:20 +0000175 if (BaseMD->getCanonicalDecl() == OverriddenMD->getCanonicalDecl())
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000176 return true;
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000177 }
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000178
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000179 return false;
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000180}
181
182bool VirtualNearMissCheck::isPossibleToBeOverridden(
183 const CXXMethodDecl *BaseMD) {
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000184 auto Iter = PossibleMap.find(BaseMD);
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000185 if (Iter != PossibleMap.end())
186 return Iter->second;
187
188 bool IsPossible = !BaseMD->isImplicit() && !isa<CXXConstructorDecl>(BaseMD) &&
Gabor Horvath93bc5762016-01-22 21:45:51 +0000189 !isa<CXXDestructorDecl>(BaseMD) && BaseMD->isVirtual() &&
Alexander Kornienkodc841502016-01-26 10:56:27 +0000190 !BaseMD->isOverloadedOperator() &&
191 !isa<CXXConversionDecl>(BaseMD);
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000192 PossibleMap[BaseMD] = IsPossible;
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000193 return IsPossible;
194}
195
196bool VirtualNearMissCheck::isOverriddenByDerivedClass(
197 const CXXMethodDecl *BaseMD, const CXXRecordDecl *DerivedRD) {
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000198 auto Key = std::make_pair(BaseMD, DerivedRD);
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000199 auto Iter = OverriddenMap.find(Key);
200 if (Iter != OverriddenMap.end())
201 return Iter->second;
202
203 bool IsOverridden = false;
204 for (const CXXMethodDecl *DerivedMD : DerivedRD->methods()) {
205 if (!isOverrideMethod(DerivedMD))
206 continue;
207
208 if (checkOverrideByDerivedMethod(BaseMD, DerivedMD)) {
209 IsOverridden = true;
210 break;
211 }
212 }
213 OverriddenMap[Key] = IsOverridden;
214 return IsOverridden;
215}
216
217void VirtualNearMissCheck::registerMatchers(MatchFinder *Finder) {
Gabor Horvath93bc5762016-01-22 21:45:51 +0000218 Finder->addMatcher(
Alexander Kornienkodc841502016-01-26 10:56:27 +0000219 cxxMethodDecl(
220 unless(anyOf(isOverride(), isImplicit(), cxxConstructorDecl(),
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000221 cxxDestructorDecl(), cxxConversionDecl(), isStatic(),
222 isOverloadedOperator())))
Gabor Horvath93bc5762016-01-22 21:45:51 +0000223 .bind("method"),
224 this);
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000225}
226
227void VirtualNearMissCheck::check(const MatchFinder::MatchResult &Result) {
228 const auto *DerivedMD = Result.Nodes.getNodeAs<CXXMethodDecl>("method");
Gabor Horvath93bc5762016-01-22 21:45:51 +0000229 assert(DerivedMD);
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000230
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000231 const ASTContext *Context = Result.Context;
232
Alexander Kornienko8ac20a82016-01-29 15:22:10 +0000233 const auto *DerivedRD = DerivedMD->getParent()->getDefinition();
234 assert(DerivedRD);
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000235
236 for (const auto &BaseSpec : DerivedRD->bases()) {
237 if (const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl()) {
238 for (const auto *BaseMD : BaseRD->methods()) {
239 if (!isPossibleToBeOverridden(BaseMD))
240 continue;
241
242 if (isOverriddenByDerivedClass(BaseMD, DerivedRD))
243 continue;
244
Benjamin Kramer14361922017-08-09 22:09:29 +0000245 unsigned EditDistance = BaseMD->getName().edit_distance(
246 DerivedMD->getName(), EditDistanceThreshold);
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000247 if (EditDistance > 0 && EditDistance <= EditDistanceThreshold) {
248 if (checkOverrideWithoutName(Context, BaseMD, DerivedMD)) {
249 // A "virtual near miss" is found.
Cong Liufbd01762016-02-11 16:03:27 +0000250 auto Range = CharSourceRange::getTokenRange(
251 SourceRange(DerivedMD->getLocation()));
252
253 bool ApplyFix = !BaseMD->isTemplateInstantiation() &&
254 !DerivedMD->isTemplateInstantiation();
255 auto Diag =
Stephen Kelly43465bf2018-08-09 22:42:26 +0000256 diag(DerivedMD->getBeginLoc(),
Cong Liufbd01762016-02-11 16:03:27 +0000257 "method '%0' has a similar name and the same signature as "
258 "virtual method '%1'; did you mean to override it?")
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000259 << DerivedMD->getQualifiedNameAsString()
260 << BaseMD->getQualifiedNameAsString();
Cong Liufbd01762016-02-11 16:03:27 +0000261 if (ApplyFix)
262 Diag << FixItHint::CreateReplacement(Range, BaseMD->getName());
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000263 }
264 }
265 }
266 }
267 }
268}
269
Alexander Kornienkod4ac4af2017-11-24 14:16:29 +0000270} // namespace bugprone
Alexander Kornienko98ba0812016-01-13 14:16:35 +0000271} // namespace tidy
272} // namespace clang