blob: 2909cddf3776b04523188600f9c33a3800ca0177 [file] [log] [blame]
Daniel Jasper9be2c5c2013-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"
Nico Weberb00d66e2014-01-07 16:27:35 +000020#include "clang/Basic/Version.h"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000021#include "clang/Format/Format.h"
Daniel Jasper867a9382015-09-30 13:59:29 +000022#include "clang/Rewrite/Core/Rewriter.h"
Daniel Jasper06dbac42014-10-29 22:42:53 +000023#include "llvm/Support/CommandLine.h"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000024#include "llvm/Support/FileSystem.h"
Alexander Kornienko54dcb532018-03-26 13:54:17 +000025#include "llvm/Support/Process.h"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000026#include "llvm/Support/Signals.h"
27
28using namespace llvm;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +000029using clang::tooling::Replacements;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000030
31static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
32
Alexander Kornienko88a0d932013-05-10 18:12:00 +000033// Mark all our options with this category, everything else (except for -version
34// and -help) will be hidden.
Alexander Kornienko3bb8fbf2014-02-05 13:42:43 +000035static cl::OptionCategory ClangFormatCategory("Clang-format options");
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000036
Alexander Kornienko88a0d932013-05-10 18:12:00 +000037static cl::list<unsigned>
38 Offsets("offset",
39 cl::desc("Format a range starting at this byte offset.\n"
40 "Multiple ranges can be formatted by specifying\n"
41 "several -offset and -length pairs.\n"
42 "Can only be used with one input file."),
43 cl::cat(ClangFormatCategory));
44static cl::list<unsigned>
45 Lengths("length",
46 cl::desc("Format a range of this length (in bytes).\n"
47 "Multiple ranges can be formatted by specifying\n"
48 "several -offset and -length pairs.\n"
49 "When only a single -offset is specified without\n"
50 "-length, clang-format will format up to the end\n"
51 "of the file.\n"
52 "Can only be used with one input file."),
53 cl::cat(ClangFormatCategory));
Alexander Kornienkoa49732f2013-07-18 22:54:56 +000054static cl::list<std::string>
55LineRanges("lines", 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));
Alexander Kornienko88a0d932013-05-10 18:12:00 +000062static cl::opt<std::string>
63 Style("style",
Edwin Vaned544aa72013-09-30 13:31:48 +000064 cl::desc(clang::format::StyleOptionHelpDescription),
Chandler Carruthbc36e6e02013-09-02 07:42:02 +000065 cl::init("file"), cl::cat(ClangFormatCategory));
Alexander Kornienkobc4ae442013-12-02 15:21:38 +000066static cl::opt<std::string>
67FallbackStyle("fallback-style",
Alexander Kornienko1eda3052014-02-26 15:03:57 +000068 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"
Daniel Jasperc64b09a2014-05-22 15:12:22 +000071 "file to use.\n"
72 "Use -fallback-style=none to skip formatting."),
Alexander Kornienkobc4ae442013-12-02 15:21:38 +000073 cl::init("LLVM"), cl::cat(ClangFormatCategory));
Daniel Jaspere488f5d2013-09-13 13:40:24 +000074
75static cl::opt<std::string>
Daniel Jasper85c472d2015-09-29 07:53:08 +000076AssumeFileName("assume-filename",
Daniel Jaspere488f5d2013-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"
Nico Weber337f5b22014-11-10 16:14:54 +000079 "-style=file) and to determine the language."),
Daniel Jasper867a9382015-09-30 13:59:29 +000080 cl::init("<stdin>"), cl::cat(ClangFormatCategory));
Daniel Jaspere488f5d2013-09-13 13:40:24 +000081
Alexander Kornienko88a0d932013-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));
Alexander Kornienko49149672013-05-10 11:56:10 +000089static cl::opt<bool>
90 DumpConfig("dump-config",
Alexander Kornienko88a0d932013-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));
Daniel Jasper2a250b82013-05-21 12:21:39 +000094static cl::opt<unsigned>
95 Cursor("cursor",
Alexander Kornienkod83adf32013-09-02 15:30:26 +000096 cl::desc("The position of the cursor when invoking\n"
97 "clang-format from an editor integration"),
Daniel Jasper2a250b82013-05-21 12:21:39 +000098 cl::init(0), cl::cat(ClangFormatCategory));
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000099
Daniel Jasperda446772015-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));
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000105
Sylvestre Ledrud23dd6c2017-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
Alexander Kornienko88a0d932013-05-10 18:12:00 +0000110static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
111 cl::cat(ClangFormatCategory));
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000112
113namespace clang {
114namespace format {
115
David Blaikie66cc07b2014-06-27 17:40:03 +0000116static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000117 SourceManager &Sources, FileManager &Files,
118 vfs::InMemoryFileSystem *MemFS) {
119 MemFS->addFileNoOwn(FileName, 0, Source);
120 return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
121 SrcMgr::C_User);
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000122}
123
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000124// Parses <start line>:<end line> input to a pair of line numbers.
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000125// Returns true on error.
Alexander Kornienkoa49732f2013-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
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000133static bool fillRanges(MemoryBuffer *Code,
134 std::vector<tooling::Range> &Ranges) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000135 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
136 new vfs::InMemoryFileSystem);
137 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000138 DiagnosticsEngine Diagnostics(
139 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
140 new DiagnosticOptions);
141 SourceManager Sources(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000142 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
143 InMemoryFileSystem.get());
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000144 if (!LineRanges.empty()) {
145 if (!Offsets.empty() || !Lengths.empty()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000146 errs() << "error: cannot use -lines with -offset/-length\n";
Alexander Kornienkoa49732f2013-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)) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000153 errs() << "error: invalid <start line>:<end line> pair\n";
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000154 return true;
155 }
156 if (FromLine > ToLine) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000157 errs() << "error: start line should be less than end line\n";
Alexander Kornienkoa49732f2013-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;
Daniel Jasperd89ae9d2015-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));
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000167 }
168 return false;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000169 }
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000170
Daniel Jasper9be2c5c2013-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())) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000175 errs() << "error: number of -offset and -length arguments must match.\n";
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000176 return true;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000177 }
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000178 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
179 if (Offsets[i] >= Code->getBufferSize()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000180 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000181 return true;
182 }
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000183 SourceLocation Start =
184 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
185 SourceLocation End;
186 if (i < Lengths.size()) {
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000187 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
Daniel Jasperb68aabf2015-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";
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000191 return true;
192 }
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000193 End = Start.getLocWithOffset(Lengths[i]);
194 } else {
195 End = Sources.getLocForEndOfFile(ID);
196 }
Daniel Jasperd89ae9d2015-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));
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000200 }
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000201 return false;
202}
203
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000204static void outputReplacementXML(StringRef Text) {
Daniel Jasperf39757d2015-10-15 18:39:31 +0000205 // FIXME: When we sort includes, we need to make sure the stream is correct
206 // utf-8.
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000207 size_t From = 0;
208 size_t Index;
Daniel Jasperf39757d2015-10-15 18:39:31 +0000209 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000210 outs() << Text.substr(From, Index - From);
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000211 switch (Text[Index]) {
212 case '\n':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000213 outs() << "&#10;";
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000214 break;
215 case '\r':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000216 outs() << "&#13;";
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000217 break;
Daniel Jasperf39757d2015-10-15 18:39:31 +0000218 case '<':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000219 outs() << "&lt;";
Daniel Jasperf39757d2015-10-15 18:39:31 +0000220 break;
221 case '&':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000222 outs() << "&amp;";
Daniel Jasperf39757d2015-10-15 18:39:31 +0000223 break;
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000224 default:
225 llvm_unreachable("Unexpected character encountered!");
226 }
227 From = Index + 1;
228 }
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000229 outs() << Text.substr(From);
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000230}
231
Daniel Jasperd89ae9d2015-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
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000242// Returns true on error.
Bill Wendlinge94f74f2013-11-09 00:23:58 +0000243static bool format(StringRef FileName) {
Nico Weber65da4572017-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.
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000250 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
Nico Weber65da4572017-02-27 22:59:58 +0000251 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
252 MemoryBuffer::getFileOrSTDIN(FileName);
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000253 if (std::error_code EC = CodeOrErr.getError()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000254 errs() << EC.message() << "\n";
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000255 return true;
256 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000257 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000258 if (Code->getBufferSize() == 0)
Daniel Jaspere8845ad2013-10-08 15:54:36 +0000259 return false; // Empty files are formatted correctly.
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000260 std::vector<tooling::Range> Ranges;
261 if (fillRanges(Code.get(), Ranges))
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000262 return true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000263 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000264
265 llvm::Expected<FormatStyle> FormatStyle =
Daniel Jasper03a04fe2016-12-12 12:42:29 +0000266 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000267 if (!FormatStyle) {
268 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
269 return true;
270 }
Martin Probstfa37b182017-01-27 09:09:11 +0000271
Daniel Jasperda446772015-11-16 12:38:56 +0000272 if (SortIncludes.getNumOccurrences() != 0)
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000273 FormatStyle->SortIncludes = SortIncludes;
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000274 unsigned CursorPosition = Cursor;
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000275 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000276 AssumedFileName, &CursorPosition);
Eric Liu4f8d9942016-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 }
Eric Liua992afe2016-08-10 09:32:23 +0000282 // Get new affected ranges after sorting `#includes`.
283 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000284 FormattingAttemptStatus Status;
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000285 Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000286 AssumedFileName, &Status);
Eric Liu40ef2fb2016-08-01 10:16:37 +0000287 Replaces = Replaces.merge(FormatChanges);
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000288 if (OutputXML) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000289 outs() << "<?xml version='1.0'?>\n<replacements "
290 "xml:space='preserve' incomplete_format='"
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000291 << (Status.FormatComplete ? "false" : "true") << "'";
292 if (!Status.FormatComplete)
Eric Liu35cbbdd2017-11-02 12:48:48 +0000293 outs() << " line='" << Status.Line << "'";
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000294 outs() << ">\n";
Manuel Klimek949ff4d2015-01-09 10:03:47 +0000295 if (Cursor.getNumOccurrences() != 0)
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000296 outs() << "<cursor>"
Eric Liu40ef2fb2016-08-01 10:16:37 +0000297 << FormatChanges.getShiftedCodePosition(CursorPosition)
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000298 << "</cursor>\n";
Daniel Jasper622c72d2015-05-10 07:47:19 +0000299
Eric Liu40ef2fb2016-08-01 10:16:37 +0000300 outputReplacementsXML(Replaces);
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000301 outs() << "</replacements>\n";
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000302 } else {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000303 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
304 new vfs::InMemoryFileSystem);
305 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasper867a9382015-09-30 13:59:29 +0000306 DiagnosticsEngine Diagnostics(
307 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
308 new DiagnosticOptions);
309 SourceManager Sources(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000310 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
311 InMemoryFileSystem.get());
Daniel Jasper867a9382015-09-30 13:59:29 +0000312 Rewriter Rewrite(Sources, LangOptions());
313 tooling::applyAllReplacements(Replaces, Rewrite);
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000314 if (Inplace) {
Nico Weber65da4572017-02-27 22:59:58 +0000315 if (Rewrite.overwriteChangedFiles())
Daniel Jasper867a9382015-09-30 13:59:29 +0000316 return true;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000317 } else {
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000318 if (Cursor.getNumOccurrences() != 0) {
Tobias Grossera7046002015-05-08 21:34:09 +0000319 outs() << "{ \"Cursor\": "
Eric Liu40ef2fb2016-08-01 10:16:37 +0000320 << FormatChanges.getShiftedCodePosition(CursorPosition)
Daniel Jasper622c72d2015-05-10 07:47:19 +0000321 << ", \"IncompleteFormat\": "
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000322 << (Status.FormatComplete ? "false" : "true");
323 if (!Status.FormatComplete)
324 outs() << ", \"Line\": " << Status.Line;
325 outs() << " }\n";
326 }
Daniel Jasper867a9382015-09-30 13:59:29 +0000327 Rewrite.getEditBuffer(ID).write(outs());
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000328 }
329 }
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000330 return false;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000331}
332
333} // namespace format
334} // namespace clang
335
Dimitry Andric81c40422017-06-06 21:54:21 +0000336static void PrintVersion(raw_ostream &OS) {
Nico Weberb00d66e2014-01-07 16:27:35 +0000337 OS << clang::getClangToolFullVersion("clang-format") << '\n';
338}
339
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000340int main(int argc, const char **argv) {
Richard Smithdfed58a2016-06-09 00:53:41 +0000341 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
Alexander Kornienko88a0d932013-05-10 18:12:00 +0000342
Alexander Kornienko54dcb532018-03-26 13:54:17 +0000343 SmallVector<const char *, 256> Args;
344 llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
345 std::error_code EC = llvm::sys::Process::GetArgumentVector(
346 Args, llvm::makeArrayRef(argv, argc), ArgAllocator);
347 if (EC) {
348 llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
349 }
350
Chris Bieneman0a9f6072015-01-21 23:26:11 +0000351 cl::HideUnrelatedOptions(ClangFormatCategory);
Alexander Kornienko88a0d932013-05-10 18:12:00 +0000352
Nico Weberb00d66e2014-01-07 16:27:35 +0000353 cl::SetVersionPrinter(PrintVersion);
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000354 cl::ParseCommandLineOptions(
Alexander Kornienko54dcb532018-03-26 13:54:17 +0000355 Args.size(), &Args[0],
Nico Weber373ee962015-10-19 01:03:19 +0000356 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf code.\n\n"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000357 "If no arguments are specified, it formats the code from standard input\n"
358 "and writes the result to the standard output.\n"
Alexander Kornienkod83adf32013-09-02 15:30:26 +0000359 "If <file>s are given, it reformats the files. If -i is specified\n"
360 "together with <file>s, the files are edited in-place. Otherwise, the\n"
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000361 "result is written to the standard output.\n");
362
Rafael Espindola79d9a692017-09-08 00:01:26 +0000363 if (Help) {
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000364 cl::PrintHelpMessage();
Rafael Espindola79d9a692017-09-08 00:01:26 +0000365 return 0;
366 }
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000367
Alexander Kornienko49149672013-05-10 11:56:10 +0000368 if (DumpConfig) {
Ben Hamilton6845dec2018-01-29 17:36:43 +0000369 StringRef FileName;
370 std::unique_ptr<llvm::MemoryBuffer> Code;
371 if (FileNames.empty()) {
372 // We can't read the code to detect the language if there's no
373 // file name, so leave Code empty here.
374 FileName = AssumeFileName;
375 } else {
376 // Read in the code in case the filename alone isn't enough to
377 // detect the language.
378 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
379 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
380 if (std::error_code EC = CodeOrErr.getError()) {
381 llvm::errs() << EC.message() << "\n";
382 return 1;
383 }
384 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
385 Code = std::move(CodeOrErr.get());
386 }
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000387 llvm::Expected<clang::format::FormatStyle> FormatStyle =
Ben Hamilton6845dec2018-01-29 17:36:43 +0000388 clang::format::getStyle(Style, FileName, FallbackStyle,
389 Code ? Code->getBuffer() : "");
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000390 if (!FormatStyle) {
391 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
392 return 1;
393 }
394 std::string Config = clang::format::configurationAsText(*FormatStyle);
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000395 outs() << Config << "\n";
Alexander Kornienko49149672013-05-10 11:56:10 +0000396 return 0;
397 }
398
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000399 bool Error = false;
Sylvestre Ledrud23dd6c2017-08-12 15:15:10 +0000400 if (FileNames.empty()) {
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000401 Error = clang::format::format("-");
Sylvestre Ledrud23dd6c2017-08-12 15:15:10 +0000402 return Error ? 1 : 0;
403 }
404 if (FileNames.size() != 1 && (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
405 errs() << "error: -offset, -length and -lines can only be used for "
406 "single file.\n";
407 return 1;
408 }
409 for (const auto &FileName : FileNames) {
410 if (Verbose)
411 errs() << "Formatting " << FileName << "\n";
412 Error |= clang::format::format(FileName);
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000413 }
414 return Error ? 1 : 0;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000415}