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()), |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 260 | Action(std::move(Action)), ActionRules(std::move(ActionRules)) { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 261 | // Check if the selection option is supported. |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 262 | for (const auto &Rule : this->ActionRules) { |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 263 | if (Rule->hasSelectionRequirement()) { |
| 264 | Selection = llvm::make_unique<cl::opt<std::string>>( |
| 265 | "selection", |
| 266 | cl::desc( |
| 267 | "The selected source range in which the refactoring should " |
| 268 | "be initiated (<file>:<line>:<column>-<line>:<column> or " |
| 269 | "<file>:<line>:<column>)"), |
| 270 | cl::cat(Category), cl::sub(*this)); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 271 | break; |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 272 | } |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 273 | } |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 274 | // Create the refactoring options. |
| 275 | for (const auto &Rule : this->ActionRules) { |
| 276 | CommandLineRefactoringOptionCreator OptionCreator(Category, *this, |
| 277 | Options); |
| 278 | Rule->visitRefactoringOptions(OptionCreator); |
| 279 | } |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 280 | } |
| 281 | |
| 282 | ~RefactoringActionSubcommand() { unregisterSubCommand(); } |
| 283 | |
| 284 | const RefactoringActionRules &getActionRules() const { return ActionRules; } |
| 285 | |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 286 | /// Parses the "-selection" command-line argument. |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 287 | /// |
| 288 | /// \returns true on error, false otherwise. |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 289 | bool parseSelectionArgument() { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 290 | if (Selection) { |
| 291 | ParsedSelection = SourceSelectionArgument::fromString(*Selection); |
| 292 | if (!ParsedSelection) |
| 293 | return true; |
| 294 | } |
| 295 | return false; |
| 296 | } |
| 297 | |
| 298 | SourceSelectionArgument *getSelection() const { |
| 299 | assert(Selection && "selection not supported!"); |
| 300 | return ParsedSelection.get(); |
| 301 | } |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 302 | |
| 303 | const RefactoringActionCommandLineOptions &getOptions() const { |
| 304 | return Options; |
| 305 | } |
| 306 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 307 | private: |
| 308 | std::unique_ptr<RefactoringAction> Action; |
| 309 | RefactoringActionRules ActionRules; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 310 | std::unique_ptr<cl::opt<std::string>> Selection; |
| 311 | std::unique_ptr<SourceSelectionArgument> ParsedSelection; |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 312 | RefactoringActionCommandLineOptions Options; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 313 | }; |
| 314 | |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 315 | class ClangRefactorConsumer final : public ClangRefactorToolConsumerInterface { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 316 | public: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 317 | ClangRefactorConsumer(AtomicChanges &Changes) : SourceChanges(&Changes) {} |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 318 | |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 319 | void handleError(llvm::Error Err) override { |
Alex Lorenz | f5ca27c | 2017-10-16 18:28:26 +0000 | [diff] [blame] | 320 | Optional<PartialDiagnosticAt> Diag = DiagnosticError::take(Err); |
| 321 | if (!Diag) { |
| 322 | llvm::errs() << llvm::toString(std::move(Err)) << "\n"; |
| 323 | return; |
| 324 | } |
| 325 | llvm::cantFail(std::move(Err)); // This is a success. |
| 326 | DiagnosticBuilder DB( |
| 327 | getDiags().Report(Diag->first, Diag->second.getDiagID())); |
| 328 | Diag->second.Emit(DB); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 329 | } |
| 330 | |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 331 | void handle(AtomicChanges Changes) override { |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 332 | SourceChanges->insert(SourceChanges->begin(), Changes.begin(), |
| 333 | Changes.end()); |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 334 | } |
| 335 | |
| 336 | void handle(SymbolOccurrences Occurrences) override { |
Alex Lorenz | 5284350 | 2017-10-16 18:07:16 +0000 | [diff] [blame] | 337 | llvm_unreachable("symbol occurrence results are not handled yet"); |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 338 | } |
| 339 | |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 340 | private: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 341 | AtomicChanges *SourceChanges; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 342 | }; |
| 343 | |
| 344 | class ClangRefactorTool { |
| 345 | public: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 346 | ClangRefactorTool() |
| 347 | : SelectedSubcommand(nullptr), MatchingRule(nullptr), |
| 348 | Consumer(new ClangRefactorConsumer(Changes)), HasFailed(false) { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 349 | std::vector<std::unique_ptr<RefactoringAction>> Actions = |
| 350 | createRefactoringActions(); |
| 351 | |
| 352 | // Actions must have unique command names so that we can map them to one |
| 353 | // subcommand. |
| 354 | llvm::StringSet<> CommandNames; |
| 355 | for (const auto &Action : Actions) { |
| 356 | if (!CommandNames.insert(Action->getCommand()).second) { |
| 357 | llvm::errs() << "duplicate refactoring action command '" |
| 358 | << Action->getCommand() << "'!"; |
| 359 | exit(1); |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | // Create subcommands and command-line options. |
| 364 | for (auto &Action : Actions) { |
| 365 | SubCommands.push_back(llvm::make_unique<RefactoringActionSubcommand>( |
| 366 | std::move(Action), Action->createActiveActionRules(), |
| 367 | opts::CommonRefactorOptions)); |
| 368 | } |
| 369 | } |
| 370 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 371 | // Initializes the selected subcommand and refactoring rule based on the |
| 372 | // command line options. |
| 373 | llvm::Error Init() { |
| 374 | auto Subcommand = getSelectedSubcommand(); |
| 375 | if (!Subcommand) |
| 376 | return Subcommand.takeError(); |
| 377 | auto Rule = getMatchingRule(**Subcommand); |
| 378 | if (!Rule) |
| 379 | return Rule.takeError(); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 380 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 381 | SelectedSubcommand = *Subcommand; |
| 382 | MatchingRule = *Rule; |
| 383 | |
| 384 | return llvm::Error::success(); |
| 385 | } |
| 386 | |
| 387 | bool hasFailed() const { return HasFailed; } |
| 388 | |
| 389 | using TUCallbackType = std::function<void(ASTContext &)>; |
| 390 | |
| 391 | // Callback of an AST action. This invokes the matching rule on the given AST. |
| 392 | void callback(ASTContext &AST) { |
| 393 | assert(SelectedSubcommand && MatchingRule && Consumer); |
| 394 | RefactoringRuleContext Context(AST.getSourceManager()); |
| 395 | Context.setASTContext(AST); |
| 396 | |
| 397 | // If the selection option is test specific, we use a test-specific |
| 398 | // consumer. |
| 399 | std::unique_ptr<ClangRefactorToolConsumerInterface> TestConsumer; |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 400 | bool HasSelection = MatchingRule->hasSelectionRequirement(); |
| 401 | if (HasSelection) |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 402 | TestConsumer = SelectedSubcommand->getSelection()->createCustomConsumer(); |
| 403 | ClangRefactorToolConsumerInterface *ActiveConsumer = |
| 404 | TestConsumer ? TestConsumer.get() : Consumer.get(); |
| 405 | ActiveConsumer->beginTU(AST); |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 406 | |
| 407 | auto InvokeRule = [&](RefactoringResultConsumer &Consumer) { |
| 408 | if (opts::Verbose) |
| 409 | logInvocation(*SelectedSubcommand, Context); |
| 410 | MatchingRule->invoke(*ActiveConsumer, Context); |
| 411 | }; |
| 412 | if (HasSelection) { |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 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); |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 420 | InvokeRule(*ActiveConsumer); |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 421 | })) |
| 422 | HasFailed = true; |
| 423 | ActiveConsumer->endTU(); |
| 424 | return; |
| 425 | } |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 426 | InvokeRule(*ActiveConsumer); |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 427 | ActiveConsumer->endTU(); |
| 428 | } |
| 429 | |
| 430 | llvm::Expected<std::unique_ptr<FrontendActionFactory>> |
| 431 | getFrontendActionFactory() { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 432 | class ToolASTConsumer : public ASTConsumer { |
| 433 | public: |
| 434 | TUCallbackType Callback; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 435 | ToolASTConsumer(TUCallbackType Callback) |
| 436 | : Callback(std::move(Callback)) {} |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 437 | |
| 438 | void HandleTranslationUnit(ASTContext &Context) override { |
| 439 | Callback(Context); |
| 440 | } |
| 441 | }; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 442 | class ToolASTAction : public ASTFrontendAction { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 443 | public: |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 444 | explicit ToolASTAction(TUCallbackType Callback) |
| 445 | : Callback(std::move(Callback)) {} |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 446 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 447 | protected: |
| 448 | std::unique_ptr<clang::ASTConsumer> |
| 449 | CreateASTConsumer(clang::CompilerInstance &compiler, |
| 450 | StringRef /* dummy */) override { |
| 451 | std::unique_ptr<clang::ASTConsumer> Consumer{ |
| 452 | new ToolASTConsumer(Callback)}; |
| 453 | return Consumer; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 454 | } |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 455 | |
| 456 | private: |
| 457 | TUCallbackType Callback; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 458 | }; |
| 459 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 460 | class ToolActionFactory : public FrontendActionFactory { |
| 461 | public: |
| 462 | ToolActionFactory(TUCallbackType Callback) |
| 463 | : Callback(std::move(Callback)) {} |
| 464 | |
| 465 | FrontendAction *create() override { return new ToolASTAction(Callback); } |
| 466 | |
| 467 | private: |
| 468 | TUCallbackType Callback; |
| 469 | }; |
| 470 | |
| 471 | return llvm::make_unique<ToolActionFactory>( |
| 472 | [this](ASTContext &AST) { return callback(AST); }); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 473 | } |
| 474 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 475 | // FIXME(ioeric): this seems to only works for changes in a single file at |
| 476 | // this point. |
| 477 | bool applySourceChanges() { |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 478 | std::set<std::string> Files; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 479 | for (const auto &Change : Changes) |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 480 | Files.insert(Change.getFilePath()); |
| 481 | // FIXME: Add automatic formatting support as well. |
| 482 | tooling::ApplyChangesSpec Spec; |
| 483 | // FIXME: We should probably cleanup the result by default as well. |
| 484 | Spec.Cleanup = false; |
| 485 | for (const auto &File : Files) { |
| 486 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferErr = |
| 487 | llvm::MemoryBuffer::getFile(File); |
| 488 | if (!BufferErr) { |
| 489 | llvm::errs() << "error: failed to open " << File << " for rewriting\n"; |
| 490 | return true; |
| 491 | } |
| 492 | auto Result = tooling::applyAtomicChanges(File, (*BufferErr)->getBuffer(), |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 493 | Changes, Spec); |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 494 | if (!Result) { |
| 495 | llvm::errs() << toString(Result.takeError()); |
| 496 | return true; |
| 497 | } |
| 498 | |
Haojian Wu | 5518678 | 2017-10-20 12:37:16 +0000 | [diff] [blame] | 499 | if (opts::Inplace) { |
| 500 | std::error_code EC; |
| 501 | llvm::raw_fd_ostream OS(File, EC, llvm::sys::fs::F_Text); |
| 502 | if (EC) { |
| 503 | llvm::errs() << EC.message() << "\n"; |
| 504 | return true; |
| 505 | } |
| 506 | OS << *Result; |
| 507 | continue; |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 508 | } |
Haojian Wu | 5518678 | 2017-10-20 12:37:16 +0000 | [diff] [blame] | 509 | |
| 510 | llvm::outs() << *Result; |
Alex Lorenz | e1b7b95 | 2017-10-16 17:31:16 +0000 | [diff] [blame] | 511 | } |
| 512 | return false; |
| 513 | } |
| 514 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 515 | private: |
| 516 | /// Logs an individual refactoring action invocation to STDOUT. |
| 517 | void logInvocation(RefactoringActionSubcommand &Subcommand, |
| 518 | const RefactoringRuleContext &Context) { |
| 519 | llvm::outs() << "invoking action '" << Subcommand.getName() << "':\n"; |
| 520 | if (Context.getSelectionRange().isValid()) { |
| 521 | SourceRange R = Context.getSelectionRange(); |
| 522 | llvm::outs() << " -selection="; |
| 523 | R.getBegin().print(llvm::outs(), Context.getSources()); |
| 524 | llvm::outs() << " -> "; |
| 525 | R.getEnd().print(llvm::outs(), Context.getSources()); |
| 526 | llvm::outs() << "\n"; |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | llvm::Expected<RefactoringActionRule *> |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 531 | getMatchingRule(RefactoringActionSubcommand &Subcommand) { |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 532 | SmallVector<RefactoringActionRule *, 4> MatchingRules; |
| 533 | llvm::StringSet<> MissingOptions; |
| 534 | |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 535 | for (const auto &Rule : Subcommand.getActionRules()) { |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 536 | CommandLineRefactoringOptionVisitor Visitor(Subcommand.getOptions()); |
| 537 | Rule->visitRefactoringOptions(Visitor); |
Haojian Wu | 200458f | 2017-11-08 08:56:56 +0000 | [diff] [blame^] | 538 | if (Visitor.getMissingRequiredOptions().empty()) { |
| 539 | if (!Rule->hasSelectionRequirement()) { |
| 540 | MatchingRules.push_back(Rule.get()); |
| 541 | } else { |
| 542 | Subcommand.parseSelectionArgument(); |
| 543 | if (Subcommand.getSelection()) { |
| 544 | MatchingRules.push_back(Rule.get()); |
| 545 | } else { |
| 546 | MissingOptions.insert("selection"); |
| 547 | } |
| 548 | } |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 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); |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 596 | return Subcommand; |
| 597 | } |
| 598 | |
| 599 | std::vector<std::unique_ptr<RefactoringActionSubcommand>> SubCommands; |
| 600 | RefactoringActionSubcommand *SelectedSubcommand; |
| 601 | RefactoringActionRule *MatchingRule; |
| 602 | std::unique_ptr<ClangRefactorToolConsumerInterface> Consumer; |
| 603 | AtomicChanges Changes; |
| 604 | bool HasFailed; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 605 | }; |
| 606 | |
| 607 | } // end anonymous namespace |
| 608 | |
| 609 | int main(int argc, const char **argv) { |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 610 | llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); |
| 611 | |
| 612 | ClangRefactorTool RefactorTool; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 613 | |
Alex Lorenz | 3d712c4 | 2017-09-14 13:16:14 +0000 | [diff] [blame] | 614 | CommonOptionsParser Options( |
Alex Lorenz | ad38fbf | 2017-10-13 01:53:13 +0000 | [diff] [blame] | 615 | argc, argv, cl::GeneralCategory, cl::ZeroOrMore, |
Alex Lorenz | 3d712c4 | 2017-09-14 13:16:14 +0000 | [diff] [blame] | 616 | "Clang-based refactoring tool for C, C++ and Objective-C"); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 617 | |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 618 | if (auto Err = RefactorTool.Init()) { |
| 619 | llvm::errs() << llvm::toString(std::move(Err)) << "\n"; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 620 | return 1; |
| 621 | } |
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 | auto ActionFactory = RefactorTool.getFrontendActionFactory(); |
| 624 | if (!ActionFactory) { |
| 625 | llvm::errs() << llvm::toString(ActionFactory.takeError()) << "\n"; |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 626 | return 1; |
Eric Liu | c47fd01 | 2017-11-07 14:35:03 +0000 | [diff] [blame] | 627 | } |
| 628 | ClangTool Tool(Options.getCompilations(), Options.getSourcePathList()); |
| 629 | bool Failed = false; |
| 630 | if (Tool.run(ActionFactory->get()) != 0) { |
| 631 | llvm::errs() << "Failed to run refactoring action on files\n"; |
| 632 | // It is possible that TUs are broken while changes are generated correctly, |
| 633 | // so we still try applying changes. |
| 634 | Failed = true; |
| 635 | } |
| 636 | return RefactorTool.applySourceChanges() || Failed || |
| 637 | RefactorTool.hasFailed(); |
Alex Lorenz | b54ef6a | 2017-09-14 10:06:52 +0000 | [diff] [blame] | 638 | } |