clang-tools  4.0.0
USRFindingAction.cpp
Go to the documentation of this file.
1 //===--- tools/extra/clang-rename/USRFindingAction.cpp - Clang rename tool ===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Provides an action to find USR for the symbol at <offset>, as well as
12 /// all additional USRs.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "USRFindingAction.h"
17 #include "USRFinder.h"
18 #include "clang/AST/AST.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/RecursiveASTVisitor.h"
23 #include "clang/Basic/FileManager.h"
24 #include "clang/Frontend/CompilerInstance.h"
25 #include "clang/Frontend/FrontendAction.h"
26 #include "clang/Lex/Lexer.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Tooling/CommonOptionsParser.h"
29 #include "clang/Tooling/Refactoring.h"
30 #include "clang/Tooling/Tooling.h"
31 
32 #include <algorithm>
33 #include <set>
34 #include <string>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 namespace clang {
40 namespace rename {
41 
42 namespace {
43 // \brief NamedDeclFindingConsumer should delegate finding USRs of given Decl to
44 // AdditionalUSRFinder. AdditionalUSRFinder adds USRs of ctor and dtor if given
45 // Decl refers to class and adds USRs of all overridden methods if Decl refers
46 // to virtual method.
47 class AdditionalUSRFinder : public RecursiveASTVisitor<AdditionalUSRFinder> {
48 public:
49  AdditionalUSRFinder(const Decl *FoundDecl, ASTContext &Context)
50  : FoundDecl(FoundDecl), Context(Context) {}
51 
52  std::vector<std::string> Find() {
53  // Fill OverriddenMethods and PartialSpecs storages.
54  TraverseDecl(Context.getTranslationUnitDecl());
55  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FoundDecl)) {
56  addUSRsOfOverridenFunctions(MethodDecl);
57  for (const auto &OverriddenMethod : OverriddenMethods) {
58  if (checkIfOverriddenFunctionAscends(OverriddenMethod))
59  USRSet.insert(getUSRForDecl(OverriddenMethod));
60  }
61  } else if (const auto *RecordDecl = dyn_cast<CXXRecordDecl>(FoundDecl)) {
62  handleCXXRecordDecl(RecordDecl);
63  } else if (const auto *TemplateDecl =
64  dyn_cast<ClassTemplateDecl>(FoundDecl)) {
65  handleClassTemplateDecl(TemplateDecl);
66  } else {
68  }
69  return std::vector<std::string>(USRSet.begin(), USRSet.end());
70  }
71 
72  bool VisitCXXMethodDecl(const CXXMethodDecl *MethodDecl) {
73  if (MethodDecl->isVirtual())
74  OverriddenMethods.push_back(MethodDecl);
75  return true;
76  }
77 
78  bool VisitClassTemplatePartialSpecializationDecl(
79  const ClassTemplatePartialSpecializationDecl *PartialSpec) {
80  PartialSpecs.push_back(PartialSpec);
81  return true;
82  }
83 
84 private:
85  void handleCXXRecordDecl(const CXXRecordDecl *RecordDecl) {
86  RecordDecl = RecordDecl->getDefinition();
87  if (const auto *ClassTemplateSpecDecl =
88  dyn_cast<ClassTemplateSpecializationDecl>(RecordDecl))
89  handleClassTemplateDecl(ClassTemplateSpecDecl->getSpecializedTemplate());
90  addUSRsOfCtorDtors(RecordDecl);
91  }
92 
93  void handleClassTemplateDecl(const ClassTemplateDecl *TemplateDecl) {
94  for (const auto *Specialization : TemplateDecl->specializations())
95  addUSRsOfCtorDtors(Specialization);
96 
97  for (const auto *PartialSpec : PartialSpecs) {
98  if (PartialSpec->getSpecializedTemplate() == TemplateDecl)
99  addUSRsOfCtorDtors(PartialSpec);
100  }
101  addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());
102  }
103 
104  void addUSRsOfCtorDtors(const CXXRecordDecl *RecordDecl) {
105  RecordDecl = RecordDecl->getDefinition();
106 
107  for (const auto *CtorDecl : RecordDecl->ctors())
108  USRSet.insert(getUSRForDecl(CtorDecl));
109 
110  USRSet.insert(getUSRForDecl(RecordDecl->getDestructor()));
111  USRSet.insert(getUSRForDecl(RecordDecl));
112  }
113 
114  void addUSRsOfOverridenFunctions(const CXXMethodDecl *MethodDecl) {
115  USRSet.insert(getUSRForDecl(MethodDecl));
116  // Recursively visit each OverridenMethod.
117  for (const auto &OverriddenMethod : MethodDecl->overridden_methods())
118  addUSRsOfOverridenFunctions(OverriddenMethod);
119  }
120 
121  bool checkIfOverriddenFunctionAscends(const CXXMethodDecl *MethodDecl) {
122  for (const auto &OverriddenMethod : MethodDecl->overridden_methods()) {
123  if (USRSet.find(getUSRForDecl(OverriddenMethod)) != USRSet.end())
124  return true;
125  return checkIfOverriddenFunctionAscends(OverriddenMethod);
126  }
127  return false;
128  }
129 
130  const Decl *FoundDecl;
131  ASTContext &Context;
132  std::set<std::string> USRSet;
133  std::vector<const CXXMethodDecl *> OverriddenMethods;
134  std::vector<const ClassTemplatePartialSpecializationDecl *> PartialSpecs;
135 };
136 } // namespace
137 
139 public:
141  ArrayRef<std::string> QualifiedNames,
142  std::vector<std::string> &SpellingNames,
143  std::vector<std::vector<std::string>> &USRList,
144  bool &ErrorOccurred)
145  : SymbolOffsets(SymbolOffsets), QualifiedNames(QualifiedNames),
146  SpellingNames(SpellingNames), USRList(USRList),
147  ErrorOccurred(ErrorOccurred) {}
148 
149 private:
150  bool FindSymbol(ASTContext &Context, const SourceManager &SourceMgr,
151  unsigned SymbolOffset, const std::string &QualifiedName) {
152  DiagnosticsEngine &Engine = Context.getDiagnostics();
153  const FileID MainFileID = SourceMgr.getMainFileID();
154 
155  if (SymbolOffset >= SourceMgr.getFileIDSize(MainFileID)) {
156  ErrorOccurred = true;
157  unsigned InvalidOffset = Engine.getCustomDiagID(
158  DiagnosticsEngine::Error,
159  "SourceLocation in file %0 at offset %1 is invalid");
160  Engine.Report(SourceLocation(), InvalidOffset)
161  << SourceMgr.getFileEntryForID(MainFileID)->getName() << SymbolOffset;
162  return false;
163  }
164 
165  const SourceLocation Point = SourceMgr.getLocForStartOfFile(MainFileID)
166  .getLocWithOffset(SymbolOffset);
167  const NamedDecl *FoundDecl = QualifiedName.empty()
168  ? getNamedDeclAt(Context, Point)
169  : getNamedDeclFor(Context, QualifiedName);
170 
171  if (FoundDecl == nullptr) {
172  if (QualifiedName.empty()) {
173  FullSourceLoc FullLoc(Point, SourceMgr);
174  unsigned CouldNotFindSymbolAt = Engine.getCustomDiagID(
175  DiagnosticsEngine::Error,
176  "clang-rename could not find symbol (offset %0)");
177  Engine.Report(Point, CouldNotFindSymbolAt) << SymbolOffset;
178  ErrorOccurred = true;
179  return false;
180  }
181  unsigned CouldNotFindSymbolNamed = Engine.getCustomDiagID(
182  DiagnosticsEngine::Error, "clang-rename could not find symbol %0");
183  Engine.Report(CouldNotFindSymbolNamed) << QualifiedName;
184  ErrorOccurred = true;
185  return false;
186  }
187 
188  // If FoundDecl is a constructor or destructor, we want to instead take
189  // the Decl of the corresponding class.
190  if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FoundDecl))
191  FoundDecl = CtorDecl->getParent();
192  else if (const auto *DtorDecl = dyn_cast<CXXDestructorDecl>(FoundDecl))
193  FoundDecl = DtorDecl->getParent();
194 
195  SpellingNames.push_back(FoundDecl->getNameAsString());
196  AdditionalUSRFinder Finder(FoundDecl, Context);
197  USRList.push_back(Finder.Find());
198  return true;
199  }
200 
201  void HandleTranslationUnit(ASTContext &Context) override {
202  const SourceManager &SourceMgr = Context.getSourceManager();
203  for (unsigned Offset : SymbolOffsets) {
204  if (!FindSymbol(Context, SourceMgr, Offset, ""))
205  return;
206  }
207  for (const std::string &QualifiedName : QualifiedNames) {
208  if (!FindSymbol(Context, SourceMgr, 0, QualifiedName))
209  return;
210  }
211  }
212 
213  ArrayRef<unsigned> SymbolOffsets;
214  ArrayRef<std::string> QualifiedNames;
215  std::vector<std::string> &SpellingNames;
216  std::vector<std::vector<std::string>> &USRList;
217  bool &ErrorOccurred;
218 };
219 
220 std::unique_ptr<ASTConsumer> USRFindingAction::newASTConsumer() {
221  return llvm::make_unique<NamedDeclFindingConsumer>(
222  SymbolOffsets, QualifiedNames, SpellingNames, USRList, ErrorOccurred);
223 }
224 
225 } // namespace rename
226 } // namespace clang
const SourceLocation Point
Definition: USRFinder.cpp:163
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:262
const NamedDecl * getNamedDeclAt(const ASTContext &Context, const SourceLocation Point)
Definition: USRFinder.cpp:169
std::string getUSRForDecl(const Decl *Decl)
Definition: USRFinder.cpp:201
std::vector< const CXXMethodDecl * > OverriddenMethods
NamedDeclFindingConsumer(ArrayRef< unsigned > SymbolOffsets, ArrayRef< std::string > QualifiedNames, std::vector< std::string > &SpellingNames, std::vector< std::vector< std::string >> &USRList, bool &ErrorOccurred)
SourceManager SourceMgr
Definition: ClangTidy.cpp:244
Provides an action to find all relevant USRs at a point.
Methods for determining the USR of a symbol at a location in source code.
const NamedDecl * getNamedDeclFor(const ASTContext &Context, const std::string &Name)
Definition: USRFinder.cpp:193
static cl::list< std::string > QualifiedNames("qualified-name", cl::desc("The fully qualified name of the symbol."), cl::ZeroOrMore, cl::cat(ClangRenameOptions))
const Decl * FoundDecl
ASTContext & Context
static cl::list< unsigned > SymbolOffsets("offset", cl::desc("Locates the symbol by offset as opposed to <line>:<column>."), cl::ZeroOrMore, cl::cat(ClangRenameOptions))
std::set< std::string > USRSet
std::vector< const ClassTemplatePartialSpecializationDecl * > PartialSpecs