blob: a10541d88f071d27821e887a630392798fb8c143 [file] [log] [blame]
Daniel Jasper9be2c5c2013-03-20 09:53:23 +00001//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
2//
Chandler Carruth2946cd72019-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
Daniel Jasper9be2c5c2013-03-20 09:53:23 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// This file implements a clang-format tool that automatically formats
Daniel Jasper9be2c5c2013-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"
Nico Weberb00d66e2014-01-07 16:27:35 +000019#include "clang/Basic/Version.h"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000020#include "clang/Format/Format.h"
Daniel Jasper867a9382015-09-30 13:59:29 +000021#include "clang/Rewrite/Core/Rewriter.h"
Daniel Jasper06dbac42014-10-29 22:42:53 +000022#include "llvm/Support/CommandLine.h"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000023#include "llvm/Support/FileSystem.h"
Rui Ueyamae4b59a92018-04-13 20:57:57 +000024#include "llvm/Support/InitLLVM.h"
Alexander Kornienko54dcb532018-03-26 13:54:17 +000025#include "llvm/Support/Process.h"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000026
27using namespace llvm;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +000028using clang::tooling::Replacements;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000029
30static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
31
Alexander Kornienko88a0d932013-05-10 18:12:00 +000032// Mark all our options with this category, everything else (except for -version
33// and -help) will be hidden.
Alexander Kornienko3bb8fbf2014-02-05 13:42:43 +000034static cl::OptionCategory ClangFormatCategory("Clang-format options");
Daniel Jasper9be2c5c2013-03-20 09:53:23 +000035
Alexander Kornienko88a0d932013-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));
Alexander Kornienkoa49732f2013-07-18 22:54:56 +000053static cl::list<std::string>
Paul Hoada65cfe32019-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));
Alexander Kornienko88a0d932013-05-10 18:12:00 +000062static cl::opt<std::string>
Eric Liub4adc912018-06-25 16:29:19 +000063 Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
64 cl::init(clang::format::DefaultFormatStyle),
65 cl::cat(ClangFormatCategory));
Alexander Kornienkobc4ae442013-12-02 15:21:38 +000066static cl::opt<std::string>
Eric Liub4adc912018-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));
Daniel Jaspere488f5d2013-09-13 13:40:24 +000075
Paul Hoada65cfe32019-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));
Daniel Jaspere488f5d2013-09-13 13:40:24 +000082
Alexander Kornienko88a0d932013-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));
Alexander Kornienko49149672013-05-10 11:56:10 +000090static cl::opt<bool>
91 DumpConfig("dump-config",
Alexander Kornienko88a0d932013-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));
Daniel Jasper2a250b82013-05-21 12:21:39 +000095static cl::opt<unsigned>
96 Cursor("cursor",
Alexander Kornienkod83adf32013-09-02 15:30:26 +000097 cl::desc("The position of the cursor when invoking\n"
98 "clang-format from an editor integration"),
Daniel Jasper2a250b82013-05-21 12:21:39 +000099 cl::init(0), cl::cat(ClangFormatCategory));
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000100
Daniel Jasperda446772015-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));
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000106
Sylvestre Ledrud23dd6c2017-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
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000111// Use --dry-run to match other LLVM tools when you mean do it but don't
112// actually do it
113static cl::opt<bool>
114 DryRun("dry-run",
115 cl::desc("If set, do not actually make the formatting changes"),
116 cl::cat(ClangFormatCategory));
117
118// Use -n as a common command as an alias for --dry-run. (git and make use -n)
119static cl::alias DryRunShort("n", cl::desc("Alias for --dry-run"),
120 cl::cat(ClangFormatCategory), cl::aliasopt(DryRun),
121 cl::NotHidden);
122
123// Emulate being able to turn on/off the warning.
124static cl::opt<bool>
125 WarnFormat("Wclang-format-violations",
126 cl::desc("Warnings about individual formatting changes needed. "
127 "Used only with --dry-run or -n"),
128 cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
129
130static cl::opt<bool>
131 NoWarnFormat("Wno-clang-format-violations",
132 cl::desc("Do not warn about individual formatting changes "
133 "needed. Used only with --dry-run or -n"),
134 cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
135
136static cl::opt<unsigned> ErrorLimit(
137 "ferror-limit",
138 cl::desc("Set the maximum number of clang-format errors to emit before "
139 "stopping (0 = no limit). Used only with --dry-run or -n"),
140 cl::init(0), cl::cat(ClangFormatCategory));
141
142static cl::opt<bool>
143 WarningsAsErrors("Werror",
144 cl::desc("If set, changes formatting warnings to errors"),
145 cl::cat(ClangFormatCategory));
146
147static cl::opt<bool>
148 ShowColors("fcolor-diagnostics",
149 cl::desc("If set, and on a color-capable terminal controls "
150 "whether or not to print diagnostics in color"),
151 cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
152
153static cl::opt<bool>
154 NoShowColors("fno-color-diagnostics",
155 cl::desc("If set, and on a color-capable terminal controls "
156 "whether or not to print diagnostics in color"),
157 cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
158
Alexander Kornienko88a0d932013-05-10 18:12:00 +0000159static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
160 cl::cat(ClangFormatCategory));
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000161
162namespace clang {
163namespace format {
164
David Blaikie66cc07b2014-06-27 17:40:03 +0000165static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000166 SourceManager &Sources, FileManager &Files,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000167 llvm::vfs::InMemoryFileSystem *MemFS) {
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000168 MemFS->addFileNoOwn(FileName, 0, Source);
Harlan Haskins8d323d12019-08-01 21:31:56 +0000169 auto File = Files.getFile(FileName);
170 return Sources.createFileID(File ? *File : nullptr, SourceLocation(),
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000171 SrcMgr::C_User);
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000172}
173
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000174// Parses <start line>:<end line> input to a pair of line numbers.
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000175// Returns true on error.
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000176static bool parseLineRange(StringRef Input, unsigned &FromLine,
177 unsigned &ToLine) {
178 std::pair<StringRef, StringRef> LineRange = Input.split(':');
179 return LineRange.first.getAsInteger(0, FromLine) ||
180 LineRange.second.getAsInteger(0, ToLine);
181}
182
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000183static bool fillRanges(MemoryBuffer *Code,
184 std::vector<tooling::Range> &Ranges) {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000185 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
186 new llvm::vfs::InMemoryFileSystem);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000187 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000188 DiagnosticsEngine Diagnostics(
189 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
190 new DiagnosticOptions);
191 SourceManager Sources(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000192 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
193 InMemoryFileSystem.get());
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000194 if (!LineRanges.empty()) {
195 if (!Offsets.empty() || !Lengths.empty()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000196 errs() << "error: cannot use -lines with -offset/-length\n";
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000197 return true;
198 }
199
200 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
201 unsigned FromLine, ToLine;
202 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000203 errs() << "error: invalid <start line>:<end line> pair\n";
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000204 return true;
205 }
206 if (FromLine > ToLine) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000207 errs() << "error: start line should be less than end line\n";
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000208 return true;
209 }
210 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
211 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
212 if (Start.isInvalid() || End.isInvalid())
213 return true;
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000214 unsigned Offset = Sources.getFileOffset(Start);
215 unsigned Length = Sources.getFileOffset(End) - Offset;
216 Ranges.push_back(tooling::Range(Offset, Length));
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000217 }
218 return false;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000219 }
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000220
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000221 if (Offsets.empty())
222 Offsets.push_back(0);
223 if (Offsets.size() != Lengths.size() &&
224 !(Offsets.size() == 1 && Lengths.empty())) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000225 errs() << "error: number of -offset and -length arguments must match.\n";
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000226 return true;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000227 }
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000228 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
229 if (Offsets[i] >= Code->getBufferSize()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000230 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000231 return true;
232 }
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000233 SourceLocation Start =
234 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
235 SourceLocation End;
236 if (i < Lengths.size()) {
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000237 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000238 errs() << "error: invalid length " << Lengths[i]
239 << ", offset + length (" << Offsets[i] + Lengths[i]
240 << ") is outside the file.\n";
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000241 return true;
242 }
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000243 End = Start.getLocWithOffset(Lengths[i]);
244 } else {
245 End = Sources.getLocForEndOfFile(ID);
246 }
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000247 unsigned Offset = Sources.getFileOffset(Start);
248 unsigned Length = Sources.getFileOffset(End) - Offset;
249 Ranges.push_back(tooling::Range(Offset, Length));
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000250 }
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000251 return false;
252}
253
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000254static void outputReplacementXML(StringRef Text) {
Daniel Jasperf39757d2015-10-15 18:39:31 +0000255 // FIXME: When we sort includes, we need to make sure the stream is correct
256 // utf-8.
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000257 size_t From = 0;
258 size_t Index;
Daniel Jasperf39757d2015-10-15 18:39:31 +0000259 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000260 outs() << Text.substr(From, Index - From);
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000261 switch (Text[Index]) {
262 case '\n':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000263 outs() << "&#10;";
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000264 break;
265 case '\r':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000266 outs() << "&#13;";
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000267 break;
Daniel Jasperf39757d2015-10-15 18:39:31 +0000268 case '<':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000269 outs() << "&lt;";
Daniel Jasperf39757d2015-10-15 18:39:31 +0000270 break;
271 case '&':
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000272 outs() << "&amp;";
Daniel Jasperf39757d2015-10-15 18:39:31 +0000273 break;
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000274 default:
275 llvm_unreachable("Unexpected character encountered!");
276 }
277 From = Index + 1;
278 }
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000279 outs() << Text.substr(From);
Manuel Klimekf54dcbc2013-12-03 09:46:06 +0000280}
281
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000282static void outputReplacementsXML(const Replacements &Replaces) {
283 for (const auto &R : Replaces) {
284 outs() << "<replacement "
285 << "offset='" << R.getOffset() << "' "
286 << "length='" << R.getLength() << "'>";
287 outputReplacementXML(R.getReplacementText());
288 outs() << "</replacement>\n";
289 }
290}
291
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000292// If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
293// nullptr.
294static const char *getInValidBOM(StringRef BufStr) {
295 // Check to see if the buffer has a UTF Byte Order Mark (BOM).
296 // We only support UTF-8 with and without a BOM right now. See
297 // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
298 // for more information.
299 const char *InvalidBOM =
300 llvm::StringSwitch<const char *>(BufStr)
301 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
302 "UTF-32 (BE)")
303 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
304 "UTF-32 (LE)")
305 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
306 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
307 .StartsWith("\x2B\x2F\x76", "UTF-7")
308 .StartsWith("\xF7\x64\x4C", "UTF-1")
309 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
310 .StartsWith("\x0E\xFE\xFF", "SCSU")
311 .StartsWith("\xFB\xEE\x28", "BOCU-1")
312 .StartsWith("\x84\x31\x95\x33", "GB-18030")
313 .Default(nullptr);
314 return InvalidBOM;
315}
316
317static bool
318emitReplacementWarnings(const Replacements &Replaces, StringRef AssumedFileName,
319 const std::unique_ptr<llvm::MemoryBuffer> &Code) {
320 if (Replaces.empty()) {
321 return false;
322 }
323
324 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
325 DiagOpts->ShowColors = (ShowColors && !NoShowColors);
326
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000327 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
328 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
paulhoadec666032019-10-24 19:01:47 +0100329 new DiagnosticsEngine(DiagID, &*DiagOpts));
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000330
331 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
332 new llvm::vfs::InMemoryFileSystem);
333 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
334 SourceManager Sources(*Diags, Files);
335 FileID FileID = createInMemoryFile(AssumedFileName, Code.get(), Sources,
336 Files, InMemoryFileSystem.get());
337
paulhoadec666032019-10-24 19:01:47 +0100338 FileManager &FileMgr = Sources.getFileManager();
339 llvm::ErrorOr<const FileEntry *> FileEntryPtr =
340 FileMgr.getFile(AssumedFileName);
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000341
342 unsigned Errors = 0;
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000343 if (WarnFormat && !NoWarnFormat) {
344 for (const auto &R : Replaces) {
paulhoadec666032019-10-24 19:01:47 +0100345 PresumedLoc PLoc = Sources.getPresumedLoc(
346 Sources.getLocForStartOfFile(FileID).getLocWithOffset(R.getOffset()));
347
348 SourceLocation LineBegin =
349 Sources.translateFileLineCol(FileEntryPtr.get(), PLoc.getLine(), 1);
350 SourceLocation NextLineBegin = Sources.translateFileLineCol(
351 FileEntryPtr.get(), PLoc.getLine() + 1, 1);
352
353 const char *StartBuf = Sources.getCharacterData(LineBegin);
354 const char *EndBuf = Sources.getCharacterData(NextLineBegin);
355
356 StringRef Line(StartBuf, (EndBuf - StartBuf) - 1);
357
358 SMDiagnostic Diags(
359 llvm::SourceMgr(), SMLoc(), AssumedFileName, PLoc.getLine(),
360 PLoc.getColumn(),
361 WarningsAsErrors ? SourceMgr::DiagKind::DK_Error
362 : SourceMgr::DiagKind::DK_Warning,
363 "code should be clang-formatted [-Wclang-format-violations]", Line,
364 ArrayRef<std::pair<unsigned, unsigned>>());
365
366 Diags.print(nullptr, llvm::errs(), (ShowColors && !NoShowColors));
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000367 Errors++;
368 if (ErrorLimit && Errors >= ErrorLimit)
369 break;
370 }
371 }
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000372 return WarningsAsErrors;
373}
374
375static void outputXML(const Replacements &Replaces,
376 const Replacements &FormatChanges,
377 const FormattingAttemptStatus &Status,
378 const cl::opt<unsigned> &Cursor,
379 unsigned CursorPosition) {
380 outs() << "<?xml version='1.0'?>\n<replacements "
381 "xml:space='preserve' incomplete_format='"
382 << (Status.FormatComplete ? "false" : "true") << "'";
383 if (!Status.FormatComplete)
384 outs() << " line='" << Status.Line << "'";
385 outs() << ">\n";
386 if (Cursor.getNumOccurrences() != 0)
387 outs() << "<cursor>" << FormatChanges.getShiftedCodePosition(CursorPosition)
388 << "</cursor>\n";
389
390 outputReplacementsXML(Replaces);
391 outs() << "</replacements>\n";
392}
393
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000394// Returns true on error.
Bill Wendlinge94f74f2013-11-09 00:23:58 +0000395static bool format(StringRef FileName) {
Nico Weber65da4572017-02-27 22:59:58 +0000396 if (!OutputXML && Inplace && FileName == "-") {
397 errs() << "error: cannot use -i when reading from stdin.\n";
398 return false;
399 }
400 // On Windows, overwriting a file with an open file mapping doesn't work,
401 // so read the whole file into memory when formatting in-place.
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000402 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
Paul Hoada65cfe32019-10-07 16:53:35 +0000403 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName)
404 : MemoryBuffer::getFileOrSTDIN(FileName);
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000405 if (std::error_code EC = CodeOrErr.getError()) {
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000406 errs() << EC.message() << "\n";
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000407 return true;
408 }
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000409 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000410 if (Code->getBufferSize() == 0)
Daniel Jaspere8845ad2013-10-08 15:54:36 +0000411 return false; // Empty files are formatted correctly.
Owen Pan4ba52692019-05-08 14:11:12 +0000412
Owen Pan4ba52692019-05-08 14:11:12 +0000413 StringRef BufStr = Code->getBuffer();
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000414
415 const char *InvalidBOM = getInValidBOM(BufStr);
Owen Pan4ba52692019-05-08 14:11:12 +0000416
417 if (InvalidBOM) {
418 errs() << "error: encoding with unsupported byte order mark \""
419 << InvalidBOM << "\" detected";
420 if (FileName != "-")
421 errs() << " in file '" << FileName << "'";
422 errs() << ".\n";
423 return true;
424 }
425
Daniel Jasperd89ae9d2015-09-23 08:30:47 +0000426 std::vector<tooling::Range> Ranges;
427 if (fillRanges(Code.get(), Ranges))
Alexander Kornienkoa49732f2013-07-18 22:54:56 +0000428 return true;
Daniel Jasper85c472d2015-09-29 07:53:08 +0000429 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000430
431 llvm::Expected<FormatStyle> FormatStyle =
Daniel Jasper03a04fe2016-12-12 12:42:29 +0000432 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000433 if (!FormatStyle) {
434 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
435 return true;
436 }
Martin Probstfa37b182017-01-27 09:09:11 +0000437
Daniel Jasperda446772015-11-16 12:38:56 +0000438 if (SortIncludes.getNumOccurrences() != 0)
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000439 FormatStyle->SortIncludes = SortIncludes;
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000440 unsigned CursorPosition = Cursor;
Antonio Maiorano3adfb6a2017-01-17 00:12:27 +0000441 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
Daniel Jasperb68aabf2015-11-23 08:36:35 +0000442 AssumedFileName, &CursorPosition);
Eric Liu4f8d9942016-07-11 13:53:12 +0000443 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
444 if (!ChangedCode) {
445 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
446 return true;
447 }
Eric Liua992afe2016-08-10 09:32:23 +0000448 // Get new affected ranges after sorting `#includes`.
449 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000450 FormattingAttemptStatus Status;
Paul Hoada65cfe32019-10-07 16:53:35 +0000451 Replacements FormatChanges =
452 reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status);
Eric Liu40ef2fb2016-08-01 10:16:37 +0000453 Replaces = Replaces.merge(FormatChanges);
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000454 if (OutputXML || DryRun) {
455 if (DryRun) {
456 return emitReplacementWarnings(Replaces, AssumedFileName, Code);
457 } else {
458 outputXML(Replaces, FormatChanges, Status, Cursor, CursorPosition);
459 }
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000460 } else {
Jonas Devliegherefc514902018-10-10 13:27:25 +0000461 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
462 new llvm::vfs::InMemoryFileSystem);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000463 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
Daniel Jasper867a9382015-09-30 13:59:29 +0000464 DiagnosticsEngine Diagnostics(
465 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
466 new DiagnosticOptions);
467 SourceManager Sources(Diagnostics, Files);
Benjamin Kramer2e2351a2015-10-06 10:04:08 +0000468 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
469 InMemoryFileSystem.get());
Daniel Jasper867a9382015-09-30 13:59:29 +0000470 Rewriter Rewrite(Sources, LangOptions());
471 tooling::applyAllReplacements(Replaces, Rewrite);
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000472 if (Inplace) {
Nico Weber65da4572017-02-27 22:59:58 +0000473 if (Rewrite.overwriteChangedFiles())
Daniel Jasper867a9382015-09-30 13:59:29 +0000474 return true;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000475 } else {
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000476 if (Cursor.getNumOccurrences() != 0) {
Tobias Grossera7046002015-05-08 21:34:09 +0000477 outs() << "{ \"Cursor\": "
Eric Liu40ef2fb2016-08-01 10:16:37 +0000478 << FormatChanges.getShiftedCodePosition(CursorPosition)
Daniel Jasper622c72d2015-05-10 07:47:19 +0000479 << ", \"IncompleteFormat\": "
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000480 << (Status.FormatComplete ? "false" : "true");
481 if (!Status.FormatComplete)
482 outs() << ", \"Line\": " << Status.Line;
483 outs() << " }\n";
484 }
Daniel Jasper867a9382015-09-30 13:59:29 +0000485 Rewrite.getEditBuffer(ID).write(outs());
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000486 }
487 }
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000488 return false;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000489}
490
Paul Hoada65cfe32019-10-07 16:53:35 +0000491} // namespace format
492} // namespace clang
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000493
Dimitry Andric81c40422017-06-06 21:54:21 +0000494static void PrintVersion(raw_ostream &OS) {
Nico Weberb00d66e2014-01-07 16:27:35 +0000495 OS << clang::getClangToolFullVersion("clang-format") << '\n';
496}
497
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000498// Dump the configuration.
499static int dumpConfig() {
500 StringRef FileName;
501 std::unique_ptr<llvm::MemoryBuffer> Code;
502 if (FileNames.empty()) {
503 // We can't read the code to detect the language if there's no
504 // file name, so leave Code empty here.
505 FileName = AssumeFileName;
506 } else {
507 // Read in the code in case the filename alone isn't enough to
508 // detect the language.
509 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
510 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
511 if (std::error_code EC = CodeOrErr.getError()) {
512 llvm::errs() << EC.message() << "\n";
513 return 1;
514 }
515 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
516 Code = std::move(CodeOrErr.get());
517 }
518 llvm::Expected<clang::format::FormatStyle> FormatStyle =
519 clang::format::getStyle(Style, FileName, FallbackStyle,
520 Code ? Code->getBuffer() : "");
521 if (!FormatStyle) {
522 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
523 return 1;
524 }
525 std::string Config = clang::format::configurationAsText(*FormatStyle);
526 outs() << Config << "\n";
527 return 0;
528}
529
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000530int main(int argc, const char **argv) {
Rui Ueyamae4b59a92018-04-13 20:57:57 +0000531 llvm::InitLLVM X(argc, argv);
Alexander Kornienko54dcb532018-03-26 13:54:17 +0000532
Chris Bieneman0a9f6072015-01-21 23:26:11 +0000533 cl::HideUnrelatedOptions(ClangFormatCategory);
Alexander Kornienko88a0d932013-05-10 18:12:00 +0000534
Nico Weberb00d66e2014-01-07 16:27:35 +0000535 cl::SetVersionPrinter(PrintVersion);
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000536 cl::ParseCommandLineOptions(
Rui Ueyamae4b59a92018-04-13 20:57:57 +0000537 argc, argv,
Paul Hoadcbb726d2019-03-21 13:09:22 +0000538 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n"
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000539 "If no arguments are specified, it formats the code from standard input\n"
540 "and writes the result to the standard output.\n"
Alexander Kornienkod83adf32013-09-02 15:30:26 +0000541 "If <file>s are given, it reformats the files. If -i is specified\n"
542 "together with <file>s, the files are edited in-place. Otherwise, the\n"
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000543 "result is written to the standard output.\n");
544
Rafael Espindola79d9a692017-09-08 00:01:26 +0000545 if (Help) {
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000546 cl::PrintHelpMessage();
Rafael Espindola79d9a692017-09-08 00:01:26 +0000547 return 0;
548 }
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000549
Alexander Kornienko49149672013-05-10 11:56:10 +0000550 if (DumpConfig) {
Paul Hoad6a1f7d62019-10-13 14:51:45 +0000551 return dumpConfig();
Alexander Kornienko49149672013-05-10 11:56:10 +0000552 }
553
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000554 bool Error = false;
Sylvestre Ledrud23dd6c2017-08-12 15:15:10 +0000555 if (FileNames.empty()) {
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000556 Error = clang::format::format("-");
Sylvestre Ledrud23dd6c2017-08-12 15:15:10 +0000557 return Error ? 1 : 0;
558 }
Paul Hoada65cfe32019-10-07 16:53:35 +0000559 if (FileNames.size() != 1 &&
560 (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
Sylvestre Ledrud23dd6c2017-08-12 15:15:10 +0000561 errs() << "error: -offset, -length and -lines can only be used for "
562 "single file.\n";
563 return 1;
564 }
565 for (const auto &FileName : FileNames) {
566 if (Verbose)
567 errs() << "Formatting " << FileName << "\n";
568 Error |= clang::format::format(FileName);
Alexander Kornienko3fbee012013-04-24 12:46:44 +0000569 }
570 return Error ? 1 : 0;
Daniel Jasper9be2c5c2013-03-20 09:53:23 +0000571}