blob: 27577a5a336ac40ab98b7abb886e98494aa82d9b [file] [log] [blame]
djasper7f663602013-03-20 09:53:23 +00001//===-- clang-format/ClangFormat.cpp - Clang format 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-format tool that automatically formats
12/// (fragments of) C++ code.
13///
14//===----------------------------------------------------------------------===//
15
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticOptions.h"
18#include "clang/Basic/FileManager.h"
19#include "clang/Basic/SourceManager.h"
nico436d02f2014-01-07 16:27:35 +000020#include "clang/Basic/Version.h"
djasper7f663602013-03-20 09:53:23 +000021#include "clang/Format/Format.h"
djasper44bf2ae2015-09-30 13:59:29 +000022#include "clang/Rewrite/Core/Rewriter.h"
chandlercd56704b2014-01-07 11:51:46 +000023#include "llvm/ADT/StringMap.h"
djasper1e1687b2014-10-29 22:42:53 +000024#include "llvm/Support/CommandLine.h"
alexfh59883452013-05-10 11:56:10 +000025#include "llvm/Support/Debug.h"
djasper7f663602013-03-20 09:53:23 +000026#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/Signals.h"
28
29using namespace llvm;
djasper578d2032015-09-23 08:30:47 +000030using clang::tooling::Replacements;
djasper7f663602013-03-20 09:53:23 +000031
32static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
33
alexfh725a9f72013-05-10 18:12:00 +000034// Mark all our options with this category, everything else (except for -version
35// and -help) will be hidden.
alexfhebc16002014-02-05 13:42:43 +000036static cl::OptionCategory ClangFormatCategory("Clang-format options");
djasper7f663602013-03-20 09:53:23 +000037
alexfh725a9f72013-05-10 18:12:00 +000038static cl::list<unsigned>
39 Offsets("offset",
40 cl::desc("Format a range starting at this byte offset.\n"
41 "Multiple ranges can be formatted by specifying\n"
42 "several -offset and -length pairs.\n"
43 "Can only be used with one input file."),
44 cl::cat(ClangFormatCategory));
45static cl::list<unsigned>
46 Lengths("length",
47 cl::desc("Format a range of this length (in bytes).\n"
48 "Multiple ranges can be formatted by specifying\n"
49 "several -offset and -length pairs.\n"
50 "When only a single -offset is specified without\n"
51 "-length, clang-format will format up to the end\n"
52 "of the file.\n"
53 "Can only be used with one input file."),
54 cl::cat(ClangFormatCategory));
alexfh6e701792013-07-18 22:54:56 +000055static cl::list<std::string>
56LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
57 "lines (both 1-based).\n"
58 "Multiple ranges can be formatted by specifying\n"
59 "several -lines arguments.\n"
60 "Can't be used with -offset and -length.\n"
61 "Can only be used with one input file."),
62 cl::cat(ClangFormatCategory));
alexfh725a9f72013-05-10 18:12:00 +000063static cl::opt<std::string>
64 Style("style",
revane4d118692013-09-30 13:31:48 +000065 cl::desc(clang::format::StyleOptionHelpDescription),
chandlerce6992fd2013-09-02 07:42:02 +000066 cl::init("file"), cl::cat(ClangFormatCategory));
alexfh7e0adcf2013-12-02 15:21:38 +000067static cl::opt<std::string>
68FallbackStyle("fallback-style",
alexfh07ea1ab2014-02-26 15:03:57 +000069 cl::desc("The name of the predefined style used as a\n"
70 "fallback in case clang-format is invoked with\n"
71 "-style=file, but can not find the .clang-format\n"
djasper077c43c2014-05-22 15:12:22 +000072 "file to use.\n"
73 "Use -fallback-style=none to skip formatting."),
alexfh7e0adcf2013-12-02 15:21:38 +000074 cl::init("LLVM"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000075
76static cl::opt<std::string>
djasper262cb332015-09-29 07:53:08 +000077AssumeFileName("assume-filename",
djasper05848282013-09-13 13:40:24 +000078 cl::desc("When reading from stdin, clang-format assumes this\n"
79 "filename to look for a style config file (with\n"
nico92818852014-11-10 16:14:54 +000080 "-style=file) and to determine the language."),
djasper44bf2ae2015-09-30 13:59:29 +000081 cl::init("<stdin>"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000082
alexfh725a9f72013-05-10 18:12:00 +000083static cl::opt<bool> Inplace("i",
84 cl::desc("Inplace edit <file>s, if specified."),
85 cl::cat(ClangFormatCategory));
86
87static cl::opt<bool> OutputXML("output-replacements-xml",
88 cl::desc("Output replacements as XML."),
89 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000090static cl::opt<bool>
91 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000092 cl::desc("Dump configuration options to stdout and exit.\n"
93 "Can be used with -style option."),
94 cl::cat(ClangFormatCategory));
djasperd0252b72013-05-21 12:21:39 +000095static cl::opt<unsigned>
96 Cursor("cursor",
alexfhb5b43022013-09-02 15:30:26 +000097 cl::desc("The position of the cursor when invoking\n"
98 "clang-format from an editor integration"),
djasperd0252b72013-05-21 12:21:39 +000099 cl::init(0), cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000100
djasper71631c22015-11-16 12:38:56 +0000101static cl::opt<bool> SortIncludes(
102 "sort-includes",
103 cl::desc("If set, overrides the include sorting behavior determined by the "
104 "SortIncludes style flag"),
105 cl::cat(ClangFormatCategory));
djasper578d2032015-09-23 08:30:47 +0000106
alexfh725a9f72013-05-10 18:12:00 +0000107static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
108 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000109
110namespace clang {
111namespace format {
112
dblaikieaa159c52014-06-27 17:40:03 +0000113static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
d0k39bdfea2015-10-06 10:04:08 +0000114 SourceManager &Sources, FileManager &Files,
115 vfs::InMemoryFileSystem *MemFS) {
116 MemFS->addFileNoOwn(FileName, 0, Source);
117 return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
118 SrcMgr::C_User);
djasper7f663602013-03-20 09:53:23 +0000119}
120
alexfh6e701792013-07-18 22:54:56 +0000121// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000122// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000123static bool parseLineRange(StringRef Input, unsigned &FromLine,
124 unsigned &ToLine) {
125 std::pair<StringRef, StringRef> LineRange = Input.split(':');
126 return LineRange.first.getAsInteger(0, FromLine) ||
127 LineRange.second.getAsInteger(0, ToLine);
128}
129
djasper578d2032015-09-23 08:30:47 +0000130static bool fillRanges(MemoryBuffer *Code,
131 std::vector<tooling::Range> &Ranges) {
d0k39bdfea2015-10-06 10:04:08 +0000132 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
133 new vfs::InMemoryFileSystem);
134 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper578d2032015-09-23 08:30:47 +0000135 DiagnosticsEngine Diagnostics(
136 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
137 new DiagnosticOptions);
138 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000139 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
140 InMemoryFileSystem.get());
alexfh6e701792013-07-18 22:54:56 +0000141 if (!LineRanges.empty()) {
142 if (!Offsets.empty() || !Lengths.empty()) {
djasper9e191b42015-11-23 08:36:35 +0000143 errs() << "error: cannot use -lines with -offset/-length\n";
alexfh6e701792013-07-18 22:54:56 +0000144 return true;
145 }
146
147 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
148 unsigned FromLine, ToLine;
149 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
djasper9e191b42015-11-23 08:36:35 +0000150 errs() << "error: invalid <start line>:<end line> pair\n";
alexfh6e701792013-07-18 22:54:56 +0000151 return true;
152 }
153 if (FromLine > ToLine) {
djasper9e191b42015-11-23 08:36:35 +0000154 errs() << "error: start line should be less than end line\n";
alexfh6e701792013-07-18 22:54:56 +0000155 return true;
156 }
157 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
158 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
159 if (Start.isInvalid() || End.isInvalid())
160 return true;
djasper578d2032015-09-23 08:30:47 +0000161 unsigned Offset = Sources.getFileOffset(Start);
162 unsigned Length = Sources.getFileOffset(End) - Offset;
163 Ranges.push_back(tooling::Range(Offset, Length));
alexfh6e701792013-07-18 22:54:56 +0000164 }
165 return false;
djasper7f663602013-03-20 09:53:23 +0000166 }
alexfh6e701792013-07-18 22:54:56 +0000167
djasper7f663602013-03-20 09:53:23 +0000168 if (Offsets.empty())
169 Offsets.push_back(0);
170 if (Offsets.size() != Lengths.size() &&
171 !(Offsets.size() == 1 && Lengths.empty())) {
djasper9e191b42015-11-23 08:36:35 +0000172 errs() << "error: number of -offset and -length arguments must match.\n";
alexfh4df43642013-04-24 12:46:44 +0000173 return true;
djasper7f663602013-03-20 09:53:23 +0000174 }
alexfh4df43642013-04-24 12:46:44 +0000175 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
176 if (Offsets[i] >= Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000177 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
alexfh4df43642013-04-24 12:46:44 +0000178 return true;
179 }
djasper7f663602013-03-20 09:53:23 +0000180 SourceLocation Start =
181 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
182 SourceLocation End;
183 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000184 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000185 errs() << "error: invalid length " << Lengths[i]
186 << ", offset + length (" << Offsets[i] + Lengths[i]
187 << ") is outside the file.\n";
alexfh4df43642013-04-24 12:46:44 +0000188 return true;
189 }
djasper7f663602013-03-20 09:53:23 +0000190 End = Start.getLocWithOffset(Lengths[i]);
191 } else {
192 End = Sources.getLocForEndOfFile(ID);
193 }
djasper578d2032015-09-23 08:30:47 +0000194 unsigned Offset = Sources.getFileOffset(Start);
195 unsigned Length = Sources.getFileOffset(End) - Offset;
196 Ranges.push_back(tooling::Range(Offset, Length));
djasper7f663602013-03-20 09:53:23 +0000197 }
alexfh6e701792013-07-18 22:54:56 +0000198 return false;
199}
200
klimek82392d72013-12-03 09:46:06 +0000201static void outputReplacementXML(StringRef Text) {
djasperc8a1a082015-10-15 18:39:31 +0000202 // FIXME: When we sort includes, we need to make sure the stream is correct
203 // utf-8.
klimek82392d72013-12-03 09:46:06 +0000204 size_t From = 0;
205 size_t Index;
djasperc8a1a082015-10-15 18:39:31 +0000206 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
djasper9e191b42015-11-23 08:36:35 +0000207 outs() << Text.substr(From, Index - From);
klimek82392d72013-12-03 09:46:06 +0000208 switch (Text[Index]) {
209 case '\n':
djasper9e191b42015-11-23 08:36:35 +0000210 outs() << "&#10;";
klimek82392d72013-12-03 09:46:06 +0000211 break;
212 case '\r':
djasper9e191b42015-11-23 08:36:35 +0000213 outs() << "&#13;";
klimek82392d72013-12-03 09:46:06 +0000214 break;
djasperc8a1a082015-10-15 18:39:31 +0000215 case '<':
djasper9e191b42015-11-23 08:36:35 +0000216 outs() << "&lt;";
djasperc8a1a082015-10-15 18:39:31 +0000217 break;
218 case '&':
djasper9e191b42015-11-23 08:36:35 +0000219 outs() << "&amp;";
djasperc8a1a082015-10-15 18:39:31 +0000220 break;
klimek82392d72013-12-03 09:46:06 +0000221 default:
222 llvm_unreachable("Unexpected character encountered!");
223 }
224 From = Index + 1;
225 }
djasper9e191b42015-11-23 08:36:35 +0000226 outs() << Text.substr(From);
klimek82392d72013-12-03 09:46:06 +0000227}
228
djasper578d2032015-09-23 08:30:47 +0000229static void outputReplacementsXML(const Replacements &Replaces) {
230 for (const auto &R : Replaces) {
231 outs() << "<replacement "
232 << "offset='" << R.getOffset() << "' "
233 << "length='" << R.getLength() << "'>";
234 outputReplacementXML(R.getReplacementText());
235 outs() << "</replacement>\n";
236 }
237}
238
alexfh6e701792013-07-18 22:54:56 +0000239// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000240static bool format(StringRef FileName) {
rafael54c71a82014-07-06 17:43:24 +0000241 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
242 MemoryBuffer::getFileOrSTDIN(FileName);
243 if (std::error_code EC = CodeOrErr.getError()) {
djasper9e191b42015-11-23 08:36:35 +0000244 errs() << EC.message() << "\n";
alexfh6e701792013-07-18 22:54:56 +0000245 return true;
246 }
rafael54c71a82014-07-06 17:43:24 +0000247 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
alexfh6e701792013-07-18 22:54:56 +0000248 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000249 return false; // Empty files are formatted correctly.
djasper578d2032015-09-23 08:30:47 +0000250 std::vector<tooling::Range> Ranges;
251 if (fillRanges(Code.get(), Ranges))
alexfh6e701792013-07-18 22:54:56 +0000252 return true;
djasper262cb332015-09-29 07:53:08 +0000253 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
254 FormatStyle FormatStyle = getStyle(Style, AssumedFileName, FallbackStyle);
djasper71631c22015-11-16 12:38:56 +0000255 if (SortIncludes.getNumOccurrences() != 0)
256 FormatStyle.SortIncludes = SortIncludes;
djasper9e191b42015-11-23 08:36:35 +0000257 unsigned CursorPosition = Cursor;
258 Replacements Replaces = sortIncludes(FormatStyle, Code->getBuffer(), Ranges,
259 AssumedFileName, &CursorPosition);
ioeric2b036d32016-07-11 13:53:12 +0000260 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
261 if (!ChangedCode) {
262 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
263 return true;
264 }
djasper71631c22015-11-16 12:38:56 +0000265 for (const auto &R : Replaces)
266 Ranges.push_back({R.getOffset(), R.getLength()});
djasper578d2032015-09-23 08:30:47 +0000267
djasper0c6c9472015-05-10 07:47:19 +0000268 bool IncompleteFormat = false;
ioeric2b036d32016-07-11 13:53:12 +0000269 Replacements FormatChanges = reformat(FormatStyle, *ChangedCode, Ranges,
djasper9e191b42015-11-23 08:36:35 +0000270 AssumedFileName, &IncompleteFormat);
271 Replaces = tooling::mergeReplacements(Replaces, FormatChanges);
djasper7f663602013-03-20 09:53:23 +0000272 if (OutputXML) {
djasper9e191b42015-11-23 08:36:35 +0000273 outs() << "<?xml version='1.0'?>\n<replacements "
274 "xml:space='preserve' incomplete_format='"
275 << (IncompleteFormat ? "true" : "false") << "'>\n";
klimekbf977882015-01-09 10:03:47 +0000276 if (Cursor.getNumOccurrences() != 0)
djasper9e191b42015-11-23 08:36:35 +0000277 outs() << "<cursor>"
278 << tooling::shiftedCodePosition(FormatChanges, CursorPosition)
279 << "</cursor>\n";
djasper0c6c9472015-05-10 07:47:19 +0000280
djasper578d2032015-09-23 08:30:47 +0000281 outputReplacementsXML(Replaces);
djasper9e191b42015-11-23 08:36:35 +0000282 outs() << "</replacements>\n";
djasper7f663602013-03-20 09:53:23 +0000283 } else {
d0k39bdfea2015-10-06 10:04:08 +0000284 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
285 new vfs::InMemoryFileSystem);
286 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper44bf2ae2015-09-30 13:59:29 +0000287 DiagnosticsEngine Diagnostics(
288 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
289 new DiagnosticOptions);
290 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000291 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
292 InMemoryFileSystem.get());
djasper44bf2ae2015-09-30 13:59:29 +0000293 Rewriter Rewrite(Sources, LangOptions());
294 tooling::applyAllReplacements(Replaces, Rewrite);
djasper7f663602013-03-20 09:53:23 +0000295 if (Inplace) {
djasper529feb12015-05-06 11:56:54 +0000296 if (FileName == "-")
djasper9e191b42015-11-23 08:36:35 +0000297 errs() << "error: cannot use -i when reading from stdin.\n";
djasper44bf2ae2015-09-30 13:59:29 +0000298 else if (Rewrite.overwriteChangedFiles())
299 return true;
djasper7f663602013-03-20 09:53:23 +0000300 } else {
djasper898b4f72013-05-21 14:21:46 +0000301 if (Cursor.getNumOccurrences() != 0)
grosser7e070d52015-05-08 21:34:09 +0000302 outs() << "{ \"Cursor\": "
djasper9e191b42015-11-23 08:36:35 +0000303 << tooling::shiftedCodePosition(FormatChanges, CursorPosition)
djasper0c6c9472015-05-10 07:47:19 +0000304 << ", \"IncompleteFormat\": "
305 << (IncompleteFormat ? "true" : "false") << " }\n";
djasper44bf2ae2015-09-30 13:59:29 +0000306 Rewrite.getEditBuffer(ID).write(outs());
djasper7f663602013-03-20 09:53:23 +0000307 }
308 }
alexfh4df43642013-04-24 12:46:44 +0000309 return false;
djasper7f663602013-03-20 09:53:23 +0000310}
311
312} // namespace format
313} // namespace clang
314
nico436d02f2014-01-07 16:27:35 +0000315static void PrintVersion() {
316 raw_ostream &OS = outs();
317 OS << clang::getClangToolFullVersion("clang-format") << '\n';
318}
319
djasper7f663602013-03-20 09:53:23 +0000320int main(int argc, const char **argv) {
rsmith54e6c052016-06-09 00:53:41 +0000321 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
alexfh725a9f72013-05-10 18:12:00 +0000322
cbienemanc9f3db62015-01-21 23:26:11 +0000323 cl::HideUnrelatedOptions(ClangFormatCategory);
alexfh725a9f72013-05-10 18:12:00 +0000324
nico436d02f2014-01-07 16:27:35 +0000325 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000326 cl::ParseCommandLineOptions(
327 argc, argv,
nico636f8552015-10-19 01:03:19 +0000328 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000329 "If no arguments are specified, it formats the code from standard input\n"
330 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000331 "If <file>s are given, it reformats the files. If -i is specified\n"
332 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000333 "result is written to the standard output.\n");
334
djasper7f663602013-03-20 09:53:23 +0000335 if (Help)
336 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000337
alexfh59883452013-05-10 11:56:10 +0000338 if (DumpConfig) {
revane4d118692013-09-30 13:31:48 +0000339 std::string Config =
340 clang::format::configurationAsText(clang::format::getStyle(
djasper262cb332015-09-29 07:53:08 +0000341 Style, FileNames.empty() ? AssumeFileName : FileNames[0],
alexfh7e0adcf2013-12-02 15:21:38 +0000342 FallbackStyle));
djasper9e191b42015-11-23 08:36:35 +0000343 outs() << Config << "\n";
alexfh59883452013-05-10 11:56:10 +0000344 return 0;
345 }
346
alexfh4df43642013-04-24 12:46:44 +0000347 bool Error = false;
348 switch (FileNames.size()) {
349 case 0:
350 Error = clang::format::format("-");
351 break;
352 case 1:
353 Error = clang::format::format(FileNames[0]);
354 break;
355 default:
alexfh6e701792013-07-18 22:54:56 +0000356 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
djasper9e191b42015-11-23 08:36:35 +0000357 errs() << "error: -offset, -length and -lines can only be used for "
358 "single file.\n";
alexfh4df43642013-04-24 12:46:44 +0000359 return 1;
360 }
361 for (unsigned i = 0; i < FileNames.size(); ++i)
362 Error |= clang::format::format(FileNames[i]);
363 break;
364 }
365 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000366}
djasper44bf2ae2015-09-30 13:59:29 +0000367