Debian Codegraph @

compilerplugins/clang/unnecessaryoverride.cxx

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9
10 #ifndef LO_CLANG_SHARED_PLUGINS
11
12 #include <cassert>
13 #include <string>
14 #include <iostream>
15 #include <fstream>
16 #include <set>
17
18 #include <clang/AST/CXXInheritance.h>
19 #include "config_clang.h"
20 #include "plugin.hxx"
21 #include "check.hxx"
22 #include "compat.hxx"
23
24 /**
25 look for methods where all they do is call their superclass method
26 */
27
28 namespace {
29
30 bool hasMultipleBaseInstances_(
31 CXXRecordDecl const * derived, CXXRecordDecl const * canonicBase,
32 bool & hasAsNonVirtualBase, bool & hasAsVirtualBase)
33 {
34 for (auto i = derived->bases_begin(); i != derived->bases_end(); ++i) {
35 auto const cls = i->getType()->getAsCXXRecordDecl();
36 if (cls == nullptr) {
37 assert(i->getType()->isDependentType());
38 // Conservatively assume "yes" for dependent bases:
39 return true;
40 }
41 if (cls->getCanonicalDecl() == canonicBase) {
42 if (i->isVirtual()) {
43 if (hasAsNonVirtualBase) {
44 return true;
45 }
46 hasAsVirtualBase = true;
47 } else {
48 if (hasAsNonVirtualBase || hasAsVirtualBase) {
49 return true;
50 }
51 hasAsNonVirtualBase = true;
52 }
53 } else if (hasMultipleBaseInstances_(
54 cls, canonicBase, hasAsNonVirtualBase, hasAsVirtualBase))
55 {
56 return true;
57 }
58 }
59 return false;
60 }
61
62 bool hasMultipleBaseInstances(
63 CXXRecordDecl const * derived, CXXRecordDecl const * base)
64 {
65 bool nonVirt = false;
66 bool virt = false;
67 return hasMultipleBaseInstances_(
68 derived, base->getCanonicalDecl(), nonVirt, virt);
69 }
70
71 class UnnecessaryOverride:
72 public loplugin::FilteringPlugin<UnnecessaryOverride>
73 {
74 public:
75 explicit UnnecessaryOverride(loplugin::InstantiationData const & data): FilteringPlugin(data) {}
76
77 virtual bool preRun() override
78 {
79 // ignore some files with problematic macros
80 StringRef fn(handler.getMainFileName());
81 if (loplugin::isSamePathname(fn, SRCDIR "/sd/source/ui/framework/factories/ChildWindowPane.cxx"))
82 return false;
83 if (loplugin::isSamePathname(fn, SRCDIR "/forms/source/component/Date.cxx"))
84 return false;
85 if (loplugin::isSamePathname(fn, SRCDIR "/forms/source/component/Time.cxx"))
86 return false;
87 if (loplugin::isSamePathname(fn, SRCDIR "/svx/source/dialog/hyperdlg.cxx"))
88 return false;
89 if (loplugin::isSamePathname(fn, SRCDIR "/svx/source/dialog/rubydialog.cxx"))
90 return false;
91 if (loplugin::hasPathnamePrefix(fn, SRCDIR "/canvas/"))
92 return false;
93 if (loplugin::isSamePathname(fn, SRCDIR "/sc/source/ui/view/spelldialog.cxx"))
94 return false;
95 if (loplugin::isSamePathname(fn, SRCDIR "/sd/source/ui/dlg/SpellDialogChildWindow.cxx"))
96 return false;
97 // HAVE_ODBC_ADMINISTRATION
98 if (loplugin::isSamePathname(fn, SRCDIR "/dbaccess/source/ui/dlg/dsselect.cxx"))
99 return false;
100 if (loplugin::isSamePathname(fn, SRCDIR "/unotools/source/streaming/streamhelper.cxx"))
101 return false;
102 return true;
103 }
104
105 virtual void run() override
106 {
107 if( preRun())
108 TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
109 }
110
111 bool VisitCXXMethodDecl(const CXXMethodDecl *);
112
113 private:
114 const CXXMethodDecl * findOverriddenOrSimilarMethodInSuperclasses(const CXXMethodDecl *);
115 bool BaseCheckCallback(const CXXRecordDecl *BaseDefinition);
116 CXXMemberCallExpr const * extractCallExpr(Expr const *);
117 };
118
119 bool UnnecessaryOverride::VisitCXXMethodDecl(const CXXMethodDecl* methodDecl)
120 {
121 if (ignoreLocation(methodDecl->getCanonicalDecl())) {
122 return true;
123 }
124 if (isa<CXXConstructorDecl>(methodDecl)) {
125 return true;
126 }
127
128 StringRef aFileName = getFilenameOfLocation(
129 compiler.getSourceManager().getSpellingLoc(methodDecl->getBeginLoc()));
130
131 if (isa<CXXDestructorDecl>(methodDecl)
132 && !isInUnoIncludeFile(methodDecl))
133 {
134 // the code is this method is only __compiled__ if OSL_DEBUG_LEVEL > 1
135 if (loplugin::isSamePathname(aFileName, SRCDIR "/tools/source/stream/strmunx.cxx"))
136 return true;
137
138 // Warn about unnecessarily user-declared destructors.
139 // A destructor is deemed unnecessary if:
140 // * it is public;
141 // * its class is only defined in the .cxx file (i.e., the virtual
142 // destructor is neither used to control the place of vtable
143 // emission, nor is its definition depending on types that may still
144 // be incomplete);
145 // or
146 // the destructor is inline, the class definition is complete,
147 // and the class has no superclasses
148 // * it either does not have an explicit exception specification, or has
149 // a non-dependent explicit exception specification that is compatible
150 // with a non-dependent exception specification the destructor would
151 // have if it did not have an explicit one (TODO);
152 // * it is either defined as defaulted or with an empty body.
153 // Removing the user-declared destructor may cause the class to get an
154 // implicitly declared move constructor and/or move assignment operator;
155 // that is considered acceptable: If any subobject cannot be moved, the
156 // implicitly declared function will be defined as deleted (which is in
157 // practice not much different from not having it declared), and
158 // otherwise offering movability is likely even an improvement over not
159 // offering it due to a "pointless" user-declared destructor.
160 // Similarly, removing the user-declared destructor may cause the
161 // implicit definition of a copy constructor and/or copy assignment
162 // operator to change from being an obsolete feature to being a standard
163 // feature. That difference is not taken into account here.
164 auto cls = methodDecl->getParent();
165 if (methodDecl->getAccess() != AS_public)
166 {
167 return true;
168 }
169 if (!compiler.getSourceManager().isInMainFile(
170 methodDecl->getCanonicalDecl()->getLocation())
171 && !( methodDecl->isInlined()))
172 {
173 return true;
174 }
175 // if it's virtual, but it has a base-class with a non-virtual destructor
176 if (methodDecl->isVirtual())
177 {
178 bool baseWithVirtualDtor = false;
179 for (auto baseSpecifier = cls->bases_begin(); baseSpecifier != cls->bases_end(); ++baseSpecifier)
180 {
181 const RecordType* baseRecordType = baseSpecifier->getType()->getAs<RecordType>();
182 if (baseRecordType)
183 {
184 const CXXRecordDecl* baseRecordDecl = dyn_cast<CXXRecordDecl>(compat::getDecl(baseRecordType));
185 if (baseRecordDecl && baseRecordDecl->getDestructor()
186 && baseRecordDecl->getDestructor()->isVirtual())
187 {
188 baseWithVirtualDtor = true;
189 break;
190 }
191 }
192 }
193 if (!baseWithVirtualDtor)
194 {
195 return true;
196 }
197 }
198 if (methodDecl->isExplicitlyDefaulted()) {
199 if (methodDecl->getPreviousDecl() != nullptr) {
200 return true;
201 }
202 } else {
203 if (!methodDecl->doesThisDeclarationHaveABody()
204 || methodDecl->isLateTemplateParsed())
205 {
206 return true;
207 }
208 auto stmt = dyn_cast<CompoundStmt>(methodDecl->getBody());
209 if (stmt == nullptr || stmt->size() != 0) {
210 return true;
211 }
212 }
213 //TODO: exception specification
214 if (!(cls->hasUserDeclaredCopyConstructor()
215 || cls->hasUserDeclaredCopyAssignment()
216 || cls->hasUserDeclaredMoveConstructor()
217 || cls->hasUserDeclaredMoveAssignment()))
218 {
219 }
220 if ((cls->needsImplicitMoveConstructor()
221 && !(cls->hasUserDeclaredCopyConstructor()
222 || cls->hasUserDeclaredCopyAssignment()
223 || cls->hasUserDeclaredMoveAssignment()))
224 || (cls->needsImplicitMoveAssignment()
225 && !(cls->hasUserDeclaredCopyConstructor()
226 || cls->hasUserDeclaredCopyAssignment()
227 || cls->hasUserDeclaredMoveConstructor())))
228 {
229 report(DiagnosticsEngine::Fatal, "TODO", methodDecl->getLocation());
230 return true;
231 }
232 report(
233 DiagnosticsEngine::Warning, "unnecessary user-declared destructor",
234 methodDecl->getLocation())
235 << methodDecl->getSourceRange();
236 auto cd = methodDecl->getCanonicalDecl();
237 if (cd->getLocation() != methodDecl->getLocation()) {
238 report(DiagnosticsEngine::Note, "declared here", cd->getLocation())
239 << cd->getSourceRange();
240 }
241 return true;
242 }
243
244 if (!methodDecl->doesThisDeclarationHaveABody()
245 || methodDecl->isLateTemplateParsed())
246 {
247 return true;
248 }
249
250 // If overriding more than one base member function, or one base member
251 // function that is available in multiple (non-virtual) base class
252 // instances, then this is a disambiguating override:
253 if (methodDecl->isVirtual()) {
254 if (methodDecl->size_overridden_methods() != 1)
255 {
256 return true;
257 }
258 if (hasMultipleBaseInstances(
259 methodDecl->getParent(),
260 (*methodDecl->begin_overridden_methods())->getParent()))
261 {
262 return true;
263 }
264 }
265
266 const CXXMethodDecl* overriddenMethodDecl = findOverriddenOrSimilarMethodInSuperclasses(methodDecl);
267 if (!overriddenMethodDecl) {
268 return true;
269 }
270
271 // Check for differences in default parameters:
272 unsigned const numParams = methodDecl->getNumParams();
273 assert(overriddenMethodDecl->getNumParams() == numParams);
274 for (unsigned i = 0; i != numParams; ++i) {
275 if (checkIdenticalDefaultArguments(
276 methodDecl->getParamDecl(i)->getDefaultArg(),
277 overriddenMethodDecl->getParamDecl(i)->getDefaultArg())
278 != IdenticalDefaultArgumentsResult::Yes)
279 {
280 return true;
281 }
282 }
283
284 if (methodDecl->getReturnType().getCanonicalType()
285 != overriddenMethodDecl->getReturnType().getCanonicalType())
286 {
287 return true;
288 }
289
290 //TODO: check for identical exception specifications
291
292 const CompoundStmt* compoundStmt = dyn_cast<CompoundStmt>(methodDecl->getBody());
293 if (!compoundStmt || compoundStmt->size() > 2)
294 return true;
295
296 const CXXMemberCallExpr* callExpr = nullptr;
297 if (compoundStmt->size() == 1)
298 {
299 if (methodDecl->getReturnType().getCanonicalType()->isVoidType())
300 {
301 if (auto const e = dyn_cast<Expr>(*compoundStmt->body_begin())) {
302 callExpr = dyn_cast<CXXMemberCallExpr>(e->IgnoreImplicit()->IgnoreParens());
303 }
304 }
305 else
306 {
307 auto returnStmt = dyn_cast<ReturnStmt>(*compoundStmt->body_begin());
308 if (returnStmt == nullptr) {
309 return true;
310 }
311 auto returnExpr = returnStmt->getRetValue();
312 if (returnExpr == nullptr) {
313 return true;
314 }
315 callExpr = extractCallExpr(returnExpr);
316 }
317 }
318 else if (!methodDecl->getReturnType().getCanonicalType()->isVoidType())
319 {
320 /** handle constructions like
321 bool foo() {
322 bool ret = Base::foo();
323 return ret;
324 }
325 */
326 auto bodyIt = compoundStmt->body_begin();
327 if (bodyIt == compoundStmt->body_end()) {
328 return true;
329 }
330 auto declStmt = dyn_cast<DeclStmt>(*bodyIt);
331 if (!declStmt || !declStmt->isSingleDecl())
332 return true;
333 auto varDecl = dyn_cast<VarDecl>(declStmt->getSingleDecl());
334 ++bodyIt;
335 auto returnStmt = dyn_cast<ReturnStmt>(*bodyIt);
336 if (!varDecl || !returnStmt)
337 return true;
338 Expr const * retValue = returnStmt->getRetValue()->IgnoreParenImpCasts();
339 if (auto exprWithCleanups = dyn_cast<ExprWithCleanups>(retValue))
340 retValue = exprWithCleanups->getSubExpr()->IgnoreParenImpCasts();
341 if (auto constructExpr = dyn_cast<CXXConstructExpr>(retValue)) {
342 if (constructExpr->getNumArgs() == 1)
343 retValue = constructExpr->getArg(0)->IgnoreParenImpCasts();
344 }
345 if (!isa<DeclRefExpr>(retValue))
346 return true;
347 callExpr = extractCallExpr(varDecl->getInit());
348 }
349
350 if (!callExpr || callExpr->getMethodDecl() != overriddenMethodDecl)
351 return true;
352 const Expr* expr1 = callExpr->getImplicitObjectArgument()->IgnoreImpCasts();
353 if (!expr1)
354 return true;
355 const CXXThisExpr* expr2 = dyn_cast_or_null<CXXThisExpr>(expr1);
356 if (!expr2)
357 return true;
358 for (unsigned i = 0; i<callExpr->getNumArgs(); ++i) {
359 auto e = callExpr->getArg(i)->IgnoreImplicit();
360 if (auto const e1 = dyn_cast<CXXConstructExpr>(e)) {
361 if (e1->getConstructor()->isCopyOrMoveConstructor() && e1->getNumArgs() == 1) {
362 e = e1->getArg(0)->IgnoreImpCasts();
363 }
364 }
365 const DeclRefExpr * declRefExpr = dyn_cast<DeclRefExpr>(e);
366 if (!declRefExpr || declRefExpr->getDecl() != methodDecl->getParamDecl(i))
367 return true;
368 }
369
370 const CXXMethodDecl* pOther = nullptr;
371 if (methodDecl->getCanonicalDecl()->getLocation() != methodDecl->getLocation())
372 pOther = methodDecl->getCanonicalDecl();
373
374 if (pOther) {
375 StringRef aFileName = getFilenameOfLocation(
376 compiler.getSourceManager().getSpellingLoc(pOther->getBeginLoc()));
377 // SFX_DECL_CHILDWINDOW_WITHID macro
378 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/sfx2/childwin.hxx"))
379 return true;
380 }
381
382 if (containsPreprocessingConditionalInclusion(methodDecl->getBody()->getSourceRange())) {
383 return true;
384 }
385
386 report(
387 DiagnosticsEngine::Warning, "%0%1 function just calls %2 parent",
388 methodDecl->getLocation())
389 << methodDecl->getAccess()
390 << (methodDecl->isVirtual() ? " virtual" : "")
391 << overriddenMethodDecl->getAccess()
392 << methodDecl->getSourceRange();
393 if (methodDecl->getCanonicalDecl()->getLocation() != methodDecl->getLocation()) {
394 const CXXMethodDecl* pOther = methodDecl->getCanonicalDecl();
395 report(
396 DiagnosticsEngine::Note,
397 "method declaration here",
398 pOther->getLocation())
399 << pOther->getSourceRange();
400 }
401 return true;
402 }
403
404 const CXXMethodDecl* UnnecessaryOverride::findOverriddenOrSimilarMethodInSuperclasses(const CXXMethodDecl* methodDecl)
405 {
406 if (methodDecl->isVirtual()) {
407 return *methodDecl->begin_overridden_methods();
408 }
409 if (!methodDecl->getDeclName().isIdentifier()) {
410 return nullptr;
411 }
412
413 const CXXMethodDecl* similarMethod = nullptr;
414 CXXBasePath similarBasePath;
415
416 auto BaseMatchesCallback = [&](const CXXBaseSpecifier *cxxBaseSpecifier, CXXBasePath& path)
417 {
418 if (cxxBaseSpecifier->getAccessSpecifier() != AS_public && cxxBaseSpecifier->getAccessSpecifier() != AS_protected)
419 return false;
420 if (!cxxBaseSpecifier->getType().getTypePtr())
421 return false;
422 const CXXRecordDecl* baseCXXRecordDecl = cxxBaseSpecifier->getType()->getAsCXXRecordDecl();
423 if (!baseCXXRecordDecl)
424 return false;
425 if (baseCXXRecordDecl->isInvalidDecl())
426 return false;
427 for (const CXXMethodDecl* baseMethod : baseCXXRecordDecl->methods())
428 {
429 auto effectiveBaseMethodAccess = baseMethod->getAccess();
430 if (effectiveBaseMethodAccess == AS_public && path.Access == AS_protected)
431 effectiveBaseMethodAccess = AS_protected;
432 if (effectiveBaseMethodAccess != methodDecl->getAccess())
433 continue;
434 if (!baseMethod->getDeclName().isIdentifier() || methodDecl->getName() != baseMethod->getName()) {
435 continue;
436 }
437 if (methodDecl->isStatic() != baseMethod->isStatic()
438 || methodDecl->isConst() != baseMethod->isConst()
439 || methodDecl->isVolatile() != baseMethod->isVolatile()
440 || (methodDecl->getRefQualifier()
441 != baseMethod->getRefQualifier())
442 || methodDecl->isVariadic() != baseMethod->isVariadic())
443 {
444 continue;
445 }
446 if (methodDecl->getReturnType().getCanonicalType()
447 != baseMethod->getReturnType().getCanonicalType())
448 {
449 continue;
450 }
451 if (methodDecl->getNumParams() != baseMethod->getNumParams())
452 continue;
453 bool bParamsMatch = true;
454 for (unsigned i=0; i<methodDecl->param_size(); ++i)
455 {
456 if (!loplugin::areSameSugaredType(methodDecl->parameters()[i]->getType(), baseMethod->parameters()[i]->getType()))
457 {
458 bParamsMatch = false;
459 break;
460 }
461 }
462 if (bParamsMatch)
463 {
464 // if we have already found a method directly below us in the inheritance hierarchy, just ignore this one
465 auto Compare = [&](CXXBasePathElement const & lhs, CXXBasePathElement const & rhs)
466 {
467 return lhs.Class == rhs.Class;
468 };
469 if (similarMethod
470 && similarBasePath.size() < path.size()
471 && std::equal(similarBasePath.begin(), similarBasePath.end(),
472 path.begin(), Compare))
473 break;
474 if (similarMethod)
475 return true; // short circuit the process
476 similarMethod = baseMethod;
477 similarBasePath = path;
478 }
479 }
480 return false;
481 };
482
483 CXXBasePaths aPaths;
484 if (methodDecl->getParent()->lookupInBases(BaseMatchesCallback, aPaths))
485 return nullptr;
486
487 return similarMethod;
488 }
489
490 CXXMemberCallExpr const * UnnecessaryOverride::extractCallExpr(Expr const *returnExpr)
491 {
492 returnExpr = returnExpr->IgnoreImplicit();
493
494 // In something like
495 //
496 // Reference< XResultSet > SAL_CALL OPreparedStatement::executeQuery(
497 // const rtl::OUString& sql)
498 // throw(SQLException, RuntimeException, std::exception)
499 // {
500 // return OCommonStatement::executeQuery( sql );
501 // }
502 //
503 // look down through all the
504 //
505 // ReturnStmt
506 // `-ExprWithCleanups
507 // `-CXXConstructExpr
508 // `-MaterializeTemporaryExpr
509 // `-ImplicitCastExpr
510 // `-CXXBindTemporaryExpr
511 // `-CXXMemberCallExpr
512 //
513 // where the fact that the overriding and overridden function have identical
514 // return types makes us confident that all we need to check here is whether
515 // there's an (arbitrary, one-argument) CXXConstructorExpr and
516 // CXXBindTemporaryExpr in between:
517 if (auto ctorExpr = dyn_cast<CXXConstructExpr>(returnExpr)) {
518 if (ctorExpr->getNumArgs() == 1) {
519 auto tempExpr1 = ctorExpr->getArg(0)->IgnoreImplicit();
520 if (auto tempExpr2 = dyn_cast<CXXBindTemporaryExpr>(tempExpr1))
521 {
522 returnExpr = tempExpr2->getSubExpr();
523 }
524 else if (auto tempExpr2 = dyn_cast<CXXMemberCallExpr>(tempExpr1))
525 {
526 returnExpr = tempExpr2;
527 }
528 }
529 }
530
531 return dyn_cast<CXXMemberCallExpr>(returnExpr->IgnoreParenImpCasts());
532 }
533
534 loplugin::Plugin::Registration< UnnecessaryOverride > unnecessaryoverride("unnecessaryoverride", true);
535
536 }
537
538 #endif // LO_CLANG_SHARED_PLUGINS
539
540 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */