1 //===--- TriviallyDestructibleCheck.cpp - clang-tidy ----------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
15 using namespace clang::ast_matchers
;
16 using namespace clang::ast_matchers::internal
;
17 using namespace clang::tidy::matchers
;
19 namespace clang::tidy::performance
{
23 AST_MATCHER(Decl
, isFirstDecl
) { return Node
.isFirstDecl(); }
25 AST_MATCHER_P(CXXRecordDecl
, hasBase
, Matcher
<QualType
>, InnerMatcher
) {
26 for (const CXXBaseSpecifier
&BaseSpec
: Node
.bases()) {
27 QualType BaseType
= BaseSpec
.getType();
28 if (InnerMatcher
.matches(BaseType
, Finder
, Builder
))
36 void TriviallyDestructibleCheck::registerMatchers(MatchFinder
*Finder
) {
40 unless(anyOf(isFirstDecl(), isVirtual(),
41 ofClass(cxxRecordDecl(
42 anyOf(hasBase(unless(isTriviallyDestructible())),
44 hasType(isTriviallyDestructible()))))))))))
49 void TriviallyDestructibleCheck::check(const MatchFinder::MatchResult
&Result
) {
50 const auto *MatchedDecl
= Result
.Nodes
.getNodeAs
<CXXDestructorDecl
>("decl");
52 // Get locations of both first and out-of-line declarations.
53 SourceManager
&SM
= *Result
.SourceManager
;
54 const auto *FirstDecl
= cast
<CXXMethodDecl
>(MatchedDecl
->getFirstDecl());
55 const SourceLocation FirstDeclEnd
= utils::lexer::findNextTerminator(
56 FirstDecl
->getEndLoc(), SM
, getLangOpts());
57 const CharSourceRange SecondDeclRange
= CharSourceRange::getTokenRange(
58 MatchedDecl
->getBeginLoc(),
59 utils::lexer::findNextTerminator(MatchedDecl
->getEndLoc(), SM
,
61 if (FirstDeclEnd
.isInvalid() || SecondDeclRange
.isInvalid())
65 diag(FirstDecl
->getLocation(),
66 "class %0 can be made trivially destructible by defaulting the "
67 "destructor on its first declaration")
68 << FirstDecl
->getParent()
69 << FixItHint::CreateInsertion(FirstDeclEnd
, " = default")
70 << FixItHint::CreateRemoval(SecondDeclRange
);
71 diag(MatchedDecl
->getLocation(), "destructor definition is here",
75 } // namespace clang::tidy::performance