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 
9 #include "RedundantStringInitCheck.h"
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 
69 void RedundantStringInitCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
70   Options.store(Opts, "StringNames", DefaultStringNames);
71 }
72 
73 void RedundantStringInitCheck::registerMatchers(MatchFinder *Finder) {
74   const auto hasStringTypeName = hasAnyNameStdString(StringNames);
75   const auto hasStringCtorName =
76       hasAnyNameStdString(removeNamespaces(StringNames));
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 = expr(ignoringImplicit(
100       anyOf(EmptyStringCtorExpr, EmptyStringCtorExprWithTemporaries)));
101 
102   // Match a variable declaration with an empty string literal as initializer.
103   // Examples:
104   //     string foo = "";
105   //     string bar("");
106   Finder->addMatcher(
107       namedDecl(
108           varDecl(StringType, hasInitializer(EmptyStringInit)).bind("vardecl"),
109           unless(parmVarDecl())),
110       this);
111   // Match a field declaration with an empty string literal as initializer.
112   Finder->addMatcher(
113       namedDecl(fieldDecl(StringType, hasInClassInitializer(EmptyStringInit))
114                     .bind("fieldDecl")),
115       this);
116   // Matches Constructor Initializers with an empty string literal as
117   // initializer.
118   // Examples:
119   //     Foo() : SomeString("") {}
120   Finder->addMatcher(
121       cxxCtorInitializer(
122           isWritten(),
123           forField(allOf(StringType, optionally(hasInClassInitializer(
124                                          EmptyStringInit.bind("empty_init"))))),
125           withInitializer(EmptyStringInit))
126           .bind("ctorInit"),
127       this);
128 }
129 
130 void RedundantStringInitCheck::check(const MatchFinder::MatchResult &Result) {
131   if (const auto *VDecl = Result.Nodes.getNodeAs<VarDecl>("vardecl")) {
132     // VarDecl's getSourceRange() spans 'string foo = ""' or 'string bar("")'.
133     // So start at getLocation() to span just 'foo = ""' or 'bar("")'.
134     SourceRange ReplaceRange(VDecl->getLocation(), VDecl->getEndLoc());
135     diag(VDecl->getLocation(), "redundant string initialization")
136         << FixItHint::CreateReplacement(ReplaceRange, VDecl->getName());
137   }
138   if (const auto *FDecl = Result.Nodes.getNodeAs<FieldDecl>("fieldDecl")) {
139     // FieldDecl's getSourceRange() spans 'string foo = ""'.
140     // So start at getLocation() to span just 'foo = ""'.
141     SourceRange ReplaceRange(FDecl->getLocation(), FDecl->getEndLoc());
142     diag(FDecl->getLocation(), "redundant string initialization")
143         << FixItHint::CreateReplacement(ReplaceRange, FDecl->getName());
144   }
145   if (const auto *CtorInit =
146           Result.Nodes.getNodeAs<CXXCtorInitializer>("ctorInit")) {
147     if (const FieldDecl *Member = CtorInit->getMember()) {
148       if (!Member->hasInClassInitializer() ||
149           Result.Nodes.getNodeAs<Expr>("empty_init")) {
150         // The String isn't declared in the class with an initializer or its
151         // declared with a redundant initializer, which will be removed. Either
152         // way the string will be default initialized, therefore we can remove
153         // the constructor initializer entirely.
154         diag(CtorInit->getMemberLocation(), "redundant string initialization")
155             << FixItHint::CreateRemoval(CtorInit->getSourceRange());
156         return;
157       }
158     }
159     const CXXConstructExpr *Construct = getConstructExpr(*CtorInit);
160     if (!Construct)
161       return;
162     if (llvm::Optional<SourceRange> RemovalRange =
163             getConstructExprArgRange(*Construct))
164       diag(CtorInit->getMemberLocation(), "redundant string initialization")
165           << FixItHint::CreateRemoval(*RemovalRange);
166   }
167 }
168 
169 } // namespace readability
170 } // namespace tidy
171 } // namespace clang
172