clang-tools 22.0.0git
UndelegatedConstructorCheck.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 "clang/AST/ASTContext.h"
11
12using namespace clang::ast_matchers;
13
14namespace clang::tidy::bugprone {
15
16namespace {
17AST_MATCHER_P(Stmt, ignoringTemporaryExpr,
18 ast_matchers::internal::Matcher<Stmt>, InnerMatcher) {
19 const Stmt *E = &Node;
20 for (;;) {
21 // Temporaries with non-trivial dtors.
22 if (const auto *EWC = dyn_cast<ExprWithCleanups>(E))
23 E = EWC->getSubExpr();
24 // Temporaries with zero or more than two ctor arguments.
25 else if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
26 E = BTE->getSubExpr();
27 // Temporaries with exactly one ctor argument.
28 else if (const auto *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
29 E = FCE->getSubExpr();
30 else
31 break;
32 }
33
34 return InnerMatcher.matches(*E, Finder, Builder);
35}
36
37// Finds a node if it's a base of an already bound node.
38AST_MATCHER_P(CXXRecordDecl, baseOfBoundNode, std::string, ID) {
39 return Builder->removeBindings(
40 [&](const ast_matchers::internal::BoundNodesMap &Nodes) {
41 const auto *Derived = Nodes.getNodeAs<CXXRecordDecl>(ID);
42 return Derived != &Node && !Derived->isDerivedFrom(&Node);
43 });
44}
45} // namespace
46
48 // We look for calls to constructors of the same type in constructors. To do
49 // this we have to look through a variety of nodes that occur in the path,
50 // depending on the type's destructor and the number of arguments on the
51 // constructor call, this is handled by ignoringTemporaryExpr. Ignore template
52 // instantiations to reduce the number of duplicated warnings.
53
54 Finder->addMatcher(
55 traverse(
56 TK_AsIs,
57 compoundStmt(hasParent(cxxConstructorDecl(
58 ofClass(cxxRecordDecl().bind("parent")))),
59 forEach(ignoringTemporaryExpr(
60 cxxConstructExpr(
61 hasDeclaration(cxxConstructorDecl(ofClass(
62 cxxRecordDecl(baseOfBoundNode("parent"))))))
63 .bind("construct"))),
64 unless(isInTemplateInstantiation()))),
65 this);
66}
67
69 const MatchFinder::MatchResult &Result) {
70 const auto *E = Result.Nodes.getNodeAs<CXXConstructExpr>("construct");
71 diag(E->getBeginLoc(), "did you intend to call a delegated constructor? "
72 "A temporary object is created here instead");
73}
74
75} // namespace clang::tidy::bugprone
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)