blob: 655a8d8e8728da7d373726df863df037222ead4b [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);
120 return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
121 SrcMgr::C_User);
djasper7f663602013-03-20 09:53:23 +0000122}
123
alexfh6e701792013-07-18 22:54:56 +0000124// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000125// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000126static bool parseLineRange(StringRef Input, unsigned &FromLine,
127 unsigned &ToLine) {
128 std::pair<StringRef, StringRef> LineRange = Input.split(':');
129 return LineRange.first.getAsInteger(0, FromLine) ||
130 LineRange.second.getAsInteger(0, ToLine);
131}
132
djasper578d2032015-09-23 08:30:47 +0000133static bool fillRanges(MemoryBuffer *Code,
134 std::vector<tooling::Range> &Ranges) {
jdevlieghere96636aa2018-10-10 13:27:25 +0000135 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
136 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000137 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper578d2032015-09-23 08:30:47 +0000138 DiagnosticsEngine Diagnostics(
139 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
140 new DiagnosticOptions);
141 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000142 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
143 InMemoryFileSystem.get());
alexfh6e701792013-07-18 22:54:56 +0000144 if (!LineRanges.empty()) {
145 if (!Offsets.empty() || !Lengths.empty()) {
djasper9e191b42015-11-23 08:36:35 +0000146 errs() << "error: cannot use -lines with -offset/-length\n";
alexfh6e701792013-07-18 22:54:56 +0000147 return true;
148 }
149
150 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
151 unsigned FromLine, ToLine;
152 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
djasper9e191b42015-11-23 08:36:35 +0000153 errs() << "error: invalid <start line>:<end line> pair\n";
alexfh6e701792013-07-18 22:54:56 +0000154 return true;
155 }
156 if (FromLine > ToLine) {
djasper9e191b42015-11-23 08:36:35 +0000157 errs() << "error: start line should be less than end line\n";
alexfh6e701792013-07-18 22:54:56 +0000158 return true;
159 }
160 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
161 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
162 if (Start.isInvalid() || End.isInvalid())
163 return true;
djasper578d2032015-09-23 08:30:47 +0000164 unsigned Offset = Sources.getFileOffset(Start);
165 unsigned Length = Sources.getFileOffset(End) - Offset;
166 Ranges.push_back(tooling::Range(Offset, Length));
alexfh6e701792013-07-18 22:54:56 +0000167 }
168 return false;
djasper7f663602013-03-20 09:53:23 +0000169 }
alexfh6e701792013-07-18 22:54:56 +0000170
djasper7f663602013-03-20 09:53:23 +0000171 if (Offsets.empty())
172 Offsets.push_back(0);
173 if (Offsets.size() != Lengths.size() &&
174 !(Offsets.size() == 1 && Lengths.empty())) {
djasper9e191b42015-11-23 08:36:35 +0000175 errs() << "error: number of -offset and -length arguments must match.\n";
alexfh4df43642013-04-24 12:46:44 +0000176 return true;
djasper7f663602013-03-20 09:53:23 +0000177 }
alexfh4df43642013-04-24 12:46:44 +0000178 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
179 if (Offsets[i] >= Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000180 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
alexfh4df43642013-04-24 12:46:44 +0000181 return true;
182 }
djasper7f663602013-03-20 09:53:23 +0000183 SourceLocation Start =
184 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
185 SourceLocation End;
186 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000187 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000188 errs() << "error: invalid length " << Lengths[i]
189 << ", offset + length (" << Offsets[i] + Lengths[i]
190 << ") is outside the file.\n";
alexfh4df43642013-04-24 12:46:44 +0000191 return true;
192 }
djasper7f663602013-03-20 09:53:23 +0000193 End = Start.getLocWithOffset(Lengths[i]);
194 } else {
195 End = Sources.getLocForEndOfFile(ID);
196 }
djasper578d2032015-09-23 08:30:47 +0000197 unsigned Offset = Sources.getFileOffset(Start);
198 unsigned Length = Sources.getFileOffset(End) - Offset;
199 Ranges.push_back(tooling::Range(Offset, Length));
djasper7f663602013-03-20 09:53:23 +0000200 }
alexfh6e701792013-07-18 22:54:56 +0000201 return false;
202}
203
klimek82392d72013-12-03 09:46:06 +0000204static void outputReplacementXML(StringRef Text) {
djasperc8a1a082015-10-15 18:39:31 +0000205 // FIXME: When we sort includes, we need to make sure the stream is correct
206 // utf-8.
klimek82392d72013-12-03 09:46:06 +0000207 size_t From = 0;
208 size_t Index;
djasperc8a1a082015-10-15 18:39:31 +0000209 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
djasper9e191b42015-11-23 08:36:35 +0000210 outs() << Text.substr(From, Index - From);
klimek82392d72013-12-03 09:46:06 +0000211 switch (Text[Index]) {
212 case '\n':
djasper9e191b42015-11-23 08:36:35 +0000213 outs() << "&#10;";
klimek82392d72013-12-03 09:46:06 +0000214 break;
215 case '\r':
djasper9e191b42015-11-23 08:36:35 +0000216 outs() << "&#13;";
klimek82392d72013-12-03 09:46:06 +0000217 break;
djasperc8a1a082015-10-15 18:39:31 +0000218 case '<':
djasper9e191b42015-11-23 08:36:35 +0000219 outs() << "&lt;";
djasperc8a1a082015-10-15 18:39:31 +0000220 break;
221 case '&':
djasper9e191b42015-11-23 08:36:35 +0000222 outs() << "&amp;";
djasperc8a1a082015-10-15 18:39:31 +0000223 break;
klimek82392d72013-12-03 09:46:06 +0000224 default:
225 llvm_unreachable("Unexpected character encountered!");
226 }
227 From = Index + 1;
228 }
djasper9e191b42015-11-23 08:36:35 +0000229 outs() << Text.substr(From);
klimek82392d72013-12-03 09:46:06 +0000230}
231
djasper578d2032015-09-23 08:30:47 +0000232static void outputReplacementsXML(const Replacements &Replaces) {
233 for (const auto &R : Replaces) {
234 outs() << "<replacement "
235 << "offset='" << R.getOffset() << "' "
236 << "length='" << R.getLength() << "'>";
237 outputReplacementXML(R.getReplacementText());
238 outs() << "</replacement>\n";
239 }
240}
241
alexfh6e701792013-07-18 22:54:56 +0000242// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000243static bool format(StringRef FileName) {
nicoc09c8de2017-02-27 22:59:58 +0000244 if (!OutputXML && Inplace && FileName == "-") {
245 errs() << "error: cannot use -i when reading from stdin.\n";
246 return false;
247 }
248 // On Windows, overwriting a file with an open file mapping doesn't work,
249 // so read the whole file into memory when formatting in-place.
rafael54c71a82014-07-06 17:43:24 +0000250 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
nicoc09c8de2017-02-27 22:59:58 +0000251 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
252 MemoryBuffer::getFileOrSTDIN(FileName);
rafael54c71a82014-07-06 17:43:24 +0000253 if (std::error_code EC = CodeOrErr.getError()) {
djasper9e191b42015-11-23 08:36:35 +0000254 errs() << EC.message() << "\n";
alexfh6e701792013-07-18 22:54:56 +0000255 return true;
256 }
rafael54c71a82014-07-06 17:43:24 +0000257 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
alexfh6e701792013-07-18 22:54:56 +0000258 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000259 return false; // Empty files are formatted correctly.
djasper578d2032015-09-23 08:30:47 +0000260 std::vector<tooling::Range> Ranges;
261 if (fillRanges(Code.get(), Ranges))
alexfh6e701792013-07-18 22:54:56 +0000262 return true;
djasper262cb332015-09-29 07:53:08 +0000263 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
amaioranoa7d62362017-01-17 00:12:27 +0000264
265 llvm::Expected<FormatStyle> FormatStyle =
djasper4be7a6c2016-12-12 12:42:29 +0000266 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
amaioranoa7d62362017-01-17 00:12:27 +0000267 if (!FormatStyle) {
268 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
269 return true;
270 }
mprobstf9dd41b2017-01-27 09:09:11 +0000271
djasper71631c22015-11-16 12:38:56 +0000272 if (SortIncludes.getNumOccurrences() != 0)
amaioranoa7d62362017-01-17 00:12:27 +0000273 FormatStyle->SortIncludes = SortIncludes;
djasper9e191b42015-11-23 08:36:35 +0000274 unsigned CursorPosition = Cursor;
amaioranoa7d62362017-01-17 00:12:27 +0000275 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
djasper9e191b42015-11-23 08:36:35 +0000276 AssumedFileName, &CursorPosition);
ioeric2b036d32016-07-11 13:53:12 +0000277 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
278 if (!ChangedCode) {
279 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
280 return true;
281 }
ioeric51590652016-08-10 09:32:23 +0000282 // Get new affected ranges after sorting `#includes`.
283 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
krasimir0653eee2017-04-21 14:35:20 +0000284 FormattingAttemptStatus Status;
amaioranoa7d62362017-01-17 00:12:27 +0000285 Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
krasimir0653eee2017-04-21 14:35:20 +0000286 AssumedFileName, &Status);
ioeric531dffd2016-08-01 10:16:37 +0000287 Replaces = Replaces.merge(FormatChanges);
djasper7f663602013-03-20 09:53:23 +0000288 if (OutputXML) {
djasper9e191b42015-11-23 08:36:35 +0000289 outs() << "<?xml version='1.0'?>\n<replacements "
290 "xml:space='preserve' incomplete_format='"
krasimir0653eee2017-04-21 14:35:20 +0000291 << (Status.FormatComplete ? "false" : "true") << "'";
292 if (!Status.FormatComplete)
ioeric35c8ff02017-11-02 12:48:48 +0000293 outs() << " line='" << Status.Line << "'";
krasimir0653eee2017-04-21 14:35:20 +0000294 outs() << ">\n";
klimekbf977882015-01-09 10:03:47 +0000295 if (Cursor.getNumOccurrences() != 0)
djasper9e191b42015-11-23 08:36:35 +0000296 outs() << "<cursor>"
ioeric531dffd2016-08-01 10:16:37 +0000297 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper9e191b42015-11-23 08:36:35 +0000298 << "</cursor>\n";
djasper0c6c9472015-05-10 07:47:19 +0000299
ioeric531dffd2016-08-01 10:16:37 +0000300 outputReplacementsXML(Replaces);
djasper9e191b42015-11-23 08:36:35 +0000301 outs() << "</replacements>\n";
djasper7f663602013-03-20 09:53:23 +0000302 } else {
jdevlieghere96636aa2018-10-10 13:27:25 +0000303 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
304 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000305 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper44bf2ae2015-09-30 13:59:29 +0000306 DiagnosticsEngine Diagnostics(
307 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
308 new DiagnosticOptions);
309 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000310 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
311 InMemoryFileSystem.get());
djasper44bf2ae2015-09-30 13:59:29 +0000312 Rewriter Rewrite(Sources, LangOptions());
313 tooling::applyAllReplacements(Replaces, Rewrite);
djasper7f663602013-03-20 09:53:23 +0000314 if (Inplace) {
nicoc09c8de2017-02-27 22:59:58 +0000315 if (Rewrite.overwriteChangedFiles())
djasper44bf2ae2015-09-30 13:59:29 +0000316 return true;
djasper7f663602013-03-20 09:53:23 +0000317 } else {
krasimir0653eee2017-04-21 14:35:20 +0000318 if (Cursor.getNumOccurrences() != 0) {
grosser7e070d52015-05-08 21:34:09 +0000319 outs() << "{ \"Cursor\": "
ioeric531dffd2016-08-01 10:16:37 +0000320 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper0c6c9472015-05-10 07:47:19 +0000321 << ", \"IncompleteFormat\": "
krasimir0653eee2017-04-21 14:35:20 +0000322 << (Status.FormatComplete ? "false" : "true");
323 if (!Status.FormatComplete)
324 outs() << ", \"Line\": " << Status.Line;
325 outs() << " }\n";
326 }
djasper44bf2ae2015-09-30 13:59:29 +0000327 Rewrite.getEditBuffer(ID).write(outs());
djasper7f663602013-03-20 09:53:23 +0000328 }
329 }
alexfh4df43642013-04-24 12:46:44 +0000330 return false;
djasper7f663602013-03-20 09:53:23 +0000331}
332
333} // namespace format
334} // namespace clang
335
dim00bed782017-06-06 21:54:21 +0000336static void PrintVersion(raw_ostream &OS) {
nico436d02f2014-01-07 16:27:35 +0000337 OS << clang::getClangToolFullVersion("clang-format") << '\n';
338}
339
djasper7f663602013-03-20 09:53:23 +0000340int main(int argc, const char **argv) {
ruiucdaacac2018-04-13 20:57:57 +0000341 llvm::InitLLVM X(argc, argv);
alexfh9b1d30f2018-03-26 13:54:17 +0000342
cbienemanc9f3db62015-01-21 23:26:11 +0000343 cl::HideUnrelatedOptions(ClangFormatCategory);
alexfh725a9f72013-05-10 18:12:00 +0000344
nico436d02f2014-01-07 16:27:35 +0000345 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000346 cl::ParseCommandLineOptions(
ruiucdaacac2018-04-13 20:57:57 +0000347 argc, argv,
paulhoad3e050fe2019-03-21 13:09:22 +0000348 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000349 "If no arguments are specified, it formats the code from standard input\n"
350 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000351 "If <file>s are given, it reformats the files. If -i is specified\n"
352 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000353 "result is written to the standard output.\n");
354
rafaelf94a89d2017-09-08 00:01:26 +0000355 if (Help) {
djasper7f663602013-03-20 09:53:23 +0000356 cl::PrintHelpMessage();
rafaelf94a89d2017-09-08 00:01:26 +0000357 return 0;
358 }
alexfh4df43642013-04-24 12:46:44 +0000359
alexfh59883452013-05-10 11:56:10 +0000360 if (DumpConfig) {
benhamilton3597d092018-01-29 17:36:43 +0000361 StringRef FileName;
362 std::unique_ptr<llvm::MemoryBuffer> Code;
363 if (FileNames.empty()) {
364 // We can't read the code to detect the language if there's no
365 // file name, so leave Code empty here.
366 FileName = AssumeFileName;
367 } else {
368 // Read in the code in case the filename alone isn't enough to
369 // detect the language.
370 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
371 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
372 if (std::error_code EC = CodeOrErr.getError()) {
373 llvm::errs() << EC.message() << "\n";
374 return 1;
375 }
376 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
377 Code = std::move(CodeOrErr.get());
378 }
amaioranoa7d62362017-01-17 00:12:27 +0000379 llvm::Expected<clang::format::FormatStyle> FormatStyle =
benhamilton3597d092018-01-29 17:36:43 +0000380 clang::format::getStyle(Style, FileName, FallbackStyle,
381 Code ? Code->getBuffer() : "");
amaioranoa7d62362017-01-17 00:12:27 +0000382 if (!FormatStyle) {
383 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
384 return 1;
385 }
386 std::string Config = clang::format::configurationAsText(*FormatStyle);
djasper9e191b42015-11-23 08:36:35 +0000387 outs() << Config << "\n";
alexfh59883452013-05-10 11:56:10 +0000388 return 0;
389 }
390
alexfh4df43642013-04-24 12:46:44 +0000391 bool Error = false;
sylvestrea23fc482017-08-12 15:15:10 +0000392 if (FileNames.empty()) {
alexfh4df43642013-04-24 12:46:44 +0000393 Error = clang::format::format("-");
sylvestrea23fc482017-08-12 15:15:10 +0000394 return Error ? 1 : 0;
395 }
396 if (FileNames.size() != 1 && (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
397 errs() << "error: -offset, -length and -lines can only be used for "
398 "single file.\n";
399 return 1;
400 }
401 for (const auto &FileName : FileNames) {
402 if (Verbose)
403 errs() << "Formatting " << FileName << "\n";
404 Error |= clang::format::format(FileName);
alexfh4df43642013-04-24 12:46:44 +0000405 }
406 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000407}