File: ImplementDeclaredMethods.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 (460 lines) | stat: -rw-r--r-- 17,933 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//===--- ImplementDeclaredMethods.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 "Generate missing method definitions" refactoring
// operation.
//
//===----------------------------------------------------------------------===//

#include "RefactoringContinuations.h"
#include "RefactoringOperations.h"
#include "SourceLocationUtilities.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"

using namespace clang;
using namespace clang::tooling;

namespace {

template <typename ClassType, typename MethodType, typename Derived>
class ImplementDeclaredMethodsOperation : public RefactoringOperation {
public:
  ImplementDeclaredMethodsOperation(
      const ClassType *Container, ArrayRef<const MethodType *> SelectedMethods)
      : Container(Container),
        SelectedMethods(SelectedMethods.begin(), SelectedMethods.end()) {}

  const Decl *getTransformedDecl() const override {
    return SelectedMethods.front();
  }

  const Decl *getLastTransformedDecl() const override {
    return SelectedMethods.back();
  }

  static RefactoringOperationResult
  initiate(const ClassType *Container, ArrayRef<const MethodType *> Methods,
           bool CreateOperation) {
    if (Methods.empty())
      return std::nullopt;

    RefactoringOperationResult Result;
    Result.Initiated = true;
    if (!CreateOperation)
      return Result;
    auto Operation = std::make_unique<Derived>(Container, Methods);
    Result.RefactoringOp = std::move(Operation);
    return Result;
  }

  const ClassType *Container;
  llvm::SmallVector<const MethodType *, 8> SelectedMethods;
};

class ImplementDeclaredCXXMethodsOperation
    : public ImplementDeclaredMethodsOperation<
          CXXRecordDecl, CXXMethodDecl, ImplementDeclaredCXXMethodsOperation> {
public:
  ImplementDeclaredCXXMethodsOperation(
      const CXXRecordDecl *Container,
      ArrayRef<const CXXMethodDecl *> SelectedMethods)
      : ImplementDeclaredMethodsOperation(Container, SelectedMethods) {}

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

  static void addInlineBody(const CXXMethodDecl *MD, const ASTContext &Context,
                            std::vector<RefactoringReplacement> &Replacements);

  static llvm::Expected<RefactoringResult> runInImplementationAST(
      ASTContext &Context, const FileID &File, const CXXRecordDecl *Class,
      ArrayRef<indexer::Indexed<const CXXMethodDecl *>> SelectedMethods);
};

class ImplementDeclaredObjCMethodsOperation
    : public ImplementDeclaredMethodsOperation<
          ObjCContainerDecl, ObjCMethodDecl,
          ImplementDeclaredObjCMethodsOperation> {
  const ObjCInterfaceDecl *Interface;

public:
  ImplementDeclaredObjCMethodsOperation(
      const ObjCContainerDecl *Container,
      ArrayRef<const ObjCMethodDecl *> SelectedMethods)
      : ImplementDeclaredMethodsOperation(Container, SelectedMethods) {
    if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Container))
      Interface = CD->getClassInterface();
    else
      Interface = nullptr;
  }

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

  static llvm::Expected<RefactoringResult> runInImplementationAST(
      ASTContext &Context, const FileID &File,
      const ObjCContainerDecl *Container, const ObjCInterfaceDecl *Interface,
      ArrayRef<std::string> MethodDeclarations,
      ArrayRef<indexer::Indexed<const ObjCMethodDecl *>> SelectedMethods);
};

/// Returns true if the given Objective-C method has an implementation.
bool isImplemented(const ObjCMethodDecl *M) {
  if (M->hasBody() || M->isDefined())
    return true;
  return false;
}

} // end anonymous namespace

RefactoringOperationResult
clang::tooling::initiateImplementDeclaredMethodsOperation(
    ASTSlice &Slice, ASTContext &Context, SourceLocation Location,
    SourceRange SelectionRange, bool CreateOperation) {
  // Find the selected Class.
  auto SelectedDecl = Slice.innermostSelectedDecl([](const Decl *D) {
    return isa<CXXRecordDecl>(D) || isa<ObjCInterfaceDecl>(D) ||
           isa<ObjCCategoryDecl>(D);
  });
  if (!SelectedDecl)
    return std::nullopt;
  // Look at the set of methods that intersect with the selection.
  if (const auto *CXXClass = dyn_cast<CXXRecordDecl>(SelectedDecl->getDecl())) {
    if (CXXClass->isDependentType())
      return RefactoringOperationResult("templates are unsupported");
    llvm::SmallVector<const CXXMethodDecl *, 8> SelectedMethods;
    for (const CXXMethodDecl *M : CXXClass->methods()) {
      if (M->isImplicit() || M->hasBody() || M->isPure() || M->isDefaulted() ||
          M->isDeletedAsWritten() || M->getDescribedFunctionTemplate())
        continue;
      if (Slice.isSourceRangeSelected(
              CharSourceRange::getTokenRange(M->getSourceRange())))
        SelectedMethods.push_back(M);
    }
    return ImplementDeclaredCXXMethodsOperation::initiate(
        CXXClass, SelectedMethods, CreateOperation);
  }
  const ObjCContainerDecl *Container =
      cast<ObjCContainerDecl>(SelectedDecl->getDecl());
  llvm::SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
  for (const ObjCMethodDecl *M : Container->methods()) {
    if (M->isImplicit() || isImplemented(M))
      continue;
    if (Slice.isSourceRangeSelected(
            CharSourceRange::getTokenRange(M->getSourceRange())))
      SelectedMethods.push_back(M);
  }
  // Method declarations from class extensions should be defined in class
  // @implementations.
  if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
    if (Category->IsClassExtension())
      Container = Category->getClassInterface();
  }
  return ImplementDeclaredObjCMethodsOperation::initiate(
      Container, SelectedMethods, CreateOperation);
}

static bool isInLocalScope(const Decl *D) {
  const DeclContext *LDC = D->getLexicalDeclContext();
  while (true) {
    if (LDC->isFunctionOrMethod())
      return true;
    if (!isa<TagDecl>(LDC))
      return false;
    if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
      if (CRD->isLambda())
        return true;
    LDC = LDC->getLexicalParent();
  }
  return false;
}

llvm::Expected<RefactoringResult>
ImplementDeclaredCXXMethodsOperation::perform(
    ASTContext &Context, const Preprocessor &ThePreprocessor,
    const RefactoringOptionSet &Options, unsigned SelectedCandidateIndex) {
  if (isInLocalScope(Container)) {
    // Local methods can be implemented inline.
    std::vector<RefactoringReplacement> Replacements;
    for (const CXXMethodDecl *MD : SelectedMethods)
      addInlineBody(MD, Context, Replacements);
    return std::move(Replacements);
  }
  using namespace indexer;
  return continueInExternalASTUnit(
      fileThatShouldContainImplementationOf(Container), runInImplementationAST,
      Container, filter(ArrayRef(SelectedMethods),
                        [](const DeclEntity &D) { return !D.isDefined(); }));
}

void ImplementDeclaredCXXMethodsOperation::addInlineBody(
    const CXXMethodDecl *MD, const ASTContext &Context,
    std::vector<RefactoringReplacement> &Replacements) {
  SourceLocation EndLoc = MD->getEndLoc();
  SourceRange SemiRange = getRangeOfNextToken(
      EndLoc, tok::semi, Context.getSourceManager(), Context.getLangOpts());
  if (SemiRange.isValid()) {
    Replacements.push_back(RefactoringReplacement(SemiRange));
    EndLoc = SemiRange.getEnd();
  }
  SourceLocation InsertionLoc = getLastLineLocationUnlessItHasOtherTokens(
      EndLoc, Context.getSourceManager(), Context.getLangOpts());
  Replacements.push_back(
      RefactoringReplacement(SourceRange(InsertionLoc, InsertionLoc),
                             StringRef(" { \n  <#code#>;\n}")));
}

static const RecordDecl *findOutermostRecord(const RecordDecl *RD) {
  const RecordDecl *Result = RD;
  for (const DeclContext *DC = Result->getLexicalDeclContext();
       isa<RecordDecl>(DC); DC = Result->getLexicalDeclContext())
    Result = cast<RecordDecl>(DC);
  return Result;
}

static bool containsUsingOf(const NamespaceDecl *ND,
                            const ASTContext &Context) {
  for (const Decl *D : Context.getTranslationUnitDecl()->decls()) {
    if (const auto *UDD = dyn_cast<UsingDirectiveDecl>(D)) {
      if (UDD->getNominatedNamespace() == ND)
        return true;
    }
  }
  return false;
}

llvm::Expected<RefactoringResult>
ImplementDeclaredCXXMethodsOperation::runInImplementationAST(
    ASTContext &Context, const FileID &File, const CXXRecordDecl *Class,
    ArrayRef<indexer::Indexed<const CXXMethodDecl *>> SelectedMethods) {
  if (!Class)
    return llvm::make_error<RefactoringOperationError>(
        "the target class is not defined in the continuation AST unit");

  SourceManager &SM = Context.getSourceManager();

  // Find the defined methods of the class.
  llvm::SmallVector<const CXXMethodDecl *, 8> DefinedOutOfLineMethods;
  for (const CXXMethodDecl *M : Class->methods()) {
    if (M->isImplicit())
      continue;
    if (const FunctionDecl *MD = M->getDefinition()) {
      if (!MD->isOutOfLine())
        continue;
      SourceLocation Loc = SM.getExpansionLoc(MD->getBeginLoc());
      if (SM.getFileID(Loc) == File)
        DefinedOutOfLineMethods.push_back(cast<CXXMethodDecl>(MD));
    }
  }

  std::vector<RefactoringReplacement> Replacements;
  std::string MethodString;
  llvm::raw_string_ostream OS(MethodString);

  // Pick a good insertion location.
  SourceLocation InsertionLoc;
  const CXXMethodDecl *InsertAfterMethod = nullptr;
  NestedNameSpecifier *NamePrefix = nullptr;
  if (DefinedOutOfLineMethods.empty()) {
    const RecordDecl *OutermostRecord = findOutermostRecord(Class);
    InsertionLoc = SM.getExpansionRange(OutermostRecord->getEndLoc()).getEnd();
    if (SM.getFileID(InsertionLoc) == File) {
      // We can insert right after the class. Compute the appropriate
      // qualification.
      NamePrefix = NestedNameSpecifier::getRequiredQualification(
          Context, OutermostRecord->getLexicalDeclContext(),
          Class->getLexicalDeclContext());
    } else {
      // We can't insert after the end of the class, since the indexer told us
      // that some file should have the implementation of it, even when there
      // are no methods here. We should try to insert at the end of the file.
      InsertionLoc = SM.getLocForEndOfFile(File);
      NamePrefix = NestedNameSpecifier::getRequiredQualification(
          Context, Context.getTranslationUnitDecl(),
          Class->getLexicalDeclContext());
      llvm::SmallVector<const NamespaceDecl *, 4> Namespaces;
      for (const NestedNameSpecifier *Qualifier = NamePrefix; Qualifier;
           Qualifier = Qualifier->getPrefix()) {
        if (const NamespaceDecl *ND = Qualifier->getAsNamespace())
          Namespaces.push_back(ND);
      }
      // When the class is in a namespace, add a 'using' declaration if it's
      // needed and adjust the out-of-line qualification.
      if (!Namespaces.empty()) {
        const NamespaceDecl *InnermostNamespace = Namespaces[0];
        if (!containsUsingOf(InnermostNamespace, Context)) {
          std::string NamespaceString;
          llvm::raw_string_ostream NamespaceOS(NamespaceString);
          for (const NamespaceDecl *ND : llvm::reverse(Namespaces)) {
            if (!NamespaceOS.str().empty())
              NamespaceOS << "::";
            NamespaceOS << ND->getDeclName();
          }
          OS << "\nusing namespace " << NamespaceOS.str() << ";";
        }
        // Re-compute the name qualifier without the namespace.
        NamePrefix = NestedNameSpecifier::getRequiredQualification(
            Context, InnermostNamespace, Class->getLexicalDeclContext());
      }
    }
  } else {
    // Insert at the end of the defined methods.
    for (const CXXMethodDecl *M : DefinedOutOfLineMethods) {
      SourceLocation EndLoc = SM.getExpansionRange(M->getEndLoc()).getEnd();
      if (InsertionLoc.isInvalid() ||
          SM.isBeforeInTranslationUnit(InsertionLoc, EndLoc)) {
        InsertionLoc = EndLoc;
        InsertAfterMethod = M;
      }
    }
  }
  InsertionLoc = getLastLineLocationUnlessItHasOtherTokens(
      InsertionLoc, SM, Context.getLangOpts());

  PrintingPolicy PP = Context.getPrintingPolicy();
  PP.PolishForDeclaration = true;
  PP.SupressStorageClassSpecifiers = true;
  PP.SuppressStrongLifetime = true;
  PP.SuppressLifetimeQualifiers = true;
  PP.SuppressUnwrittenScope = true;
  OS << "\n";
  for (const auto &I : SelectedMethods) {
    const CXXMethodDecl *MD = I.Decl;
    // Check if the method is already defined.
    if (!MD)
      continue;

    // Drop the 'virtual' specifier.
    bool IsVirtual = MD->isVirtualAsWritten();
    const_cast<CXXMethodDecl *>(MD)->setVirtualAsWritten(false);

    // Drop the default arguments.
    llvm::SmallVector<std::pair<ParmVarDecl *, Expr *>, 4> DefaultArgs;
    for (const ParmVarDecl *P : MD->parameters()) {
      if (!P->hasDefaultArg())
        continue;
      Expr *E = const_cast<ParmVarDecl *>(P)->getDefaultArg();
      const_cast<ParmVarDecl *>(P)->setDefaultArg(nullptr);
      DefaultArgs.emplace_back(const_cast<ParmVarDecl *>(P), E);
    }

    // Add the nested name specifiers that are appropriate for an out-of-line
    // method.
    auto *Qualifier =
        InsertAfterMethod
            ? InsertAfterMethod->getQualifier()
            : NestedNameSpecifier::Create(
                  Context, /*Prefix=*/NamePrefix, /*Template=*/false,
                  Context.getRecordType(Class).getTypePtr());
    NestedNameSpecifierLoc PrevQualifierInfo = MD->getQualifierLoc();
    const_cast<CXXMethodDecl *>(MD)->setQualifierInfo(
        NestedNameSpecifierLoc(Qualifier, /*Loc=*/nullptr));

    OS << "\n";
    MD->print(OS, PP);
    OS << " { \n  <#code#>;\n}\n";

    // Restore the original method
    for (const auto &DefaultArg : DefaultArgs)
      DefaultArg.first->setDefaultArg(DefaultArg.second);
    const_cast<CXXMethodDecl *>(MD)->setVirtualAsWritten(IsVirtual);
    const_cast<CXXMethodDecl *>(MD)->setQualifierInfo(PrevQualifierInfo);
  }

  Replacements.push_back(RefactoringReplacement(
      SourceRange(InsertionLoc, InsertionLoc), std::move(OS.str())));

  return std::move(Replacements);
}

llvm::Expected<RefactoringResult>
ImplementDeclaredObjCMethodsOperation::perform(
    ASTContext &Context, const Preprocessor &ThePreprocessor,
    const RefactoringOptionSet &Options, unsigned SelectedCandidateIndex) {
  using namespace indexer;

  // Print the methods before running the continuation because the continuation
  // TU might not have these method declarations (e.g. category implemented in
  // the class implementation).
  PrintingPolicy PP = Context.getPrintingPolicy();
  PP.PolishForDeclaration = true;
  PP.SuppressStrongLifetime = true;
  PP.SuppressLifetimeQualifiers = true;
  PP.SuppressUnwrittenScope = true;
  std::vector<std::string> MethodDeclarations;
  for (const ObjCMethodDecl *MD : SelectedMethods) {
    std::string MethodDeclStr;
    llvm::raw_string_ostream MethodOS(MethodDeclStr);
    MD->print(MethodOS, PP);
    MethodDeclarations.push_back(std::move(MethodOS.str()));
  }

  return continueInExternalASTUnit(
      fileThatShouldContainImplementationOf(Container), runInImplementationAST,
      Container, Interface, MethodDeclarations,
      filter(ArrayRef(SelectedMethods),
             [](const DeclEntity &D) { return !D.isDefined(); }));
}

static const ObjCImplDecl *
getImplementationContainer(const ObjCContainerDecl *Container,
                           const ObjCInterfaceDecl *Interface = nullptr) {
  if (!Container)
    return Interface ? getImplementationContainer(Interface) : nullptr;
  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Container))
    return ID->getImplementation();
  if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Container)) {
    if (const auto *Impl = CD->getImplementation())
      return Impl;
    return getImplementationContainer(Interface);
  }
  return nullptr;
}

llvm::Expected<RefactoringResult>
ImplementDeclaredObjCMethodsOperation::runInImplementationAST(
    ASTContext &Context, const FileID &File, const ObjCContainerDecl *Container,
    const ObjCInterfaceDecl *Interface,
    ArrayRef<std::string> MethodDeclarations,
    ArrayRef<indexer::Indexed<const ObjCMethodDecl *>> SelectedMethods) {
  const ObjCImplDecl *ImplementationContainer =
      getImplementationContainer(Container, Interface);
  if (!ImplementationContainer)
    return llvm::make_error<RefactoringOperationError>(
        "the target @interface is not implemented in the continuation AST "
        "unit");

  std::vector<RefactoringReplacement> Replacements;

  std::string MethodString;
  llvm::raw_string_ostream OS(MethodString);

  assert(MethodDeclarations.size() >= SelectedMethods.size() &&
         "fewer declarations than selected methods?");
  for (const auto &I : llvm::enumerate(SelectedMethods)) {
    indexer::Indexed<const ObjCMethodDecl *> Decl = I.value();
    // Skip methods that are already defined.
    if (!Decl.isNotDefined())
      continue;

    OS << StringRef(MethodDeclarations[I.index()]).drop_back(); // Drop the ';'
    OS << " { \n  <#code#>;\n}\n\n";
  }
  SourceLocation InsertionLoc = ImplementationContainer->getEndLoc();

  Replacements.push_back(RefactoringReplacement(
      SourceRange(InsertionLoc, InsertionLoc), std::move(OS.str())));

  return std::move(Replacements);
}