10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
19 UnhandledSelfAssignmentCheck::UnhandledSelfAssignmentCheck(
22 WarnOnlyIfThisHasSuspiciousField(
23 Options.get(
"WarnOnlyIfThisHasSuspiciousField", true)) {}
28 WarnOnlyIfThisHasSuspiciousField);
33 const auto IsUserDefined = cxxMethodDecl(
34 isDefinition(), unless(anyOf(isDeleted(), isImplicit(), isDefaulted())));
38 const auto HasReferenceParam =
39 cxxMethodDecl(hasParameter(0, parmVarDecl(hasType(referenceType()))));
43 const auto HasNoSelfCheck = cxxMethodDecl(unless(anyOf(
44 hasDescendant(binaryOperator(hasAnyOperatorName(
"==",
"!="),
45 has(ignoringParenCasts(cxxThisExpr())))),
46 hasDescendant(cxxOperatorCallExpr(
47 hasAnyOverloadedOperatorName(
"==",
"!="), argumentCountIs(2),
48 has(ignoringParenCasts(cxxThisExpr())))))));
53 const auto HasNonTemplateSelfCopy = cxxMethodDecl(
54 ofClass(cxxRecordDecl(unless(hasAncestor(classTemplateDecl())))),
55 traverse(ast_type_traits::TK_AsIs,
56 hasDescendant(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
57 isCopyConstructor(), ofClass(equalsBoundNode(
"class"))))))));
62 const auto HasTemplateSelfCopy = cxxMethodDecl(
63 ofClass(cxxRecordDecl(hasAncestor(classTemplateDecl()))),
65 varDecl(hasType(cxxRecordDecl(equalsBoundNode(
"class"))),
66 hasDescendant(parenListExpr()))),
67 hasDescendant(cxxUnresolvedConstructExpr(hasDescendant(declRefExpr(
68 hasType(cxxRecordDecl(equalsBoundNode(
"class")))))))));
73 const auto HasNoNestedSelfAssign =
74 cxxMethodDecl(unless(hasDescendant(cxxMemberCallExpr(callee(cxxMethodDecl(
75 hasName(
"operator="), ofClass(equalsBoundNode(
"class"))))))));
77 DeclarationMatcher AdditionalMatcher = cxxMethodDecl();
78 if (WarnOnlyIfThisHasSuspiciousField) {
80 const auto SmartPointerType = qualType(hasUnqualifiedDesugaredType(
81 recordType(hasDeclaration(classTemplateSpecializationDecl(
82 hasAnyName(
"::std::shared_ptr",
"::std::unique_ptr",
83 "::std::weak_ptr",
"::std::auto_ptr"),
84 templateArgumentCountIs(1))))));
90 AdditionalMatcher = cxxMethodDecl(ofClass(cxxRecordDecl(
91 has(fieldDecl(anyOf(hasType(pointerType()), hasType(SmartPointerType),
92 hasType(arrayType())))))));
95 Finder->addMatcher(cxxMethodDecl(ofClass(cxxRecordDecl().bind(
"class")),
96 isCopyAssignmentOperator(), IsUserDefined,
97 HasReferenceParam, HasNoSelfCheck,
98 unless(HasNonTemplateSelfCopy),
99 unless(HasTemplateSelfCopy),
100 HasNoNestedSelfAssign, AdditionalMatcher)
101 .bind(
"copyAssignmentOperator"),
106 const MatchFinder::MatchResult &Result) {
107 const auto *MatchedDecl =
108 Result.Nodes.getNodeAs<CXXMethodDecl>(
"copyAssignmentOperator");
109 diag(MatchedDecl->getLocation(),
110 "operator=() does not handle self-assignment properly");