File: FillInMissingMethodStubsFromAbstractClasses.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (292 lines) | stat: -rw-r--r-- 10,365 bytes parent folder | download
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//===--- FillInMissingMethodStubsFromAbstractClasses.cpp -  ---------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Implements the "Add missing abstract class method overrides" refactoring
// operation.
//
//===----------------------------------------------------------------------===//

#include "RefactoringOperations.h"
#include "SourceLocationUtilities.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"
#include "llvm/ADT/DenseSet.h"

using namespace clang;
using namespace clang::tooling;

namespace {

class FillInMissingMethodStubsFromAbstractClassesOperation
    : public RefactoringOperation {
public:
  FillInMissingMethodStubsFromAbstractClassesOperation(
      const CXXRecordDecl *Class)
      : Class(Class) {}

  const Decl *getTransformedDecl() const override { return Class; }

  llvm::Expected<RefactoringResult> perform(ASTContext &Context, const Preprocessor &ThePreprocessor,
          const RefactoringOptionSet &Options,
          unsigned SelectedCandidateIndex) override;

  const CXXRecordDecl *Class;
};

} // end anonymous namespace

static bool hasAbstractBases(const CXXRecordDecl *Class) {
  for (const CXXBaseSpecifier &Base : Class->bases()) {
    if (const auto *RD = Base.getType()->getAsCXXRecordDecl()) {
      if (RD->isAbstract())
        return true;
    }
  }
  return false;
}

RefactoringOperationResult
clang::tooling::initiateFillInMissingMethodStubsFromAbstractClassesOperation(
    ASTSlice &Slice, ASTContext &Context, SourceLocation Location,
    SourceRange SelectionRange, bool CreateOperation) {
  auto SelectedDecl = Slice.innermostSelectedDecl(
      ArrayRef(Decl::CXXRecord), ASTSlice::InnermostDeclOnly);
  if (!SelectedDecl)
    return std::nullopt;
  const auto *Class = cast<CXXRecordDecl>(SelectedDecl->getDecl());
  if (Class->isUnion() || !Class->isThisDeclarationADefinition())
    return std::nullopt;
  if (!hasAbstractBases(Class))
    return RefactoringOperationResult("The class has no abstract bases");
  if (!Class->isDependentType() && !Class->isAbstract())
    return RefactoringOperationResult(
        "The class has no missing abstract class methods");

  RefactoringOperationResult Result;
  Result.Initiated = true;
  if (!CreateOperation)
    return Result;
  auto Operation =
      std::make_unique<FillInMissingMethodStubsFromAbstractClassesOperation>(
          Class);
  Result.RefactoringOp = std::move(Operation);
  return Result;
}

namespace {

class PureMethodSet {
  llvm::DenseMap<const CXXMethodDecl *, int> Methods;

  void addPureMethodsFromAbstractClasses(const CXXRecordDecl *Class,
                                         int &Priority) {
    for (const CXXBaseSpecifier &Base : Class->bases()) {
      const auto *RD = Base.getType()->getAsCXXRecordDecl();
      if (!RD || !RD->isAbstract())
        continue;
      for (const CXXMethodDecl *M : RD->methods()) {
        if (M->isPure())
          Methods.insert(std::make_pair(M->getCanonicalDecl(), Priority++));
      }
      addPureMethodsFromAbstractClasses(RD, Priority);
    }
  }

  void addPureMethodsFromAbstractClasses(const CXXRecordDecl *Class) {
    int Priority = 0;
    addPureMethodsFromAbstractClasses(Class, Priority);
  }

  void subtractImplementedPureMethods(const CXXRecordDecl *Class) {
    for (const CXXMethodDecl *M : Class->methods()) {
      if (!M->isVirtual() || M->isPure())
        continue;
      for (const CXXMethodDecl *OM : M->overridden_methods()) {
        OM = OM->getCanonicalDecl();
        if (OM->isPure())
          Methods.erase(OM);
      }
    }
    for (const CXXBaseSpecifier &Base : Class->bases()) {
      const auto *RD = Base.getType()->getAsCXXRecordDecl();
      if (!RD || !RD->isAbstract())
        continue;
      subtractImplementedPureMethods(RD);
    }
  }

public:
  static std::vector<const CXXMethodDecl *>
  gatherMissingMethods(const CXXRecordDecl *Class) {
    PureMethodSet MethodSet;
    MethodSet.addPureMethodsFromAbstractClasses(Class);
    MethodSet.subtractImplementedPureMethods(Class);
    // Sort the missing methods. That will place methods from the same abstract
    // class together in the order in which they were declared.
    struct MethodInfo {
      const CXXMethodDecl *M;
      int Priority;
    };
    std::vector<MethodInfo> MissingMethods;
    for (const auto &M : MethodSet.Methods)
      MissingMethods.push_back({M.first, M.second});
    std::sort(MissingMethods.begin(), MissingMethods.end(),
              [](const MethodInfo &LHS, const MethodInfo &RHS) {
                return LHS.Priority < RHS.Priority;
              });
    std::vector<const CXXMethodDecl *> Result;
    Result.reserve(MissingMethods.size());
    for (const auto &M : MissingMethods)
      Result.push_back(M.M);
    return Result;
  }
};

} // end anonymous namespace

static SourceLocation findInsertionLocationForMethodsFromAbstractClass(
    const CXXRecordDecl *AbstractClass, const CXXRecordDecl *Class,
    const SourceManager &SM, const LangOptions &LangOpts) {
  SourceLocation Loc;
  for (const CXXMethodDecl *M : Class->methods()) {
    if (!M->isVirtual() || M->isPure() || M->isImplicit())
      continue;
    for (const CXXMethodDecl *OM : M->overridden_methods()) {
      OM = OM->getCanonicalDecl();
      if (OM->getLexicalDeclContext() == AbstractClass) {
        SourceLocation EndLoc = M->getEndLoc();
        if (EndLoc.isMacroID())
          EndLoc = SM.getExpansionRange(EndLoc).getEnd();
        if (Loc.isInvalid())
          Loc = EndLoc;
        else if (SM.isBeforeInTranslationUnit(Loc, EndLoc))
          Loc = EndLoc;
        break;
      }
    }
  }
  if (Loc.isInvalid())
    return Loc;
  return getLastLineLocationUnlessItHasOtherTokens(Loc, SM, LangOpts);
}

/// Returns true if the given \p Class implements the majority of declared
/// methods in the class itself.
static bool shouldImplementMethodsInClass(const CXXRecordDecl *Class) {
  // Check if this class implements the methods in the class itself.
  unsigned NumMethods = 0, NumImplementedMethods = 0;
  for (const CXXMethodDecl *M : Class->methods()) {
    if (M->isImplicit())
      continue;
    // Only look at methods/operators.
    if (isa<CXXConstructorDecl>(M) || isa<CXXDestructorDecl>(M))
      continue;
    ++NumMethods;
    if (M->hasBody())
      ++NumImplementedMethods;
  }
  if (!NumMethods)
    return false;
  // Use the following arbitrary heuristic:
  // If the number of method declarations is less than 4, then all of the
  // methods must have bodies. Otherwise, at least 75% of the methods must
  // have bodies.
  return NumMethods < 4
             ? NumMethods == NumImplementedMethods
             : float(NumImplementedMethods) / float(NumMethods) > 0.75;
}

llvm::Expected<RefactoringResult>
FillInMissingMethodStubsFromAbstractClassesOperation::perform(
    ASTContext &Context, const Preprocessor &ThePreprocessor,
    const RefactoringOptionSet &Options, unsigned SelectedCandidateIndex) {
  std::vector<RefactoringReplacement> Replacements;

  std::vector<const CXXMethodDecl *> MissingMethods =
      PureMethodSet::gatherMissingMethods(Class);

  bool GenerateBodyDummies = shouldImplementMethodsInClass(Class);

  PrintingPolicy PP = Context.getPrintingPolicy();
  PP.PolishForDeclaration = true;
  PP.SuppressStrongLifetime = true;
  PP.SuppressLifetimeQualifiers = true;
  PP.SuppressUnwrittenScope = true;

  std::string EndInsertionOSStr;
  llvm::raw_string_ostream EndInsertionOS(EndInsertionOSStr);

  std::string InsertionGroupOSStr;
  llvm::raw_string_ostream InsertionGroupOS(InsertionGroupOSStr);

  SourceLocation InsertionLoc = Class->getEndLoc();
  const CXXRecordDecl *CurrentAbstractClass = nullptr;
  SourceLocation CurrentGroupInsertionLoc;
  for (const auto &I : llvm::enumerate(MissingMethods)) {
    const CXXMethodDecl *Method = I.value();
    const CXXRecordDecl *AbstractClass = Method->getParent();
    if (CurrentAbstractClass != AbstractClass) {
      if (!InsertionGroupOS.str().empty()) {
        assert(CurrentGroupInsertionLoc.isValid());
        Replacements.emplace_back(
            SourceRange(CurrentGroupInsertionLoc, CurrentGroupInsertionLoc),
            InsertionGroupOS.str());
      }
      InsertionGroupOSStr.clear();
      CurrentAbstractClass = AbstractClass;
      CurrentGroupInsertionLoc =
          findInsertionLocationForMethodsFromAbstractClass(
              CurrentAbstractClass, Class, Context.getSourceManager(),
              Context.getLangOpts());
    }
    bool IsInsertingAfterRelatedMethods = CurrentGroupInsertionLoc.isValid();
    raw_ostream &OS =
        IsInsertingAfterRelatedMethods ? InsertionGroupOS : EndInsertionOS;

    if (IsInsertingAfterRelatedMethods && InsertionGroupOS.str().empty())
      OS << "\n\n";
    // Print the method without the 'virtual' specifier and the pure '= 0'
    // annotation.
    auto *MD = const_cast<CXXMethodDecl *>(Method);
    bool IsVirtual = MD->isVirtualAsWritten();
    MD->setVirtualAsWritten(false);
    bool IsPure = MD->isPure();
    MD->setPure(false);
    MD->print(OS, PP);
    MD->setVirtualAsWritten(IsVirtual);
    MD->setPure(IsPure);

    OS << " override";
    if (GenerateBodyDummies)
      OS << " { \n  <#code#>\n}\n";
    else
      OS << ";\n";
    // Avoid an additional newline for the last method in an insertion group.
    if (IsInsertingAfterRelatedMethods) {
      const CXXRecordDecl *NextAbstractClass =
          (I.index() + 1) != MissingMethods.size()
              ? MissingMethods[I.index() + 1]->getParent()
              : nullptr;
      if (NextAbstractClass == CurrentAbstractClass)
        OS << "\n";
    } else
      OS << "\n";
  }
  if (!InsertionGroupOS.str().empty()) {
    assert(CurrentGroupInsertionLoc.isValid());
    Replacements.emplace_back(
        SourceRange(CurrentGroupInsertionLoc, CurrentGroupInsertionLoc),
        InsertionGroupOS.str());
  }
  if (!EndInsertionOS.str().empty())
    Replacements.emplace_back(SourceRange(InsertionLoc, InsertionLoc),
                              EndInsertionOS.str());

  return std::move(Replacements);
}