blob: c0c8dc0e2c7ba2ecfafadacf5906a82bbd1ead2b [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>
54LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
55 "lines (both 1-based).\n"
56 "Multiple ranges can be formatted by specifying\n"
57 "several -lines arguments.\n"
58 "Can't be used with -offset and -length.\n"
59 "Can only be used with one input file."),
60 cl::cat(ClangFormatCategory));
alexfh725a9f72013-05-10 18:12:00 +000061static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000062 Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
63 cl::init(clang::format::DefaultFormatStyle),
64 cl::cat(ClangFormatCategory));
alexfh7e0adcf2013-12-02 15:21:38 +000065static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000066 FallbackStyle("fallback-style",
67 cl::desc("The name of the predefined style used as a\n"
68 "fallback in case clang-format is invoked with\n"
69 "-style=file, but can not find the .clang-format\n"
70 "file to use.\n"
71 "Use -fallback-style=none to skip formatting."),
72 cl::init(clang::format::DefaultFallbackStyle),
73 cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000074
75static cl::opt<std::string>
djasper262cb332015-09-29 07:53:08 +000076AssumeFileName("assume-filename",
djasper05848282013-09-13 13:40:24 +000077 cl::desc("When reading from stdin, clang-format assumes this\n"
78 "filename to look for a style config file (with\n"
nico92818852014-11-10 16:14:54 +000079 "-style=file) and to determine the language."),
djasper44bf2ae2015-09-30 13:59:29 +000080 cl::init("<stdin>"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000081
alexfh725a9f72013-05-10 18:12:00 +000082static cl::opt<bool> Inplace("i",
83 cl::desc("Inplace edit <file>s, if specified."),
84 cl::cat(ClangFormatCategory));
85
86static cl::opt<bool> OutputXML("output-replacements-xml",
87 cl::desc("Output replacements as XML."),
88 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000089static cl::opt<bool>
90 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000091 cl::desc("Dump configuration options to stdout and exit.\n"
92 "Can be used with -style option."),
93 cl::cat(ClangFormatCategory));
djasperd0252b72013-05-21 12:21:39 +000094static cl::opt<unsigned>
95 Cursor("cursor",
alexfhb5b43022013-09-02 15:30:26 +000096 cl::desc("The position of the cursor when invoking\n"
97 "clang-format from an editor integration"),
djasperd0252b72013-05-21 12:21:39 +000098 cl::init(0), cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000099
djasper71631c22015-11-16 12:38:56 +0000100static cl::opt<bool> SortIncludes(
101 "sort-includes",
102 cl::desc("If set, overrides the include sorting behavior determined by the "
103 "SortIncludes style flag"),
104 cl::cat(ClangFormatCategory));
djasper578d2032015-09-23 08:30:47 +0000105
sylvestrea23fc482017-08-12 15:15:10 +0000106static cl::opt<bool>
107 Verbose("verbose", cl::desc("If set, shows the list of processed files"),
108 cl::cat(ClangFormatCategory));
109
alexfh725a9f72013-05-10 18:12:00 +0000110static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
111 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000112
113namespace clang {
114namespace format {
115
dblaikieaa159c52014-06-27 17:40:03 +0000116static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
d0k39bdfea2015-10-06 10:04:08 +0000117 SourceManager &Sources, FileManager &Files,
jdevlieghere96636aa2018-10-10 13:27:25 +0000118 llvm::vfs::InMemoryFileSystem *MemFS) {
d0k39bdfea2015-10-06 10:04:08 +0000119 MemFS->addFileNoOwn(FileName, 0, Source);
harlanhaskinsb0308d52019-08-01 21:31:56 +0000120 auto File = Files.getFile(FileName);
121 return Sources.createFileID(File ? *File : nullptr, SourceLocation(),
d0k39bdfea2015-10-06 10:04:08 +0000122 SrcMgr::C_User);
djasper7f663602013-03-20 09:53:23 +0000123}
124
alexfh6e701792013-07-18 22:54:56 +0000125// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000126// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000127static bool parseLineRange(StringRef Input, unsigned &FromLine,
128 unsigned &ToLine) {
129 std::pair<StringRef, StringRef> LineRange = Input.split(':');
130 return LineRange.first.getAsInteger(0, FromLine) ||
131 LineRange.second.getAsInteger(0, ToLine);
132}
133
djasper578d2032015-09-23 08:30:47 +0000134static bool fillRanges(MemoryBuffer *Code,
135 std::vector<tooling::Range> &Ranges) {
jdevlieghere96636aa2018-10-10 13:27:25 +0000136 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
137 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000138 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper578d2032015-09-23 08:30:47 +0000139 DiagnosticsEngine Diagnostics(
140 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
141 new DiagnosticOptions);
142 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000143 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
144 InMemoryFileSystem.get());
alexfh6e701792013-07-18 22:54:56 +0000145 if (!LineRanges.empty()) {
146 if (!Offsets.empty() || !Lengths.empty()) {
djasper9e191b42015-11-23 08:36:35 +0000147 errs() << "error: cannot use -lines with -offset/-length\n";
alexfh6e701792013-07-18 22:54:56 +0000148 return true;
149 }
150
151 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
152 unsigned FromLine, ToLine;
153 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
djasper9e191b42015-11-23 08:36:35 +0000154 errs() << "error: invalid <start line>:<end line> pair\n";
alexfh6e701792013-07-18 22:54:56 +0000155 return true;
156 }
157 if (FromLine > ToLine) {
djasper9e191b42015-11-23 08:36:35 +0000158 errs() << "error: start line should be less than end line\n";
alexfh6e701792013-07-18 22:54:56 +0000159 return true;
160 }
161 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
162 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
163 if (Start.isInvalid() || End.isInvalid())
164 return true;
djasper578d2032015-09-23 08:30:47 +0000165 unsigned Offset = Sources.getFileOffset(Start);
166 unsigned Length = Sources.getFileOffset(End) - Offset;
167 Ranges.push_back(tooling::Range(Offset, Length));
alexfh6e701792013-07-18 22:54:56 +0000168 }
169 return false;
djasper7f663602013-03-20 09:53:23 +0000170 }
alexfh6e701792013-07-18 22:54:56 +0000171
djasper7f663602013-03-20 09:53:23 +0000172 if (Offsets.empty())
173 Offsets.push_back(0);
174 if (Offsets.size() != Lengths.size() &&
175 !(Offsets.size() == 1 && Lengths.empty())) {
djasper9e191b42015-11-23 08:36:35 +0000176 errs() << "error: number of -offset and -length arguments must match.\n";
alexfh4df43642013-04-24 12:46:44 +0000177 return true;
djasper7f663602013-03-20 09:53:23 +0000178 }
alexfh4df43642013-04-24 12:46:44 +0000179 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
180 if (Offsets[i] >= Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000181 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
alexfh4df43642013-04-24 12:46:44 +0000182 return true;
183 }
djasper7f663602013-03-20 09:53:23 +0000184 SourceLocation Start =
185 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
186 SourceLocation End;
187 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000188 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000189 errs() << "error: invalid length " << Lengths[i]
190 << ", offset + length (" << Offsets[i] + Lengths[i]
191 << ") is outside the file.\n";
alexfh4df43642013-04-24 12:46:44 +0000192 return true;
193 }
djasper7f663602013-03-20 09:53:23 +0000194 End = Start.getLocWithOffset(Lengths[i]);
195 } else {
196 End = Sources.getLocForEndOfFile(ID);
197 }
djasper578d2032015-09-23 08:30:47 +0000198 unsigned Offset = Sources.getFileOffset(Start);
199 unsigned Length = Sources.getFileOffset(End) - Offset;
200 Ranges.push_back(tooling::Range(Offset, Length));
djasper7f663602013-03-20 09:53:23 +0000201 }
alexfh6e701792013-07-18 22:54:56 +0000202 return false;
203}
204
klimek82392d72013-12-03 09:46:06 +0000205static void outputReplacementXML(StringRef Text) {
djasperc8a1a082015-10-15 18:39:31 +0000206 // FIXME: When we sort includes, we need to make sure the stream is correct
207 // utf-8.
klimek82392d72013-12-03 09:46:06 +0000208 size_t From = 0;
209 size_t Index;
djasperc8a1a082015-10-15 18:39:31 +0000210 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
djasper9e191b42015-11-23 08:36:35 +0000211 outs() << Text.substr(From, Index - From);
klimek82392d72013-12-03 09:46:06 +0000212 switch (Text[Index]) {
213 case '\n':
djasper9e191b42015-11-23 08:36:35 +0000214 outs() << "&#10;";
klimek82392d72013-12-03 09:46:06 +0000215 break;
216 case '\r':
djasper9e191b42015-11-23 08:36:35 +0000217 outs() << "&#13;";
klimek82392d72013-12-03 09:46:06 +0000218 break;
djasperc8a1a082015-10-15 18:39:31 +0000219 case '<':
djasper9e191b42015-11-23 08:36:35 +0000220 outs() << "&lt;";
djasperc8a1a082015-10-15 18:39:31 +0000221 break;
222 case '&':
djasper9e191b42015-11-23 08:36:35 +0000223 outs() << "&amp;";
djasperc8a1a082015-10-15 18:39:31 +0000224 break;
klimek82392d72013-12-03 09:46:06 +0000225 default:
226 llvm_unreachable("Unexpected character encountered!");
227 }
228 From = Index + 1;
229 }
djasper9e191b42015-11-23 08:36:35 +0000230 outs() << Text.substr(From);
klimek82392d72013-12-03 09:46:06 +0000231}
232
djasper578d2032015-09-23 08:30:47 +0000233static void outputReplacementsXML(const Replacements &Replaces) {
234 for (const auto &R : Replaces) {
235 outs() << "<replacement "
236 << "offset='" << R.getOffset() << "' "
237 << "length='" << R.getLength() << "'>";
238 outputReplacementXML(R.getReplacementText());
239 outs() << "</replacement>\n";
240 }
241}
242
alexfh6e701792013-07-18 22:54:56 +0000243// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000244static bool format(StringRef FileName) {
nicoc09c8de2017-02-27 22:59:58 +0000245 if (!OutputXML && Inplace && FileName == "-") {
246 errs() << "error: cannot use -i when reading from stdin.\n";
247 return false;
248 }
249 // On Windows, overwriting a file with an open file mapping doesn't work,
250 // so read the whole file into memory when formatting in-place.
rafael54c71a82014-07-06 17:43:24 +0000251 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
nicoc09c8de2017-02-27 22:59:58 +0000252 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
253 MemoryBuffer::getFileOrSTDIN(FileName);
rafael54c71a82014-07-06 17:43:24 +0000254 if (std::error_code EC = CodeOrErr.getError()) {
djasper9e191b42015-11-23 08:36:35 +0000255 errs() << EC.message() << "\n";
alexfh6e701792013-07-18 22:54:56 +0000256 return true;
257 }
rafael54c71a82014-07-06 17:43:24 +0000258 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
alexfh6e701792013-07-18 22:54:56 +0000259 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000260 return false; // Empty files are formatted correctly.
owenpan77a4b6d2019-05-08 14:11:12 +0000261
262 // Check to see if the buffer has a UTF Byte Order Mark (BOM).
263 // We only support UTF-8 with and without a BOM right now. See
264 // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
265 // for more information.
266 StringRef BufStr = Code->getBuffer();
267 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
268 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
269 "UTF-32 (BE)")
270 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
271 "UTF-32 (LE)")
272 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
273 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
274 .StartsWith("\x2B\x2F\x76", "UTF-7")
275 .StartsWith("\xF7\x64\x4C", "UTF-1")
276 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
277 .StartsWith("\x0E\xFE\xFF", "SCSU")
278 .StartsWith("\xFB\xEE\x28", "BOCU-1")
279 .StartsWith("\x84\x31\x95\x33", "GB-18030")
280 .Default(nullptr);
281
282 if (InvalidBOM) {
283 errs() << "error: encoding with unsupported byte order mark \""
284 << InvalidBOM << "\" detected";
285 if (FileName != "-")
286 errs() << " in file '" << FileName << "'";
287 errs() << ".\n";
288 return true;
289 }
290
djasper578d2032015-09-23 08:30:47 +0000291 std::vector<tooling::Range> Ranges;
292 if (fillRanges(Code.get(), Ranges))
alexfh6e701792013-07-18 22:54:56 +0000293 return true;
djasper262cb332015-09-29 07:53:08 +0000294 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
amaioranoa7d62362017-01-17 00:12:27 +0000295
296 llvm::Expected<FormatStyle> FormatStyle =
djasper4be7a6c2016-12-12 12:42:29 +0000297 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
amaioranoa7d62362017-01-17 00:12:27 +0000298 if (!FormatStyle) {
299 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
300 return true;
301 }
mprobstf9dd41b2017-01-27 09:09:11 +0000302
djasper71631c22015-11-16 12:38:56 +0000303 if (SortIncludes.getNumOccurrences() != 0)
amaioranoa7d62362017-01-17 00:12:27 +0000304 FormatStyle->SortIncludes = SortIncludes;
djasper9e191b42015-11-23 08:36:35 +0000305 unsigned CursorPosition = Cursor;
amaioranoa7d62362017-01-17 00:12:27 +0000306 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
djasper9e191b42015-11-23 08:36:35 +0000307 AssumedFileName, &CursorPosition);
ioeric2b036d32016-07-11 13:53:12 +0000308 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
309 if (!ChangedCode) {
310 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
311 return true;
312 }
ioeric51590652016-08-10 09:32:23 +0000313 // Get new affected ranges after sorting `#includes`.
314 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
krasimir0653eee2017-04-21 14:35:20 +0000315 FormattingAttemptStatus Status;
amaioranoa7d62362017-01-17 00:12:27 +0000316 Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
krasimir0653eee2017-04-21 14:35:20 +0000317 AssumedFileName, &Status);
ioeric531dffd2016-08-01 10:16:37 +0000318 Replaces = Replaces.merge(FormatChanges);
djasper7f663602013-03-20 09:53:23 +0000319 if (OutputXML) {
djasper9e191b42015-11-23 08:36:35 +0000320 outs() << "<?xml version='1.0'?>\n<replacements "
321 "xml:space='preserve' incomplete_format='"
krasimir0653eee2017-04-21 14:35:20 +0000322 << (Status.FormatComplete ? "false" : "true") << "'";
323 if (!Status.FormatComplete)
ioeric35c8ff02017-11-02 12:48:48 +0000324 outs() << " line='" << Status.Line << "'";
krasimir0653eee2017-04-21 14:35:20 +0000325 outs() << ">\n";
klimekbf977882015-01-09 10:03:47 +0000326 if (Cursor.getNumOccurrences() != 0)
djasper9e191b42015-11-23 08:36:35 +0000327 outs() << "<cursor>"
ioeric531dffd2016-08-01 10:16:37 +0000328 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper9e191b42015-11-23 08:36:35 +0000329 << "</cursor>\n";
djasper0c6c9472015-05-10 07:47:19 +0000330
ioeric531dffd2016-08-01 10:16:37 +0000331 outputReplacementsXML(Replaces);
djasper9e191b42015-11-23 08:36:35 +0000332 outs() << "</replacements>\n";
djasper7f663602013-03-20 09:53:23 +0000333 } else {
jdevlieghere96636aa2018-10-10 13:27:25 +0000334 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
335 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000336 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper44bf2ae2015-09-30 13:59:29 +0000337 DiagnosticsEngine Diagnostics(
338 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
339 new DiagnosticOptions);
340 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000341 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
342 InMemoryFileSystem.get());
djasper44bf2ae2015-09-30 13:59:29 +0000343 Rewriter Rewrite(Sources, LangOptions());
344 tooling::applyAllReplacements(Replaces, Rewrite);
djasper7f663602013-03-20 09:53:23 +0000345 if (Inplace) {
nicoc09c8de2017-02-27 22:59:58 +0000346 if (Rewrite.overwriteChangedFiles())
djasper44bf2ae2015-09-30 13:59:29 +0000347 return true;
djasper7f663602013-03-20 09:53:23 +0000348 } else {
krasimir0653eee2017-04-21 14:35:20 +0000349 if (Cursor.getNumOccurrences() != 0) {
grosser7e070d52015-05-08 21:34:09 +0000350 outs() << "{ \"Cursor\": "
ioeric531dffd2016-08-01 10:16:37 +0000351 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper0c6c9472015-05-10 07:47:19 +0000352 << ", \"IncompleteFormat\": "
krasimir0653eee2017-04-21 14:35:20 +0000353 << (Status.FormatComplete ? "false" : "true");
354 if (!Status.FormatComplete)
355 outs() << ", \"Line\": " << Status.Line;
356 outs() << " }\n";
357 }
djasper44bf2ae2015-09-30 13:59:29 +0000358 Rewrite.getEditBuffer(ID).write(outs());
djasper7f663602013-03-20 09:53:23 +0000359 }
360 }
alexfh4df43642013-04-24 12:46:44 +0000361 return false;
djasper7f663602013-03-20 09:53:23 +0000362}
363
364} // namespace format
365} // namespace clang
366
dim00bed782017-06-06 21:54:21 +0000367static void PrintVersion(raw_ostream &OS) {
nico436d02f2014-01-07 16:27:35 +0000368 OS << clang::getClangToolFullVersion("clang-format") << '\n';
369}
370
djasper7f663602013-03-20 09:53:23 +0000371int main(int argc, const char **argv) {
ruiucdaacac2018-04-13 20:57:57 +0000372 llvm::InitLLVM X(argc, argv);
alexfh9b1d30f2018-03-26 13:54:17 +0000373
cbienemanc9f3db62015-01-21 23:26:11 +0000374 cl::HideUnrelatedOptions(ClangFormatCategory);
alexfh725a9f72013-05-10 18:12:00 +0000375
nico436d02f2014-01-07 16:27:35 +0000376 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000377 cl::ParseCommandLineOptions(
ruiucdaacac2018-04-13 20:57:57 +0000378 argc, argv,
paulhoad3e050fe2019-03-21 13:09:22 +0000379 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000380 "If no arguments are specified, it formats the code from standard input\n"
381 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000382 "If <file>s are given, it reformats the files. If -i is specified\n"
383 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000384 "result is written to the standard output.\n");
385
rafaelf94a89d2017-09-08 00:01:26 +0000386 if (Help) {
djasper7f663602013-03-20 09:53:23 +0000387 cl::PrintHelpMessage();
rafaelf94a89d2017-09-08 00:01:26 +0000388 return 0;
389 }
alexfh4df43642013-04-24 12:46:44 +0000390
alexfh59883452013-05-10 11:56:10 +0000391 if (DumpConfig) {
benhamilton3597d092018-01-29 17:36:43 +0000392 StringRef FileName;
393 std::unique_ptr<llvm::MemoryBuffer> Code;
394 if (FileNames.empty()) {
395 // We can't read the code to detect the language if there's no
396 // file name, so leave Code empty here.
397 FileName = AssumeFileName;
398 } else {
399 // Read in the code in case the filename alone isn't enough to
400 // detect the language.
401 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
402 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
403 if (std::error_code EC = CodeOrErr.getError()) {
404 llvm::errs() << EC.message() << "\n";
405 return 1;
406 }
407 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
408 Code = std::move(CodeOrErr.get());
409 }
amaioranoa7d62362017-01-17 00:12:27 +0000410 llvm::Expected<clang::format::FormatStyle> FormatStyle =
benhamilton3597d092018-01-29 17:36:43 +0000411 clang::format::getStyle(Style, FileName, FallbackStyle,
412 Code ? Code->getBuffer() : "");
amaioranoa7d62362017-01-17 00:12:27 +0000413 if (!FormatStyle) {
414 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
415 return 1;
416 }
417 std::string Config = clang::format::configurationAsText(*FormatStyle);
djasper9e191b42015-11-23 08:36:35 +0000418 outs() << Config << "\n";
alexfh59883452013-05-10 11:56:10 +0000419 return 0;
420 }
421
alexfh4df43642013-04-24 12:46:44 +0000422 bool Error = false;
sylvestrea23fc482017-08-12 15:15:10 +0000423 if (FileNames.empty()) {
alexfh4df43642013-04-24 12:46:44 +0000424 Error = clang::format::format("-");
sylvestrea23fc482017-08-12 15:15:10 +0000425 return Error ? 1 : 0;
426 }
427 if (FileNames.size() != 1 && (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
428 errs() << "error: -offset, -length and -lines can only be used for "
429 "single file.\n";
430 return 1;
431 }
432 for (const auto &FileName : FileNames) {
433 if (Verbose)
434 errs() << "Formatting " << FileName << "\n";
435 Error |= clang::format::format(FileName);
alexfh4df43642013-04-24 12:46:44 +0000436 }
437 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000438}