blob: f2d57ee2832dcc312e026e890c70c5e5b2eab123 [file] [log] [blame]
djasper7f663602013-03-20 09:53:23 +00001//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
2//
chandlerc079ee0b2019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
djasper7f663602013-03-20 09:53:23 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
adrian78220842018-05-09 01:00:01 +000010/// This file implements a clang-format tool that automatically formats
djasper7f663602013-03-20 09:53:23 +000011/// (fragments of) C++ code.
12///
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Basic/DiagnosticOptions.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/SourceManager.h"
nico436d02f2014-01-07 16:27:35 +000019#include "clang/Basic/Version.h"
djasper7f663602013-03-20 09:53:23 +000020#include "clang/Format/Format.h"
djasper44bf2ae2015-09-30 13:59:29 +000021#include "clang/Rewrite/Core/Rewriter.h"
djasper1e1687b2014-10-29 22:42:53 +000022#include "llvm/Support/CommandLine.h"
djasper7f663602013-03-20 09:53:23 +000023#include "llvm/Support/FileSystem.h"
ruiucdaacac2018-04-13 20:57:57 +000024#include "llvm/Support/InitLLVM.h"
alexfh9b1d30f2018-03-26 13:54:17 +000025#include "llvm/Support/Process.h"
djasper7f663602013-03-20 09:53:23 +000026
27using namespace llvm;
djasper578d2032015-09-23 08:30:47 +000028using clang::tooling::Replacements;
djasper7f663602013-03-20 09:53:23 +000029
30static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
31
alexfh725a9f72013-05-10 18:12:00 +000032// Mark all our options with this category, everything else (except for -version
33// and -help) will be hidden.
alexfhebc16002014-02-05 13:42:43 +000034static cl::OptionCategory ClangFormatCategory("Clang-format options");
djasper7f663602013-03-20 09:53:23 +000035
alexfh725a9f72013-05-10 18:12:00 +000036static cl::list<unsigned>
37 Offsets("offset",
38 cl::desc("Format a range starting at this byte offset.\n"
39 "Multiple ranges can be formatted by specifying\n"
40 "several -offset and -length pairs.\n"
41 "Can only be used with one input file."),
42 cl::cat(ClangFormatCategory));
43static cl::list<unsigned>
44 Lengths("length",
45 cl::desc("Format a range of this length (in bytes).\n"
46 "Multiple ranges can be formatted by specifying\n"
47 "several -offset and -length pairs.\n"
48 "When only a single -offset is specified without\n"
49 "-length, clang-format will format up to the end\n"
50 "of the file.\n"
51 "Can only be used with one input file."),
52 cl::cat(ClangFormatCategory));
alexfh6e701792013-07-18 22:54:56 +000053static cl::list<std::string>
paulhoadb125d502019-10-07 16:53:35 +000054 LineRanges("lines",
55 cl::desc("<start line>:<end line> - format a range of\n"
56 "lines (both 1-based).\n"
57 "Multiple ranges can be formatted by specifying\n"
58 "several -lines arguments.\n"
59 "Can't be used with -offset and -length.\n"
60 "Can only be used with one input file."),
61 cl::cat(ClangFormatCategory));
alexfh725a9f72013-05-10 18:12:00 +000062static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000063 Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
64 cl::init(clang::format::DefaultFormatStyle),
65 cl::cat(ClangFormatCategory));
alexfh7e0adcf2013-12-02 15:21:38 +000066static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000067 FallbackStyle("fallback-style",
68 cl::desc("The name of the predefined style used as a\n"
69 "fallback in case clang-format is invoked with\n"
70 "-style=file, but can not find the .clang-format\n"
71 "file to use.\n"
72 "Use -fallback-style=none to skip formatting."),
73 cl::init(clang::format::DefaultFallbackStyle),
74 cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000075
paulhoadb125d502019-10-07 16:53:35 +000076static cl::opt<std::string> AssumeFileName(
77 "assume-filename",
78 cl::desc("When reading from stdin, clang-format assumes this\n"
79 "filename to look for a style config file (with\n"
80 "-style=file) and to determine the language."),
81 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
sylvestrea23fc482017-08-12 15:15:10 +0000107static cl::opt<bool>
108 Verbose("verbose", cl::desc("If set, shows the list of processed files"),
109 cl::cat(ClangFormatCategory));
110
alexfh725a9f72013-05-10 18:12:00 +0000111static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
112 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000113
114namespace clang {
115namespace format {
116
dblaikieaa159c52014-06-27 17:40:03 +0000117static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
d0k39bdfea2015-10-06 10:04:08 +0000118 SourceManager &Sources, FileManager &Files,
jdevlieghere96636aa2018-10-10 13:27:25 +0000119 llvm::vfs::InMemoryFileSystem *MemFS) {
d0k39bdfea2015-10-06 10:04:08 +0000120 MemFS->addFileNoOwn(FileName, 0, Source);
harlanhaskinsb0308d52019-08-01 21:31:56 +0000121 auto File = Files.getFile(FileName);
122 return Sources.createFileID(File ? *File : nullptr, SourceLocation(),
d0k39bdfea2015-10-06 10:04:08 +0000123 SrcMgr::C_User);
djasper7f663602013-03-20 09:53:23 +0000124}
125
alexfh6e701792013-07-18 22:54:56 +0000126// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000127// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000128static bool parseLineRange(StringRef Input, unsigned &FromLine,
129 unsigned &ToLine) {
130 std::pair<StringRef, StringRef> LineRange = Input.split(':');
131 return LineRange.first.getAsInteger(0, FromLine) ||
132 LineRange.second.getAsInteger(0, ToLine);
133}
134
djasper578d2032015-09-23 08:30:47 +0000135static bool fillRanges(MemoryBuffer *Code,
136 std::vector<tooling::Range> &Ranges) {
jdevlieghere96636aa2018-10-10 13:27:25 +0000137 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
138 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000139 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper578d2032015-09-23 08:30:47 +0000140 DiagnosticsEngine Diagnostics(
141 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
142 new DiagnosticOptions);
143 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000144 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
145 InMemoryFileSystem.get());
alexfh6e701792013-07-18 22:54:56 +0000146 if (!LineRanges.empty()) {
147 if (!Offsets.empty() || !Lengths.empty()) {
djasper9e191b42015-11-23 08:36:35 +0000148 errs() << "error: cannot use -lines with -offset/-length\n";
alexfh6e701792013-07-18 22:54:56 +0000149 return true;
150 }
151
152 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
153 unsigned FromLine, ToLine;
154 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
djasper9e191b42015-11-23 08:36:35 +0000155 errs() << "error: invalid <start line>:<end line> pair\n";
alexfh6e701792013-07-18 22:54:56 +0000156 return true;
157 }
158 if (FromLine > ToLine) {
djasper9e191b42015-11-23 08:36:35 +0000159 errs() << "error: start line should be less than end line\n";
alexfh6e701792013-07-18 22:54:56 +0000160 return true;
161 }
162 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
163 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
164 if (Start.isInvalid() || End.isInvalid())
165 return true;
djasper578d2032015-09-23 08:30:47 +0000166 unsigned Offset = Sources.getFileOffset(Start);
167 unsigned Length = Sources.getFileOffset(End) - Offset;
168 Ranges.push_back(tooling::Range(Offset, Length));
alexfh6e701792013-07-18 22:54:56 +0000169 }
170 return false;
djasper7f663602013-03-20 09:53:23 +0000171 }
alexfh6e701792013-07-18 22:54:56 +0000172
djasper7f663602013-03-20 09:53:23 +0000173 if (Offsets.empty())
174 Offsets.push_back(0);
175 if (Offsets.size() != Lengths.size() &&
176 !(Offsets.size() == 1 && Lengths.empty())) {
djasper9e191b42015-11-23 08:36:35 +0000177 errs() << "error: number of -offset and -length arguments must match.\n";
alexfh4df43642013-04-24 12:46:44 +0000178 return true;
djasper7f663602013-03-20 09:53:23 +0000179 }
alexfh4df43642013-04-24 12:46:44 +0000180 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
181 if (Offsets[i] >= Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000182 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
alexfh4df43642013-04-24 12:46:44 +0000183 return true;
184 }
djasper7f663602013-03-20 09:53:23 +0000185 SourceLocation Start =
186 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
187 SourceLocation End;
188 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000189 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000190 errs() << "error: invalid length " << Lengths[i]
191 << ", offset + length (" << Offsets[i] + Lengths[i]
192 << ") is outside the file.\n";
alexfh4df43642013-04-24 12:46:44 +0000193 return true;
194 }
djasper7f663602013-03-20 09:53:23 +0000195 End = Start.getLocWithOffset(Lengths[i]);
196 } else {
197 End = Sources.getLocForEndOfFile(ID);
198 }
djasper578d2032015-09-23 08:30:47 +0000199 unsigned Offset = Sources.getFileOffset(Start);
200 unsigned Length = Sources.getFileOffset(End) - Offset;
201 Ranges.push_back(tooling::Range(Offset, Length));
djasper7f663602013-03-20 09:53:23 +0000202 }
alexfh6e701792013-07-18 22:54:56 +0000203 return false;
204}
205
klimek82392d72013-12-03 09:46:06 +0000206static void outputReplacementXML(StringRef Text) {
djasperc8a1a082015-10-15 18:39:31 +0000207 // FIXME: When we sort includes, we need to make sure the stream is correct
208 // utf-8.
klimek82392d72013-12-03 09:46:06 +0000209 size_t From = 0;
210 size_t Index;
djasperc8a1a082015-10-15 18:39:31 +0000211 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
djasper9e191b42015-11-23 08:36:35 +0000212 outs() << Text.substr(From, Index - From);
klimek82392d72013-12-03 09:46:06 +0000213 switch (Text[Index]) {
214 case '\n':
djasper9e191b42015-11-23 08:36:35 +0000215 outs() << "&#10;";
klimek82392d72013-12-03 09:46:06 +0000216 break;
217 case '\r':
djasper9e191b42015-11-23 08:36:35 +0000218 outs() << "&#13;";
klimek82392d72013-12-03 09:46:06 +0000219 break;
djasperc8a1a082015-10-15 18:39:31 +0000220 case '<':
djasper9e191b42015-11-23 08:36:35 +0000221 outs() << "&lt;";
djasperc8a1a082015-10-15 18:39:31 +0000222 break;
223 case '&':
djasper9e191b42015-11-23 08:36:35 +0000224 outs() << "&amp;";
djasperc8a1a082015-10-15 18:39:31 +0000225 break;
klimek82392d72013-12-03 09:46:06 +0000226 default:
227 llvm_unreachable("Unexpected character encountered!");
228 }
229 From = Index + 1;
230 }
djasper9e191b42015-11-23 08:36:35 +0000231 outs() << Text.substr(From);
klimek82392d72013-12-03 09:46:06 +0000232}
233
djasper578d2032015-09-23 08:30:47 +0000234static void outputReplacementsXML(const Replacements &Replaces) {
235 for (const auto &R : Replaces) {
236 outs() << "<replacement "
237 << "offset='" << R.getOffset() << "' "
238 << "length='" << R.getLength() << "'>";
239 outputReplacementXML(R.getReplacementText());
240 outs() << "</replacement>\n";
241 }
242}
243
alexfh6e701792013-07-18 22:54:56 +0000244// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000245static bool format(StringRef FileName) {
nicoc09c8de2017-02-27 22:59:58 +0000246 if (!OutputXML && Inplace && FileName == "-") {
247 errs() << "error: cannot use -i when reading from stdin.\n";
248 return false;
249 }
250 // On Windows, overwriting a file with an open file mapping doesn't work,
251 // so read the whole file into memory when formatting in-place.
rafael54c71a82014-07-06 17:43:24 +0000252 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
paulhoadb125d502019-10-07 16:53:35 +0000253 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName)
254 : MemoryBuffer::getFileOrSTDIN(FileName);
rafael54c71a82014-07-06 17:43:24 +0000255 if (std::error_code EC = CodeOrErr.getError()) {
djasper9e191b42015-11-23 08:36:35 +0000256 errs() << EC.message() << "\n";
alexfh6e701792013-07-18 22:54:56 +0000257 return true;
258 }
rafael54c71a82014-07-06 17:43:24 +0000259 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
alexfh6e701792013-07-18 22:54:56 +0000260 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000261 return false; // Empty files are formatted correctly.
owenpan77a4b6d2019-05-08 14:11:12 +0000262
263 // Check to see if the buffer has a UTF Byte Order Mark (BOM).
264 // We only support UTF-8 with and without a BOM right now. See
265 // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
266 // for more information.
267 StringRef BufStr = Code->getBuffer();
paulhoadb125d502019-10-07 16:53:35 +0000268 const char *InvalidBOM =
269 llvm::StringSwitch<const char *>(BufStr)
270 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
271 "UTF-32 (BE)")
272 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
273 "UTF-32 (LE)")
274 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
275 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
276 .StartsWith("\x2B\x2F\x76", "UTF-7")
277 .StartsWith("\xF7\x64\x4C", "UTF-1")
278 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
279 .StartsWith("\x0E\xFE\xFF", "SCSU")
280 .StartsWith("\xFB\xEE\x28", "BOCU-1")
281 .StartsWith("\x84\x31\x95\x33", "GB-18030")
282 .Default(nullptr);
owenpan77a4b6d2019-05-08 14:11:12 +0000283
284 if (InvalidBOM) {
285 errs() << "error: encoding with unsupported byte order mark \""
286 << InvalidBOM << "\" detected";
287 if (FileName != "-")
288 errs() << " in file '" << FileName << "'";
289 errs() << ".\n";
290 return true;
291 }
292
djasper578d2032015-09-23 08:30:47 +0000293 std::vector<tooling::Range> Ranges;
294 if (fillRanges(Code.get(), Ranges))
alexfh6e701792013-07-18 22:54:56 +0000295 return true;
djasper262cb332015-09-29 07:53:08 +0000296 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
amaioranoa7d62362017-01-17 00:12:27 +0000297
298 llvm::Expected<FormatStyle> FormatStyle =
djasper4be7a6c2016-12-12 12:42:29 +0000299 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
amaioranoa7d62362017-01-17 00:12:27 +0000300 if (!FormatStyle) {
301 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
302 return true;
303 }
mprobstf9dd41b2017-01-27 09:09:11 +0000304
djasper71631c22015-11-16 12:38:56 +0000305 if (SortIncludes.getNumOccurrences() != 0)
amaioranoa7d62362017-01-17 00:12:27 +0000306 FormatStyle->SortIncludes = SortIncludes;
djasper9e191b42015-11-23 08:36:35 +0000307 unsigned CursorPosition = Cursor;
amaioranoa7d62362017-01-17 00:12:27 +0000308 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
djasper9e191b42015-11-23 08:36:35 +0000309 AssumedFileName, &CursorPosition);
ioeric2b036d32016-07-11 13:53:12 +0000310 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
311 if (!ChangedCode) {
312 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
313 return true;
314 }
ioeric51590652016-08-10 09:32:23 +0000315 // Get new affected ranges after sorting `#includes`.
316 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
krasimir0653eee2017-04-21 14:35:20 +0000317 FormattingAttemptStatus Status;
paulhoadb125d502019-10-07 16:53:35 +0000318 Replacements FormatChanges =
319 reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status);
ioeric531dffd2016-08-01 10:16:37 +0000320 Replaces = Replaces.merge(FormatChanges);
djasper7f663602013-03-20 09:53:23 +0000321 if (OutputXML) {
djasper9e191b42015-11-23 08:36:35 +0000322 outs() << "<?xml version='1.0'?>\n<replacements "
323 "xml:space='preserve' incomplete_format='"
krasimir0653eee2017-04-21 14:35:20 +0000324 << (Status.FormatComplete ? "false" : "true") << "'";
325 if (!Status.FormatComplete)
ioeric35c8ff02017-11-02 12:48:48 +0000326 outs() << " line='" << Status.Line << "'";
krasimir0653eee2017-04-21 14:35:20 +0000327 outs() << ">\n";
klimekbf977882015-01-09 10:03:47 +0000328 if (Cursor.getNumOccurrences() != 0)
djasper9e191b42015-11-23 08:36:35 +0000329 outs() << "<cursor>"
ioeric531dffd2016-08-01 10:16:37 +0000330 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper9e191b42015-11-23 08:36:35 +0000331 << "</cursor>\n";
djasper0c6c9472015-05-10 07:47:19 +0000332
ioeric531dffd2016-08-01 10:16:37 +0000333 outputReplacementsXML(Replaces);
djasper9e191b42015-11-23 08:36:35 +0000334 outs() << "</replacements>\n";
djasper7f663602013-03-20 09:53:23 +0000335 } else {
jdevlieghere96636aa2018-10-10 13:27:25 +0000336 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
337 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000338 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper44bf2ae2015-09-30 13:59:29 +0000339 DiagnosticsEngine Diagnostics(
340 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
341 new DiagnosticOptions);
342 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000343 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
344 InMemoryFileSystem.get());
djasper44bf2ae2015-09-30 13:59:29 +0000345 Rewriter Rewrite(Sources, LangOptions());
346 tooling::applyAllReplacements(Replaces, Rewrite);
djasper7f663602013-03-20 09:53:23 +0000347 if (Inplace) {
nicoc09c8de2017-02-27 22:59:58 +0000348 if (Rewrite.overwriteChangedFiles())
djasper44bf2ae2015-09-30 13:59:29 +0000349 return true;
djasper7f663602013-03-20 09:53:23 +0000350 } else {
krasimir0653eee2017-04-21 14:35:20 +0000351 if (Cursor.getNumOccurrences() != 0) {
grosser7e070d52015-05-08 21:34:09 +0000352 outs() << "{ \"Cursor\": "
ioeric531dffd2016-08-01 10:16:37 +0000353 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper0c6c9472015-05-10 07:47:19 +0000354 << ", \"IncompleteFormat\": "
krasimir0653eee2017-04-21 14:35:20 +0000355 << (Status.FormatComplete ? "false" : "true");
356 if (!Status.FormatComplete)
357 outs() << ", \"Line\": " << Status.Line;
358 outs() << " }\n";
359 }
djasper44bf2ae2015-09-30 13:59:29 +0000360 Rewrite.getEditBuffer(ID).write(outs());
djasper7f663602013-03-20 09:53:23 +0000361 }
362 }
alexfh4df43642013-04-24 12:46:44 +0000363 return false;
djasper7f663602013-03-20 09:53:23 +0000364}
365
paulhoadb125d502019-10-07 16:53:35 +0000366} // namespace format
367} // namespace clang
djasper7f663602013-03-20 09:53:23 +0000368
dim00bed782017-06-06 21:54:21 +0000369static void PrintVersion(raw_ostream &OS) {
nico436d02f2014-01-07 16:27:35 +0000370 OS << clang::getClangToolFullVersion("clang-format") << '\n';
371}
372
djasper7f663602013-03-20 09:53:23 +0000373int main(int argc, const char **argv) {
ruiucdaacac2018-04-13 20:57:57 +0000374 llvm::InitLLVM X(argc, argv);
alexfh9b1d30f2018-03-26 13:54:17 +0000375
cbienemanc9f3db62015-01-21 23:26:11 +0000376 cl::HideUnrelatedOptions(ClangFormatCategory);
alexfh725a9f72013-05-10 18:12:00 +0000377
nico436d02f2014-01-07 16:27:35 +0000378 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000379 cl::ParseCommandLineOptions(
ruiucdaacac2018-04-13 20:57:57 +0000380 argc, argv,
paulhoad3e050fe2019-03-21 13:09:22 +0000381 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000382 "If no arguments are specified, it formats the code from standard input\n"
383 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000384 "If <file>s are given, it reformats the files. If -i is specified\n"
385 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000386 "result is written to the standard output.\n");
387
rafaelf94a89d2017-09-08 00:01:26 +0000388 if (Help) {
djasper7f663602013-03-20 09:53:23 +0000389 cl::PrintHelpMessage();
rafaelf94a89d2017-09-08 00:01:26 +0000390 return 0;
391 }
alexfh4df43642013-04-24 12:46:44 +0000392
alexfh59883452013-05-10 11:56:10 +0000393 if (DumpConfig) {
benhamilton3597d092018-01-29 17:36:43 +0000394 StringRef FileName;
395 std::unique_ptr<llvm::MemoryBuffer> Code;
396 if (FileNames.empty()) {
397 // We can't read the code to detect the language if there's no
398 // file name, so leave Code empty here.
399 FileName = AssumeFileName;
400 } else {
401 // Read in the code in case the filename alone isn't enough to
402 // detect the language.
403 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
404 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
405 if (std::error_code EC = CodeOrErr.getError()) {
406 llvm::errs() << EC.message() << "\n";
407 return 1;
408 }
409 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
410 Code = std::move(CodeOrErr.get());
411 }
amaioranoa7d62362017-01-17 00:12:27 +0000412 llvm::Expected<clang::format::FormatStyle> FormatStyle =
benhamilton3597d092018-01-29 17:36:43 +0000413 clang::format::getStyle(Style, FileName, FallbackStyle,
414 Code ? Code->getBuffer() : "");
amaioranoa7d62362017-01-17 00:12:27 +0000415 if (!FormatStyle) {
416 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
417 return 1;
418 }
419 std::string Config = clang::format::configurationAsText(*FormatStyle);
djasper9e191b42015-11-23 08:36:35 +0000420 outs() << Config << "\n";
alexfh59883452013-05-10 11:56:10 +0000421 return 0;
422 }
423
alexfh4df43642013-04-24 12:46:44 +0000424 bool Error = false;
sylvestrea23fc482017-08-12 15:15:10 +0000425 if (FileNames.empty()) {
alexfh4df43642013-04-24 12:46:44 +0000426 Error = clang::format::format("-");
sylvestrea23fc482017-08-12 15:15:10 +0000427 return Error ? 1 : 0;
428 }
paulhoadb125d502019-10-07 16:53:35 +0000429 if (FileNames.size() != 1 &&
430 (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
sylvestrea23fc482017-08-12 15:15:10 +0000431 errs() << "error: -offset, -length and -lines can only be used for "
432 "single file.\n";
433 return 1;
434 }
435 for (const auto &FileName : FileNames) {
436 if (Verbose)
437 errs() << "Formatting " << FileName << "\n";
438 Error |= clang::format::format(FileName);
alexfh4df43642013-04-24 12:46:44 +0000439 }
440 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000441}