clang-tools  10.0.0
StrCatAppendCheck.cpp
Go to the documentation of this file.
1 //===--- StrCatAppendCheck.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 "StrCatAppendCheck.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 namespace {
20 // Skips any combination of temporary materialization, temporary binding and
21 // implicit casting.
22 AST_MATCHER_P(Stmt, IgnoringTemporaries, ast_matchers::internal::Matcher<Stmt>,
23  InnerMatcher) {
24  const Stmt *E = &Node;
25  while (true) {
26  if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
27  E = MTE->getSubExpr();
28  if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
29  E = BTE->getSubExpr();
30  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
31  E = ICE->getSubExpr();
32  else
33  break;
34  }
35 
36  return InnerMatcher.matches(*E, Finder, Builder);
37 }
38 
39 } // namespace
40 
41 // TODO: str += StrCat(...)
42 // str.append(StrCat(...))
43 
44 void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) {
45  if (!getLangOpts().CPlusPlus)
46  return;
47  const auto StrCat = functionDecl(hasName("::absl::StrCat"));
48  // The arguments of absl::StrCat are implicitly converted to AlphaNum. This
49  // matches to the arguments because of that behavior.
50  const auto AlphaNum = IgnoringTemporaries(cxxConstructExpr(
51  argumentCountIs(1), hasType(cxxRecordDecl(hasName("::absl::AlphaNum"))),
52  hasArgument(0, ignoringImpCasts(declRefExpr(to(equalsBoundNode("LHS")),
53  expr().bind("Arg0"))))));
54 
55  const auto HasAnotherReferenceToLhs =
56  callExpr(hasAnyArgument(expr(hasDescendant(declRefExpr(
57  to(equalsBoundNode("LHS")), unless(equalsBoundNode("Arg0")))))));
58 
59  // Now look for calls to operator= with an object on the LHS and a call to
60  // StrCat on the RHS. The first argument of the StrCat call should be the same
61  // as the LHS. Ignore calls from template instantiations.
62  Finder->addMatcher(
63  cxxOperatorCallExpr(
64  unless(isInTemplateInstantiation()), hasOverloadedOperatorName("="),
65  hasArgument(0, declRefExpr(to(decl().bind("LHS")))),
66  hasArgument(1, IgnoringTemporaries(
67  callExpr(callee(StrCat), hasArgument(0, AlphaNum),
68  unless(HasAnotherReferenceToLhs))
69  .bind("Call"))))
70  .bind("Op"),
71  this);
72 }
73 
74 void StrCatAppendCheck::check(const MatchFinder::MatchResult &Result) {
75  const auto *Op = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("Op");
76  const auto *Call = Result.Nodes.getNodeAs<CallExpr>("Call");
77  assert(Op != nullptr && Call != nullptr && "Matcher does not work as expected");
78 
79  // Handles the case 'x = absl::StrCat(x)', which has no effect.
80  if (Call->getNumArgs() == 1) {
81  diag(Op->getBeginLoc(), "call to 'absl::StrCat' has no effect");
82  return;
83  }
84 
85  // Emit a warning and emit fixits to go from
86  // x = absl::StrCat(x, ...)
87  // to
88  // absl::StrAppend(&x, ...)
89  diag(Op->getBeginLoc(),
90  "call 'absl::StrAppend' instead of 'absl::StrCat' when appending to a "
91  "string to avoid a performance penalty")
92  << FixItHint::CreateReplacement(
93  CharSourceRange::getTokenRange(Op->getBeginLoc(),
94  Call->getCallee()->getEndLoc()),
95  "absl::StrAppend")
96  << FixItHint::CreateInsertion(Call->getArg(0)->getBeginLoc(), "&");
97 }
98 
99 } // namespace abseil
100 } // namespace tidy
101 } // namespace clang
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:227
CodeCompletionBuilder Builder
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
const Expr * E
AST_MATCHER_P(CXXMethodDecl, hasCanonicalDecl, ast_matchers::internal::Matcher< CXXMethodDecl >, InnerMatcher)