blob: dcbfd2a310e9fd89aed270ebdbd393ba0f63045d [file] [log] [blame]
Manuel Klimekde237262014-08-20 01:39:05 +00001//===--- tools/extra/clang-rename/ClangRename.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 This file implements a clang-rename tool that automatically finds and
12/// renames symbols in C++ code.
13///
14//===----------------------------------------------------------------------===//
15
Manuel Klimek3f840a92014-10-13 11:30:27 +000016#include "../RenamingAction.h"
Kirill Bobyrev81009402016-08-04 09:23:30 +000017#include "../USRFindingAction.h"
Eugene Zelenkoa4c2efb2016-07-25 20:30:13 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/DiagnosticOptions.h"
Manuel Klimekde237262014-08-20 01:39:05 +000020#include "clang/Basic/FileManager.h"
Eugene Zelenkoa4c2efb2016-07-25 20:30:13 +000021#include "clang/Basic/IdentifierTable.h"
Manuel Klimekde237262014-08-20 01:39:05 +000022#include "clang/Basic/LangOptions.h"
Eugene Zelenkoa4c2efb2016-07-25 20:30:13 +000023#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TokenKinds.h"
Manuel Klimekde237262014-08-20 01:39:05 +000025#include "clang/Frontend/TextDiagnosticPrinter.h"
Manuel Klimekde237262014-08-20 01:39:05 +000026#include "clang/Rewrite/Core/Rewriter.h"
27#include "clang/Tooling/CommonOptionsParser.h"
28#include "clang/Tooling/Refactoring.h"
Miklos Vajnaa2ca3ed2016-06-27 19:34:47 +000029#include "clang/Tooling/ReplacementsYaml.h"
Manuel Klimekde237262014-08-20 01:39:05 +000030#include "clang/Tooling/Tooling.h"
31#include "llvm/ADT/IntrusiveRefCntPtr.h"
Eugene Zelenkoa4c2efb2016-07-25 20:30:13 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/FileSystem.h"
Eugene Zelenkoa4c2efb2016-07-25 20:30:13 +000034#include "llvm/Support/YAMLTraits.h"
Kirill Bobyrev81009402016-08-04 09:23:30 +000035#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoa4c2efb2016-07-25 20:30:13 +000036#include <cstdlib>
Manuel Klimekde237262014-08-20 01:39:05 +000037#include <string>
Eugene Zelenkoa4c2efb2016-07-25 20:30:13 +000038#include <system_error>
Manuel Klimekde237262014-08-20 01:39:05 +000039
40using namespace llvm;
41
Manuel Klimekde237262014-08-20 01:39:05 +000042using namespace clang;
43
Miklos Vajnaaaec9b62016-08-02 09:51:31 +000044cl::OptionCategory ClangRenameAtCategory("clang-rename rename-at options");
45cl::OptionCategory ClangRenameAllCategory("clang-rename rename-all options");
46
47const char RenameAtUsage[] = "A tool to rename symbols in C/C++ code.\n\
Manuel Klimekde237262014-08-20 01:39:05 +000048clang-rename renames every occurrence of a symbol found at <offset> in\n\
49<source0>. If -i is specified, the edited files are overwritten to disk.\n\
50Otherwise, the results are written to stdout.\n";
51
Miklos Vajnaaaec9b62016-08-02 09:51:31 +000052const char RenameAllUsage[] = "A tool to rename symbols in C/C++ code.\n\
53clang-rename renames every occurrence of a symbol named <old-name>.\n";
54
55static int renameAtMain(int argc, const char *argv[]);
56static int renameAllMain(int argc, const char *argv[]);
57static int helpMain(int argc, const char *argv[]);
58
Miklos Vajna3d71b512016-08-09 18:20:41 +000059/// \brief An oldname -> newname rename.
60struct RenameAllInfo {
61 std::string OldName;
62 unsigned Offset;
63 std::string NewName;
64
65 RenameAllInfo() : Offset(0) {}
66};
67
68LLVM_YAML_IS_SEQUENCE_VECTOR(RenameAllInfo)
69
70namespace llvm {
71namespace yaml {
72
73/// \brief Specialized MappingTraits to describe how a RenameAllInfo is /
74/// (de)serialized.
75template <> struct MappingTraits<RenameAllInfo> {
76 static void mapping(IO &IO, RenameAllInfo &Info) {
77 IO.mapOptional("OldName", Info.OldName);
78 IO.mapOptional("Offset", Info.Offset);
79 IO.mapRequired("NewName", Info.NewName);
80 }
81};
82
83} // end namespace yaml
84} // end namespace llvm
85
Manuel Klimekde237262014-08-20 01:39:05 +000086int main(int argc, const char **argv) {
Miklos Vajnaaaec9b62016-08-02 09:51:31 +000087 if (argc > 1) {
88 using MainFunction = std::function<int(int, const char *[])>;
89 MainFunction Func = StringSwitch<MainFunction>(argv[1])
90 .Case("rename-at", renameAtMain)
91 .Case("rename-all", renameAllMain)
92 .Cases("-help", "--help", helpMain)
93 .Default(nullptr);
94
95 if (Func) {
96 std::string Invocation = std::string(argv[0]) + " " + argv[1];
97 argv[1] = Invocation.c_str();
98 return Func(argc - 1, argv + 1);
99 } else {
100 return renameAtMain(argc, argv);
101 }
102 }
103
104 helpMain(argc, argv);
105 return 1;
106}
107
108int subcommandMain(bool isRenameAll, int argc, const char **argv) {
109 cl::OptionCategory *Category = nullptr;
110 const char *Usage = nullptr;
111 if (isRenameAll) {
112 Category = &ClangRenameAllCategory;
113 Usage = RenameAllUsage;
114 } else {
115 Category = &ClangRenameAtCategory;
116 Usage = RenameAtUsage;
117 }
118
119 cl::list<std::string> NewNames(
120 "new-name", cl::desc("The new name to change the symbol to."),
Miklos Vajna3d71b512016-08-09 18:20:41 +0000121 (isRenameAll ? cl::ZeroOrMore : cl::Required), cl::cat(*Category));
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000122 cl::list<unsigned> SymbolOffsets(
123 "offset",
124 cl::desc("Locates the symbol by offset as opposed to <line>:<column>."),
125 (isRenameAll ? cl::ZeroOrMore : cl::Required), cl::cat(*Category));
126 cl::list<std::string> OldNames(
127 "old-name",
128 cl::desc(
129 "The fully qualified name of the symbol, if -offset is not used."),
130 (isRenameAll ? cl::ZeroOrMore : cl::Optional),
131 cl::cat(ClangRenameAllCategory));
132 cl::opt<bool> Inplace("i", cl::desc("Overwrite edited <file>s."),
133 cl::cat(*Category));
134 cl::opt<bool> PrintName(
135 "pn",
136 cl::desc("Print the found symbol's name prior to renaming to stderr."),
137 cl::cat(ClangRenameAtCategory));
138 cl::opt<bool> PrintLocations(
139 "pl", cl::desc("Print the locations affected by renaming to stderr."),
140 cl::cat(ClangRenameAtCategory));
141 cl::opt<std::string> ExportFixes(
142 "export-fixes", cl::desc("YAML file to store suggested fixes in."),
143 cl::value_desc("filename"), cl::cat(*Category));
Miklos Vajna3d71b512016-08-09 18:20:41 +0000144 cl::opt<std::string> Input(
145 "input", cl::desc("YAML file to load oldname-newname pairs from."),
146 cl::Optional, cl::cat(ClangRenameAllCategory));
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000147
148 tooling::CommonOptionsParser OP(argc, argv, *Category, Usage);
Manuel Klimekde237262014-08-20 01:39:05 +0000149
Miklos Vajna3d71b512016-08-09 18:20:41 +0000150 if (!Input.empty()) {
151 // Populate OldNames and NewNames from a YAML file.
152 auto Buffer = llvm::MemoryBuffer::getFile(Input);
153 if (!Buffer) {
154 errs() << "clang-rename: failed to read " << Input << ": "
155 << Buffer.getError().message() << "\n";
156 exit(1);
157 }
158
159 std::vector<RenameAllInfo> Infos;
160 llvm::yaml::Input YAML(Buffer.get()->getBuffer());
161 YAML >> Infos;
162 for (const auto &Info : Infos) {
163 if (!Info.OldName.empty())
164 OldNames.push_back(Info.OldName);
165 else
166 SymbolOffsets.push_back(Info.Offset);
167 NewNames.push_back(Info.NewName);
168 }
169 }
170
Manuel Klimekde237262014-08-20 01:39:05 +0000171 // Check the arguments for correctness.
172
Miklos Vajna3d71b512016-08-09 18:20:41 +0000173 if (NewNames.empty()) {
174 errs() << "clang-rename: either -new-name or -input is required.\n\n";
175 exit(1);
176 }
177
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000178 // Check if NewNames is a valid identifier in C++17.
179 for (const auto &NewName : NewNames) {
180 LangOptions Options;
181 Options.CPlusPlus = true;
182 Options.CPlusPlus1z = true;
183 IdentifierTable Table(Options);
184 auto NewNameTokKind = Table.get(NewName).getTokenID();
185 if (!tok::isAnyIdentifier(NewNameTokKind)) {
186 errs() << "ERROR: new name is not a valid identifier in C++17.\n\n";
187 exit(1);
188 }
189 }
190
191 if (!OldNames.empty() && OldNames.size() != NewNames.size()) {
192 errs() << "clang-rename: number of old names (" << OldNames.size()
193 << ") do not equal to number of new names (" << NewNames.size()
194 << ").\n\n";
195 cl::PrintHelpMessage();
Kirill Bobyrev08c588c2016-07-21 10:21:31 +0000196 exit(1);
197 }
198
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000199 if (!SymbolOffsets.empty() && SymbolOffsets.size() != NewNames.size()) {
200 errs() << "clang-rename: number of symbol offsets (" << SymbolOffsets.size()
201 << ") do not equal to number of new names (" << NewNames.size()
202 << ").\n\n";
203 cl::PrintHelpMessage();
Manuel Klimekde237262014-08-20 01:39:05 +0000204 exit(1);
205 }
206
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000207 std::vector<std::vector<std::string>> USRList;
208 std::vector<std::string> PrevNames;
Manuel Klimekde237262014-08-20 01:39:05 +0000209 auto Files = OP.getSourcePathList();
210 tooling::RefactoringTool Tool(OP.getCompilations(), Files);
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000211 unsigned Count = OldNames.size() ? OldNames.size() : SymbolOffsets.size();
212 for (unsigned I = 0; I < Count; ++I) {
213 unsigned SymbolOffset = SymbolOffsets.empty() ? 0 : SymbolOffsets[I];
214 const std::string &OldName = OldNames.empty() ? std::string() : OldNames[I];
Manuel Klimekde237262014-08-20 01:39:05 +0000215
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000216 // Get the USRs.
217 rename::USRFindingAction USRAction(SymbolOffset, OldName);
Manuel Klimekde237262014-08-20 01:39:05 +0000218
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000219 // Find the USRs.
220 Tool.run(tooling::newFrontendActionFactory(&USRAction).get());
221 const auto &USRs = USRAction.getUSRs();
222 USRList.push_back(USRs);
223 const auto &PrevName = USRAction.getUSRSpelling();
224 PrevNames.push_back(PrevName);
Manuel Klimekde237262014-08-20 01:39:05 +0000225
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000226 if (PrevName.empty()) {
227 // An error should have already been printed.
228 exit(1);
229 }
230
231 if (PrintName) {
232 errs() << "clang-rename: found name: " << PrevName << '\n';
233 }
Benjamin Kramer1afefc02016-07-14 09:46:03 +0000234 }
Manuel Klimekde237262014-08-20 01:39:05 +0000235
236 // Perform the renaming.
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000237 rename::RenamingAction RenameAction(NewNames, PrevNames, USRList,
Manuel Klimekde237262014-08-20 01:39:05 +0000238 Tool.getReplacements(), PrintLocations);
239 auto Factory = tooling::newFrontendActionFactory(&RenameAction);
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000240 int ExitCode;
Manuel Klimekde237262014-08-20 01:39:05 +0000241
242 if (Inplace) {
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000243 ExitCode = Tool.runAndSave(Factory.get());
Manuel Klimekde237262014-08-20 01:39:05 +0000244 } else {
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000245 ExitCode = Tool.run(Factory.get());
Manuel Klimekde237262014-08-20 01:39:05 +0000246
Miklos Vajnaa2ca3ed2016-06-27 19:34:47 +0000247 if (!ExportFixes.empty()) {
248 std::error_code EC;
249 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
250 if (EC) {
251 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
252 exit(1);
253 }
254
255 // Export replacements.
256 tooling::TranslationUnitReplacements TUR;
Eric Liu267034c2016-08-01 10:16:39 +0000257 const auto &FileToReplacements = Tool.getReplacements();
258 for (const auto &Entry : FileToReplacements)
259 TUR.Replacements.insert(TUR.Replacements.end(), Entry.second.begin(),
260 Entry.second.end());
Miklos Vajnaa2ca3ed2016-06-27 19:34:47 +0000261
262 yaml::Output YAML(OS);
263 YAML << TUR;
264 OS.close();
265 exit(0);
266 }
267
Manuel Klimekde237262014-08-20 01:39:05 +0000268 // Write every file to stdout. Right now we just barf the files without any
269 // indication of which files start where, other than that we print the files
270 // in the same order we see them.
271 LangOptions DefaultLangOptions;
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000272 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimekde237262014-08-20 01:39:05 +0000273 TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
274 DiagnosticsEngine Diagnostics(
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000275 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
276 &DiagnosticPrinter, false);
Manuel Klimekde237262014-08-20 01:39:05 +0000277 auto &FileMgr = Tool.getFiles();
278 SourceManager Sources(Diagnostics, FileMgr);
279 Rewriter Rewrite(Sources, DefaultLangOptions);
280
281 Tool.applyAllReplacements(Rewrite);
282 for (const auto &File : Files) {
283 const auto *Entry = FileMgr.getFile(File);
284 auto ID = Sources.translateFile(Entry);
285 Rewrite.getEditBuffer(ID).write(outs());
286 }
287 }
288
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000289 exit(ExitCode);
Manuel Klimekde237262014-08-20 01:39:05 +0000290}
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000291
292/// \brief Top level help.
293/// FIXME It would be better if this could be auto-generated.
294static int helpMain(int argc, const char *argv[]) {
295 errs() << "Usage: clang-rename {rename-at|rename-all} [OPTION]...\n\n"
296 "A tool to rename symbols in C/C++ code.\n\n"
297 "Subcommands:\n"
298 " rename-at: Perform rename off of a location in a file. (This "
299 "is the default.)\n"
300 " rename-all: Perform rename of all symbols matching one or more "
301 "fully qualified names.\n";
302 return 0;
303}
304
305static int renameAtMain(int argc, const char *argv[]) {
306 return subcommandMain(false, argc, argv);
307}
308
309static int renameAllMain(int argc, const char *argv[]) {
310 return subcommandMain(true, argc, argv);
311}