clang-tools  7.0.0
RedundantMemberInitCheck.cpp
Go to the documentation of this file.
1 //===--- RedundantMemberInitCheck.cpp - clang-tidy-------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "../utils/Matchers.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Lex/Lexer.h"
15 #include <algorithm>
16 
17 using namespace clang::ast_matchers;
18 using namespace clang::tidy::matchers;
19 
20 namespace clang {
21 namespace tidy {
22 namespace readability {
23 
24 void RedundantMemberInitCheck::registerMatchers(MatchFinder *Finder) {
25  if (!getLangOpts().CPlusPlus)
26  return;
27 
28  auto Construct =
29  cxxConstructExpr(
30  hasDeclaration(cxxConstructorDecl(hasParent(
31  cxxRecordDecl(unless(isTriviallyDefaultConstructible()))))))
32  .bind("construct");
33 
34  Finder->addMatcher(
35  cxxConstructorDecl(
36  unless(isDelegatingConstructor()),
37  ofClass(unless(
38  anyOf(isUnion(), ast_matchers::isTemplateInstantiation()))),
39  forEachConstructorInitializer(
40  cxxCtorInitializer(isWritten(),
41  withInitializer(ignoringImplicit(Construct)),
42  unless(forField(hasType(isConstQualified()))),
43  unless(forField(hasParent(recordDecl(isUnion())))))
44  .bind("init"))),
45  this);
46 }
47 
48 void RedundantMemberInitCheck::check(const MatchFinder::MatchResult &Result) {
49  const auto *Init = Result.Nodes.getNodeAs<CXXCtorInitializer>("init");
50  const auto *Construct = Result.Nodes.getNodeAs<CXXConstructExpr>("construct");
51 
52  if (Construct->getNumArgs() == 0 ||
53  Construct->getArg(0)->isDefaultArgument()) {
54  if (Init->isAnyMemberInitializer()) {
55  diag(Init->getSourceLocation(), "initializer for member %0 is redundant")
56  << Init->getAnyMember()
57  << FixItHint::CreateRemoval(Init->getSourceRange());
58  } else {
59  diag(Init->getSourceLocation(),
60  "initializer for base class %0 is redundant")
61  << Construct->getType()
62  << FixItHint::CreateRemoval(Init->getSourceRange());
63  }
64  }
65 }
66 
67 } // namespace readability
68 } // namespace tidy
69 } // namespace clang
bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context)
Returns true if Type is trivially default constructible.
Definition: TypeTraits.cpp:89
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//