1 //===--- TriviallyDestructibleCheck.cpp - clang-tidy ----------------------===//
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
9 #include "TriviallyDestructibleCheck.h"
10 #include "../utils/LexerUtils.h"
11 #include "../utils/Matchers.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14
15 using namespace clang::ast_matchers;
16 using namespace clang::ast_matchers::internal;
17 using namespace clang::tidy::matchers;
18
19 namespace clang {
20 namespace tidy {
21 namespace performance {
22
23 namespace {
24
AST_MATCHER(Decl,isFirstDecl)25 AST_MATCHER(Decl, isFirstDecl) { return Node.isFirstDecl(); }
26
AST_MATCHER_P(CXXRecordDecl,hasBase,Matcher<QualType>,InnerMatcher)27 AST_MATCHER_P(CXXRecordDecl, hasBase, Matcher<QualType>, InnerMatcher) {
28 for (const CXXBaseSpecifier &BaseSpec : Node.bases()) {
29 QualType BaseType = BaseSpec.getType();
30 if (InnerMatcher.matches(BaseType, Finder, Builder))
31 return true;
32 }
33 return false;
34 }
35
36 } // namespace
37
registerMatchers(MatchFinder * Finder)38 void TriviallyDestructibleCheck::registerMatchers(MatchFinder *Finder) {
39 Finder->addMatcher(
40 cxxDestructorDecl(
41 isDefaulted(),
42 unless(anyOf(isFirstDecl(), isVirtual(),
43 ofClass(cxxRecordDecl(
44 anyOf(hasBase(unless(isTriviallyDestructible())),
45 has(fieldDecl(unless(
46 hasType(isTriviallyDestructible()))))))))))
47 .bind("decl"),
48 this);
49 }
50
check(const MatchFinder::MatchResult & Result)51 void TriviallyDestructibleCheck::check(const MatchFinder::MatchResult &Result) {
52 const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXDestructorDecl>("decl");
53
54 // Get locations of both first and out-of-line declarations.
55 SourceManager &SM = *Result.SourceManager;
56 const auto *FirstDecl = cast<CXXMethodDecl>(MatchedDecl->getFirstDecl());
57 const SourceLocation FirstDeclEnd = utils::lexer::findNextTerminator(
58 FirstDecl->getEndLoc(), SM, getLangOpts());
59 const CharSourceRange SecondDeclRange = CharSourceRange::getTokenRange(
60 MatchedDecl->getBeginLoc(),
61 utils::lexer::findNextTerminator(MatchedDecl->getEndLoc(), SM,
62 getLangOpts()));
63 if (FirstDeclEnd.isInvalid() || SecondDeclRange.isInvalid())
64 return;
65
66 // Report diagnostic.
67 diag(FirstDecl->getLocation(),
68 "class %0 can be made trivially destructible by defaulting the "
69 "destructor on its first declaration")
70 << FirstDecl->getParent()
71 << FixItHint::CreateInsertion(FirstDeclEnd, " = default")
72 << FixItHint::CreateRemoval(SecondDeclRange);
73 diag(MatchedDecl->getLocation(), "destructor definition is here",
74 DiagnosticIDs::Note);
75 }
76
77 } // namespace performance
78 } // namespace tidy
79 } // namespace clang
80