1 //===--- RedundantStrcatCallsCheck.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 
9 #include "RedundantStrcatCallsCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace abseil {
18 
19 // TODO: Features to add to the check:
20 //  - Make it work if num_args > 26.
21 //  - Remove empty literal string arguments.
22 //  - Collapse consecutive literal string arguments into one (remove the ,).
23 //  - Replace StrCat(a + b)  ->  StrCat(a, b)  if a or b are strings.
24 //  - Make it work in macros if the outer and inner StrCats are both in the
25 //    argument.
26 
registerMatchers(MatchFinder * Finder)27 void RedundantStrcatCallsCheck::registerMatchers(MatchFinder* Finder) {
28   if (!getLangOpts().CPlusPlus)
29   	return;
30   const auto CallToStrcat =
31       callExpr(callee(functionDecl(hasName("::absl::StrCat"))));
32   const auto CallToStrappend =
33       callExpr(callee(functionDecl(hasName("::absl::StrAppend"))));
34   // Do not match StrCat() calls that are descendants of other StrCat calls.
35   // Those are handled on the ancestor call.
36   const auto CallToEither = callExpr(
37       callee(functionDecl(hasAnyName("::absl::StrCat", "::absl::StrAppend"))));
38   Finder->addMatcher(
39       callExpr(CallToStrcat, unless(hasAncestor(CallToEither))).bind("StrCat"),
40       this);
41   Finder->addMatcher(CallToStrappend.bind("StrAppend"), this);
42 }
43 
44 namespace {
45 
46 struct StrCatCheckResult {
47   int NumCalls = 0;
48   std::vector<FixItHint> Hints;
49 };
50 
RemoveCallLeaveArgs(const CallExpr * Call,StrCatCheckResult * CheckResult)51 void RemoveCallLeaveArgs(const CallExpr* Call, StrCatCheckResult* CheckResult) {
52   // Remove 'Foo('
53   CheckResult->Hints.push_back(
54       FixItHint::CreateRemoval(CharSourceRange::getCharRange(
55           Call->getBeginLoc(), Call->getArg(0)->getBeginLoc())));
56   // Remove the ')'
57   CheckResult->Hints.push_back(
58       FixItHint::CreateRemoval(CharSourceRange::getCharRange(
59           Call->getRParenLoc(), Call->getEndLoc().getLocWithOffset(1))));
60 }
61 
ProcessArgument(const Expr * Arg,const MatchFinder::MatchResult & Result,StrCatCheckResult * CheckResult)62 const clang::CallExpr* ProcessArgument(const Expr* Arg,
63                                        const MatchFinder::MatchResult& Result,
64                                        StrCatCheckResult* CheckResult) {
65   const auto IsAlphanum = hasDeclaration(cxxMethodDecl(hasName("AlphaNum")));
66   static const auto* const Strcat = new auto(hasName("::absl::StrCat"));
67   const auto IsStrcat = cxxBindTemporaryExpr(
68       has(callExpr(callee(functionDecl(*Strcat))).bind("StrCat")));
69   if (const auto* SubStrcatCall = selectFirst<const CallExpr>(
70           "StrCat",
71           match(stmt(anyOf(
72                     cxxConstructExpr(IsAlphanum, hasArgument(0, IsStrcat)),
73                     IsStrcat)),
74                 *Arg->IgnoreParenImpCasts(), *Result.Context))) {
75     RemoveCallLeaveArgs(SubStrcatCall, CheckResult);
76     return SubStrcatCall;
77   }
78   return nullptr;
79 }
80 
ProcessCall(const CallExpr * RootCall,bool IsAppend,const MatchFinder::MatchResult & Result)81 StrCatCheckResult ProcessCall(const CallExpr* RootCall, bool IsAppend,
82                               const MatchFinder::MatchResult& Result) {
83   StrCatCheckResult CheckResult;
84   std::deque<const CallExpr*> CallsToProcess = {RootCall};
85 
86   while (!CallsToProcess.empty()) {
87     ++CheckResult.NumCalls;
88 
89     const CallExpr* CallExpr = CallsToProcess.front();
90     CallsToProcess.pop_front();
91 
92     int StartArg = CallExpr == RootCall && IsAppend;
93     for (const auto *Arg : CallExpr->arguments()) {
94       if (StartArg-- > 0)
95       	continue;
96       if (const clang::CallExpr* Sub =
97               ProcessArgument(Arg, Result, &CheckResult)) {
98         CallsToProcess.push_back(Sub);
99       }
100     }
101   }
102   return CheckResult;
103 }
104 }  // namespace
105 
check(const MatchFinder::MatchResult & Result)106 void RedundantStrcatCallsCheck::check(const MatchFinder::MatchResult& Result) {
107   bool IsAppend;
108 
109   const CallExpr* RootCall;
110   if ((RootCall = Result.Nodes.getNodeAs<CallExpr>("StrCat")))
111   	IsAppend = false;
112   else if ((RootCall = Result.Nodes.getNodeAs<CallExpr>("StrAppend")))
113   	IsAppend = true;
114   else
115   	return;
116 
117   if (RootCall->getBeginLoc().isMacroID()) {
118     // Ignore calls within macros.
119     // In many cases the outer StrCat part of the macro and the inner StrCat is
120     // a macro argument. Removing the inner StrCat() converts one macro
121     // argument into many.
122     return;
123   }
124 
125   const StrCatCheckResult CheckResult =
126       ProcessCall(RootCall, IsAppend, Result);
127   if (CheckResult.NumCalls == 1) {
128     // Just one call, so nothing to fix.
129     return;
130   }
131 
132   diag(RootCall->getBeginLoc(),
133   	   "multiple calls to 'absl::StrCat' can be flattened into a single call")
134       << CheckResult.Hints;
135 }
136 
137 }  // namespace abseil
138 }  // namespace tidy
139 }  // namespace clang
140