11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
14 using namespace clang::ast_matchers;
20 void UnconventionalAssignOperatorCheck::registerMatchers(ast_matchers::MatchFinder *
Finder) {
23 if (!getLangOpts().CPlusPlus)
26 const auto HasGoodReturnType = cxxMethodDecl(returns(
27 lValueReferenceType(pointee(unless(isConstQualified()),
28 hasDeclaration(equalsBoundNode(
"class"))))));
30 const auto IsSelf = qualType(
31 anyOf(hasDeclaration(equalsBoundNode(
"class")),
32 referenceType(pointee(hasDeclaration(equalsBoundNode(
"class"))))));
34 cxxMethodDecl(unless(anyOf(isDeleted(), isPrivate(), isImplicit())),
35 hasName(
"operator="), ofClass(recordDecl().bind(
"class")))
37 const auto IsSelfAssign =
38 cxxMethodDecl(IsAssign, hasParameter(0, parmVarDecl(hasType(IsSelf))))
42 cxxMethodDecl(IsAssign, unless(HasGoodReturnType)).bind(
"ReturnType"),
45 const auto BadSelf = referenceType(
46 anyOf(lValueReferenceType(pointee(unless(isConstQualified()))),
47 rValueReferenceType(pointee(isConstQualified()))));
50 cxxMethodDecl(IsSelfAssign,
51 hasParameter(0, parmVarDecl(hasType(BadSelf))))
52 .bind(
"ArgumentType"),
56 cxxMethodDecl(IsSelfAssign, anyOf(isConst(), isVirtual())).bind(
"cv"),
59 const auto IsBadReturnStatement = returnStmt(unless(has(ignoringParenImpCasts(
60 unaryOperator(hasOperatorName(
"*"), hasUnaryOperand(cxxThisExpr()))))));
61 const auto IsGoodAssign = cxxMethodDecl(IsAssign, HasGoodReturnType);
63 Finder->addMatcher(returnStmt(IsBadReturnStatement, forFunction(IsGoodAssign))
68 void UnconventionalAssignOperatorCheck::check(
const MatchFinder::MatchResult &
Result) {
69 if (
const auto *RetStmt = Result.Nodes.getNodeAs<ReturnStmt>(
"returnStmt")) {
70 diag(RetStmt->getLocStart(),
"operator=() should always return '*this'");
72 static const char *
const Messages[][2] = {
73 {
"ReturnType",
"operator=() should return '%0&'"},
74 {
"ArgumentType",
"operator=() should take '%0 const&', '%0&&' or '%0'"},
75 {
"cv",
"operator=() should not be marked '%1'"}};
77 const auto *Method = Result.Nodes.getNodeAs<CXXMethodDecl>(
"method");
78 for (
const auto &Message : Messages) {
79 if (Result.Nodes.getNodeAs<Decl>(Message[0]))
80 diag(Method->getLocStart(), Message[1])
81 << Method->getParent()->getName()
82 << (Method->isConst() ?
"const" :
"virtual");
std::unique_ptr< ast_matchers::MatchFinder > Finder