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