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