10 #include "clang/ASTMatchers/ASTMatchFinder.h"
11 #include "clang/ASTMatchers/ASTMatchers.h"
19 void UnconventionalAssignOperatorCheck::registerMatchers(
20 ast_matchers::MatchFinder *Finder) {
21 const auto HasGoodReturnType = cxxMethodDecl(returns(lValueReferenceType(
22 pointee(unless(isConstQualified()),
23 anyOf(autoType(), hasDeclaration(equalsBoundNode(
"class")))))));
25 const auto IsSelf = qualType(
26 anyOf(hasDeclaration(equalsBoundNode(
"class")),
27 referenceType(pointee(hasDeclaration(equalsBoundNode(
"class"))))));
29 cxxMethodDecl(unless(anyOf(isDeleted(), isPrivate(), isImplicit())),
30 hasName(
"operator="), ofClass(recordDecl().bind(
"class")))
32 const auto IsSelfAssign =
33 cxxMethodDecl(IsAssign, hasParameter(0, parmVarDecl(hasType(IsSelf))))
37 cxxMethodDecl(IsAssign, unless(HasGoodReturnType)).bind(
"ReturnType"),
40 const auto BadSelf = referenceType(
41 anyOf(lValueReferenceType(pointee(unless(isConstQualified()))),
42 rValueReferenceType(pointee(isConstQualified()))));
45 cxxMethodDecl(IsSelfAssign,
46 hasParameter(0, parmVarDecl(hasType(BadSelf))))
47 .bind(
"ArgumentType"),
51 cxxMethodDecl(IsSelfAssign, anyOf(isConst(), isVirtual())).bind(
"cv"),
54 const auto IsBadReturnStatement = returnStmt(unless(has(ignoringParenImpCasts(
55 anyOf(unaryOperator(hasOperatorName(
"*"), hasUnaryOperand(cxxThisExpr())),
56 cxxOperatorCallExpr(argumentCountIs(1),
57 callee(unresolvedLookupExpr()),
58 hasArgument(0, cxxThisExpr())),
60 hasOverloadedOperatorName(
"="),
62 0, unaryOperator(hasOperatorName(
"*"),
63 hasUnaryOperand(cxxThisExpr())))))))));
64 const auto IsGoodAssign = cxxMethodDecl(IsAssign, HasGoodReturnType);
66 Finder->addMatcher(returnStmt(IsBadReturnStatement, forFunction(IsGoodAssign))
71 void UnconventionalAssignOperatorCheck::check(
72 const MatchFinder::MatchResult &Result) {
73 if (
const auto *RetStmt = Result.Nodes.getNodeAs<ReturnStmt>(
"returnStmt")) {
74 diag(RetStmt->getBeginLoc(),
"operator=() should always return '*this'");
76 static const char *
const Messages[][2] = {
77 {
"ReturnType",
"operator=() should return '%0&'"},
79 getLangOpts().CPlusPlus11
80 ?
"operator=() should take '%0 const&', '%0&&' or '%0'"
81 :
"operator=() should take '%0 const&' or '%0'"},
82 {
"cv",
"operator=() should not be marked '%1'"}};
84 const auto *Method = Result.Nodes.getNodeAs<CXXMethodDecl>(
"method");
85 for (
const auto &
Message : Messages) {
87 diag(Method->getBeginLoc(),
Message[1])
88 << Method->getParent()->getName()
89 << (Method->isConst() ?
"const" :
"virtual");