Edwin Vane | b225be2 | 2013-09-03 17:58:19 +0000 | [diff] [blame] | 1 | //===-- ClangApplyReplacementsMain.cpp - Main file for the tool -----------===// |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 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 |
Edwin Vane | b225be2 | 2013-09-03 17:58:19 +0000 | [diff] [blame] | 11 | /// \brief This file provides the main function for the |
| 12 | /// clang-apply-replacements tool. |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 13 | /// |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Edwin Vane | b225be2 | 2013-09-03 17:58:19 +0000 | [diff] [blame] | 16 | #include "clang-apply-replacements/Tooling/ApplyReplacements.h" |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 17 | #include "clang/Basic/Diagnostic.h" |
| 18 | #include "clang/Basic/DiagnosticOptions.h" |
Edwin Vane | 1106ef2 | 2013-08-22 13:40:32 +0000 | [diff] [blame] | 19 | #include "clang/Basic/SourceManager.h" |
Edwin Vane | 6d5350c | 2013-09-24 18:14:54 +0000 | [diff] [blame] | 20 | #include "clang/Basic/Version.h" |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 21 | #include "clang/Format/Format.h" |
Edwin Vane | f18633c | 2013-08-28 17:19:10 +0000 | [diff] [blame] | 22 | #include "clang/Rewrite/Core/Rewriter.h" |
Edwin Vane | 6d5350c | 2013-09-24 18:14:54 +0000 | [diff] [blame] | 23 | #include "llvm/ADT/STLExtras.h" |
| 24 | #include "llvm/ADT/StringSet.h" |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 25 | #include "llvm/Support/CommandLine.h" |
| 26 | |
| 27 | using namespace llvm; |
| 28 | using namespace clang; |
| 29 | using namespace clang::replace; |
| 30 | |
| 31 | static cl::opt<std::string> Directory(cl::Positional, cl::Required, |
| 32 | cl::desc("<Search Root Directory>")); |
| 33 | |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 34 | static cl::OptionCategory FormattingCategory("Formatting Options"); |
| 35 | |
Tareq A. Siraj | 1175552 | 2013-08-26 19:58:59 +0000 | [diff] [blame] | 36 | static cl::opt<bool> RemoveTUReplacementFiles( |
| 37 | "remove-change-desc-files", |
| 38 | cl::desc("Remove the change description files regardless of successful\n" |
| 39 | "merging/replacing."), |
| 40 | cl::init(false)); |
| 41 | |
Edwin Vane | 6d5350c | 2013-09-24 18:14:54 +0000 | [diff] [blame] | 42 | // Update this list of options to show in -help as new options are added. |
| 43 | // Should add even those options marked as 'Hidden'. Any option not listed |
| 44 | // here will get marked 'ReallyHidden' so they don't appear in any -help text. |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 45 | const char *OptionsToShow[] = { "help", "version", |
| 46 | "remove-change-desc-files", "format", |
| 47 | "style-config", "style" }; |
| 48 | |
| 49 | static cl::opt<bool> DoFormat( |
| 50 | "format", |
| 51 | cl::desc("Enable formatting of code changed by applying replacements.\n" |
| 52 | "Use -style to choose formatting style.\n"), |
| 53 | cl::cat(FormattingCategory)); |
| 54 | |
| 55 | // FIXME: Consider making the default behaviour for finding a style |
| 56 | // configuration file to start the search anew for every file being changed to |
| 57 | // handle situations where the style is different for different parts of a |
| 58 | // project. |
| 59 | |
| 60 | static cl::opt<std::string> FormatStyleConfig( |
| 61 | "style-config", |
| 62 | cl::desc("Path to a directory containing a .clang-format file\n" |
| 63 | "describing a formatting style to use for formatting\n" |
| 64 | "code when -style=file.\n"), |
| 65 | cl::init(""), cl::cat(FormattingCategory)); |
| 66 | |
| 67 | static cl::opt<std::string> |
| 68 | FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription), |
| 69 | cl::init("LLVM"), cl::cat(FormattingCategory)); |
Edwin Vane | 6d5350c | 2013-09-24 18:14:54 +0000 | [diff] [blame] | 70 | |
Tareq A. Siraj | 1175552 | 2013-08-26 19:58:59 +0000 | [diff] [blame] | 71 | // Helper object to remove the TUReplacement files (triggered by |
| 72 | // "remove-change-desc-files" command line option) when exiting current scope. |
| 73 | class ScopedFileRemover { |
| 74 | public: |
| 75 | ScopedFileRemover(const TUReplacementFiles &Files, |
| 76 | clang::DiagnosticsEngine &Diagnostics) |
| 77 | : TURFiles(Files), Diag(Diagnostics) {} |
| 78 | |
| 79 | ~ScopedFileRemover() { |
| 80 | deleteReplacementFiles(TURFiles, Diag); |
| 81 | } |
| 82 | |
| 83 | private: |
| 84 | const TUReplacementFiles &TURFiles; |
| 85 | clang::DiagnosticsEngine &Diag; |
| 86 | }; |
| 87 | |
Edwin Vane | 6d5350c | 2013-09-24 18:14:54 +0000 | [diff] [blame] | 88 | void printVersion() { |
| 89 | outs() << "clang-apply-replacements version " CLANG_VERSION_STRING << "\n"; |
| 90 | } |
| 91 | |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 92 | /// \brief Convenience function to get rewritten content for \c Filename from |
| 93 | /// \c Rewrites. |
| 94 | /// |
| 95 | /// \pre Replacements[i].getFilePath() == Replacements[i+1].getFilePath(). |
| 96 | /// \post Replacements.empty() -> Result.empty() |
| 97 | /// |
| 98 | /// \param[in] Replacements Replacements to apply |
| 99 | /// \param[in] Rewrites Rewriter to use to apply replacements. |
| 100 | /// \param[out] Result Contents of the file after applying replacements if |
| 101 | /// replacements were provided. |
| 102 | /// |
| 103 | /// \returns \li true if all replacements were applied successfully. |
| 104 | /// \li false if at least one replacement failed to apply. |
| 105 | static bool |
| 106 | getRewrittenData(const std::vector<tooling::Replacement> &Replacements, |
| 107 | Rewriter &Rewrites, std::string &Result) { |
| 108 | if (Replacements.empty()) return true; |
| 109 | |
| 110 | if (!tooling::applyAllReplacements(Replacements, Rewrites)) |
| 111 | return false; |
| 112 | |
| 113 | SourceManager &SM = Rewrites.getSourceMgr(); |
| 114 | FileManager &Files = SM.getFileManager(); |
| 115 | |
| 116 | StringRef FileName = Replacements.begin()->getFilePath(); |
| 117 | const clang::FileEntry *Entry = Files.getFile(FileName); |
| 118 | assert(Entry && "Expected an existing file"); |
| 119 | FileID ID = SM.translateFile(Entry); |
| 120 | assert(!ID.isInvalid() && "Expected a valid FileID"); |
| 121 | const RewriteBuffer *Buffer = Rewrites.getRewriteBufferFor(ID); |
| 122 | Result = std::string(Buffer->begin(), Buffer->end()); |
| 123 | |
| 124 | return true; |
| 125 | } |
| 126 | |
| 127 | /// \brief Apply \c Replacements and return the new file contents. |
| 128 | /// |
| 129 | /// \pre Replacements[i].getFilePath() == Replacements[i+1].getFilePath(). |
| 130 | /// \post Replacements.empty() -> Result.empty() |
| 131 | /// |
| 132 | /// \param[in] Replacements Replacements to apply. |
| 133 | /// \param[out] Result Contents of the file after applying replacements if |
| 134 | /// replacements were provided. |
| 135 | /// \param[in] Diagnostics For diagnostic output. |
| 136 | /// |
| 137 | /// \returns \li true if all replacements applied successfully. |
| 138 | /// \li false if at least one replacement failed to apply. |
| 139 | bool applyReplacements(const std::vector<tooling::Replacement> &Replacements, |
| 140 | std::string &Result, |
| 141 | DiagnosticsEngine &Diagnostics) { |
| 142 | FileManager Files((FileSystemOptions())); |
| 143 | SourceManager SM(Diagnostics, Files); |
| 144 | Rewriter Rewrites(SM, LangOptions()); |
| 145 | |
| 146 | return getRewrittenData(Replacements, Rewrites, Result); |
| 147 | } |
| 148 | |
| 149 | /// \brief Apply code formatting to all places where replacements were made. |
| 150 | /// |
| 151 | /// \pre !Replacements.empty(). |
| 152 | /// \pre Replacements[i].getFilePath() == Replacements[i+1].getFilePath(). |
| 153 | /// \pre Replacements[i].getOffset() <= Replacements[i+1].getOffset(). |
| 154 | /// |
| 155 | /// \param[in] Replacements Replacements that were made to the file. Provided |
| 156 | /// to indicate where changes were made. |
| 157 | /// \param[in] FileData The contents of the file \b after \c Replacements have |
| 158 | /// been applied. |
| 159 | /// \param[out] FormattedFileData The contents of the file after reformatting. |
Edwin Vane | 2fb10d1 | 2013-10-01 13:21:39 +0000 | [diff] [blame] | 160 | /// \param[in] FormatStyle Style to apply. |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 161 | /// \param[in] Diagnostics For diagnostic output. |
| 162 | /// |
| 163 | /// \returns \li true if reformatting replacements were all successfully |
| 164 | /// applied. |
| 165 | /// \li false if at least one reformatting replacement failed to apply. |
| 166 | bool applyFormatting(const std::vector<tooling::Replacement> &Replacements, |
| 167 | const StringRef FileData, |
| 168 | std::string &FormattedFileData, |
| 169 | const format::FormatStyle &FormatStyle, |
| 170 | DiagnosticsEngine &Diagnostics) { |
| 171 | assert(!Replacements.empty() && "Need at least one replacement"); |
| 172 | |
| 173 | RangeVector Ranges = calculateChangedRanges(Replacements); |
| 174 | |
| 175 | StringRef FileName = Replacements.begin()->getFilePath(); |
| 176 | tooling::Replacements R = |
| 177 | format::reformat(FormatStyle, FileData, Ranges, FileName); |
| 178 | |
| 179 | // FIXME: Remove this copy when tooling::Replacements is implemented as a |
| 180 | // vector instead of a set. |
| 181 | std::vector<tooling::Replacement> FormattingReplacements; |
| 182 | std::copy(R.begin(), R.end(), back_inserter(FormattingReplacements)); |
| 183 | |
| 184 | if (FormattingReplacements.empty()) { |
| 185 | FormattedFileData = FileData; |
| 186 | return true; |
| 187 | } |
| 188 | |
| 189 | FileManager Files((FileSystemOptions())); |
| 190 | SourceManager SM(Diagnostics, Files); |
| 191 | SM.overrideFileContents(Files.getFile(FileName), |
| 192 | llvm::MemoryBuffer::getMemBufferCopy(FileData)); |
| 193 | Rewriter Rewrites(SM, LangOptions()); |
| 194 | |
| 195 | return getRewrittenData(FormattingReplacements, Rewrites, FormattedFileData); |
| 196 | } |
| 197 | |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 198 | int main(int argc, char **argv) { |
Edwin Vane | 6d5350c | 2013-09-24 18:14:54 +0000 | [diff] [blame] | 199 | // Only include our options in -help output. |
| 200 | StringMap<cl::Option*> OptMap; |
| 201 | cl::getRegisteredOptions(OptMap); |
| 202 | const char **EndOpts = OptionsToShow + array_lengthof(OptionsToShow); |
| 203 | for (StringMap<cl::Option *>::iterator I = OptMap.begin(), E = OptMap.end(); |
| 204 | I != E; ++I) { |
| 205 | if (std::find(OptionsToShow, EndOpts, I->getKey()) == EndOpts) |
| 206 | I->getValue()->setHiddenFlag(cl::ReallyHidden); |
| 207 | } |
| 208 | |
| 209 | cl::SetVersionPrinter(&printVersion); |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 210 | cl::ParseCommandLineOptions(argc, argv); |
| 211 | |
| 212 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions()); |
| 213 | DiagnosticsEngine Diagnostics( |
| 214 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), |
Alp Toker | 573583e | 2014-07-05 03:04:33 +0000 | [diff] [blame] | 215 | DiagOpts.get()); |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 216 | |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 217 | // Determine a formatting style from options. |
| 218 | format::FormatStyle FormatStyle; |
| 219 | if (DoFormat) |
Alexander Kornienko | 3daaf32 | 2013-12-02 15:22:30 +0000 | [diff] [blame] | 220 | FormatStyle = format::getStyle(FormatStyleOpt, FormatStyleConfig, "LLVM"); |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 221 | |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 222 | TUReplacements TUs; |
Tareq A. Siraj | 1175552 | 2013-08-26 19:58:59 +0000 | [diff] [blame] | 223 | TUReplacementFiles TURFiles; |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 224 | |
Rafael Espindola | c7f0d23 | 2014-06-12 22:08:48 +0000 | [diff] [blame] | 225 | std::error_code ErrorCode = |
Tareq A. Siraj | 1175552 | 2013-08-26 19:58:59 +0000 | [diff] [blame] | 226 | collectReplacementsFromDirectory(Directory, TUs, TURFiles, Diagnostics); |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 227 | |
| 228 | if (ErrorCode) { |
| 229 | errs() << "Trouble iterating over directory '" << Directory |
| 230 | << "': " << ErrorCode.message() << "\n"; |
Edwin Vane | c0f00b7 | 2013-10-05 12:15:58 +0000 | [diff] [blame] | 231 | return 1; |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 232 | } |
| 233 | |
Tareq A. Siraj | 1175552 | 2013-08-26 19:58:59 +0000 | [diff] [blame] | 234 | // Remove the TUReplacementFiles (triggered by "remove-change-desc-files" |
| 235 | // command line option) when exiting main(). |
Ahmed Charles | 6a2dc5c | 2014-03-09 09:24:40 +0000 | [diff] [blame] | 236 | std::unique_ptr<ScopedFileRemover> Remover; |
Tareq A. Siraj | 1175552 | 2013-08-26 19:58:59 +0000 | [diff] [blame] | 237 | if (RemoveTUReplacementFiles) |
| 238 | Remover.reset(new ScopedFileRemover(TURFiles, Diagnostics)); |
| 239 | |
Edwin Vane | 1106ef2 | 2013-08-22 13:40:32 +0000 | [diff] [blame] | 240 | FileManager Files((FileSystemOptions())); |
| 241 | SourceManager SM(Diagnostics, Files); |
| 242 | |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 243 | FileToReplacementsMap GroupedReplacements; |
Edwin Vane | 1106ef2 | 2013-08-22 13:40:32 +0000 | [diff] [blame] | 244 | if (!mergeAndDeduplicate(TUs, GroupedReplacements, SM)) |
| 245 | return 1; |
| 246 | |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 247 | Rewriter ReplacementsRewriter(SM, LangOptions()); |
Edwin Vane | f18633c | 2013-08-28 17:19:10 +0000 | [diff] [blame] | 248 | |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 249 | for (FileToReplacementsMap::const_iterator I = GroupedReplacements.begin(), |
| 250 | E = GroupedReplacements.end(); |
| 251 | I != E; ++I) { |
| 252 | |
| 253 | std::string NewFileData; |
| 254 | |
| 255 | // This shouldn't happen but if a file somehow has no replacements skip to |
| 256 | // next file. |
| 257 | if (I->getValue().empty()) |
| 258 | continue; |
| 259 | |
| 260 | if (!applyReplacements(I->getValue(), NewFileData, Diagnostics)) { |
| 261 | errs() << "Failed to apply replacements to " << I->getKey() << "\n"; |
| 262 | continue; |
| 263 | } |
| 264 | |
| 265 | // Apply formatting if requested. |
| 266 | if (DoFormat && !applyFormatting(I->getValue(), NewFileData, NewFileData, |
| 267 | FormatStyle, Diagnostics)) { |
| 268 | errs() << "Failed to apply reformatting replacements for " << I->getKey() |
| 269 | << "\n"; |
| 270 | continue; |
| 271 | } |
| 272 | |
| 273 | // Write new file to disk |
| 274 | std::string ErrorInfo; |
Rafael Espindola | dc59a36 | 2014-02-24 15:41:44 +0000 | [diff] [blame] | 275 | llvm::raw_fd_ostream FileStream(I->getKey().str().c_str(), ErrorInfo, |
Rafael Espindola | 26af262 | 2014-02-24 18:21:04 +0000 | [diff] [blame] | 276 | llvm::sys::fs::F_Text); |
Edwin Vane | 59d93af | 2013-09-30 13:59:21 +0000 | [diff] [blame] | 277 | if (!ErrorInfo.empty()) { |
| 278 | llvm::errs() << "Could not open " << I->getKey() << " for writing\n"; |
| 279 | continue; |
| 280 | } |
| 281 | |
| 282 | FileStream << NewFileData; |
| 283 | } |
Edwin Vane | f18633c | 2013-08-28 17:19:10 +0000 | [diff] [blame] | 284 | |
| 285 | return 0; |
Edwin Vane | 3bf14ce | 2013-08-22 13:07:14 +0000 | [diff] [blame] | 286 | } |