blob: f39c18bae3ff4cd05b0b24c885e189203410f325 [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"
paulhoadf40d1f42019-10-13 14:51:45 +000021#include "clang/Frontend/TextDiagnosticPrinter.h"
djasper44bf2ae2015-09-30 13:59:29 +000022#include "clang/Rewrite/Core/Rewriter.h"
djasper1e1687b2014-10-29 22:42:53 +000023#include "llvm/Support/CommandLine.h"
djasper7f663602013-03-20 09:53:23 +000024#include "llvm/Support/FileSystem.h"
ruiucdaacac2018-04-13 20:57:57 +000025#include "llvm/Support/InitLLVM.h"
alexfh9b1d30f2018-03-26 13:54:17 +000026#include "llvm/Support/Process.h"
djasper7f663602013-03-20 09:53:23 +000027
28using namespace llvm;
djasper578d2032015-09-23 08:30:47 +000029using clang::tooling::Replacements;
djasper7f663602013-03-20 09:53:23 +000030
31static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
32
alexfh725a9f72013-05-10 18:12:00 +000033// Mark all our options with this category, everything else (except for -version
34// and -help) will be hidden.
alexfhebc16002014-02-05 13:42:43 +000035static cl::OptionCategory ClangFormatCategory("Clang-format options");
djasper7f663602013-03-20 09:53:23 +000036
alexfh725a9f72013-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));
alexfh6e701792013-07-18 22:54:56 +000054static cl::list<std::string>
paulhoadb125d502019-10-07 16:53:35 +000055 LineRanges("lines",
56 cl::desc("<start line>:<end line> - format a range of\n"
57 "lines (both 1-based).\n"
58 "Multiple ranges can be formatted by specifying\n"
59 "several -lines arguments.\n"
60 "Can't be used with -offset and -length.\n"
61 "Can only be used with one input file."),
62 cl::cat(ClangFormatCategory));
alexfh725a9f72013-05-10 18:12:00 +000063static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000064 Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
65 cl::init(clang::format::DefaultFormatStyle),
66 cl::cat(ClangFormatCategory));
alexfh7e0adcf2013-12-02 15:21:38 +000067static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000068 FallbackStyle("fallback-style",
69 cl::desc("The name of the predefined style used as a\n"
70 "fallback in case clang-format is invoked with\n"
71 "-style=file, but can not find the .clang-format\n"
72 "file to use.\n"
73 "Use -fallback-style=none to skip formatting."),
74 cl::init(clang::format::DefaultFallbackStyle),
75 cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000076
paulhoadb125d502019-10-07 16:53:35 +000077static cl::opt<std::string> AssumeFileName(
78 "assume-filename",
79 cl::desc("When reading from stdin, clang-format assumes this\n"
80 "filename to look for a style config file (with\n"
81 "-style=file) and to determine the language."),
82 cl::init("<stdin>"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000083
alexfh725a9f72013-05-10 18:12:00 +000084static cl::opt<bool> Inplace("i",
85 cl::desc("Inplace edit <file>s, if specified."),
86 cl::cat(ClangFormatCategory));
87
88static cl::opt<bool> OutputXML("output-replacements-xml",
89 cl::desc("Output replacements as XML."),
90 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000091static cl::opt<bool>
92 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000093 cl::desc("Dump configuration options to stdout and exit.\n"
94 "Can be used with -style option."),
95 cl::cat(ClangFormatCategory));
djasperd0252b72013-05-21 12:21:39 +000096static cl::opt<unsigned>
97 Cursor("cursor",
alexfhb5b43022013-09-02 15:30:26 +000098 cl::desc("The position of the cursor when invoking\n"
99 "clang-format from an editor integration"),
djasperd0252b72013-05-21 12:21:39 +0000100 cl::init(0), cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000101
djasper71631c22015-11-16 12:38:56 +0000102static cl::opt<bool> SortIncludes(
103 "sort-includes",
104 cl::desc("If set, overrides the include sorting behavior determined by the "
105 "SortIncludes style flag"),
106 cl::cat(ClangFormatCategory));
djasper578d2032015-09-23 08:30:47 +0000107
sylvestrea23fc482017-08-12 15:15:10 +0000108static cl::opt<bool>
109 Verbose("verbose", cl::desc("If set, shows the list of processed files"),
110 cl::cat(ClangFormatCategory));
111
paulhoadf40d1f42019-10-13 14:51:45 +0000112// Use --dry-run to match other LLVM tools when you mean do it but don't
113// actually do it
114static cl::opt<bool>
115 DryRun("dry-run",
116 cl::desc("If set, do not actually make the formatting changes"),
117 cl::cat(ClangFormatCategory));
118
119// Use -n as a common command as an alias for --dry-run. (git and make use -n)
120static cl::alias DryRunShort("n", cl::desc("Alias for --dry-run"),
121 cl::cat(ClangFormatCategory), cl::aliasopt(DryRun),
122 cl::NotHidden);
123
124// Emulate being able to turn on/off the warning.
125static cl::opt<bool>
126 WarnFormat("Wclang-format-violations",
127 cl::desc("Warnings about individual formatting changes needed. "
128 "Used only with --dry-run or -n"),
129 cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
130
131static cl::opt<bool>
132 NoWarnFormat("Wno-clang-format-violations",
133 cl::desc("Do not warn about individual formatting changes "
134 "needed. Used only with --dry-run or -n"),
135 cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
136
137static cl::opt<unsigned> ErrorLimit(
138 "ferror-limit",
139 cl::desc("Set the maximum number of clang-format errors to emit before "
140 "stopping (0 = no limit). Used only with --dry-run or -n"),
141 cl::init(0), cl::cat(ClangFormatCategory));
142
143static cl::opt<bool>
144 WarningsAsErrors("Werror",
145 cl::desc("If set, changes formatting warnings to errors"),
146 cl::cat(ClangFormatCategory));
147
148static cl::opt<bool>
149 ShowColors("fcolor-diagnostics",
150 cl::desc("If set, and on a color-capable terminal controls "
151 "whether or not to print diagnostics in color"),
152 cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
153
154static cl::opt<bool>
155 NoShowColors("fno-color-diagnostics",
156 cl::desc("If set, and on a color-capable terminal controls "
157 "whether or not to print diagnostics in color"),
158 cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
159
alexfh725a9f72013-05-10 18:12:00 +0000160static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
161 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000162
163namespace clang {
164namespace format {
165
dblaikieaa159c52014-06-27 17:40:03 +0000166static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
d0k39bdfea2015-10-06 10:04:08 +0000167 SourceManager &Sources, FileManager &Files,
jdevlieghere96636aa2018-10-10 13:27:25 +0000168 llvm::vfs::InMemoryFileSystem *MemFS) {
d0k39bdfea2015-10-06 10:04:08 +0000169 MemFS->addFileNoOwn(FileName, 0, Source);
harlanhaskinsb0308d52019-08-01 21:31:56 +0000170 auto File = Files.getFile(FileName);
171 return Sources.createFileID(File ? *File : nullptr, SourceLocation(),
d0k39bdfea2015-10-06 10:04:08 +0000172 SrcMgr::C_User);
djasper7f663602013-03-20 09:53:23 +0000173}
174
alexfh6e701792013-07-18 22:54:56 +0000175// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000176// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000177static bool parseLineRange(StringRef Input, unsigned &FromLine,
178 unsigned &ToLine) {
179 std::pair<StringRef, StringRef> LineRange = Input.split(':');
180 return LineRange.first.getAsInteger(0, FromLine) ||
181 LineRange.second.getAsInteger(0, ToLine);
182}
183
djasper578d2032015-09-23 08:30:47 +0000184static bool fillRanges(MemoryBuffer *Code,
185 std::vector<tooling::Range> &Ranges) {
jdevlieghere96636aa2018-10-10 13:27:25 +0000186 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
187 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000188 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper578d2032015-09-23 08:30:47 +0000189 DiagnosticsEngine Diagnostics(
190 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
191 new DiagnosticOptions);
192 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000193 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
194 InMemoryFileSystem.get());
alexfh6e701792013-07-18 22:54:56 +0000195 if (!LineRanges.empty()) {
196 if (!Offsets.empty() || !Lengths.empty()) {
djasper9e191b42015-11-23 08:36:35 +0000197 errs() << "error: cannot use -lines with -offset/-length\n";
alexfh6e701792013-07-18 22:54:56 +0000198 return true;
199 }
200
201 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
202 unsigned FromLine, ToLine;
203 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
djasper9e191b42015-11-23 08:36:35 +0000204 errs() << "error: invalid <start line>:<end line> pair\n";
alexfh6e701792013-07-18 22:54:56 +0000205 return true;
206 }
207 if (FromLine > ToLine) {
djasper9e191b42015-11-23 08:36:35 +0000208 errs() << "error: start line should be less than end line\n";
alexfh6e701792013-07-18 22:54:56 +0000209 return true;
210 }
211 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
212 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
213 if (Start.isInvalid() || End.isInvalid())
214 return true;
djasper578d2032015-09-23 08:30:47 +0000215 unsigned Offset = Sources.getFileOffset(Start);
216 unsigned Length = Sources.getFileOffset(End) - Offset;
217 Ranges.push_back(tooling::Range(Offset, Length));
alexfh6e701792013-07-18 22:54:56 +0000218 }
219 return false;
djasper7f663602013-03-20 09:53:23 +0000220 }
alexfh6e701792013-07-18 22:54:56 +0000221
djasper7f663602013-03-20 09:53:23 +0000222 if (Offsets.empty())
223 Offsets.push_back(0);
224 if (Offsets.size() != Lengths.size() &&
225 !(Offsets.size() == 1 && Lengths.empty())) {
djasper9e191b42015-11-23 08:36:35 +0000226 errs() << "error: number of -offset and -length arguments must match.\n";
alexfh4df43642013-04-24 12:46:44 +0000227 return true;
djasper7f663602013-03-20 09:53:23 +0000228 }
alexfh4df43642013-04-24 12:46:44 +0000229 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
230 if (Offsets[i] >= Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000231 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
alexfh4df43642013-04-24 12:46:44 +0000232 return true;
233 }
djasper7f663602013-03-20 09:53:23 +0000234 SourceLocation Start =
235 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
236 SourceLocation End;
237 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000238 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000239 errs() << "error: invalid length " << Lengths[i]
240 << ", offset + length (" << Offsets[i] + Lengths[i]
241 << ") is outside the file.\n";
alexfh4df43642013-04-24 12:46:44 +0000242 return true;
243 }
djasper7f663602013-03-20 09:53:23 +0000244 End = Start.getLocWithOffset(Lengths[i]);
245 } else {
246 End = Sources.getLocForEndOfFile(ID);
247 }
djasper578d2032015-09-23 08:30:47 +0000248 unsigned Offset = Sources.getFileOffset(Start);
249 unsigned Length = Sources.getFileOffset(End) - Offset;
250 Ranges.push_back(tooling::Range(Offset, Length));
djasper7f663602013-03-20 09:53:23 +0000251 }
alexfh6e701792013-07-18 22:54:56 +0000252 return false;
253}
254
klimek82392d72013-12-03 09:46:06 +0000255static void outputReplacementXML(StringRef Text) {
djasperc8a1a082015-10-15 18:39:31 +0000256 // FIXME: When we sort includes, we need to make sure the stream is correct
257 // utf-8.
klimek82392d72013-12-03 09:46:06 +0000258 size_t From = 0;
259 size_t Index;
djasperc8a1a082015-10-15 18:39:31 +0000260 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
djasper9e191b42015-11-23 08:36:35 +0000261 outs() << Text.substr(From, Index - From);
klimek82392d72013-12-03 09:46:06 +0000262 switch (Text[Index]) {
263 case '\n':
djasper9e191b42015-11-23 08:36:35 +0000264 outs() << "&#10;";
klimek82392d72013-12-03 09:46:06 +0000265 break;
266 case '\r':
djasper9e191b42015-11-23 08:36:35 +0000267 outs() << "&#13;";
klimek82392d72013-12-03 09:46:06 +0000268 break;
djasperc8a1a082015-10-15 18:39:31 +0000269 case '<':
djasper9e191b42015-11-23 08:36:35 +0000270 outs() << "&lt;";
djasperc8a1a082015-10-15 18:39:31 +0000271 break;
272 case '&':
djasper9e191b42015-11-23 08:36:35 +0000273 outs() << "&amp;";
djasperc8a1a082015-10-15 18:39:31 +0000274 break;
klimek82392d72013-12-03 09:46:06 +0000275 default:
276 llvm_unreachable("Unexpected character encountered!");
277 }
278 From = Index + 1;
279 }
djasper9e191b42015-11-23 08:36:35 +0000280 outs() << Text.substr(From);
klimek82392d72013-12-03 09:46:06 +0000281}
282
djasper578d2032015-09-23 08:30:47 +0000283static void outputReplacementsXML(const Replacements &Replaces) {
284 for (const auto &R : Replaces) {
285 outs() << "<replacement "
286 << "offset='" << R.getOffset() << "' "
287 << "length='" << R.getLength() << "'>";
288 outputReplacementXML(R.getReplacementText());
289 outs() << "</replacement>\n";
290 }
291}
292
paulhoadf40d1f42019-10-13 14:51:45 +0000293// If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
294// nullptr.
295static const char *getInValidBOM(StringRef BufStr) {
296 // Check to see if the buffer has a UTF Byte Order Mark (BOM).
297 // We only support UTF-8 with and without a BOM right now. See
298 // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
299 // for more information.
300 const char *InvalidBOM =
301 llvm::StringSwitch<const char *>(BufStr)
302 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
303 "UTF-32 (BE)")
304 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
305 "UTF-32 (LE)")
306 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
307 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
308 .StartsWith("\x2B\x2F\x76", "UTF-7")
309 .StartsWith("\xF7\x64\x4C", "UTF-1")
310 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
311 .StartsWith("\x0E\xFE\xFF", "SCSU")
312 .StartsWith("\xFB\xEE\x28", "BOCU-1")
313 .StartsWith("\x84\x31\x95\x33", "GB-18030")
314 .Default(nullptr);
315 return InvalidBOM;
316}
317
318static bool
319emitReplacementWarnings(const Replacements &Replaces, StringRef AssumedFileName,
320 const std::unique_ptr<llvm::MemoryBuffer> &Code) {
321 if (Replaces.empty()) {
322 return false;
323 }
324
325 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
326 DiagOpts->ShowColors = (ShowColors && !NoShowColors);
327
328 TextDiagnosticPrinter *DiagsBuffer =
329 new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts, false);
330
331 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
332 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
333 new DiagnosticsEngine(DiagID, &*DiagOpts, DiagsBuffer));
334
335 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
336 new llvm::vfs::InMemoryFileSystem);
337 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
338 SourceManager Sources(*Diags, Files);
339 FileID FileID = createInMemoryFile(AssumedFileName, Code.get(), Sources,
340 Files, InMemoryFileSystem.get());
341
342 const unsigned ID = Diags->getCustomDiagID(
343 WarningsAsErrors ? clang::DiagnosticsEngine::Error
344 : clang::DiagnosticsEngine::Warning,
345 "code should be clang-formatted [-Wclang-format-violations]");
346
347 unsigned Errors = 0;
348 DiagsBuffer->BeginSourceFile(LangOptions(), nullptr);
349 if (WarnFormat && !NoWarnFormat) {
350 for (const auto &R : Replaces) {
351 Diags->Report(
352 Sources.getLocForStartOfFile(FileID).getLocWithOffset(R.getOffset()),
353 ID);
354 Errors++;
355 if (ErrorLimit && Errors >= ErrorLimit)
356 break;
357 }
358 }
359 DiagsBuffer->EndSourceFile();
360 return WarningsAsErrors;
361}
362
363static void outputXML(const Replacements &Replaces,
364 const Replacements &FormatChanges,
365 const FormattingAttemptStatus &Status,
366 const cl::opt<unsigned> &Cursor,
367 unsigned CursorPosition) {
368 outs() << "<?xml version='1.0'?>\n<replacements "
369 "xml:space='preserve' incomplete_format='"
370 << (Status.FormatComplete ? "false" : "true") << "'";
371 if (!Status.FormatComplete)
372 outs() << " line='" << Status.Line << "'";
373 outs() << ">\n";
374 if (Cursor.getNumOccurrences() != 0)
375 outs() << "<cursor>" << FormatChanges.getShiftedCodePosition(CursorPosition)
376 << "</cursor>\n";
377
378 outputReplacementsXML(Replaces);
379 outs() << "</replacements>\n";
380}
381
alexfh6e701792013-07-18 22:54:56 +0000382// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000383static bool format(StringRef FileName) {
nicoc09c8de2017-02-27 22:59:58 +0000384 if (!OutputXML && Inplace && FileName == "-") {
385 errs() << "error: cannot use -i when reading from stdin.\n";
386 return false;
387 }
388 // On Windows, overwriting a file with an open file mapping doesn't work,
389 // so read the whole file into memory when formatting in-place.
rafael54c71a82014-07-06 17:43:24 +0000390 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
paulhoadb125d502019-10-07 16:53:35 +0000391 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName)
392 : MemoryBuffer::getFileOrSTDIN(FileName);
rafael54c71a82014-07-06 17:43:24 +0000393 if (std::error_code EC = CodeOrErr.getError()) {
djasper9e191b42015-11-23 08:36:35 +0000394 errs() << EC.message() << "\n";
alexfh6e701792013-07-18 22:54:56 +0000395 return true;
396 }
rafael54c71a82014-07-06 17:43:24 +0000397 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
alexfh6e701792013-07-18 22:54:56 +0000398 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000399 return false; // Empty files are formatted correctly.
owenpan77a4b6d2019-05-08 14:11:12 +0000400
owenpan77a4b6d2019-05-08 14:11:12 +0000401 StringRef BufStr = Code->getBuffer();
paulhoadf40d1f42019-10-13 14:51:45 +0000402
403 const char *InvalidBOM = getInValidBOM(BufStr);
owenpan77a4b6d2019-05-08 14:11:12 +0000404
405 if (InvalidBOM) {
406 errs() << "error: encoding with unsupported byte order mark \""
407 << InvalidBOM << "\" detected";
408 if (FileName != "-")
409 errs() << " in file '" << FileName << "'";
410 errs() << ".\n";
411 return true;
412 }
413
djasper578d2032015-09-23 08:30:47 +0000414 std::vector<tooling::Range> Ranges;
415 if (fillRanges(Code.get(), Ranges))
alexfh6e701792013-07-18 22:54:56 +0000416 return true;
djasper262cb332015-09-29 07:53:08 +0000417 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
amaioranoa7d62362017-01-17 00:12:27 +0000418
419 llvm::Expected<FormatStyle> FormatStyle =
djasper4be7a6c2016-12-12 12:42:29 +0000420 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
amaioranoa7d62362017-01-17 00:12:27 +0000421 if (!FormatStyle) {
422 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
423 return true;
424 }
mprobstf9dd41b2017-01-27 09:09:11 +0000425
djasper71631c22015-11-16 12:38:56 +0000426 if (SortIncludes.getNumOccurrences() != 0)
amaioranoa7d62362017-01-17 00:12:27 +0000427 FormatStyle->SortIncludes = SortIncludes;
djasper9e191b42015-11-23 08:36:35 +0000428 unsigned CursorPosition = Cursor;
amaioranoa7d62362017-01-17 00:12:27 +0000429 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
djasper9e191b42015-11-23 08:36:35 +0000430 AssumedFileName, &CursorPosition);
ioeric2b036d32016-07-11 13:53:12 +0000431 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
432 if (!ChangedCode) {
433 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
434 return true;
435 }
ioeric51590652016-08-10 09:32:23 +0000436 // Get new affected ranges after sorting `#includes`.
437 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
krasimir0653eee2017-04-21 14:35:20 +0000438 FormattingAttemptStatus Status;
paulhoadb125d502019-10-07 16:53:35 +0000439 Replacements FormatChanges =
440 reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status);
ioeric531dffd2016-08-01 10:16:37 +0000441 Replaces = Replaces.merge(FormatChanges);
paulhoadf40d1f42019-10-13 14:51:45 +0000442 if (OutputXML || DryRun) {
443 if (DryRun) {
444 return emitReplacementWarnings(Replaces, AssumedFileName, Code);
445 } else {
446 outputXML(Replaces, FormatChanges, Status, Cursor, CursorPosition);
447 }
djasper7f663602013-03-20 09:53:23 +0000448 } else {
jdevlieghere96636aa2018-10-10 13:27:25 +0000449 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
450 new llvm::vfs::InMemoryFileSystem);
d0k39bdfea2015-10-06 10:04:08 +0000451 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper44bf2ae2015-09-30 13:59:29 +0000452 DiagnosticsEngine Diagnostics(
453 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
454 new DiagnosticOptions);
455 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000456 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
457 InMemoryFileSystem.get());
djasper44bf2ae2015-09-30 13:59:29 +0000458 Rewriter Rewrite(Sources, LangOptions());
459 tooling::applyAllReplacements(Replaces, Rewrite);
djasper7f663602013-03-20 09:53:23 +0000460 if (Inplace) {
nicoc09c8de2017-02-27 22:59:58 +0000461 if (Rewrite.overwriteChangedFiles())
djasper44bf2ae2015-09-30 13:59:29 +0000462 return true;
djasper7f663602013-03-20 09:53:23 +0000463 } else {
krasimir0653eee2017-04-21 14:35:20 +0000464 if (Cursor.getNumOccurrences() != 0) {
grosser7e070d52015-05-08 21:34:09 +0000465 outs() << "{ \"Cursor\": "
ioeric531dffd2016-08-01 10:16:37 +0000466 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper0c6c9472015-05-10 07:47:19 +0000467 << ", \"IncompleteFormat\": "
krasimir0653eee2017-04-21 14:35:20 +0000468 << (Status.FormatComplete ? "false" : "true");
469 if (!Status.FormatComplete)
470 outs() << ", \"Line\": " << Status.Line;
471 outs() << " }\n";
472 }
djasper44bf2ae2015-09-30 13:59:29 +0000473 Rewrite.getEditBuffer(ID).write(outs());
djasper7f663602013-03-20 09:53:23 +0000474 }
475 }
alexfh4df43642013-04-24 12:46:44 +0000476 return false;
djasper7f663602013-03-20 09:53:23 +0000477}
478
paulhoadb125d502019-10-07 16:53:35 +0000479} // namespace format
480} // namespace clang
djasper7f663602013-03-20 09:53:23 +0000481
dim00bed782017-06-06 21:54:21 +0000482static void PrintVersion(raw_ostream &OS) {
nico436d02f2014-01-07 16:27:35 +0000483 OS << clang::getClangToolFullVersion("clang-format") << '\n';
484}
485
paulhoadf40d1f42019-10-13 14:51:45 +0000486// Dump the configuration.
487static int dumpConfig() {
488 StringRef FileName;
489 std::unique_ptr<llvm::MemoryBuffer> Code;
490 if (FileNames.empty()) {
491 // We can't read the code to detect the language if there's no
492 // file name, so leave Code empty here.
493 FileName = AssumeFileName;
494 } else {
495 // Read in the code in case the filename alone isn't enough to
496 // detect the language.
497 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
498 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
499 if (std::error_code EC = CodeOrErr.getError()) {
500 llvm::errs() << EC.message() << "\n";
501 return 1;
502 }
503 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
504 Code = std::move(CodeOrErr.get());
505 }
506 llvm::Expected<clang::format::FormatStyle> FormatStyle =
507 clang::format::getStyle(Style, FileName, FallbackStyle,
508 Code ? Code->getBuffer() : "");
509 if (!FormatStyle) {
510 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
511 return 1;
512 }
513 std::string Config = clang::format::configurationAsText(*FormatStyle);
514 outs() << Config << "\n";
515 return 0;
516}
517
djasper7f663602013-03-20 09:53:23 +0000518int main(int argc, const char **argv) {
ruiucdaacac2018-04-13 20:57:57 +0000519 llvm::InitLLVM X(argc, argv);
alexfh9b1d30f2018-03-26 13:54:17 +0000520
cbienemanc9f3db62015-01-21 23:26:11 +0000521 cl::HideUnrelatedOptions(ClangFormatCategory);
alexfh725a9f72013-05-10 18:12:00 +0000522
nico436d02f2014-01-07 16:27:35 +0000523 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000524 cl::ParseCommandLineOptions(
ruiucdaacac2018-04-13 20:57:57 +0000525 argc, argv,
paulhoad3e050fe2019-03-21 13:09:22 +0000526 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000527 "If no arguments are specified, it formats the code from standard input\n"
528 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000529 "If <file>s are given, it reformats the files. If -i is specified\n"
530 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000531 "result is written to the standard output.\n");
532
rafaelf94a89d2017-09-08 00:01:26 +0000533 if (Help) {
djasper7f663602013-03-20 09:53:23 +0000534 cl::PrintHelpMessage();
rafaelf94a89d2017-09-08 00:01:26 +0000535 return 0;
536 }
alexfh4df43642013-04-24 12:46:44 +0000537
alexfh59883452013-05-10 11:56:10 +0000538 if (DumpConfig) {
paulhoadf40d1f42019-10-13 14:51:45 +0000539 return dumpConfig();
alexfh59883452013-05-10 11:56:10 +0000540 }
541
alexfh4df43642013-04-24 12:46:44 +0000542 bool Error = false;
sylvestrea23fc482017-08-12 15:15:10 +0000543 if (FileNames.empty()) {
alexfh4df43642013-04-24 12:46:44 +0000544 Error = clang::format::format("-");
sylvestrea23fc482017-08-12 15:15:10 +0000545 return Error ? 1 : 0;
546 }
paulhoadb125d502019-10-07 16:53:35 +0000547 if (FileNames.size() != 1 &&
548 (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
sylvestrea23fc482017-08-12 15:15:10 +0000549 errs() << "error: -offset, -length and -lines can only be used for "
550 "single file.\n";
551 return 1;
552 }
553 for (const auto &FileName : FileNames) {
554 if (Verbose)
555 errs() << "Formatting " << FileName << "\n";
556 Error |= clang::format::format(FileName);
alexfh4df43642013-04-24 12:46:44 +0000557 }
558 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000559}