Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 1 | //===--- ClangRefactor.cpp - Clang-based refactoring 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-refactor tool that performs various |
| 12 | /// source transformations. |
| 13 | /// |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #include "TestSupport.h" |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 17 | #include "clang/Frontend/CommandLineSourceLoc.h" |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 18 | #include "clang/Frontend/TextDiagnosticPrinter.h" |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 19 | #include "clang/Rewrite/Core/Rewriter.h" |
Alex Lorenz | 3d712c4 | 2017-09-14 13:16:14 +0000 | [diff] [blame] | 20 | #include "clang/Tooling/CommonOptionsParser.h" |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 21 | #include "clang/Tooling/Refactoring.h" |
| 22 | #include "clang/Tooling/Refactoring/RefactoringAction.h" |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 23 | #include "clang/Tooling/Refactoring/RefactoringOptions.h" |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 24 | #include "clang/Tooling/Refactoring/Rename/RenamingAction.h" |
| 25 | #include "clang/Tooling/Tooling.h" |
| 26 | #include "llvm/Support/CommandLine.h" |
| 27 | #include "llvm/Support/FileSystem.h" |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 28 | #include "llvm/Support/Signals.h" |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 29 | #include "llvm/Support/raw_ostream.h" |
| 30 | #include <string> |
| 31 | |
| 32 | using namespace clang; |
| 33 | using namespace tooling; |
| 34 | using namespace refactor; |
| 35 | namespace cl = llvm::cl; |
| 36 | |
| 37 | namespace opts { |
| 38 | |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 39 | static cl::OptionCategory CommonRefactorOptions("Refactoring options"); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 40 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 41 | static cl::opt<bool> Verbose("v", cl::desc("Use verbose output"), |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 42 | cl::cat(cl::GeneralCategory), |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 43 | cl::sub(*cl::AllSubCommands)); |
Haojian Wu | 5518678 | 2017-10-20 12:37:16 +0000 | [diff] [blame] | 44 | |
| 45 | static cl::opt<bool> Inplace("i", cl::desc("Inplace edit <file>s"), |
| 46 | cl::cat(cl::GeneralCategory), |
| 47 | cl::sub(*cl::AllSubCommands)); |
| 48 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 49 | } // end namespace opts |
| 50 | |
| 51 | namespace { |
| 52 | |
| 53 | /// Stores the parsed `-selection` argument. |
| 54 | class SourceSelectionArgument { |
| 55 | public: |
| 56 | virtual ~SourceSelectionArgument() {} |
| 57 | |
| 58 | /// Parse the `-selection` argument. |
| 59 | /// |
| 60 | /// \returns A valid argument when the parse succedeed, null otherwise. |
| 61 | static std::unique_ptr<SourceSelectionArgument> fromString(StringRef Value); |
| 62 | |
| 63 | /// Prints any additional state associated with the selection argument to |
| 64 | /// the given output stream. |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 65 | virtual void print(raw_ostream &OS) {} |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 66 | |
| 67 | /// Returns a replacement refactoring result consumer (if any) that should |
| 68 | /// consume the results of a refactoring operation. |
| 69 | /// |
| 70 | /// The replacement refactoring result consumer is used by \c |
| 71 | /// TestSourceSelectionArgument to inject a test-specific result handling |
| 72 | /// logic into the refactoring operation. The test-specific consumer |
| 73 | /// ensures that the individual results in a particular test group are |
| 74 | /// identical. |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 75 | virtual std::unique_ptr<ClangRefactorToolConsumerInterface> |
| 76 | createCustomConsumer() { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 77 | return nullptr; |
| 78 | } |
| 79 | |
| 80 | /// Runs the give refactoring function for each specified selection. |
| 81 | /// |
| 82 | /// \returns true if an error occurred, false otherwise. |
| 83 | virtual bool |
| 84 | forAllRanges(const SourceManager &SM, |
| 85 | llvm::function_ref<void(SourceRange R)> Callback) = 0; |
| 86 | }; |
| 87 | |
| 88 | /// Stores the parsed -selection=test:<filename> option. |
| 89 | class TestSourceSelectionArgument final : public SourceSelectionArgument { |
| 90 | public: |
| 91 | TestSourceSelectionArgument(TestSelectionRangesInFile TestSelections) |
| 92 | : TestSelections(std::move(TestSelections)) {} |
| 93 | |
| 94 | void print(raw_ostream &OS) override { TestSelections.dump(OS); } |
| 95 | |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 96 | std::unique_ptr<ClangRefactorToolConsumerInterface> |
| 97 | createCustomConsumer() override { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 98 | return TestSelections.createConsumer(); |
| 99 | } |
| 100 | |
| 101 | /// Testing support: invokes the selection action for each selection range in |
| 102 | /// the test file. |
| 103 | bool forAllRanges(const SourceManager &SM, |
| 104 | llvm::function_ref<void(SourceRange R)> Callback) override { |
| 105 | return TestSelections.foreachRange(SM, Callback); |
| 106 | } |
| 107 | |
| 108 | private: |
| 109 | TestSelectionRangesInFile TestSelections; |
| 110 | }; |
| 111 | |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 112 | /// Stores the parsed -selection=filename:line:column[-line:column] option. |
| 113 | class SourceRangeSelectionArgument final : public SourceSelectionArgument { |
| 114 | public: |
| 115 | SourceRangeSelectionArgument(ParsedSourceRange Range) |
| 116 | : Range(std::move(Range)) {} |
| 117 | |
| 118 | bool forAllRanges(const SourceManager &SM, |
| 119 | llvm::function_ref<void(SourceRange R)> Callback) override { |
| 120 | const FileEntry *FE = SM.getFileManager().getFile(Range.FileName); |
| 121 | FileID FID = FE ? SM.translateFile(FE) : FileID(); |
| 122 | if (!FE || FID.isInvalid()) { |
| 123 | llvm::errs() << "error: -selection=" << Range.FileName |
| 124 | << ":... : given file is not in the target TU\n"; |
| 125 | return true; |
| 126 | } |
| 127 | |
| 128 | SourceLocation Start = SM.getMacroArgExpandedLocation( |
| 129 | SM.translateLineCol(FID, Range.Begin.first, Range.Begin.second)); |
| 130 | SourceLocation End = SM.getMacroArgExpandedLocation( |
| 131 | SM.translateLineCol(FID, Range.End.first, Range.End.second)); |
| 132 | if (Start.isInvalid() || End.isInvalid()) { |
| 133 | llvm::errs() << "error: -selection=" << Range.FileName << ':' |
| 134 | << Range.Begin.first << ':' << Range.Begin.second << '-' |
| 135 | << Range.End.first << ':' << Range.End.second |
| 136 | << " : invalid source location\n"; |
| 137 | return true; |
| 138 | } |
| 139 | Callback(SourceRange(Start, End)); |
| 140 | return false; |
| 141 | } |
| 142 | |
| 143 | private: |
| 144 | ParsedSourceRange Range; |
| 145 | }; |
| 146 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 147 | std::unique_ptr<SourceSelectionArgument> |
| 148 | SourceSelectionArgument::fromString(StringRef Value) { |
| 149 | if (Value.startswith("test:")) { |
| 150 | StringRef Filename = Value.drop_front(strlen("test:")); |
| 151 | Optional<TestSelectionRangesInFile> ParsedTestSelection = |
| 152 | findTestSelectionRanges(Filename); |
| 153 | if (!ParsedTestSelection) |
| 154 | return nullptr; // A parsing error was already reported. |
| 155 | return llvm::make_unique<TestSourceSelectionArgument>( |
| 156 | std::move(*ParsedTestSelection)); |
| 157 | } |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 158 | Optional<ParsedSourceRange> Range = ParsedSourceRange::fromString(Value); |
| 159 | if (Range) |
| 160 | return llvm::make_unique<SourceRangeSelectionArgument>(std::move(*Range)); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 161 | llvm::errs() << "error: '-selection' option must be specified using " |
| 162 | "<file>:<line>:<column> or " |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 163 | "<file>:<line>:<column>-<line>:<column> format\n"; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 164 | return nullptr; |
| 165 | } |
| 166 | |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 167 | /// A container that stores the command-line options used by a single |
| 168 | /// refactoring option. |
| 169 | class RefactoringActionCommandLineOptions { |
| 170 | public: |
| 171 | void addStringOption(const RefactoringOption &Option, |
| 172 | std::unique_ptr<cl::opt<std::string>> CLOption) { |
| 173 | StringOptions[&Option] = std::move(CLOption); |
| 174 | } |
| 175 | |
| 176 | const cl::opt<std::string> & |
| 177 | getStringOption(const RefactoringOption &Opt) const { |
| 178 | auto It = StringOptions.find(&Opt); |
| 179 | return *It->second; |
| 180 | } |
| 181 | |
| 182 | private: |
| 183 | llvm::DenseMap<const RefactoringOption *, |
| 184 | std::unique_ptr<cl::opt<std::string>>> |
| 185 | StringOptions; |
| 186 | }; |
| 187 | |
| 188 | /// Passes the command-line option values to the options used by a single |
| 189 | /// refactoring action rule. |
| 190 | class CommandLineRefactoringOptionVisitor final |
| 191 | : public RefactoringOptionVisitor { |
| 192 | public: |
| 193 | CommandLineRefactoringOptionVisitor( |
| 194 | const RefactoringActionCommandLineOptions &Options) |
| 195 | : Options(Options) {} |
| 196 | |
| 197 | void visit(const RefactoringOption &Opt, |
| 198 | Optional<std::string> &Value) override { |
| 199 | const cl::opt<std::string> &CLOpt = Options.getStringOption(Opt); |
| 200 | if (!CLOpt.getValue().empty()) { |
| 201 | Value = CLOpt.getValue(); |
| 202 | return; |
| 203 | } |
| 204 | Value = None; |
| 205 | if (Opt.isRequired()) |
| 206 | MissingRequiredOptions.push_back(&Opt); |
| 207 | } |
| 208 | |
| 209 | ArrayRef<const RefactoringOption *> getMissingRequiredOptions() const { |
| 210 | return MissingRequiredOptions; |
| 211 | } |
| 212 | |
| 213 | private: |
| 214 | llvm::SmallVector<const RefactoringOption *, 4> MissingRequiredOptions; |
| 215 | const RefactoringActionCommandLineOptions &Options; |
| 216 | }; |
| 217 | |
| 218 | /// Creates the refactoring options used by all the rules in a single |
| 219 | /// refactoring action. |
| 220 | class CommandLineRefactoringOptionCreator final |
| 221 | : public RefactoringOptionVisitor { |
| 222 | public: |
| 223 | CommandLineRefactoringOptionCreator( |
| 224 | cl::OptionCategory &Category, cl::SubCommand &Subcommand, |
| 225 | RefactoringActionCommandLineOptions &Options) |
| 226 | : Category(Category), Subcommand(Subcommand), Options(Options) {} |
| 227 | |
| 228 | void visit(const RefactoringOption &Opt, Optional<std::string> &) override { |
| 229 | if (Visited.insert(&Opt).second) |
| 230 | Options.addStringOption(Opt, create<std::string>(Opt)); |
| 231 | } |
| 232 | |
| 233 | private: |
| 234 | template <typename T> |
| 235 | std::unique_ptr<cl::opt<T>> create(const RefactoringOption &Opt) { |
| 236 | if (!OptionNames.insert(Opt.getName()).second) |
| 237 | llvm::report_fatal_error("Multiple identical refactoring options " |
| 238 | "specified for one refactoring action"); |
| 239 | // FIXME: cl::Required can be specified when this option is present |
| 240 | // in all rules in an action. |
| 241 | return llvm::make_unique<cl::opt<T>>( |
| 242 | Opt.getName(), cl::desc(Opt.getDescription()), cl::Optional, |
| 243 | cl::cat(Category), cl::sub(Subcommand)); |
| 244 | } |
| 245 | |
| 246 | llvm::SmallPtrSet<const RefactoringOption *, 8> Visited; |
| 247 | llvm::StringSet<> OptionNames; |
| 248 | cl::OptionCategory &Category; |
| 249 | cl::SubCommand &Subcommand; |
| 250 | RefactoringActionCommandLineOptions &Options; |
| 251 | }; |
| 252 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 253 | /// A subcommand that corresponds to individual refactoring action. |
| 254 | class RefactoringActionSubcommand : public cl::SubCommand { |
| 255 | public: |
| 256 | RefactoringActionSubcommand(std::unique_ptr<RefactoringAction> Action, |
| 257 | RefactoringActionRules ActionRules, |
| 258 | cl::OptionCategory &Category) |
| 259 | : SubCommand(Action->getCommand(), Action->getDescription()), |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 260 | Action(std::move(Action)), ActionRules(std::move(ActionRules)), |
| 261 | HasSelection(false) { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 262 | // Check if the selection option is supported. |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 263 | for (const auto &Rule : this->ActionRules) { |
| 264 | if ((HasSelection = Rule->hasSelectionRequirement())) |
| 265 | break; |
| 266 | } |
| 267 | if (HasSelection) { |
| 268 | Selection = llvm::make_unique<cl::opt<std::string>>( |
| 269 | "selection", |
| 270 | cl::desc("The selected source range in which the refactoring should " |
| 271 | "be initiated (<file>:<line>:<column>-<line>:<column> or " |
| 272 | "<file>:<line>:<column>)"), |
| 273 | cl::cat(Category), cl::sub(*this)); |
| 274 | } |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 275 | // Create the refactoring options. |
| 276 | for (const auto &Rule : this->ActionRules) { |
| 277 | CommandLineRefactoringOptionCreator OptionCreator(Category, *this, |
| 278 | Options); |
| 279 | Rule->visitRefactoringOptions(OptionCreator); |
| 280 | } |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 281 | } |
| 282 | |
| 283 | ~RefactoringActionSubcommand() { unregisterSubCommand(); } |
| 284 | |
| 285 | const RefactoringActionRules &getActionRules() const { return ActionRules; } |
| 286 | |
| 287 | /// Parses the command-line arguments that are specific to this rule. |
| 288 | /// |
| 289 | /// \returns true on error, false otherwise. |
| 290 | bool parseArguments() { |
| 291 | if (Selection) { |
| 292 | ParsedSelection = SourceSelectionArgument::fromString(*Selection); |
| 293 | if (!ParsedSelection) |
| 294 | return true; |
| 295 | } |
| 296 | return false; |
| 297 | } |
| 298 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 299 | // Whether the selection is supported by any rule in the subcommand. |
| 300 | bool hasSelection() const { return HasSelection; } |
| 301 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 302 | SourceSelectionArgument *getSelection() const { |
| 303 | assert(Selection && "selection not supported!"); |
| 304 | return ParsedSelection.get(); |
| 305 | } |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 306 | |
| 307 | const RefactoringActionCommandLineOptions &getOptions() const { |
| 308 | return Options; |
| 309 | } |
| 310 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 311 | private: |
| 312 | std::unique_ptr<RefactoringAction> Action; |
| 313 | RefactoringActionRules ActionRules; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 314 | std::unique_ptr<cl::opt<std::string>> Selection; |
| 315 | std::unique_ptr<SourceSelectionArgument> ParsedSelection; |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 316 | RefactoringActionCommandLineOptions Options; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 317 | // Whether the selection is supported by any rule in the subcommand. |
| 318 | bool HasSelection; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 319 | }; |
| 320 | |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 321 | class ClangRefactorConsumer final : public ClangRefactorToolConsumerInterface { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 322 | public: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 323 | ClangRefactorConsumer(AtomicChanges &Changes) : SourceChanges(&Changes) {} |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 324 | |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 325 | void handleError(llvm::Error Err) override { |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 326 | Optional<PartialDiagnosticAt> Diag = DiagnosticError::take(Err); |
| 327 | if (!Diag) { |
| 328 | llvm::errs() << llvm::toString(std::move(Err)) << "\n"; |
| 329 | return; |
| 330 | } |
| 331 | llvm::cantFail(std::move(Err)); // This is a success. |
| 332 | DiagnosticBuilder DB( |
| 333 | getDiags().Report(Diag->first, Diag->second.getDiagID())); |
| 334 | Diag->second.Emit(DB); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 335 | } |
| 336 | |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 337 | void handle(AtomicChanges Changes) override { |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 338 | SourceChanges->insert(SourceChanges->begin(), Changes.begin(), |
| 339 | Changes.end()); |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 340 | } |
| 341 | |
| 342 | void handle(SymbolOccurrences Occurrences) override { |
Alex Lorenz | 5284350 | 2017-10-16 18:07:16 +0000 | [diff] [blame] | 343 | llvm_unreachable("symbol occurrence results are not handled yet"); |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 344 | } |
| 345 | |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 346 | private: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 347 | AtomicChanges *SourceChanges; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 348 | }; |
| 349 | |
| 350 | class ClangRefactorTool { |
| 351 | public: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 352 | ClangRefactorTool() |
| 353 | : SelectedSubcommand(nullptr), MatchingRule(nullptr), |
| 354 | Consumer(new ClangRefactorConsumer(Changes)), HasFailed(false) { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 355 | std::vector<std::unique_ptr<RefactoringAction>> Actions = |
| 356 | createRefactoringActions(); |
| 357 | |
| 358 | // Actions must have unique command names so that we can map them to one |
| 359 | // subcommand. |
| 360 | llvm::StringSet<> CommandNames; |
| 361 | for (const auto &Action : Actions) { |
| 362 | if (!CommandNames.insert(Action->getCommand()).second) { |
| 363 | llvm::errs() << "duplicate refactoring action command '" |
| 364 | << Action->getCommand() << "'!"; |
| 365 | exit(1); |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | // Create subcommands and command-line options. |
| 370 | for (auto &Action : Actions) { |
| 371 | SubCommands.push_back(llvm::make_unique<RefactoringActionSubcommand>( |
| 372 | std::move(Action), Action->createActiveActionRules(), |
| 373 | opts::CommonRefactorOptions)); |
| 374 | } |
| 375 | } |
| 376 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 377 | // Initializes the selected subcommand and refactoring rule based on the |
| 378 | // command line options. |
| 379 | llvm::Error Init() { |
| 380 | auto Subcommand = getSelectedSubcommand(); |
| 381 | if (!Subcommand) |
| 382 | return Subcommand.takeError(); |
| 383 | auto Rule = getMatchingRule(**Subcommand); |
| 384 | if (!Rule) |
| 385 | return Rule.takeError(); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 386 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 387 | SelectedSubcommand = *Subcommand; |
| 388 | MatchingRule = *Rule; |
| 389 | |
| 390 | return llvm::Error::success(); |
| 391 | } |
| 392 | |
| 393 | bool hasFailed() const { return HasFailed; } |
| 394 | |
| 395 | using TUCallbackType = std::function<void(ASTContext &)>; |
| 396 | |
| 397 | // Callback of an AST action. This invokes the matching rule on the given AST. |
| 398 | void callback(ASTContext &AST) { |
| 399 | assert(SelectedSubcommand && MatchingRule && Consumer); |
| 400 | RefactoringRuleContext Context(AST.getSourceManager()); |
| 401 | Context.setASTContext(AST); |
| 402 | |
| 403 | // If the selection option is test specific, we use a test-specific |
| 404 | // consumer. |
| 405 | std::unique_ptr<ClangRefactorToolConsumerInterface> TestConsumer; |
| 406 | if (SelectedSubcommand->hasSelection()) |
| 407 | TestConsumer = SelectedSubcommand->getSelection()->createCustomConsumer(); |
| 408 | ClangRefactorToolConsumerInterface *ActiveConsumer = |
| 409 | TestConsumer ? TestConsumer.get() : Consumer.get(); |
| 410 | ActiveConsumer->beginTU(AST); |
| 411 | // FIXME (Alex L): Implement non-selection based invocation path. |
| 412 | if (SelectedSubcommand->hasSelection()) { |
| 413 | assert(SelectedSubcommand->getSelection() && |
| 414 | "Missing selection argument?"); |
| 415 | if (opts::Verbose) |
| 416 | SelectedSubcommand->getSelection()->print(llvm::outs()); |
| 417 | if (SelectedSubcommand->getSelection()->forAllRanges( |
| 418 | Context.getSources(), [&](SourceRange R) { |
| 419 | Context.setSelectionRange(R); |
| 420 | if (opts::Verbose) |
| 421 | logInvocation(*SelectedSubcommand, Context); |
| 422 | MatchingRule->invoke(*ActiveConsumer, Context); |
| 423 | })) |
| 424 | HasFailed = true; |
| 425 | ActiveConsumer->endTU(); |
| 426 | return; |
| 427 | } |
| 428 | ActiveConsumer->endTU(); |
| 429 | } |
| 430 | |
| 431 | llvm::Expected<std::unique_ptr<FrontendActionFactory>> |
| 432 | getFrontendActionFactory() { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 433 | class ToolASTConsumer : public ASTConsumer { |
| 434 | public: |
| 435 | TUCallbackType Callback; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 436 | ToolASTConsumer(TUCallbackType Callback) |
| 437 | : Callback(std::move(Callback)) {} |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 438 | |
| 439 | void HandleTranslationUnit(ASTContext &Context) override { |
| 440 | Callback(Context); |
| 441 | } |
| 442 | }; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 443 | class ToolASTAction : public ASTFrontendAction { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 444 | public: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 445 | explicit ToolASTAction(TUCallbackType Callback) |
| 446 | : Callback(std::move(Callback)) {} |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 447 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 448 | protected: |
| 449 | std::unique_ptr<clang::ASTConsumer> |
| 450 | CreateASTConsumer(clang::CompilerInstance &compiler, |
| 451 | StringRef /* dummy */) override { |
| 452 | std::unique_ptr<clang::ASTConsumer> Consumer{ |
| 453 | new ToolASTConsumer(Callback)}; |
| 454 | return Consumer; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 455 | } |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 456 | |
| 457 | private: |
| 458 | TUCallbackType Callback; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 459 | }; |
| 460 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 461 | class ToolActionFactory : public FrontendActionFactory { |
| 462 | public: |
| 463 | ToolActionFactory(TUCallbackType Callback) |
| 464 | : Callback(std::move(Callback)) {} |
| 465 | |
| 466 | FrontendAction *create() override { return new ToolASTAction(Callback); } |
| 467 | |
| 468 | private: |
| 469 | TUCallbackType Callback; |
| 470 | }; |
| 471 | |
| 472 | return llvm::make_unique<ToolActionFactory>( |
| 473 | [this](ASTContext &AST) { return callback(AST); }); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 474 | } |
| 475 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 476 | // FIXME(ioeric): this seems to only works for changes in a single file at |
| 477 | // this point. |
| 478 | bool applySourceChanges() { |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 479 | std::set<std::string> Files; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 480 | for (const auto &Change : Changes) |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 481 | Files.insert(Change.getFilePath()); |
| 482 | // FIXME: Add automatic formatting support as well. |
| 483 | tooling::ApplyChangesSpec Spec; |
| 484 | // FIXME: We should probably cleanup the result by default as well. |
| 485 | Spec.Cleanup = false; |
| 486 | for (const auto &File : Files) { |
| 487 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferErr = |
| 488 | llvm::MemoryBuffer::getFile(File); |
| 489 | if (!BufferErr) { |
| 490 | llvm::errs() << "error: failed to open " << File << " for rewriting\n"; |
| 491 | return true; |
| 492 | } |
| 493 | auto Result = tooling::applyAtomicChanges(File, (*BufferErr)->getBuffer(), |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 494 | Changes, Spec); |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 495 | if (!Result) { |
| 496 | llvm::errs() << toString(Result.takeError()); |
| 497 | return true; |
| 498 | } |
| 499 | |
Haojian Wu | 5518678 | 2017-10-20 12:37:16 +0000 | [diff] [blame] | 500 | if (opts::Inplace) { |
| 501 | std::error_code EC; |
| 502 | llvm::raw_fd_ostream OS(File, EC, llvm::sys::fs::F_Text); |
| 503 | if (EC) { |
| 504 | llvm::errs() << EC.message() << "\n"; |
| 505 | return true; |
| 506 | } |
| 507 | OS << *Result; |
| 508 | continue; |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 509 | } |
Haojian Wu | 5518678 | 2017-10-20 12:37:16 +0000 | [diff] [blame] | 510 | |
| 511 | llvm::outs() << *Result; |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 512 | } |
| 513 | return false; |
| 514 | } |
| 515 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 516 | private: |
| 517 | /// Logs an individual refactoring action invocation to STDOUT. |
| 518 | void logInvocation(RefactoringActionSubcommand &Subcommand, |
| 519 | const RefactoringRuleContext &Context) { |
| 520 | llvm::outs() << "invoking action '" << Subcommand.getName() << "':\n"; |
| 521 | if (Context.getSelectionRange().isValid()) { |
| 522 | SourceRange R = Context.getSelectionRange(); |
| 523 | llvm::outs() << " -selection="; |
| 524 | R.getBegin().print(llvm::outs(), Context.getSources()); |
| 525 | llvm::outs() << " -> "; |
| 526 | R.getEnd().print(llvm::outs(), Context.getSources()); |
| 527 | llvm::outs() << "\n"; |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | llvm::Expected<RefactoringActionRule *> |
| 532 | getMatchingRule(const RefactoringActionSubcommand &Subcommand) { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 533 | SmallVector<RefactoringActionRule *, 4> MatchingRules; |
| 534 | llvm::StringSet<> MissingOptions; |
| 535 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 536 | for (const auto &Rule : Subcommand.getActionRules()) { |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 537 | bool SelectionMatches = true; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 538 | if (Rule->hasSelectionRequirement()) { |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 539 | if (!Subcommand.getSelection()) { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 540 | MissingOptions.insert("selection"); |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 541 | SelectionMatches = false; |
| 542 | } |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 543 | } |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 544 | CommandLineRefactoringOptionVisitor Visitor(Subcommand.getOptions()); |
| 545 | Rule->visitRefactoringOptions(Visitor); |
| 546 | if (SelectionMatches && Visitor.getMissingRequiredOptions().empty()) { |
| 547 | MatchingRules.push_back(Rule.get()); |
| 548 | continue; |
| 549 | } |
| 550 | for (const RefactoringOption *Opt : Visitor.getMissingRequiredOptions()) |
| 551 | MissingOptions.insert(Opt->getName()); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 552 | } |
| 553 | if (MatchingRules.empty()) { |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 554 | std::string Error; |
| 555 | llvm::raw_string_ostream OS(Error); |
| 556 | OS << "ERROR: '" << Subcommand.getName() |
| 557 | << "' can't be invoked with the given arguments:\n"; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 558 | for (const auto &Opt : MissingOptions) |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 559 | OS << " missing '-" << Opt.getKey() << "' option\n"; |
| 560 | OS.flush(); |
| 561 | return llvm::make_error<llvm::StringError>( |
| 562 | Error, llvm::inconvertibleErrorCode()); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 563 | } |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 564 | if (MatchingRules.size() != 1) { |
| 565 | return llvm::make_error<llvm::StringError>( |
| 566 | llvm::Twine("ERROR: more than one matching rule of action") + |
| 567 | Subcommand.getName() + "was found with given options.", |
| 568 | llvm::inconvertibleErrorCode()); |
| 569 | } |
| 570 | return MatchingRules.front(); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 571 | } |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 572 | // Figure out which action is specified by the user. The user must specify the |
| 573 | // action using a command-line subcommand, e.g. the invocation `clang-refactor |
| 574 | // local-rename` corresponds to the `LocalRename` refactoring action. All |
| 575 | // subcommands must have a unique names. This allows us to figure out which |
| 576 | // refactoring action should be invoked by looking at the first subcommand |
| 577 | // that's enabled by LLVM's command-line parser. |
| 578 | llvm::Expected<RefactoringActionSubcommand *> getSelectedSubcommand() { |
| 579 | auto It = llvm::find_if( |
| 580 | SubCommands, |
| 581 | [](const std::unique_ptr<RefactoringActionSubcommand> &SubCommand) { |
| 582 | return !!(*SubCommand); |
| 583 | }); |
| 584 | if (It == SubCommands.end()) { |
| 585 | std::string Error; |
| 586 | llvm::raw_string_ostream OS(Error); |
| 587 | OS << "error: no refactoring action given\n"; |
| 588 | OS << "note: the following actions are supported:\n"; |
| 589 | for (const auto &Subcommand : SubCommands) |
| 590 | OS.indent(2) << Subcommand->getName() << "\n"; |
| 591 | OS.flush(); |
| 592 | return llvm::make_error<llvm::StringError>( |
| 593 | Error, llvm::inconvertibleErrorCode()); |
| 594 | } |
| 595 | RefactoringActionSubcommand *Subcommand = &(**It); |
| 596 | if (Subcommand->parseArguments()) |
| 597 | return llvm::make_error<llvm::StringError>( |
| 598 | llvm::Twine("Failed to parse arguments for subcommand ") + |
| 599 | Subcommand->getName(), |
| 600 | llvm::inconvertibleErrorCode()); |
| 601 | return Subcommand; |
| 602 | } |
| 603 | |
| 604 | std::vector<std::unique_ptr<RefactoringActionSubcommand>> SubCommands; |
| 605 | RefactoringActionSubcommand *SelectedSubcommand; |
| 606 | RefactoringActionRule *MatchingRule; |
| 607 | std::unique_ptr<ClangRefactorToolConsumerInterface> Consumer; |
| 608 | AtomicChanges Changes; |
| 609 | bool HasFailed; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 610 | }; |
| 611 | |
| 612 | } // end anonymous namespace |
| 613 | |
| 614 | int main(int argc, const char **argv) { |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 615 | llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); |
| 616 | |
| 617 | ClangRefactorTool RefactorTool; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 618 | |
Alex Lorenz | 3d712c4 | 2017-09-14 13:16:14 +0000 | [diff] [blame] | 619 | CommonOptionsParser Options( |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 620 | argc, argv, cl::GeneralCategory, cl::ZeroOrMore, |
Alex Lorenz | 3d712c4 | 2017-09-14 13:16:14 +0000 | [diff] [blame] | 621 | "Clang-based refactoring tool for C, C++ and Objective-C"); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 622 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 623 | if (auto Err = RefactorTool.Init()) { |
| 624 | llvm::errs() << llvm::toString(std::move(Err)) << "\n"; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 625 | return 1; |
| 626 | } |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 627 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 628 | auto ActionFactory = RefactorTool.getFrontendActionFactory(); |
| 629 | if (!ActionFactory) { |
| 630 | llvm::errs() << llvm::toString(ActionFactory.takeError()) << "\n"; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 631 | return 1; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame^] | 632 | } |
| 633 | ClangTool Tool(Options.getCompilations(), Options.getSourcePathList()); |
| 634 | bool Failed = false; |
| 635 | if (Tool.run(ActionFactory->get()) != 0) { |
| 636 | llvm::errs() << "Failed to run refactoring action on files\n"; |
| 637 | // It is possible that TUs are broken while changes are generated correctly, |
| 638 | // so we still try applying changes. |
| 639 | Failed = true; |
| 640 | } |
| 641 | return RefactorTool.applySourceChanges() || Failed || |
| 642 | RefactorTool.hasFailed(); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 643 | } |