clang-tools  11.0.0
RedundantStringInitCheck.cpp
Go to the documentation of this file.
1 //===- RedundantStringInitCheck.cpp - clang-tidy ----------------*- C++ -*-===//
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 "../utils/OptionsUtils.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 
14 using namespace clang::ast_matchers;
15 using namespace clang::tidy::matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace readability {
20 
21 const char DefaultStringNames[] = "::std::basic_string";
22 
23 static ast_matchers::internal::Matcher<NamedDecl>
24 hasAnyNameStdString(std::vector<std::string> Names) {
25  return ast_matchers::internal::Matcher<NamedDecl>(
26  new ast_matchers::internal::HasNameMatcher(std::move(Names)));
27 }
28 
29 static std::vector<std::string>
30 removeNamespaces(const std::vector<std::string> &Names) {
31  std::vector<std::string> Result;
32  Result.reserve(Names.size());
33  for (const std::string &Name : Names) {
34  std::string::size_type ColonPos = Name.rfind(':');
35  Result.push_back(
36  Name.substr(ColonPos == std::string::npos ? 0 : ColonPos + 1));
37  }
38  return Result;
39 }
40 
41 static const CXXConstructExpr *
42 getConstructExpr(const CXXCtorInitializer &CtorInit) {
43  const Expr *InitExpr = CtorInit.getInit();
44  if (const auto *CleanUpExpr = dyn_cast<ExprWithCleanups>(InitExpr))
45  InitExpr = CleanUpExpr->getSubExpr();
46  return dyn_cast<CXXConstructExpr>(InitExpr);
47 }
48 
49 static llvm::Optional<SourceRange>
50 getConstructExprArgRange(const CXXConstructExpr &Construct) {
51  SourceLocation B, E;
52  for (const Expr *Arg : Construct.arguments()) {
53  if (B.isInvalid())
54  B = Arg->getBeginLoc();
55  if (Arg->getEndLoc().isValid())
56  E = Arg->getEndLoc();
57  }
58  if (B.isInvalid() || E.isInvalid())
59  return llvm::None;
60  return SourceRange(B, E);
61 }
62 
63 RedundantStringInitCheck::RedundantStringInitCheck(StringRef Name,
64  ClangTidyContext *Context)
65  : ClangTidyCheck(Name, Context),
66  StringNames(utils::options::parseStringList(
67  Options.get("StringNames", DefaultStringNames))) {}
68 
70  Options.store(Opts, "StringNames", DefaultStringNames);
71 }
72 
73 void RedundantStringInitCheck::registerMatchers(MatchFinder *Finder) {
74  const auto hasStringTypeName = hasAnyNameStdString(StringNames);
75  const auto hasStringCtorName =
77 
78  // Match string constructor.
79  const auto StringConstructorExpr = expr(
80  anyOf(cxxConstructExpr(argumentCountIs(1),
81  hasDeclaration(cxxMethodDecl(hasStringCtorName))),
82  // If present, the second argument is the alloc object which must
83  // not be present explicitly.
84  cxxConstructExpr(argumentCountIs(2),
85  hasDeclaration(cxxMethodDecl(hasStringCtorName)),
86  hasArgument(1, cxxDefaultArgExpr()))));
87 
88  // Match a string constructor expression with an empty string literal.
89  const auto EmptyStringCtorExpr = cxxConstructExpr(
90  StringConstructorExpr,
91  hasArgument(0, ignoringParenImpCasts(stringLiteral(hasSize(0)))));
92 
93  const auto EmptyStringCtorExprWithTemporaries =
94  cxxConstructExpr(StringConstructorExpr,
95  hasArgument(0, ignoringImplicit(EmptyStringCtorExpr)));
96 
97  const auto StringType = hasType(hasUnqualifiedDesugaredType(
98  recordType(hasDeclaration(cxxRecordDecl(hasStringTypeName)))));
99  const auto EmptyStringInit =
100  traverse(ast_type_traits::TK_AsIs, expr(ignoringImplicit(
101  anyOf(EmptyStringCtorExpr, EmptyStringCtorExprWithTemporaries))));
102 
103  // Match a variable declaration with an empty string literal as initializer.
104  // Examples:
105  // string foo = "";
106  // string bar("");
107  Finder->addMatcher(
108  traverse(ast_type_traits::TK_AsIs,
109  namedDecl(varDecl(StringType, hasInitializer(EmptyStringInit))
110  .bind("vardecl"),
111  unless(parmVarDecl()))),
112  this);
113  // Match a field declaration with an empty string literal as initializer.
114  Finder->addMatcher(
115  namedDecl(fieldDecl(StringType, hasInClassInitializer(EmptyStringInit))
116  .bind("fieldDecl")),
117  this);
118  // Matches Constructor Initializers with an empty string literal as
119  // initializer.
120  // Examples:
121  // Foo() : SomeString("") {}
122  Finder->addMatcher(
123  cxxCtorInitializer(
124  isWritten(),
125  forField(allOf(StringType, optionally(hasInClassInitializer(
126  EmptyStringInit.bind("empty_init"))))),
127  withInitializer(EmptyStringInit))
128  .bind("ctorInit"),
129  this);
130 }
131 
132 void RedundantStringInitCheck::check(const MatchFinder::MatchResult &Result) {
133  if (const auto *VDecl = Result.Nodes.getNodeAs<VarDecl>("vardecl")) {
134  // VarDecl's getSourceRange() spans 'string foo = ""' or 'string bar("")'.
135  // So start at getLocation() to span just 'foo = ""' or 'bar("")'.
136  SourceRange ReplaceRange(VDecl->getLocation(), VDecl->getEndLoc());
137  diag(VDecl->getLocation(), "redundant string initialization")
138  << FixItHint::CreateReplacement(ReplaceRange, VDecl->getName());
139  }
140  if (const auto *FDecl = Result.Nodes.getNodeAs<FieldDecl>("fieldDecl")) {
141  // FieldDecl's getSourceRange() spans 'string foo = ""'.
142  // So start at getLocation() to span just 'foo = ""'.
143  SourceRange ReplaceRange(FDecl->getLocation(), FDecl->getEndLoc());
144  diag(FDecl->getLocation(), "redundant string initialization")
145  << FixItHint::CreateReplacement(ReplaceRange, FDecl->getName());
146  }
147  if (const auto *CtorInit =
148  Result.Nodes.getNodeAs<CXXCtorInitializer>("ctorInit")) {
149  if (const FieldDecl *Member = CtorInit->getMember()) {
150  if (!Member->hasInClassInitializer() ||
151  Result.Nodes.getNodeAs<Expr>("empty_init")) {
152  // The String isn't declared in the class with an initializer or its
153  // declared with a redundant initializer, which will be removed. Either
154  // way the string will be default initialized, therefore we can remove
155  // the constructor initializer entirely.
156  diag(CtorInit->getMemberLocation(), "redundant string initialization")
157  << FixItHint::CreateRemoval(CtorInit->getSourceRange());
158  return;
159  }
160  }
161  const CXXConstructExpr *Construct = getConstructExpr(*CtorInit);
162  if (!Construct)
163  return;
164  if (llvm::Optional<SourceRange> RemovalRange =
165  getConstructExprArgRange(*Construct))
166  diag(CtorInit->getMemberLocation(), "redundant string initialization")
167  << FixItHint::CreateRemoval(*RemovalRange);
168  }
169 }
170 
171 } // namespace readability
172 } // namespace tidy
173 } // namespace clang
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
clang::tidy::readability::getConstructExprArgRange
static llvm::Optional< SourceRange > getConstructExprArgRange(const CXXConstructExpr &Construct)
Definition: RedundantStringInitCheck.cpp:50
clang::tidy::readability::RedundantStringInitCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: RedundantStringInitCheck.cpp:69
clang::tidy::readability::DefaultStringNames
const char DefaultStringNames[]
Definition: RedundantStringInitCheck.cpp:21
RedundantStringInitCheck.h
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:114
clang::tidy::matchers
Definition: clang-tidy/utils/Matchers.h:17
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::tidy::utils::options::parseStringList
std::vector< std::string > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
Definition: OptionsUtils.cpp:18
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:471
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:76
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidyCheck.cpp:55
clang::tidy::readability::RedundantStringInitCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: RedundantStringInitCheck.cpp:73
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::tidy::readability::removeNamespaces
static std::vector< std::string > removeNamespaces(const std::vector< std::string > &Names)
Definition: RedundantStringInitCheck.cpp:30
clang::tidy::readability::hasAnyNameStdString
static ast_matchers::internal::Matcher< NamedDecl > hasAnyNameStdString(std::vector< std::string > Names)
Definition: RedundantStringInitCheck.cpp:24
clang::tidy::ClangTidyCheck::OptionsView::store
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidyCheck.cpp:152
clang::tidy::readability::RedundantStringInitCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: RedundantStringInitCheck.cpp:132
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, ClangTidyValue > OptionMap
Definition: ClangTidyOptions.h:111
clang::tidy::readability::getConstructExpr
static const CXXConstructExpr * getConstructExpr(const CXXCtorInitializer &CtorInit)
Definition: RedundantStringInitCheck.cpp:42