11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 #include "clang/Lex/Lexer.h" 14 #include "llvm/ADT/StringRef.h" 22 void ShrinkToFitCheck::registerMatchers(MatchFinder *Finder) {
23 if (!getLangOpts().CPlusPlus11)
28 const auto ShrinkableAsMember =
29 memberExpr(member(valueDecl().bind(
"ContainerDecl")));
30 const auto ShrinkableAsDecl =
31 declRefExpr(hasDeclaration(valueDecl().bind(
"ContainerDecl")));
32 const auto CopyCtorCall = cxxConstructExpr(hasArgument(
33 0, anyOf(ShrinkableAsMember, ShrinkableAsDecl,
34 unaryOperator(has(ignoringParenImpCasts(ShrinkableAsMember))),
35 unaryOperator(has(ignoringParenImpCasts(ShrinkableAsDecl))))));
36 const auto SwapParam =
37 expr(anyOf(memberExpr(member(equalsBoundNode(
"ContainerDecl"))),
38 declRefExpr(hasDeclaration(equalsBoundNode(
"ContainerDecl"))),
39 unaryOperator(has(ignoringParenImpCasts(
40 memberExpr(member(equalsBoundNode(
"ContainerDecl")))))),
41 unaryOperator(has(ignoringParenImpCasts(declRefExpr(
42 hasDeclaration(equalsBoundNode(
"ContainerDecl"))))))));
47 hasAnyName(
"std::basic_string",
"std::deque",
"std::vector")))),
48 callee(cxxMethodDecl(hasName(
"swap"))),
49 has(ignoringParenImpCasts(memberExpr(hasDescendant(CopyCtorCall)))),
50 hasArgument(0, SwapParam.bind(
"ContainerToShrink")),
51 unless(isInTemplateInstantiation()))
52 .bind(
"CopyAndSwapTrick"),
56 void ShrinkToFitCheck::check(
const MatchFinder::MatchResult &Result) {
57 const auto *MemberCall =
58 Result.Nodes.getNodeAs<CXXMemberCallExpr>(
"CopyAndSwapTrick");
59 const auto *Container = Result.Nodes.getNodeAs<Expr>(
"ContainerToShrink");
62 if (!MemberCall->getLocStart().isMacroID()) {
63 const LangOptions &Opts = getLangOpts();
64 std::string ReplacementText;
65 if (
const auto *UnaryOp = llvm::dyn_cast<UnaryOperator>(Container)) {
67 Lexer::getSourceText(CharSourceRange::getTokenRange(
68 UnaryOp->getSubExpr()->getSourceRange()),
69 *Result.SourceManager, Opts);
70 ReplacementText +=
"->shrink_to_fit()";
72 ReplacementText = Lexer::getSourceText(
73 CharSourceRange::getTokenRange(Container->getSourceRange()),
74 *Result.SourceManager, Opts);
75 ReplacementText +=
".shrink_to_fit()";
78 Hint = FixItHint::CreateReplacement(MemberCall->getSourceRange(),
82 diag(MemberCall->getLocStart(),
"the shrink_to_fit method should be used " 83 "to reduce the capacity of a shrinkable "