11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
14 using namespace clang::ast_matchers;
20 void UnconventionalAssignOperatorCheck::registerMatchers(
21 ast_matchers::MatchFinder *
Finder) {
24 if (!getLangOpts().CPlusPlus)
27 const auto HasGoodReturnType = cxxMethodDecl(returns(
28 lValueReferenceType(pointee(unless(isConstQualified()),
29 hasDeclaration(equalsBoundNode(
"class"))))));
31 const auto IsSelf = qualType(
32 anyOf(hasDeclaration(equalsBoundNode(
"class")),
33 referenceType(pointee(hasDeclaration(equalsBoundNode(
"class"))))));
35 cxxMethodDecl(unless(anyOf(isDeleted(), isPrivate(), isImplicit())),
36 hasName(
"operator="), ofClass(recordDecl().bind(
"class")))
38 const auto IsSelfAssign =
39 cxxMethodDecl(IsAssign, hasParameter(0, parmVarDecl(hasType(IsSelf))))
43 cxxMethodDecl(IsAssign, unless(HasGoodReturnType)).bind(
"ReturnType"),
46 const auto BadSelf = referenceType(
47 anyOf(lValueReferenceType(pointee(unless(isConstQualified()))),
48 rValueReferenceType(pointee(isConstQualified()))));
51 cxxMethodDecl(IsSelfAssign,
52 hasParameter(0, parmVarDecl(hasType(BadSelf))))
53 .bind(
"ArgumentType"),
57 cxxMethodDecl(IsSelfAssign, anyOf(isConst(), isVirtual())).bind(
"cv"),
60 const auto IsBadReturnStatement = returnStmt(unless(has(ignoringParenImpCasts(
61 anyOf(unaryOperator(hasOperatorName(
"*"), hasUnaryOperand(cxxThisExpr())),
62 cxxOperatorCallExpr(argumentCountIs(1),
63 callee(unresolvedLookupExpr()),
64 hasArgument(0, cxxThisExpr())))))));
65 const auto IsGoodAssign = cxxMethodDecl(IsAssign, HasGoodReturnType);
67 Finder->addMatcher(returnStmt(IsBadReturnStatement, forFunction(IsGoodAssign))
72 void UnconventionalAssignOperatorCheck::check(
73 const MatchFinder::MatchResult &Result) {
74 if (
const auto *RetStmt = Result.Nodes.getNodeAs<ReturnStmt>(
"returnStmt")) {
75 diag(RetStmt->getLocStart(),
"operator=() should always return '*this'");
77 static const char *
const Messages[][2] = {
78 {
"ReturnType",
"operator=() should return '%0&'"},
79 {
"ArgumentType",
"operator=() should take '%0 const&', '%0&&' or '%0'"},
80 {
"cv",
"operator=() should not be marked '%1'"}};
82 const auto *Method = Result.Nodes.getNodeAs<CXXMethodDecl>(
"method");
83 for (
const auto &
Message : Messages) {
84 if (Result.Nodes.getNodeAs<Decl>(
Message[0]))
85 diag(Method->getLocStart(),
Message[1])
86 << Method->getParent()->getName()
87 << (Method->isConst() ?
"const" :
"virtual");
std::unique_ptr< ast_matchers::MatchFinder > Finder
static const StringRef Message