10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Lexer.h"
13#include "llvm/ADT/StringRef.h"
22 const auto ShrinkableExpr = mapAnyOf(memberExpr, declRefExpr);
23 const auto Shrinkable =
24 ShrinkableExpr.with(hasDeclaration(valueDecl().bind(
"ContainerDecl")));
25 const auto BoundShrinkable = ShrinkableExpr.with(
26 hasDeclaration(valueDecl(equalsBoundNode(
"ContainerDecl"))));
30 callee(cxxMethodDecl(hasName(
"swap"))),
32 0, anyOf(Shrinkable, unaryOperator(hasUnaryOperand(Shrinkable)))),
33 on(cxxConstructExpr(hasArgument(
35 expr(anyOf(BoundShrinkable,
36 unaryOperator(hasUnaryOperand(BoundShrinkable))),
37 hasType(hasCanonicalType(hasDeclaration(namedDecl(hasAnyName(
38 "std::basic_string",
"std::deque",
"std::vector"))))))
39 .bind(
"ContainerToShrink")))))
40 .bind(
"CopyAndSwapTrick"),
45 const auto *MemberCall =
46 Result.Nodes.getNodeAs<CXXMemberCallExpr>(
"CopyAndSwapTrick");
47 const auto *
Container = Result.Nodes.getNodeAs<Expr>(
"ContainerToShrink");
50 if (!MemberCall->getBeginLoc().isMacroID()) {
52 std::string ReplacementText;
53 if (
const auto *UnaryOp = llvm::dyn_cast<UnaryOperator>(
Container)) {
54 ReplacementText = std::string(
55 Lexer::getSourceText(CharSourceRange::getTokenRange(
56 UnaryOp->getSubExpr()->getSourceRange()),
57 *Result.SourceManager, Opts));
58 ReplacementText +=
"->shrink_to_fit()";
60 ReplacementText = std::string(Lexer::getSourceText(
61 CharSourceRange::getTokenRange(
Container->getSourceRange()),
62 *Result.SourceManager, Opts));
63 ReplacementText +=
".shrink_to_fit()";
66 Hint = FixItHint::CreateReplacement(MemberCall->getSourceRange(),
70 diag(MemberCall->getBeginLoc(),
"the shrink_to_fit method should be used "
71 "to reduce the capacity of a shrinkable "
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.