blob: dc2b7a55b7222ec8cd35e7c01828fa12e5445b5e [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
Manuel Klimekde237262014-08-20 01:39:05 +000059int main(int argc, const char **argv) {
Miklos Vajnaaaec9b62016-08-02 09:51:31 +000060 if (argc > 1) {
61 using MainFunction = std::function<int(int, const char *[])>;
62 MainFunction Func = StringSwitch<MainFunction>(argv[1])
63 .Case("rename-at", renameAtMain)
64 .Case("rename-all", renameAllMain)
65 .Cases("-help", "--help", helpMain)
66 .Default(nullptr);
67
68 if (Func) {
69 std::string Invocation = std::string(argv[0]) + " " + argv[1];
70 argv[1] = Invocation.c_str();
71 return Func(argc - 1, argv + 1);
72 } else {
73 return renameAtMain(argc, argv);
74 }
75 }
76
77 helpMain(argc, argv);
78 return 1;
79}
80
81int subcommandMain(bool isRenameAll, int argc, const char **argv) {
82 cl::OptionCategory *Category = nullptr;
83 const char *Usage = nullptr;
84 if (isRenameAll) {
85 Category = &ClangRenameAllCategory;
86 Usage = RenameAllUsage;
87 } else {
88 Category = &ClangRenameAtCategory;
89 Usage = RenameAtUsage;
90 }
91
92 cl::list<std::string> NewNames(
93 "new-name", cl::desc("The new name to change the symbol to."),
94 (isRenameAll ? cl::OneOrMore : cl::Required), cl::cat(*Category));
95 cl::list<unsigned> SymbolOffsets(
96 "offset",
97 cl::desc("Locates the symbol by offset as opposed to <line>:<column>."),
98 (isRenameAll ? cl::ZeroOrMore : cl::Required), cl::cat(*Category));
99 cl::list<std::string> OldNames(
100 "old-name",
101 cl::desc(
102 "The fully qualified name of the symbol, if -offset is not used."),
103 (isRenameAll ? cl::ZeroOrMore : cl::Optional),
104 cl::cat(ClangRenameAllCategory));
105 cl::opt<bool> Inplace("i", cl::desc("Overwrite edited <file>s."),
106 cl::cat(*Category));
107 cl::opt<bool> PrintName(
108 "pn",
109 cl::desc("Print the found symbol's name prior to renaming to stderr."),
110 cl::cat(ClangRenameAtCategory));
111 cl::opt<bool> PrintLocations(
112 "pl", cl::desc("Print the locations affected by renaming to stderr."),
113 cl::cat(ClangRenameAtCategory));
114 cl::opt<std::string> ExportFixes(
115 "export-fixes", cl::desc("YAML file to store suggested fixes in."),
116 cl::value_desc("filename"), cl::cat(*Category));
117
118 tooling::CommonOptionsParser OP(argc, argv, *Category, Usage);
Manuel Klimekde237262014-08-20 01:39:05 +0000119
120 // Check the arguments for correctness.
121
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000122 // Check if NewNames is a valid identifier in C++17.
123 for (const auto &NewName : NewNames) {
124 LangOptions Options;
125 Options.CPlusPlus = true;
126 Options.CPlusPlus1z = true;
127 IdentifierTable Table(Options);
128 auto NewNameTokKind = Table.get(NewName).getTokenID();
129 if (!tok::isAnyIdentifier(NewNameTokKind)) {
130 errs() << "ERROR: new name is not a valid identifier in C++17.\n\n";
131 exit(1);
132 }
133 }
134
135 if (!OldNames.empty() && OldNames.size() != NewNames.size()) {
136 errs() << "clang-rename: number of old names (" << OldNames.size()
137 << ") do not equal to number of new names (" << NewNames.size()
138 << ").\n\n";
139 cl::PrintHelpMessage();
Kirill Bobyrev08c588c2016-07-21 10:21:31 +0000140 exit(1);
141 }
142
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000143 if (!SymbolOffsets.empty() && SymbolOffsets.size() != NewNames.size()) {
144 errs() << "clang-rename: number of symbol offsets (" << SymbolOffsets.size()
145 << ") do not equal to number of new names (" << NewNames.size()
146 << ").\n\n";
147 cl::PrintHelpMessage();
Manuel Klimekde237262014-08-20 01:39:05 +0000148 exit(1);
149 }
150
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000151 std::vector<std::vector<std::string>> USRList;
152 std::vector<std::string> PrevNames;
Manuel Klimekde237262014-08-20 01:39:05 +0000153 auto Files = OP.getSourcePathList();
154 tooling::RefactoringTool Tool(OP.getCompilations(), Files);
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000155 unsigned Count = OldNames.size() ? OldNames.size() : SymbolOffsets.size();
156 for (unsigned I = 0; I < Count; ++I) {
157 unsigned SymbolOffset = SymbolOffsets.empty() ? 0 : SymbolOffsets[I];
158 const std::string &OldName = OldNames.empty() ? std::string() : OldNames[I];
Manuel Klimekde237262014-08-20 01:39:05 +0000159
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000160 // Get the USRs.
161 rename::USRFindingAction USRAction(SymbolOffset, OldName);
Manuel Klimekde237262014-08-20 01:39:05 +0000162
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000163 // Find the USRs.
164 Tool.run(tooling::newFrontendActionFactory(&USRAction).get());
165 const auto &USRs = USRAction.getUSRs();
166 USRList.push_back(USRs);
167 const auto &PrevName = USRAction.getUSRSpelling();
168 PrevNames.push_back(PrevName);
Manuel Klimekde237262014-08-20 01:39:05 +0000169
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000170 if (PrevName.empty()) {
171 // An error should have already been printed.
172 exit(1);
173 }
174
175 if (PrintName) {
176 errs() << "clang-rename: found name: " << PrevName << '\n';
177 }
Benjamin Kramer1afefc02016-07-14 09:46:03 +0000178 }
Manuel Klimekde237262014-08-20 01:39:05 +0000179
180 // Perform the renaming.
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000181 rename::RenamingAction RenameAction(NewNames, PrevNames, USRList,
Manuel Klimekde237262014-08-20 01:39:05 +0000182 Tool.getReplacements(), PrintLocations);
183 auto Factory = tooling::newFrontendActionFactory(&RenameAction);
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000184 int ExitCode;
Manuel Klimekde237262014-08-20 01:39:05 +0000185
186 if (Inplace) {
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000187 ExitCode = Tool.runAndSave(Factory.get());
Manuel Klimekde237262014-08-20 01:39:05 +0000188 } else {
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000189 ExitCode = Tool.run(Factory.get());
Manuel Klimekde237262014-08-20 01:39:05 +0000190
Miklos Vajnaa2ca3ed2016-06-27 19:34:47 +0000191 if (!ExportFixes.empty()) {
192 std::error_code EC;
193 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
194 if (EC) {
195 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
196 exit(1);
197 }
198
199 // Export replacements.
200 tooling::TranslationUnitReplacements TUR;
Eric Liu267034c2016-08-01 10:16:39 +0000201 const auto &FileToReplacements = Tool.getReplacements();
202 for (const auto &Entry : FileToReplacements)
203 TUR.Replacements.insert(TUR.Replacements.end(), Entry.second.begin(),
204 Entry.second.end());
Miklos Vajnaa2ca3ed2016-06-27 19:34:47 +0000205
206 yaml::Output YAML(OS);
207 YAML << TUR;
208 OS.close();
209 exit(0);
210 }
211
Manuel Klimekde237262014-08-20 01:39:05 +0000212 // Write every file to stdout. Right now we just barf the files without any
213 // indication of which files start where, other than that we print the files
214 // in the same order we see them.
215 LangOptions DefaultLangOptions;
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000216 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Manuel Klimekde237262014-08-20 01:39:05 +0000217 TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
218 DiagnosticsEngine Diagnostics(
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000219 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
220 &DiagnosticPrinter, false);
Manuel Klimekde237262014-08-20 01:39:05 +0000221 auto &FileMgr = Tool.getFiles();
222 SourceManager Sources(Diagnostics, FileMgr);
223 Rewriter Rewrite(Sources, DefaultLangOptions);
224
225 Tool.applyAllReplacements(Rewrite);
226 for (const auto &File : Files) {
227 const auto *Entry = FileMgr.getFile(File);
228 auto ID = Sources.translateFile(Entry);
229 Rewrite.getEditBuffer(ID).write(outs());
230 }
231 }
232
Kirill Bobyrev32db7692016-07-15 11:29:16 +0000233 exit(ExitCode);
Manuel Klimekde237262014-08-20 01:39:05 +0000234}
Miklos Vajnaaaec9b62016-08-02 09:51:31 +0000235
236/// \brief Top level help.
237/// FIXME It would be better if this could be auto-generated.
238static int helpMain(int argc, const char *argv[]) {
239 errs() << "Usage: clang-rename {rename-at|rename-all} [OPTION]...\n\n"
240 "A tool to rename symbols in C/C++ code.\n\n"
241 "Subcommands:\n"
242 " rename-at: Perform rename off of a location in a file. (This "
243 "is the default.)\n"
244 " rename-all: Perform rename of all symbols matching one or more "
245 "fully qualified names.\n";
246 return 0;
247}
248
249static int renameAtMain(int argc, const char *argv[]) {
250 return subcommandMain(false, argc, argv);
251}
252
253static int renameAllMain(int argc, const char *argv[]) {
254 return subcommandMain(true, argc, argv);
255}