10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
22 const auto MemberExprOrSourceObject = anyOf(
24 declRefExpr(to(decl(equalsBoundNode(std::string(
SourceDeclName))))));
26 const auto IsPartOfSource =
27 allOf(unless(hasDescendant(expr(unless(MemberExprOrSourceObject)))),
28 MemberExprOrSourceObject);
30 const auto IsSourceMutatingAssignment = traverse(
31 TK_AsIs, binaryOperation(hasOperatorName(
"="), hasLHS(IsPartOfSource))
34 const auto MemberExprOrSelf = anyOf(memberExpr(), cxxThisExpr());
36 const auto IsPartOfSelf = allOf(
37 unless(hasDescendant(expr(unless(MemberExprOrSelf)))), MemberExprOrSelf);
39 const auto IsSelfMutatingAssignment =
40 binaryOperation(isAssignmentOperator(), hasLHS(IsPartOfSelf));
42 const auto IsSelfMutatingMemberFunction =
43 functionDecl(hasBody(hasDescendant(IsSelfMutatingAssignment)));
45 const auto IsSourceMutatingMemberCall =
46 cxxMemberCallExpr(on(IsPartOfSource),
47 callee(IsSelfMutatingMemberFunction))
50 const auto MutatesSource = allOf(
52 0, parmVarDecl(hasType(lValueReferenceType())).bind(
SourceDeclName)),
53 anyOf(forEachDescendant(IsSourceMutatingAssignment),
54 forEachDescendant(IsSourceMutatingMemberCall)));
56 Finder->addMatcher(cxxConstructorDecl(isCopyConstructor(), MutatesSource),
59 Finder->addMatcher(cxxMethodDecl(isCopyAssignmentOperator(), MutatesSource),
64 if (
const auto *MemberCall =
66 diag(MemberCall->getBeginLoc(),
"call mutates copied object");
67 else if (
const auto *Assignment =
69 diag(Assignment->getBeginLoc(),
"mutating copied object");
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
static constexpr llvm::StringLiteral SourceDeclName
static constexpr llvm::StringLiteral MutatingCallName
static constexpr llvm::StringLiteral MutatingOperatorName