File: USRFinder.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 (705 lines) | stat: -rw-r--r-- 25,443 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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//===--- USRFinder.cpp - Clang refactoring library ------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file Implements a recursive AST visitor that finds the USR of a symbol at a
/// point.
///
//===----------------------------------------------------------------------===//

#include "clang/Tooling/Refactor/USRFinder.h"
#include "SourceLocationUtilities.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DependentASTVisitor.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Lex/Lexer.h"
#include "clang/Tooling/Refactoring/RefactoringDiagnostic.h"
#include "llvm/ADT/SmallVector.h"
#include <functional>

using namespace llvm;

namespace clang {
namespace tooling {
namespace rename {

typedef std::function<bool(const NamedDecl *, SourceLocation, SourceLocation)>
    OccurrenceCheckerType;

// NamedDeclFindingASTVisitor recursively visits each AST node to find the
// symbol underneath the cursor.
// FIXME: move to seperate .h/.cc file if this gets too large.
namespace {
class NamedDeclFindingASTVisitor
    : public DependentASTVisitor<NamedDeclFindingASTVisitor> {
public:
  // \brief Finds the NamedDecl at a point in the source.
  // \param Point the location in the source to search for the NamedDecl.
  explicit NamedDeclFindingASTVisitor(
      const OccurrenceCheckerType &OccurrenceChecker, const ASTContext &Context)
      : Result(nullptr), OccurrenceChecker(OccurrenceChecker),
        Context(Context) {}

  // Declaration visitors:

  // \brief Checks if the point falls within the NameDecl. This covers every
  // declaration of a named entity that we may come across. Usually, just
  // checking if the point lies within the length of the name of the declaration
  // and the start location is sufficient.
  bool VisitNamedDecl(const NamedDecl *Decl) {
    return dyn_cast<CXXConversionDecl>(Decl)
               ? true
               : checkOccurrence(Decl, Decl->getLocation(),
                                 Decl->getNameAsString().length());
  }

  bool WalkUpFromTypedefNameDecl(const TypedefNameDecl *D) {
    // Don't visit the NamedDecl for TypedefNameDecl.
    return VisitTypedefNamedDecl(D);
  }

  bool VisitTypedefNamedDecl(const TypedefNameDecl *D) {
    if (D->isTransparentTag()) {
      if (const auto *Underlying = D->getUnderlyingType()->getAsTagDecl())
        return checkOccurrence(Underlying, D->getLocation(),
                               D->getNameAsString().size());
    }
    return VisitNamedDecl(D);
  }

  bool WalkUpFromUsingDecl(const UsingDecl *D) {
    // Don't visit the NamedDecl for UsingDecl.
    return VisitUsingDecl(D);
  }

  bool VisitUsingDecl(const UsingDecl *D) {
    for (const auto *Shadow : D->shadows()) {
      // Currently we always find the first declaration, but is this the right
      // behaviour?
      const NamedDecl *UD = Shadow->getUnderlyingDecl();
      if (UD->isImplicit() || UD == D)
        continue;
      if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(UD)) {
        UD = FTD->getTemplatedDecl();
        if (!UD)
          continue;
      }
      if (!checkOccurrence(UD, D->getLocation()))
        return false;
    }
    return true;
  }

  bool WalkUpFromUsingDirectiveDecl(const UsingDirectiveDecl *D) {
    // Don't visit the NamedDecl for UsingDirectiveDecl.
    return VisitUsingDirectiveDecl(D);
  }

  bool VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
    return checkOccurrence(D->getNominatedNamespaceAsWritten(),
                           D->getLocation());
  }

  bool WalkUpFromUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
    // Don't visit the NamedDecl for UnresolvedUsingValueDecl.
    // FIXME: Can we try to lookup the name?
    return true;
  }

  bool
  WalkUpFromUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D) {
    // Don't visit the NamedDecl for UnresolvedUsingTypenameDecl.
    // FIXME: Can we try to lookup the name?
    return true;
  }

  bool WalkUpFromObjCMethodDecl(const ObjCMethodDecl *Decl) {
    // Don't visit the NamedDecl for Objective-C methods.
    return VisitObjCMethodDecl(Decl);
  }

  bool VisitObjCMethodDecl(const ObjCMethodDecl *Decl) {
    // Check all of the selector source ranges.
    for (unsigned I = 0, E = Decl->getNumSelectorLocs(); I != E; ++I) {
      SourceLocation Loc = Decl->getSelectorLoc(I);
      if (!checkOccurrence(Decl, Loc,
                           Loc.getLocWithOffset(
                               Decl->getSelector().getNameForSlot(I).size())))
        return false;
    }
    return true;
  }

  bool VisitObjCProtocolList(const ObjCProtocolList &Protocols) {
    for (unsigned I = 0, E = Protocols.size(); I != E; ++I) {
      if (!checkOccurrence(Protocols[I], Protocols.loc_begin()[I]))
        return false;
    }
    return true;
  }

  bool VisitObjCInterfaceDecl(const ObjCInterfaceDecl *Decl) {
    if (!Decl->hasDefinition())
      return true;
    return VisitObjCProtocolList(Decl->getReferencedProtocols());
  }

  bool VisitObjCProtocolDecl(const ObjCProtocolDecl *Decl) {
    if (!Decl->hasDefinition())
      return true;
    return VisitObjCProtocolList(Decl->getReferencedProtocols());
  }

  bool WalkUpFromObjCCategoryDecl(const ObjCCategoryDecl *Decl) {
    // Don't visit the NamedDecl for Objective-C categories because the location
    // of the name refers to the interface declaration.
    return VisitObjCCategoryDecl(Decl);
  }

  bool VisitObjCCategoryDecl(const ObjCCategoryDecl *Decl) {
    if (!checkOccurrence(Decl, Decl->getCategoryNameLoc()))
      return false;
    if (const auto *Class = Decl->getClassInterface()) {
      // The location of the class name is the location of the declaration.
      if (!checkOccurrence(Class, Decl->getLocation()))
        return false;
    }
    return VisitObjCProtocolList(Decl->getReferencedProtocols());
  }

  bool WalkUpFromObjCCategoryImplDecl(const ObjCCategoryImplDecl *Decl) {
    // Don't visit the NamedDecl for Objective-C categories because the location
    // of the name refers to the interface declaration.
    return VisitObjCCategoryImplDecl(Decl);
  }

  bool VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *Decl) {
    if (!checkOccurrence(Decl, Decl->getCategoryNameLoc()))
      return false;
    if (const auto *Class = Decl->getClassInterface()) {
      // The location of the class name is the location of the declaration.
      if (!checkOccurrence(Class, Decl->getLocation()))
        return false;
    }
    return true;
  }

  bool VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *Decl) {
    return checkOccurrence(Decl->getClassInterface(),
                           Decl->getClassInterfaceLoc());
  }

  bool WalkUpFromObjCIvarDecl(ObjCIvarDecl *Decl) {
    // Don't visit the NamedDecl for automatically synthesized ivars as the
    // implicit ivars have the same location as the property declarations, and
    // we want to find the property declarations.
    if (Decl->getSynthesize())
      return true;
    return RecursiveASTVisitor::WalkUpFromObjCIvarDecl(Decl);
  }

  bool VisitObjCPropertyDecl(const ObjCPropertyDecl *Decl) {
    if (Decl->hasExplicitGetterName()) {
      if (const auto *Getter = Decl->getGetterMethodDecl())
        if (!checkOccurrence(Getter, Decl->getGetterNameLoc(),
                             Decl->getGetterName().getNameForSlot(0).size()))
          return false;
    }
    if (Decl->hasExplicitSetterName()) {
      if (const auto *Setter = Decl->getSetterMethodDecl())
        return checkOccurrence(Setter, Decl->getSetterNameLoc(),
                               Decl->getSetterName().getNameForSlot(0).size());
    }
    return true;
  }

  bool VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *Decl) {
    if (!checkOccurrence(Decl->getPropertyDecl(), Decl->getLocation()))
      return false;
    if (Decl->isIvarNameSpecified())
      return checkOccurrence(Decl->getPropertyIvarDecl(),
                             Decl->getPropertyIvarDeclLoc());
    return true;
  }

  // Expression visitors:

  bool VisitDeclRefExpr(const DeclRefExpr *Expr) {
    const NamedDecl *Decl = Expr->getFoundDecl();
    return checkOccurrence(Decl, Expr->getLocation(),
                           Decl->getNameAsString().length());
  }

  bool VisitMemberExpr(const MemberExpr *Expr) {
    const NamedDecl *Decl = Expr->getFoundDecl().getDecl();
    return checkOccurrence(Decl, Expr->getMemberLoc(),
                           Decl->getNameAsString().length());
  }

  bool VisitObjCMessageExpr(const ObjCMessageExpr *Expr) {
    const ObjCMethodDecl *Decl = Expr->getMethodDecl();
    if (Decl == nullptr)
      return true;

    // Check all of the selector source ranges.
    for (unsigned I = 0, E = Expr->getNumSelectorLocs(); I != E; ++I) {
      SourceLocation Loc = Expr->getSelectorLoc(I);
      if (!checkOccurrence(Decl, Loc,
                           Loc.getLocWithOffset(
                               Decl->getSelector().getNameForSlot(I).size())))
        return false;
    }
    return true;
  }

  bool VisitObjCProtocolExpr(const ObjCProtocolExpr *Expr) {
    return checkOccurrence(Expr->getProtocol(), Expr->getProtocolIdLoc());
  }

  bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Expr) {
    return checkOccurrence(Expr->getDecl(), Expr->getLocation());
  }

  bool VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Expr) {
    if (Expr->isClassReceiver())
      checkOccurrence(Expr->getClassReceiver(), Expr->getReceiverLocation());
    if (Expr->isImplicitProperty()) {
      // Class properties that are explicitly defined using @property
      // declarations are represented implicitly as there is no ivar for class
      // properties.
      if (const ObjCMethodDecl *Getter = Expr->getImplicitPropertyGetter()) {
        if (Getter->isClassMethod()) {
          if (const auto *PD = Getter->getCanonicalDecl()->findPropertyDecl())
            return checkOccurrence(PD, Expr->getLocation());
        }
      }

      if (Expr->isMessagingGetter()) {
        if (const ObjCMethodDecl *Getter = Expr->getImplicitPropertyGetter())
          return checkOccurrence(Getter, Expr->getLocation());
      } else if (const ObjCMethodDecl *Setter =
                     Expr->getImplicitPropertySetter()) {
        return checkOccurrence(Setter, Expr->getLocation());
      }

      return true;
    }
    return checkOccurrence(Expr->getExplicitProperty(), Expr->getLocation());
  }

  // Other visitors:

  bool VisitTypeLoc(const TypeLoc Loc) {
    const SourceLocation TypeBeginLoc = Loc.getBeginLoc();
    const SourceLocation TypeEndLoc = Lexer::getLocForEndOfToken(
        TypeBeginLoc, 0, Context.getSourceManager(), Context.getLangOpts());
    if (const auto *TemplateTypeParm =
            dyn_cast<TemplateTypeParmType>(Loc.getType()))
      return checkOccurrence(TemplateTypeParm->getDecl(), TypeBeginLoc,
                             TypeEndLoc);
    if (const auto *TemplateSpecType =
            dyn_cast<TemplateSpecializationType>(Loc.getType())) {
      return checkOccurrence(
          TemplateSpecType->getTemplateName().getAsTemplateDecl(), TypeBeginLoc,
          TypeEndLoc);
    }
    TypedefTypeLoc TTL = Loc.getAs<TypedefTypeLoc>();
    if (TTL) {
      const auto *TND = TTL.getTypedefNameDecl();
      if (TND->isTransparentTag()) {
        if (const auto *Underlying = TND->getUnderlyingType()->getAsTagDecl())
          return checkOccurrence(Underlying, TTL.getNameLoc());
      }
      return checkOccurrence(TND, TTL.getNameLoc());
    }
    TypeSpecTypeLoc TSTL = Loc.getAs<TypeSpecTypeLoc>();
    if (TSTL) {
      return checkOccurrence(Loc.getType()->getAsTagDecl(), TSTL.getNameLoc());
    }
    return true;
  }

  bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc Loc) {
    return checkOccurrence(Loc.getIFaceDecl(), Loc.getNameLoc());
  }

  bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc Loc) {
    for (unsigned I = 0, E = Loc.getNumProtocols(); I < E; ++I) {
      if (!checkOccurrence(Loc.getProtocol(I), Loc.getProtocolLoc(I)))
        return false;
    }
    return true;
  }

  bool VisitCXXConstructorDecl(clang::CXXConstructorDecl *ConstructorDecl) {
    for (const auto *Initializer : ConstructorDecl->inits()) {
      // Ignore implicit initializers.
      if (!Initializer->isWritten())
        continue;
      if (const clang::FieldDecl *FieldDecl = Initializer->getMember()) {
        const SourceLocation InitBeginLoc = Initializer->getSourceLocation(),
                             InitEndLoc = Lexer::getLocForEndOfToken(
                                 InitBeginLoc, 0, Context.getSourceManager(),
                                 Context.getLangOpts());
        if (!checkOccurrence(FieldDecl, InitBeginLoc, InitEndLoc))
          return false;
      }
    }
    return true;
  }

  bool VisitDependentSymbolReference(const NamedDecl *Symbol,
                                     SourceLocation SymbolNameLoc) {
    return checkOccurrence(Symbol, SymbolNameLoc);
  }

  // Other:

  const NamedDecl *getNamedDecl() { return Result; }

  bool isDone() const { return Result; }

  // \brief Determines if a namespace qualifier contains the point.
  // \returns false on success and sets Result.
  void handleNestedNameSpecifierLoc(NestedNameSpecifierLoc NameLoc) {
    while (NameLoc) {
      const NamespaceDecl *Decl =
          NameLoc.getNestedNameSpecifier()->getAsNamespace();
      checkOccurrence(Decl, NameLoc.getLocalBeginLoc(),
                      NameLoc.getLocalEndLoc());
      NameLoc = NameLoc.getPrefix();
    }
  }

private:
  /// \brief Sets Result to \p Decl if the occurrence checker returns true.
  ///
  /// \returns false on success.
  bool checkRange(const NamedDecl *Decl, SourceLocation Start,
                  SourceLocation End) {
    assert(!Start.isMacroID() && !End.isMacroID() && "Macro location?");
    if (!Decl)
      return true;
    if (isa<ImplicitParamDecl>(Decl))
      return true;
    if (const auto *FD = dyn_cast<FunctionDecl>(Decl)) {
      // Don't match operators.
      if (FD->isOverloadedOperator())
        return true;
    }
    if (!OccurrenceChecker(Decl, Start, End))
      return true;
    Result = Decl;
    return false;
  }

  /// Checks if the given declaration is valid, and if it is, sets Result to
  /// \p Decl if the occurrence checker returns true.
  ///
  /// \returns false if the point of interest is inside the range that
  /// corresponds the occurrence of this declaration.
  bool checkOccurrence(const NamedDecl *Decl, SourceLocation Loc) {
    if (!Decl)
      return true;
    return checkOccurrence(Decl, Loc, Decl->getNameAsString().size());
  }

  /// \brief Sets Result to \p Decl if the occurrence checker returns true.
  ///
  /// \returns false on success.
  bool checkOccurrence(const NamedDecl *Decl, SourceLocation Loc,
                       unsigned Length) {
    if (Loc.isMacroID()) {
      const SourceManager &SM = Context.getSourceManager();
      if (SM.isMacroArgExpansion(Loc))
        Loc = SM.getSpellingLoc(Loc);
      else
        return true;
    }

    return Length == 0 ||
           checkRange(Decl, Loc, Loc.getLocWithOffset(Length - 1));
  }

  bool checkOccurrence(const NamedDecl *ND, SourceLocation Start,
                       SourceLocation End) {
    const SourceManager &SM = Context.getSourceManager();
    if (Start.isMacroID()) {
      if (SM.isMacroArgExpansion(Start))
        Start = SM.getSpellingLoc(Start);
      else
        return true;
    }
    if (End.isMacroID()) {
      if (SM.isMacroArgExpansion(End))
        End = SM.getSpellingLoc(End);
      else
        return true;
    }
    return checkRange(ND, Start, End);
  }

  const NamedDecl *Result;
  const OccurrenceCheckerType &OccurrenceChecker;
  const ASTContext &Context;
};

} // namespace

static const ExternalSourceSymbolAttr *getExternalSymAttr(const Decl *D) {
  if (const auto *A = D->getAttr<ExternalSourceSymbolAttr>())
    return A;
  if (const auto *DCD = dyn_cast<Decl>(D->getDeclContext())) {
    if (const auto *A = DCD->getAttr<ExternalSourceSymbolAttr>())
      return A;
  }
  return nullptr;
}

static bool overridesSystemMethod(const ObjCMethodDecl *MD,
                                  const SourceManager &SM) {
  SmallVector<const ObjCMethodDecl *, 8> Overrides;
  MD->getOverriddenMethods(Overrides);
  for (const auto *Override : Overrides) {
    SourceLocation Loc = Override->getBeginLoc();
    if (Loc.isValid()) {
      if (SM.getFileCharacteristic(Loc) != SrcMgr::C_User)
        return true;
    }
    if (overridesSystemMethod(Override, SM))
      return true;
  }
  return false;
}

// TODO: Share with the indexer?
static bool isTemplateImplicitInstantiation(const Decl *D) {
  TemplateSpecializationKind TKind = TSK_Undeclared;
  if (const ClassTemplateSpecializationDecl *SD =
          dyn_cast<ClassTemplateSpecializationDecl>(D)) {
    TKind = SD->getSpecializationKind();
  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    TKind = FD->getTemplateSpecializationKind();
  } else if (auto *VD = dyn_cast<VarDecl>(D)) {
    TKind = VD->getTemplateSpecializationKind();
  } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
    if (RD->getInstantiatedFromMemberClass())
      TKind = RD->getTemplateSpecializationKind();
  } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
    if (ED->getInstantiatedFromMemberEnum())
      TKind = ED->getTemplateSpecializationKind();
  } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D) ||
             isa<EnumConstantDecl>(D)) {
    if (const auto *Parent = dyn_cast<Decl>(D->getDeclContext()))
      return isTemplateImplicitInstantiation(Parent);
  }
  switch (TKind) {
  case TSK_Undeclared:
  case TSK_ExplicitSpecialization:
    return false;
  case TSK_ImplicitInstantiation:
  case TSK_ExplicitInstantiationDeclaration:
  case TSK_ExplicitInstantiationDefinition:
    return true;
  }
  llvm_unreachable("invalid TemplateSpecializationKind");
}

static const CXXRecordDecl *
getDeclContextForTemplateInstationPattern(const Decl *D) {
  if (const auto *CTSD =
          dyn_cast<ClassTemplateSpecializationDecl>(D->getDeclContext()))
    return CTSD->getTemplateInstantiationPattern();
  else if (const auto *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
    return RD->getInstantiatedFromMemberClass();
  return nullptr;
}

static const NamedDecl *
adjustTemplateImplicitInstantiation(const NamedDecl *D) {
  if (const ClassTemplateSpecializationDecl *SD =
          dyn_cast<ClassTemplateSpecializationDecl>(D)) {
    return SD->getTemplateInstantiationPattern();
  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    return FD->getTemplateInstantiationPattern();
  } else if (auto *VD = dyn_cast<VarDecl>(D)) {
    return VD->getTemplateInstantiationPattern();
  } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
    return RD->getInstantiatedFromMemberClass();
  } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
    return ED->getInstantiatedFromMemberEnum();
  } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) {
    const auto *ND = cast<NamedDecl>(D);
    if (const CXXRecordDecl *Pattern =
            getDeclContextForTemplateInstationPattern(ND)) {
      for (const NamedDecl *BaseND : Pattern->lookup(ND->getDeclName())) {
        if (BaseND->isImplicit())
          continue;
        if (BaseND->getKind() == ND->getKind())
          return BaseND;
      }
    }
  } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
    if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) {
      if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
        for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName()))
          return BaseECD;
      }
    }
  }
  return D;
}

const NamedDecl *getNamedDeclAt(const ASTContext &Context,
                                SourceLocation Point) {
  if (Point.isMacroID())
    Point = Context.getSourceManager().getSpellingLoc(Point);
  // FIXME: If point is in a system header, return early here.

  OccurrenceCheckerType PointChecker = [Point, &Context](
      const NamedDecl *Decl, SourceLocation Start, SourceLocation End) -> bool {
    return Start.isValid() && Start.isFileID() && End.isValid() &&
           End.isFileID() &&
           isPointWithin(Point, Start, End, Context.getSourceManager());
  };
  NamedDeclFindingASTVisitor Visitor(PointChecker, Context);

  // We only want to search the decls that exist in the same file as the point.
  FileID InitiationFile = Context.getSourceManager().getFileID(Point);
  for (auto *CurrDecl : Context.getTranslationUnitDecl()->decls()) {
    const SourceRange DeclRange = CurrDecl->getSourceRange();
    SourceLocation FileLoc;
    if (DeclRange.getBegin().isMacroID() && !DeclRange.getEnd().isMacroID())
      FileLoc = DeclRange.getEnd();
    else
      FileLoc = Context.getSourceManager().getSpellingLoc(DeclRange.getBegin());
    // FIXME: Add test.
    if (Context.getSourceManager().getFileID(FileLoc) == InitiationFile)
      Visitor.TraverseDecl(CurrDecl);
    if (Visitor.isDone())
      break;
  }

  if (!Visitor.isDone()) {
    NestedNameSpecifierLocFinder Finder(const_cast<ASTContext &>(Context));
    for (const auto &Location : Finder.getNestedNameSpecifierLocations()) {
      Visitor.handleNestedNameSpecifierLoc(Location);
      if (Visitor.isDone())
        break;
    }
  }

  const auto Diag = [&](unsigned DiagID) -> DiagnosticBuilder {
    return Context.getDiagnostics().Report(Point, DiagID);
  };
  const auto *ND = Visitor.getNamedDecl();
  if (!ND)
    return nullptr;

  // Canonicalize the found declaration.
  //
  // If FoundDecl is a constructor or destructor, we want to instead take
  // the Decl of the corresponding class.
  if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(ND))
    ND = CtorDecl->getParent();
  else if (const auto *DtorDecl = dyn_cast<CXXDestructorDecl>(ND))
    ND = DtorDecl->getParent();

  if (isTemplateImplicitInstantiation(ND))
    ND = adjustTemplateImplicitInstantiation(ND);

  // Builtins can't be renamed.
  if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
    if (FD->getBuiltinID()) {
      Diag(diag::err_rename_builtin_function) << ND->getDeclName();
      return nullptr;
    }
  }
  // Declarations with invalid locations are probably implicit.
  if (ND->getBeginLoc().isInvalid())
    return nullptr;
  // Declarations in system headers can't be renamed.
  auto CheckSystemLoc = [&](SourceLocation Loc) -> bool {
    if (Context.getSourceManager().getFileCharacteristic(Loc) !=
        SrcMgr::C_User) {
      Diag(diag::err_rename_sys_header) << ND->getDeclName();
      return true;
    }
    return false;
  };
  if (CheckSystemLoc(ND->getBeginLoc()))
    return nullptr;
  if (const auto *TD = dyn_cast<TypedefNameDecl>(ND)) {
    if (const TypedefNameDecl *CTD = TD->getCanonicalDecl()) {
      if (CheckSystemLoc(CTD->getBeginLoc()))
        return nullptr;
    }
  } else if (const auto *TD = dyn_cast<TagDecl>(ND)) {
    if (const TagDecl *CTD = TD->getCanonicalDecl()) {
      if (CheckSystemLoc(CTD->getBeginLoc()))
        return nullptr;
    }
  } else if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
    if (const FunctionDecl *CFD = FD->getCanonicalDecl()) {
      if (CheckSystemLoc(CFD->getBeginLoc()))
        return nullptr;
    }
  } else if (const auto *VD = dyn_cast<VarDecl>(ND)) {
    if (const VarDecl *CVD = VD->getCanonicalDecl()) {
      if (CheckSystemLoc(CVD->getBeginLoc()))
        return nullptr;
    }
  }
  // Declarations from other languages can't be renamed.
  if (const ExternalSourceSymbolAttr *ESSA = getExternalSymAttr(ND)) {
    Diag(diag::err_rename_external_source_symbol) << ND->getDeclName()
                                                  << ESSA->getLanguage();
    return nullptr;
  }
  // Methods that override methods from system headers can't be renamed.
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(ND)) {
    if (overridesSystemMethod(MD, Context.getSourceManager())) {
      Diag(diag::err_method_rename_override_sys_framework) << ND->getDeclName();
      return nullptr;
    }
  }
  return ND;
}

const NamedDecl *getNamedDeclWithUSR(const ASTContext &Context, StringRef USR) {
  // TODO: Remove in favour of the new converter.
  OccurrenceCheckerType USRChecker =
      [USR](const NamedDecl *Decl, SourceLocation Start, SourceLocation End) {
        return USR == getUSRForDecl(Decl);
      };
  NamedDeclFindingASTVisitor Visitor(USRChecker, Context);

  for (auto *CurrDecl : Context.getTranslationUnitDecl()->decls()) {
    Visitor.TraverseDecl(CurrDecl);
    if (Visitor.isDone())
      break;
  }

  // Don't need to visit nested name specifiers as they refer to previously
  // declared declarations that we've already seen.
  return Visitor.getNamedDecl();
}

std::string getUSRForDecl(const Decl *Decl) {
  llvm::SmallVector<char, 128> Buff;

  // FIXME: Add test for the nullptr case.
  if (Decl == nullptr || index::generateUSRForDecl(Decl, Buff))
    return "";

  return std::string(Buff.data(), Buff.size());
}

} // end namespace rename
} // end namespace tooling
} // end namespace clang