10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
22 AST_MATCHER_P(Stmt, IgnoringTemporaries, ast_matchers::internal::Matcher<Stmt>,
24 const Stmt *
E = &Node;
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();
36 return InnerMatcher.matches(*
E, Finder,
Builder);
44 void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) {
45 const auto StrCat = functionDecl(hasName(
"::absl::StrCat"));
48 const auto AlphaNum = IgnoringTemporaries(cxxConstructExpr(
49 argumentCountIs(1), hasType(cxxRecordDecl(hasName(
"::absl::AlphaNum"))),
50 hasArgument(0, ignoringImpCasts(declRefExpr(to(equalsBoundNode(
"LHS")),
51 expr().bind(
"Arg0"))))));
53 const auto HasAnotherReferenceToLhs =
54 callExpr(hasAnyArgument(expr(hasDescendant(declRefExpr(
55 to(equalsBoundNode(
"LHS")), unless(equalsBoundNode(
"Arg0")))))));
61 traverse(ast_type_traits::TK_AsIs,
63 unless(isInTemplateInstantiation()),
64 hasOverloadedOperatorName(
"="),
65 hasArgument(0, declRefExpr(to(decl().bind(
"LHS")))),
67 1, IgnoringTemporaries(
68 callExpr(callee(StrCat), hasArgument(0, AlphaNum),
69 unless(HasAnotherReferenceToLhs))
75 void StrCatAppendCheck::check(
const MatchFinder::MatchResult &Result) {
76 const auto *Op = Result.Nodes.getNodeAs<CXXOperatorCallExpr>(
"Op");
77 const auto *Call = Result.Nodes.getNodeAs<CallExpr>(
"Call");
78 assert(Op !=
nullptr && Call !=
nullptr &&
"Matcher does not work as expected");
81 if (Call->getNumArgs() == 1) {
82 diag(Op->getBeginLoc(),
"call to 'absl::StrCat' has no effect");
90 diag(Op->getBeginLoc(),
91 "call 'absl::StrAppend' instead of 'absl::StrCat' when appending to a "
92 "string to avoid a performance penalty")
93 << FixItHint::CreateReplacement(
94 CharSourceRange::getTokenRange(Op->getBeginLoc(),
95 Call->getCallee()->getEndLoc()),
97 << FixItHint::CreateInsertion(Call->getArg(0)->getBeginLoc(),
"&");