blob: f7ca39fcfec35bce2790a6878f14606bc54d6d5e [file] [log] [blame]
Alex Lorenzb54ef6a2017-09-14 10:06:52 +00001//===--- ClangRefactor.cpp - Clang-based refactoring tool -----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alex Lorenzb54ef6a2017-09-14 10:06:52 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// This file implements a clang-refactor tool that performs various
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000011/// source transformations.
12///
13//===----------------------------------------------------------------------===//
14
15#include "TestSupport.h"
Alex Lorenze1b7b952017-10-16 17:31:16 +000016#include "clang/Frontend/CommandLineSourceLoc.h"
Alex Lorenzf5ca27c2017-10-16 18:28:26 +000017#include "clang/Frontend/TextDiagnosticPrinter.h"
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000018#include "clang/Rewrite/Core/Rewriter.h"
Alex Lorenz3d712c42017-09-14 13:16:14 +000019#include "clang/Tooling/CommonOptionsParser.h"
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000020#include "clang/Tooling/Refactoring.h"
21#include "clang/Tooling/Refactoring/RefactoringAction.h"
Alex Lorenzad38fbf2017-10-13 01:53:13 +000022#include "clang/Tooling/Refactoring/RefactoringOptions.h"
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000023#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
24#include "clang/Tooling/Tooling.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/FileSystem.h"
Eric Liuc47fd012017-11-07 14:35:03 +000027#include "llvm/Support/Signals.h"
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000028#include "llvm/Support/raw_ostream.h"
29#include <string>
30
31using namespace clang;
32using namespace tooling;
33using namespace refactor;
34namespace cl = llvm::cl;
35
36namespace opts {
37
Alex Lorenzad38fbf2017-10-13 01:53:13 +000038static cl::OptionCategory CommonRefactorOptions("Refactoring options");
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000039
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000040static cl::opt<bool> Verbose("v", cl::desc("Use verbose output"),
Alex Lorenzad38fbf2017-10-13 01:53:13 +000041 cl::cat(cl::GeneralCategory),
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000042 cl::sub(*cl::AllSubCommands));
Haojian Wu55186782017-10-20 12:37:16 +000043
44static cl::opt<bool> Inplace("i", cl::desc("Inplace edit <file>s"),
45 cl::cat(cl::GeneralCategory),
46 cl::sub(*cl::AllSubCommands));
47
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000048} // end namespace opts
49
50namespace {
51
52/// Stores the parsed `-selection` argument.
53class SourceSelectionArgument {
54public:
55 virtual ~SourceSelectionArgument() {}
56
57 /// Parse the `-selection` argument.
58 ///
59 /// \returns A valid argument when the parse succedeed, null otherwise.
60 static std::unique_ptr<SourceSelectionArgument> fromString(StringRef Value);
61
62 /// Prints any additional state associated with the selection argument to
63 /// the given output stream.
Alex Lorenze1b7b952017-10-16 17:31:16 +000064 virtual void print(raw_ostream &OS) {}
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000065
66 /// Returns a replacement refactoring result consumer (if any) that should
67 /// consume the results of a refactoring operation.
68 ///
69 /// The replacement refactoring result consumer is used by \c
70 /// TestSourceSelectionArgument to inject a test-specific result handling
71 /// logic into the refactoring operation. The test-specific consumer
72 /// ensures that the individual results in a particular test group are
73 /// identical.
Alex Lorenzf5ca27c2017-10-16 18:28:26 +000074 virtual std::unique_ptr<ClangRefactorToolConsumerInterface>
75 createCustomConsumer() {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000076 return nullptr;
77 }
78
79 /// Runs the give refactoring function for each specified selection.
80 ///
81 /// \returns true if an error occurred, false otherwise.
82 virtual bool
83 forAllRanges(const SourceManager &SM,
84 llvm::function_ref<void(SourceRange R)> Callback) = 0;
85};
86
87/// Stores the parsed -selection=test:<filename> option.
88class TestSourceSelectionArgument final : public SourceSelectionArgument {
89public:
90 TestSourceSelectionArgument(TestSelectionRangesInFile TestSelections)
91 : TestSelections(std::move(TestSelections)) {}
92
93 void print(raw_ostream &OS) override { TestSelections.dump(OS); }
94
Alex Lorenzf5ca27c2017-10-16 18:28:26 +000095 std::unique_ptr<ClangRefactorToolConsumerInterface>
96 createCustomConsumer() override {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +000097 return TestSelections.createConsumer();
98 }
99
100 /// Testing support: invokes the selection action for each selection range in
101 /// the test file.
102 bool forAllRanges(const SourceManager &SM,
103 llvm::function_ref<void(SourceRange R)> Callback) override {
104 return TestSelections.foreachRange(SM, Callback);
105 }
106
107private:
108 TestSelectionRangesInFile TestSelections;
109};
110
Alex Lorenze1b7b952017-10-16 17:31:16 +0000111/// Stores the parsed -selection=filename:line:column[-line:column] option.
112class SourceRangeSelectionArgument final : public SourceSelectionArgument {
113public:
114 SourceRangeSelectionArgument(ParsedSourceRange Range)
115 : Range(std::move(Range)) {}
116
117 bool forAllRanges(const SourceManager &SM,
118 llvm::function_ref<void(SourceRange R)> Callback) override {
119 const FileEntry *FE = SM.getFileManager().getFile(Range.FileName);
120 FileID FID = FE ? SM.translateFile(FE) : FileID();
121 if (!FE || FID.isInvalid()) {
122 llvm::errs() << "error: -selection=" << Range.FileName
123 << ":... : given file is not in the target TU\n";
124 return true;
125 }
126
127 SourceLocation Start = SM.getMacroArgExpandedLocation(
128 SM.translateLineCol(FID, Range.Begin.first, Range.Begin.second));
129 SourceLocation End = SM.getMacroArgExpandedLocation(
130 SM.translateLineCol(FID, Range.End.first, Range.End.second));
131 if (Start.isInvalid() || End.isInvalid()) {
132 llvm::errs() << "error: -selection=" << Range.FileName << ':'
133 << Range.Begin.first << ':' << Range.Begin.second << '-'
134 << Range.End.first << ':' << Range.End.second
135 << " : invalid source location\n";
136 return true;
137 }
138 Callback(SourceRange(Start, End));
139 return false;
140 }
141
142private:
143 ParsedSourceRange Range;
144};
145
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000146std::unique_ptr<SourceSelectionArgument>
147SourceSelectionArgument::fromString(StringRef Value) {
148 if (Value.startswith("test:")) {
149 StringRef Filename = Value.drop_front(strlen("test:"));
150 Optional<TestSelectionRangesInFile> ParsedTestSelection =
151 findTestSelectionRanges(Filename);
152 if (!ParsedTestSelection)
153 return nullptr; // A parsing error was already reported.
154 return llvm::make_unique<TestSourceSelectionArgument>(
155 std::move(*ParsedTestSelection));
156 }
Alex Lorenze1b7b952017-10-16 17:31:16 +0000157 Optional<ParsedSourceRange> Range = ParsedSourceRange::fromString(Value);
158 if (Range)
159 return llvm::make_unique<SourceRangeSelectionArgument>(std::move(*Range));
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000160 llvm::errs() << "error: '-selection' option must be specified using "
161 "<file>:<line>:<column> or "
Alex Lorenze1b7b952017-10-16 17:31:16 +0000162 "<file>:<line>:<column>-<line>:<column> format\n";
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000163 return nullptr;
164}
165
Alex Lorenzad38fbf2017-10-13 01:53:13 +0000166/// A container that stores the command-line options used by a single
167/// refactoring option.
168class RefactoringActionCommandLineOptions {
169public:
170 void addStringOption(const RefactoringOption &Option,
171 std::unique_ptr<cl::opt<std::string>> CLOption) {
172 StringOptions[&Option] = std::move(CLOption);
173 }
174
175 const cl::opt<std::string> &
176 getStringOption(const RefactoringOption &Opt) const {
177 auto It = StringOptions.find(&Opt);
178 return *It->second;
179 }
180
181private:
182 llvm::DenseMap<const RefactoringOption *,
183 std::unique_ptr<cl::opt<std::string>>>
184 StringOptions;
185};
186
187/// Passes the command-line option values to the options used by a single
188/// refactoring action rule.
189class CommandLineRefactoringOptionVisitor final
190 : public RefactoringOptionVisitor {
191public:
192 CommandLineRefactoringOptionVisitor(
193 const RefactoringActionCommandLineOptions &Options)
194 : Options(Options) {}
195
196 void visit(const RefactoringOption &Opt,
197 Optional<std::string> &Value) override {
198 const cl::opt<std::string> &CLOpt = Options.getStringOption(Opt);
199 if (!CLOpt.getValue().empty()) {
200 Value = CLOpt.getValue();
201 return;
202 }
203 Value = None;
204 if (Opt.isRequired())
205 MissingRequiredOptions.push_back(&Opt);
206 }
207
208 ArrayRef<const RefactoringOption *> getMissingRequiredOptions() const {
209 return MissingRequiredOptions;
210 }
211
212private:
213 llvm::SmallVector<const RefactoringOption *, 4> MissingRequiredOptions;
214 const RefactoringActionCommandLineOptions &Options;
215};
216
217/// Creates the refactoring options used by all the rules in a single
218/// refactoring action.
219class CommandLineRefactoringOptionCreator final
220 : public RefactoringOptionVisitor {
221public:
222 CommandLineRefactoringOptionCreator(
223 cl::OptionCategory &Category, cl::SubCommand &Subcommand,
224 RefactoringActionCommandLineOptions &Options)
225 : Category(Category), Subcommand(Subcommand), Options(Options) {}
226
227 void visit(const RefactoringOption &Opt, Optional<std::string> &) override {
228 if (Visited.insert(&Opt).second)
229 Options.addStringOption(Opt, create<std::string>(Opt));
230 }
231
232private:
233 template <typename T>
234 std::unique_ptr<cl::opt<T>> create(const RefactoringOption &Opt) {
235 if (!OptionNames.insert(Opt.getName()).second)
236 llvm::report_fatal_error("Multiple identical refactoring options "
237 "specified for one refactoring action");
238 // FIXME: cl::Required can be specified when this option is present
239 // in all rules in an action.
240 return llvm::make_unique<cl::opt<T>>(
241 Opt.getName(), cl::desc(Opt.getDescription()), cl::Optional,
242 cl::cat(Category), cl::sub(Subcommand));
243 }
244
245 llvm::SmallPtrSet<const RefactoringOption *, 8> Visited;
246 llvm::StringSet<> OptionNames;
247 cl::OptionCategory &Category;
248 cl::SubCommand &Subcommand;
249 RefactoringActionCommandLineOptions &Options;
250};
251
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000252/// A subcommand that corresponds to individual refactoring action.
253class RefactoringActionSubcommand : public cl::SubCommand {
254public:
255 RefactoringActionSubcommand(std::unique_ptr<RefactoringAction> Action,
256 RefactoringActionRules ActionRules,
257 cl::OptionCategory &Category)
258 : SubCommand(Action->getCommand(), Action->getDescription()),
Haojian Wu200458f2017-11-08 08:56:56 +0000259 Action(std::move(Action)), ActionRules(std::move(ActionRules)) {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000260 // Check if the selection option is supported.
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000261 for (const auto &Rule : this->ActionRules) {
Haojian Wu200458f2017-11-08 08:56:56 +0000262 if (Rule->hasSelectionRequirement()) {
263 Selection = llvm::make_unique<cl::opt<std::string>>(
264 "selection",
265 cl::desc(
266 "The selected source range in which the refactoring should "
267 "be initiated (<file>:<line>:<column>-<line>:<column> or "
268 "<file>:<line>:<column>)"),
269 cl::cat(Category), cl::sub(*this));
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000270 break;
Haojian Wu200458f2017-11-08 08:56:56 +0000271 }
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000272 }
Alex Lorenzad38fbf2017-10-13 01:53:13 +0000273 // Create the refactoring options.
274 for (const auto &Rule : this->ActionRules) {
275 CommandLineRefactoringOptionCreator OptionCreator(Category, *this,
276 Options);
277 Rule->visitRefactoringOptions(OptionCreator);
278 }
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000279 }
280
281 ~RefactoringActionSubcommand() { unregisterSubCommand(); }
282
283 const RefactoringActionRules &getActionRules() const { return ActionRules; }
284
Haojian Wu200458f2017-11-08 08:56:56 +0000285 /// Parses the "-selection" command-line argument.
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000286 ///
287 /// \returns true on error, false otherwise.
Haojian Wu200458f2017-11-08 08:56:56 +0000288 bool parseSelectionArgument() {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000289 if (Selection) {
290 ParsedSelection = SourceSelectionArgument::fromString(*Selection);
291 if (!ParsedSelection)
292 return true;
293 }
294 return false;
295 }
296
297 SourceSelectionArgument *getSelection() const {
298 assert(Selection && "selection not supported!");
299 return ParsedSelection.get();
300 }
Alex Lorenzad38fbf2017-10-13 01:53:13 +0000301
302 const RefactoringActionCommandLineOptions &getOptions() const {
303 return Options;
304 }
305
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000306private:
307 std::unique_ptr<RefactoringAction> Action;
308 RefactoringActionRules ActionRules;
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000309 std::unique_ptr<cl::opt<std::string>> Selection;
310 std::unique_ptr<SourceSelectionArgument> ParsedSelection;
Alex Lorenzad38fbf2017-10-13 01:53:13 +0000311 RefactoringActionCommandLineOptions Options;
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000312};
313
Alex Lorenzf5ca27c2017-10-16 18:28:26 +0000314class ClangRefactorConsumer final : public ClangRefactorToolConsumerInterface {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000315public:
Eric Liuc47fd012017-11-07 14:35:03 +0000316 ClangRefactorConsumer(AtomicChanges &Changes) : SourceChanges(&Changes) {}
Alex Lorenzf5ca27c2017-10-16 18:28:26 +0000317
Alex Lorenze1b7b952017-10-16 17:31:16 +0000318 void handleError(llvm::Error Err) override {
Alex Lorenzf5ca27c2017-10-16 18:28:26 +0000319 Optional<PartialDiagnosticAt> Diag = DiagnosticError::take(Err);
320 if (!Diag) {
321 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
322 return;
323 }
324 llvm::cantFail(std::move(Err)); // This is a success.
325 DiagnosticBuilder DB(
326 getDiags().Report(Diag->first, Diag->second.getDiagID()));
327 Diag->second.Emit(DB);
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000328 }
329
Alex Lorenze1b7b952017-10-16 17:31:16 +0000330 void handle(AtomicChanges Changes) override {
Eric Liuc47fd012017-11-07 14:35:03 +0000331 SourceChanges->insert(SourceChanges->begin(), Changes.begin(),
332 Changes.end());
Alex Lorenze1b7b952017-10-16 17:31:16 +0000333 }
334
335 void handle(SymbolOccurrences Occurrences) override {
Alex Lorenz52843502017-10-16 18:07:16 +0000336 llvm_unreachable("symbol occurrence results are not handled yet");
Alex Lorenze1b7b952017-10-16 17:31:16 +0000337 }
338
Alex Lorenze1b7b952017-10-16 17:31:16 +0000339private:
Eric Liuc47fd012017-11-07 14:35:03 +0000340 AtomicChanges *SourceChanges;
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000341};
342
343class ClangRefactorTool {
344public:
Eric Liuc47fd012017-11-07 14:35:03 +0000345 ClangRefactorTool()
346 : SelectedSubcommand(nullptr), MatchingRule(nullptr),
347 Consumer(new ClangRefactorConsumer(Changes)), HasFailed(false) {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000348 std::vector<std::unique_ptr<RefactoringAction>> Actions =
349 createRefactoringActions();
350
351 // Actions must have unique command names so that we can map them to one
352 // subcommand.
353 llvm::StringSet<> CommandNames;
354 for (const auto &Action : Actions) {
355 if (!CommandNames.insert(Action->getCommand()).second) {
356 llvm::errs() << "duplicate refactoring action command '"
357 << Action->getCommand() << "'!";
358 exit(1);
359 }
360 }
361
362 // Create subcommands and command-line options.
363 for (auto &Action : Actions) {
364 SubCommands.push_back(llvm::make_unique<RefactoringActionSubcommand>(
365 std::move(Action), Action->createActiveActionRules(),
366 opts::CommonRefactorOptions));
367 }
368 }
369
Eric Liuc47fd012017-11-07 14:35:03 +0000370 // Initializes the selected subcommand and refactoring rule based on the
371 // command line options.
372 llvm::Error Init() {
373 auto Subcommand = getSelectedSubcommand();
374 if (!Subcommand)
375 return Subcommand.takeError();
376 auto Rule = getMatchingRule(**Subcommand);
377 if (!Rule)
378 return Rule.takeError();
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000379
Eric Liuc47fd012017-11-07 14:35:03 +0000380 SelectedSubcommand = *Subcommand;
381 MatchingRule = *Rule;
382
383 return llvm::Error::success();
384 }
385
386 bool hasFailed() const { return HasFailed; }
387
388 using TUCallbackType = std::function<void(ASTContext &)>;
389
390 // Callback of an AST action. This invokes the matching rule on the given AST.
391 void callback(ASTContext &AST) {
392 assert(SelectedSubcommand && MatchingRule && Consumer);
393 RefactoringRuleContext Context(AST.getSourceManager());
394 Context.setASTContext(AST);
395
396 // If the selection option is test specific, we use a test-specific
397 // consumer.
398 std::unique_ptr<ClangRefactorToolConsumerInterface> TestConsumer;
Haojian Wu200458f2017-11-08 08:56:56 +0000399 bool HasSelection = MatchingRule->hasSelectionRequirement();
400 if (HasSelection)
Eric Liuc47fd012017-11-07 14:35:03 +0000401 TestConsumer = SelectedSubcommand->getSelection()->createCustomConsumer();
402 ClangRefactorToolConsumerInterface *ActiveConsumer =
403 TestConsumer ? TestConsumer.get() : Consumer.get();
404 ActiveConsumer->beginTU(AST);
Haojian Wu200458f2017-11-08 08:56:56 +0000405
406 auto InvokeRule = [&](RefactoringResultConsumer &Consumer) {
407 if (opts::Verbose)
408 logInvocation(*SelectedSubcommand, Context);
409 MatchingRule->invoke(*ActiveConsumer, Context);
410 };
411 if (HasSelection) {
Eric Liuc47fd012017-11-07 14:35:03 +0000412 assert(SelectedSubcommand->getSelection() &&
413 "Missing selection argument?");
414 if (opts::Verbose)
415 SelectedSubcommand->getSelection()->print(llvm::outs());
416 if (SelectedSubcommand->getSelection()->forAllRanges(
417 Context.getSources(), [&](SourceRange R) {
418 Context.setSelectionRange(R);
Haojian Wu200458f2017-11-08 08:56:56 +0000419 InvokeRule(*ActiveConsumer);
Eric Liuc47fd012017-11-07 14:35:03 +0000420 }))
421 HasFailed = true;
422 ActiveConsumer->endTU();
423 return;
424 }
Haojian Wu200458f2017-11-08 08:56:56 +0000425 InvokeRule(*ActiveConsumer);
Eric Liuc47fd012017-11-07 14:35:03 +0000426 ActiveConsumer->endTU();
427 }
428
429 llvm::Expected<std::unique_ptr<FrontendActionFactory>>
430 getFrontendActionFactory() {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000431 class ToolASTConsumer : public ASTConsumer {
432 public:
433 TUCallbackType Callback;
Eric Liuc47fd012017-11-07 14:35:03 +0000434 ToolASTConsumer(TUCallbackType Callback)
435 : Callback(std::move(Callback)) {}
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000436
437 void HandleTranslationUnit(ASTContext &Context) override {
438 Callback(Context);
439 }
440 };
Eric Liuc47fd012017-11-07 14:35:03 +0000441 class ToolASTAction : public ASTFrontendAction {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000442 public:
Eric Liuc47fd012017-11-07 14:35:03 +0000443 explicit ToolASTAction(TUCallbackType Callback)
444 : Callback(std::move(Callback)) {}
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000445
Eric Liuc47fd012017-11-07 14:35:03 +0000446 protected:
447 std::unique_ptr<clang::ASTConsumer>
448 CreateASTConsumer(clang::CompilerInstance &compiler,
449 StringRef /* dummy */) override {
450 std::unique_ptr<clang::ASTConsumer> Consumer{
451 new ToolASTConsumer(Callback)};
452 return Consumer;
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000453 }
Eric Liuc47fd012017-11-07 14:35:03 +0000454
455 private:
456 TUCallbackType Callback;
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000457 };
458
Eric Liuc47fd012017-11-07 14:35:03 +0000459 class ToolActionFactory : public FrontendActionFactory {
460 public:
461 ToolActionFactory(TUCallbackType Callback)
462 : Callback(std::move(Callback)) {}
463
Roman Lebedev497fd982018-02-27 15:54:55 +0000464 FrontendAction *create() override { return new ToolASTAction(Callback); }
Eric Liuc47fd012017-11-07 14:35:03 +0000465
466 private:
467 TUCallbackType Callback;
468 };
469
470 return llvm::make_unique<ToolActionFactory>(
471 [this](ASTContext &AST) { return callback(AST); });
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000472 }
473
Eric Liuc47fd012017-11-07 14:35:03 +0000474 // FIXME(ioeric): this seems to only works for changes in a single file at
475 // this point.
476 bool applySourceChanges() {
Alex Lorenze1b7b952017-10-16 17:31:16 +0000477 std::set<std::string> Files;
Eric Liuc47fd012017-11-07 14:35:03 +0000478 for (const auto &Change : Changes)
Alex Lorenze1b7b952017-10-16 17:31:16 +0000479 Files.insert(Change.getFilePath());
480 // FIXME: Add automatic formatting support as well.
481 tooling::ApplyChangesSpec Spec;
482 // FIXME: We should probably cleanup the result by default as well.
483 Spec.Cleanup = false;
484 for (const auto &File : Files) {
485 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferErr =
486 llvm::MemoryBuffer::getFile(File);
487 if (!BufferErr) {
488 llvm::errs() << "error: failed to open " << File << " for rewriting\n";
489 return true;
490 }
491 auto Result = tooling::applyAtomicChanges(File, (*BufferErr)->getBuffer(),
Eric Liuc47fd012017-11-07 14:35:03 +0000492 Changes, Spec);
Alex Lorenze1b7b952017-10-16 17:31:16 +0000493 if (!Result) {
494 llvm::errs() << toString(Result.takeError());
495 return true;
496 }
497
Haojian Wu55186782017-10-20 12:37:16 +0000498 if (opts::Inplace) {
499 std::error_code EC;
500 llvm::raw_fd_ostream OS(File, EC, llvm::sys::fs::F_Text);
501 if (EC) {
502 llvm::errs() << EC.message() << "\n";
503 return true;
504 }
505 OS << *Result;
506 continue;
Alex Lorenze1b7b952017-10-16 17:31:16 +0000507 }
Haojian Wu55186782017-10-20 12:37:16 +0000508
509 llvm::outs() << *Result;
Alex Lorenze1b7b952017-10-16 17:31:16 +0000510 }
511 return false;
512 }
513
Eric Liuc47fd012017-11-07 14:35:03 +0000514private:
515 /// Logs an individual refactoring action invocation to STDOUT.
516 void logInvocation(RefactoringActionSubcommand &Subcommand,
517 const RefactoringRuleContext &Context) {
518 llvm::outs() << "invoking action '" << Subcommand.getName() << "':\n";
519 if (Context.getSelectionRange().isValid()) {
520 SourceRange R = Context.getSelectionRange();
521 llvm::outs() << " -selection=";
522 R.getBegin().print(llvm::outs(), Context.getSources());
523 llvm::outs() << " -> ";
524 R.getEnd().print(llvm::outs(), Context.getSources());
525 llvm::outs() << "\n";
526 }
527 }
528
529 llvm::Expected<RefactoringActionRule *>
Haojian Wu200458f2017-11-08 08:56:56 +0000530 getMatchingRule(RefactoringActionSubcommand &Subcommand) {
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000531 SmallVector<RefactoringActionRule *, 4> MatchingRules;
532 llvm::StringSet<> MissingOptions;
533
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000534 for (const auto &Rule : Subcommand.getActionRules()) {
Alex Lorenzad38fbf2017-10-13 01:53:13 +0000535 CommandLineRefactoringOptionVisitor Visitor(Subcommand.getOptions());
536 Rule->visitRefactoringOptions(Visitor);
Haojian Wu200458f2017-11-08 08:56:56 +0000537 if (Visitor.getMissingRequiredOptions().empty()) {
538 if (!Rule->hasSelectionRequirement()) {
539 MatchingRules.push_back(Rule.get());
540 } else {
541 Subcommand.parseSelectionArgument();
542 if (Subcommand.getSelection()) {
543 MatchingRules.push_back(Rule.get());
544 } else {
545 MissingOptions.insert("selection");
546 }
547 }
Alex Lorenzad38fbf2017-10-13 01:53:13 +0000548 }
549 for (const RefactoringOption *Opt : Visitor.getMissingRequiredOptions())
550 MissingOptions.insert(Opt->getName());
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000551 }
552 if (MatchingRules.empty()) {
Eric Liuc47fd012017-11-07 14:35:03 +0000553 std::string Error;
554 llvm::raw_string_ostream OS(Error);
555 OS << "ERROR: '" << Subcommand.getName()
556 << "' can't be invoked with the given arguments:\n";
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000557 for (const auto &Opt : MissingOptions)
Eric Liuc47fd012017-11-07 14:35:03 +0000558 OS << " missing '-" << Opt.getKey() << "' option\n";
559 OS.flush();
560 return llvm::make_error<llvm::StringError>(
561 Error, llvm::inconvertibleErrorCode());
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000562 }
Eric Liuc47fd012017-11-07 14:35:03 +0000563 if (MatchingRules.size() != 1) {
564 return llvm::make_error<llvm::StringError>(
565 llvm::Twine("ERROR: more than one matching rule of action") +
566 Subcommand.getName() + "was found with given options.",
567 llvm::inconvertibleErrorCode());
568 }
569 return MatchingRules.front();
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000570 }
Eric Liuc47fd012017-11-07 14:35:03 +0000571 // Figure out which action is specified by the user. The user must specify the
572 // action using a command-line subcommand, e.g. the invocation `clang-refactor
573 // local-rename` corresponds to the `LocalRename` refactoring action. All
574 // subcommands must have a unique names. This allows us to figure out which
575 // refactoring action should be invoked by looking at the first subcommand
576 // that's enabled by LLVM's command-line parser.
577 llvm::Expected<RefactoringActionSubcommand *> getSelectedSubcommand() {
578 auto It = llvm::find_if(
579 SubCommands,
580 [](const std::unique_ptr<RefactoringActionSubcommand> &SubCommand) {
581 return !!(*SubCommand);
582 });
583 if (It == SubCommands.end()) {
584 std::string Error;
585 llvm::raw_string_ostream OS(Error);
586 OS << "error: no refactoring action given\n";
587 OS << "note: the following actions are supported:\n";
588 for (const auto &Subcommand : SubCommands)
589 OS.indent(2) << Subcommand->getName() << "\n";
590 OS.flush();
591 return llvm::make_error<llvm::StringError>(
592 Error, llvm::inconvertibleErrorCode());
593 }
594 RefactoringActionSubcommand *Subcommand = &(**It);
Eric Liuc47fd012017-11-07 14:35:03 +0000595 return Subcommand;
596 }
597
598 std::vector<std::unique_ptr<RefactoringActionSubcommand>> SubCommands;
599 RefactoringActionSubcommand *SelectedSubcommand;
600 RefactoringActionRule *MatchingRule;
601 std::unique_ptr<ClangRefactorToolConsumerInterface> Consumer;
602 AtomicChanges Changes;
603 bool HasFailed;
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000604};
605
606} // end anonymous namespace
607
608int main(int argc, const char **argv) {
Eric Liuc47fd012017-11-07 14:35:03 +0000609 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
610
611 ClangRefactorTool RefactorTool;
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000612
Alex Lorenz3d712c42017-09-14 13:16:14 +0000613 CommonOptionsParser Options(
Alex Lorenzad38fbf2017-10-13 01:53:13 +0000614 argc, argv, cl::GeneralCategory, cl::ZeroOrMore,
Alex Lorenz3d712c42017-09-14 13:16:14 +0000615 "Clang-based refactoring tool for C, C++ and Objective-C");
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000616
Eric Liuc47fd012017-11-07 14:35:03 +0000617 if (auto Err = RefactorTool.Init()) {
618 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000619 return 1;
620 }
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000621
Eric Liuc47fd012017-11-07 14:35:03 +0000622 auto ActionFactory = RefactorTool.getFrontendActionFactory();
623 if (!ActionFactory) {
624 llvm::errs() << llvm::toString(ActionFactory.takeError()) << "\n";
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000625 return 1;
Eric Liuc47fd012017-11-07 14:35:03 +0000626 }
627 ClangTool Tool(Options.getCompilations(), Options.getSourcePathList());
628 bool Failed = false;
629 if (Tool.run(ActionFactory->get()) != 0) {
630 llvm::errs() << "Failed to run refactoring action on files\n";
631 // It is possible that TUs are broken while changes are generated correctly,
632 // so we still try applying changes.
633 Failed = true;
634 }
635 return RefactorTool.applySourceChanges() || Failed ||
636 RefactorTool.hasFailed();
Alex Lorenzb54ef6a2017-09-14 10:06:52 +0000637}