blob: ed1b2da77a39a9c821f4d0fa98f39b448a95981f [file] [log] [blame]
Edwin Vaneb225be22013-09-03 17:58:19 +00001//===-- ClangApplyReplacementsMain.cpp - Main file for the tool -----------===//
Edwin Vane3bf14ce2013-08-22 13:07:14 +00002//
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 Vaneb225be22013-09-03 17:58:19 +000011/// \brief This file provides the main function for the
12/// clang-apply-replacements tool.
Edwin Vane3bf14ce2013-08-22 13:07:14 +000013///
14//===----------------------------------------------------------------------===//
15
Edwin Vaneb225be22013-09-03 17:58:19 +000016#include "clang-apply-replacements/Tooling/ApplyReplacements.h"
Edwin Vane3bf14ce2013-08-22 13:07:14 +000017#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/DiagnosticOptions.h"
Edwin Vane1106ef22013-08-22 13:40:32 +000019#include "clang/Basic/SourceManager.h"
Edwin Vane6d5350c2013-09-24 18:14:54 +000020#include "clang/Basic/Version.h"
Edwin Vane59d93af2013-09-30 13:59:21 +000021#include "clang/Format/Format.h"
Edwin Vanef18633c2013-08-28 17:19:10 +000022#include "clang/Rewrite/Core/Rewriter.h"
Edwin Vane6d5350c2013-09-24 18:14:54 +000023#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/StringSet.h"
Edwin Vane3bf14ce2013-08-22 13:07:14 +000025#include "llvm/Support/CommandLine.h"
26
27using namespace llvm;
28using namespace clang;
29using namespace clang::replace;
30
31static cl::opt<std::string> Directory(cl::Positional, cl::Required,
32 cl::desc("<Search Root Directory>"));
33
Chris Bienemanfc4fd522015-01-28 22:45:26 +000034static cl::OptionCategory ReplacementCategory("Replacement Options");
Edwin Vane59d93af2013-09-30 13:59:21 +000035static cl::OptionCategory FormattingCategory("Formatting Options");
36
Chris Bienemanfc4fd522015-01-28 22:45:26 +000037const cl::OptionCategory *VisibleCategories[] = {&ReplacementCategory,
38 &FormattingCategory};
39
Tareq A. Siraj11755522013-08-26 19:58:59 +000040static cl::opt<bool> RemoveTUReplacementFiles(
41 "remove-change-desc-files",
42 cl::desc("Remove the change description files regardless of successful\n"
43 "merging/replacing."),
Chris Bienemanfc4fd522015-01-28 22:45:26 +000044 cl::init(false), cl::cat(ReplacementCategory));
Tareq A. Siraj11755522013-08-26 19:58:59 +000045
Edwin Vane59d93af2013-09-30 13:59:21 +000046
47static cl::opt<bool> DoFormat(
48 "format",
49 cl::desc("Enable formatting of code changed by applying replacements.\n"
50 "Use -style to choose formatting style.\n"),
51 cl::cat(FormattingCategory));
52
53// FIXME: Consider making the default behaviour for finding a style
54// configuration file to start the search anew for every file being changed to
55// handle situations where the style is different for different parts of a
56// project.
57
58static cl::opt<std::string> FormatStyleConfig(
59 "style-config",
60 cl::desc("Path to a directory containing a .clang-format file\n"
61 "describing a formatting style to use for formatting\n"
62 "code when -style=file.\n"),
63 cl::init(""), cl::cat(FormattingCategory));
64
65static cl::opt<std::string>
66FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription),
67 cl::init("LLVM"), cl::cat(FormattingCategory));
Edwin Vane6d5350c2013-09-24 18:14:54 +000068
Benjamin Kramere7103712015-03-23 12:49:15 +000069namespace {
Tareq A. Siraj11755522013-08-26 19:58:59 +000070// Helper object to remove the TUReplacement files (triggered by
71// "remove-change-desc-files" command line option) when exiting current scope.
72class ScopedFileRemover {
73public:
74 ScopedFileRemover(const TUReplacementFiles &Files,
75 clang::DiagnosticsEngine &Diagnostics)
76 : TURFiles(Files), Diag(Diagnostics) {}
77
78 ~ScopedFileRemover() {
79 deleteReplacementFiles(TURFiles, Diag);
80 }
81
82private:
83 const TUReplacementFiles &TURFiles;
84 clang::DiagnosticsEngine &Diag;
85};
Benjamin Kramere7103712015-03-23 12:49:15 +000086} // namespace
Tareq A. Siraj11755522013-08-26 19:58:59 +000087
Benjamin Kramere7103712015-03-23 12:49:15 +000088static void printVersion() {
Edwin Vane6d5350c2013-09-24 18:14:54 +000089 outs() << "clang-apply-replacements version " CLANG_VERSION_STRING << "\n";
90}
91
Edwin Vane59d93af2013-09-30 13:59:21 +000092/// \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.
105static bool
106getRewrittenData(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.
Benjamin Kramere7103712015-03-23 12:49:15 +0000139static bool
140applyReplacements(const std::vector<tooling::Replacement> &Replacements,
141 std::string &Result, DiagnosticsEngine &Diagnostics) {
Edwin Vane59d93af2013-09-30 13:59:21 +0000142 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 Vane2fb10d12013-10-01 13:21:39 +0000160/// \param[in] FormatStyle Style to apply.
Edwin Vane59d93af2013-09-30 13:59:21 +0000161/// \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.
Benjamin Kramere7103712015-03-23 12:49:15 +0000166static bool
167applyFormatting(const std::vector<tooling::Replacement> &Replacements,
168 const StringRef FileData, std::string &FormattedFileData,
169 const format::FormatStyle &FormatStyle,
170 DiagnosticsEngine &Diagnostics) {
Edwin Vane59d93af2013-09-30 13:59:21 +0000171 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);
David Blaikie715c98a2014-08-27 20:54:50 +0000191 SM.overrideFileContents(Files.getFile(FileName),
192 llvm::MemoryBuffer::getMemBufferCopy(FileData));
Edwin Vane59d93af2013-09-30 13:59:21 +0000193 Rewriter Rewrites(SM, LangOptions());
194
195 return getRewrittenData(FormattingReplacements, Rewrites, FormattedFileData);
196}
197
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000198int main(int argc, char **argv) {
Chris Bienemanfc4fd522015-01-28 22:45:26 +0000199 cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
Edwin Vane6d5350c2013-09-24 18:14:54 +0000200
201 cl::SetVersionPrinter(&printVersion);
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000202 cl::ParseCommandLineOptions(argc, argv);
203
204 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions());
205 DiagnosticsEngine Diagnostics(
206 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
Alp Toker573583e2014-07-05 03:04:33 +0000207 DiagOpts.get());
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000208
Edwin Vane59d93af2013-09-30 13:59:21 +0000209 // Determine a formatting style from options.
210 format::FormatStyle FormatStyle;
211 if (DoFormat)
Alexander Kornienko3daaf322013-12-02 15:22:30 +0000212 FormatStyle = format::getStyle(FormatStyleOpt, FormatStyleConfig, "LLVM");
Edwin Vane59d93af2013-09-30 13:59:21 +0000213
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000214 TUReplacements TUs;
Tareq A. Siraj11755522013-08-26 19:58:59 +0000215 TUReplacementFiles TURFiles;
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000216
Rafael Espindolac7f0d232014-06-12 22:08:48 +0000217 std::error_code ErrorCode =
Tareq A. Siraj11755522013-08-26 19:58:59 +0000218 collectReplacementsFromDirectory(Directory, TUs, TURFiles, Diagnostics);
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000219
220 if (ErrorCode) {
221 errs() << "Trouble iterating over directory '" << Directory
222 << "': " << ErrorCode.message() << "\n";
Edwin Vanec0f00b72013-10-05 12:15:58 +0000223 return 1;
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000224 }
225
Tareq A. Siraj11755522013-08-26 19:58:59 +0000226 // Remove the TUReplacementFiles (triggered by "remove-change-desc-files"
227 // command line option) when exiting main().
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000228 std::unique_ptr<ScopedFileRemover> Remover;
Tareq A. Siraj11755522013-08-26 19:58:59 +0000229 if (RemoveTUReplacementFiles)
230 Remover.reset(new ScopedFileRemover(TURFiles, Diagnostics));
231
Edwin Vane1106ef22013-08-22 13:40:32 +0000232 FileManager Files((FileSystemOptions()));
233 SourceManager SM(Diagnostics, Files);
234
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000235 FileToReplacementsMap GroupedReplacements;
Edwin Vane1106ef22013-08-22 13:40:32 +0000236 if (!mergeAndDeduplicate(TUs, GroupedReplacements, SM))
237 return 1;
238
Edwin Vane59d93af2013-09-30 13:59:21 +0000239 Rewriter ReplacementsRewriter(SM, LangOptions());
Edwin Vanef18633c2013-08-28 17:19:10 +0000240
Benjamin Kramerab7cefc2014-09-09 13:53:51 +0000241 for (const auto &FileAndReplacements : GroupedReplacements) {
Edwin Vane59d93af2013-09-30 13:59:21 +0000242 // This shouldn't happen but if a file somehow has no replacements skip to
243 // next file.
Benjamin Kramerab7cefc2014-09-09 13:53:51 +0000244 if (FileAndReplacements.second.empty())
Edwin Vane59d93af2013-09-30 13:59:21 +0000245 continue;
246
Benjamin Kramerab7cefc2014-09-09 13:53:51 +0000247 std::string NewFileData;
248 const char *FileName = FileAndReplacements.first->getName();
249 if (!applyReplacements(FileAndReplacements.second, NewFileData,
250 Diagnostics)) {
251 errs() << "Failed to apply replacements to " << FileName << "\n";
Edwin Vane59d93af2013-09-30 13:59:21 +0000252 continue;
253 }
254
255 // Apply formatting if requested.
Benjamin Kramerab7cefc2014-09-09 13:53:51 +0000256 if (DoFormat &&
257 !applyFormatting(FileAndReplacements.second, NewFileData, NewFileData,
258 FormatStyle, Diagnostics)) {
259 errs() << "Failed to apply reformatting replacements for " << FileName
Edwin Vane59d93af2013-09-30 13:59:21 +0000260 << "\n";
261 continue;
262 }
263
264 // Write new file to disk
Rafael Espindolab14bd532014-08-25 18:17:00 +0000265 std::error_code EC;
Nikola Smiljanic76c21b52014-12-09 02:57:56 +0000266 llvm::raw_fd_ostream FileStream(FileName, EC, llvm::sys::fs::F_None);
Rafael Espindolab14bd532014-08-25 18:17:00 +0000267 if (EC) {
Benjamin Kramerab7cefc2014-09-09 13:53:51 +0000268 llvm::errs() << "Could not open " << FileName << " for writing\n";
Edwin Vane59d93af2013-09-30 13:59:21 +0000269 continue;
270 }
271
272 FileStream << NewFileData;
273 }
Edwin Vanef18633c2013-08-28 17:19:10 +0000274
275 return 0;
Edwin Vane3bf14ce2013-08-22 13:07:14 +0000276}