aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clang-tidy/bugprone/CrtpConstructorAccessibilityCheck.cpp
blob: 6565fa3f7c85b05e0a647745661de12657debfd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
//===--- CrtpConstructorAccessibilityCheck.cpp - clang-tidy ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "CrtpConstructorAccessibilityCheck.h"
#include "../utils/LexerUtils.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang::tidy::bugprone {

static bool hasPrivateConstructor(const CXXRecordDecl *RD) {
  return llvm::any_of(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
    return Ctor->getAccess() == AS_private;
  });
}

static bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
                                         const NamedDecl *Param) {
  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
    const TypeSourceInfo *const FriendType = Friend->getFriendType();
    if (!FriendType) {
      return false;
    }

    const auto *const TTPT =
        dyn_cast<TemplateTypeParmType>(FriendType->getType());

    return TTPT && TTPT->getDecl() == Param;
  });
}

static bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
                                     const CXXRecordDecl *Derived) {
  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
    const TypeSourceInfo *const FriendType = Friend->getFriendType();
    if (!FriendType) {
      return false;
    }

    return FriendType->getType()->getAsCXXRecordDecl() == Derived;
  });
}

static const NamedDecl *
getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
                    const CXXRecordDecl *Derived) {
  size_t Idx = 0;
  const bool AnyOf = llvm::any_of(
      CRTP->getTemplateArgs().asArray(), [&](const TemplateArgument &Arg) {
        ++Idx;
        return Arg.getKind() == TemplateArgument::Type &&
               Arg.getAsType()->getAsCXXRecordDecl() == Derived;
      });

  return AnyOf ? CRTP->getSpecializedTemplate()
                     ->getTemplateParameters()
                     ->getParam(Idx - 1)
               : nullptr;
}

static std::vector<FixItHint>
hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
                    const std::string &OriginalAccess) {
  std::vector<FixItHint> Hints;

  Hints.emplace_back(FixItHint::CreateInsertion(
      Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));

  const ASTContext &ASTCtx = Ctor->getASTContext();
  const SourceLocation CtorEndLoc =
      Ctor->isExplicitlyDefaulted()
          ? utils::lexer::findNextTerminator(Ctor->getEndLoc(),
                                             ASTCtx.getSourceManager(),
                                             ASTCtx.getLangOpts())
          : Ctor->getEndLoc();
  Hints.emplace_back(FixItHint::CreateInsertion(
      CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));

  return Hints;
}

void CrtpConstructorAccessibilityCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      classTemplateSpecializationDecl(
          decl().bind("crtp"),
          hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
              cxxRecordDecl(
                  isDerivedFrom(cxxRecordDecl(equalsBoundNode("crtp"))))
                  .bind("derived")))))),
      this);
}

void CrtpConstructorAccessibilityCheck::check(
    const MatchFinder::MatchResult &Result) {
  const auto *CRTPInstantiation =
      Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>("crtp");
  const auto *DerivedRecord = Result.Nodes.getNodeAs<CXXRecordDecl>("derived");
  const CXXRecordDecl *CRTPDeclaration =
      CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();

  if (!CRTPDeclaration->hasDefinition()) {
    return;
  }

  const auto *DerivedTemplateParameter =
      getDerivedParameter(CRTPInstantiation, DerivedRecord);

  assert(DerivedTemplateParameter &&
         "No template parameter corresponds to the derived class of the CRTP.");

  bool NeedsFriend = !isDerivedParameterBefriended(CRTPDeclaration,
                                                   DerivedTemplateParameter) &&
                     !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord);

  const FixItHint HintFriend = FixItHint::CreateInsertion(
      CRTPDeclaration->getBraceRange().getEnd(),
      "friend " + DerivedTemplateParameter->getNameAsString() + ';' + '\n');

  if (hasPrivateConstructor(CRTPDeclaration) && NeedsFriend) {
    diag(CRTPDeclaration->getLocation(),
         "the CRTP cannot be constructed from the derived class; consider "
         "declaring the derived class as friend")
        << HintFriend;
  }

  auto WithFriendHintIfNeeded = [&](const DiagnosticBuilder &Diag,
                                    bool NeedsFriend) {
    if (NeedsFriend)
      Diag << HintFriend;
  };

  if (!CRTPDeclaration->hasUserDeclaredConstructor()) {
    const bool IsStruct = CRTPDeclaration->isStruct();

    WithFriendHintIfNeeded(
        diag(CRTPDeclaration->getLocation(),
             "the implicit default constructor of the CRTP is publicly "
             "accessible; consider making it private%select{| and declaring "
             "the derived class as friend}0")
            << NeedsFriend
            << FixItHint::CreateInsertion(
                   CRTPDeclaration->getBraceRange().getBegin().getLocWithOffset(
                       1),
                   (IsStruct ? "\nprivate:\n" : "\n") +
                       CRTPDeclaration->getNameAsString() + "() = default;\n" +
                       (IsStruct ? "public:\n" : "")),
        NeedsFriend);
  }

  for (auto &&Ctor : CRTPDeclaration->ctors()) {
    if (Ctor->getAccess() == AS_private || Ctor->isDeleted())
      continue;

    const bool IsPublic = Ctor->getAccess() == AS_public;
    const std::string Access = IsPublic ? "public" : "protected";

    WithFriendHintIfNeeded(
        diag(Ctor->getLocation(),
             "%0 constructor allows the CRTP to be %select{inherited "
             "from|constructed}1 as a regular template class; consider making "
             "it private%select{| and declaring the derived class as friend}2")
            << Access << IsPublic << NeedsFriend
            << hintMakeCtorPrivate(Ctor, Access),
        NeedsFriend);
  }
}

bool CrtpConstructorAccessibilityCheck::isLanguageVersionSupported(
    const LangOptions &LangOpts) const {
  return LangOpts.CPlusPlus11;
}
} // namespace clang::tidy::bugprone