blob: 3d6fef0d0994303d30f8b0057679ce348a79856f [file] [log] [blame]
djasper7f663602013-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"
nico436d02f2014-01-07 16:27:35 +000020#include "clang/Basic/Version.h"
djasper7f663602013-03-20 09:53:23 +000021#include "clang/Format/Format.h"
chandlercd56704b2014-01-07 11:51:46 +000022#include "llvm/ADT/StringMap.h"
djasper1e1687b2014-10-29 22:42:53 +000023#include "llvm/Support/CommandLine.h"
alexfh59883452013-05-10 11:56:10 +000024#include "llvm/Support/Debug.h"
djasper7f663602013-03-20 09:53:23 +000025#include "llvm/Support/FileSystem.h"
26#include "llvm/Support/Signals.h"
27
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>
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));
alexfh725a9f72013-05-10 18:12:00 +000062static cl::opt<std::string>
63 Style("style",
revane4d118692013-09-30 13:31:48 +000064 cl::desc(clang::format::StyleOptionHelpDescription),
chandlerce6992fd2013-09-02 07:42:02 +000065 cl::init("file"), cl::cat(ClangFormatCategory));
alexfh7e0adcf2013-12-02 15:21:38 +000066static cl::opt<std::string>
67FallbackStyle("fallback-style",
alexfh07ea1ab2014-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"
djasper077c43c2014-05-22 15:12:22 +000071 "file to use.\n"
72 "Use -fallback-style=none to skip formatting."),
alexfh7e0adcf2013-12-02 15:21:38 +000073 cl::init("LLVM"), 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."),
djasper05848282013-09-13 13:40:24 +000080 cl::cat(ClangFormatCategory));
81
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
djasper578d2032015-09-23 08:30:47 +0000100static cl::opt<bool> SortIncludes("sort-includes",
101 cl::desc("Sort touched include lines"),
102 cl::cat(ClangFormatCategory));
103
alexfh725a9f72013-05-10 18:12:00 +0000104static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
105 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000106
107namespace clang {
108namespace format {
109
dblaikieaa159c52014-06-27 17:40:03 +0000110static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
djasper7f663602013-03-20 09:53:23 +0000111 SourceManager &Sources, FileManager &Files) {
112 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
113 FileName,
114 Source->getBufferSize(), 0);
115 Sources.overrideFileContents(Entry, Source, true);
116 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
117}
118
alexfh6e701792013-07-18 22:54:56 +0000119// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000120// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000121static bool parseLineRange(StringRef Input, unsigned &FromLine,
122 unsigned &ToLine) {
123 std::pair<StringRef, StringRef> LineRange = Input.split(':');
124 return LineRange.first.getAsInteger(0, FromLine) ||
125 LineRange.second.getAsInteger(0, ToLine);
126}
127
djasper578d2032015-09-23 08:30:47 +0000128static bool fillRanges(MemoryBuffer *Code,
129 std::vector<tooling::Range> &Ranges) {
130 FileManager Files((FileSystemOptions()));
131 DiagnosticsEngine Diagnostics(
132 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
133 new DiagnosticOptions);
134 SourceManager Sources(Diagnostics, Files);
135 FileID ID = createInMemoryFile("-", Code, Sources, Files);
alexfh6e701792013-07-18 22:54:56 +0000136 if (!LineRanges.empty()) {
137 if (!Offsets.empty() || !Lengths.empty()) {
138 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
139 return true;
140 }
141
142 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
143 unsigned FromLine, ToLine;
144 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
145 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
146 return true;
147 }
148 if (FromLine > ToLine) {
149 llvm::errs() << "error: start line should be less than end line\n";
150 return true;
151 }
152 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
153 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
154 if (Start.isInvalid() || End.isInvalid())
155 return true;
djasper578d2032015-09-23 08:30:47 +0000156 unsigned Offset = Sources.getFileOffset(Start);
157 unsigned Length = Sources.getFileOffset(End) - Offset;
158 Ranges.push_back(tooling::Range(Offset, Length));
alexfh6e701792013-07-18 22:54:56 +0000159 }
160 return false;
djasper7f663602013-03-20 09:53:23 +0000161 }
alexfh6e701792013-07-18 22:54:56 +0000162
djasper7f663602013-03-20 09:53:23 +0000163 if (Offsets.empty())
164 Offsets.push_back(0);
165 if (Offsets.size() != Lengths.size() &&
166 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000167 llvm::errs()
168 << "error: number of -offset and -length arguments must match.\n";
169 return true;
djasper7f663602013-03-20 09:53:23 +0000170 }
alexfh4df43642013-04-24 12:46:44 +0000171 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
172 if (Offsets[i] >= Code->getBufferSize()) {
173 llvm::errs() << "error: offset " << Offsets[i]
174 << " is outside the file\n";
175 return true;
176 }
djasper7f663602013-03-20 09:53:23 +0000177 SourceLocation Start =
178 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
179 SourceLocation End;
180 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000181 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
182 llvm::errs() << "error: invalid length " << Lengths[i]
183 << ", offset + length (" << Offsets[i] + Lengths[i]
184 << ") is outside the file.\n";
185 return true;
186 }
djasper7f663602013-03-20 09:53:23 +0000187 End = Start.getLocWithOffset(Lengths[i]);
188 } else {
189 End = Sources.getLocForEndOfFile(ID);
190 }
djasper578d2032015-09-23 08:30:47 +0000191 unsigned Offset = Sources.getFileOffset(Start);
192 unsigned Length = Sources.getFileOffset(End) - Offset;
193 Ranges.push_back(tooling::Range(Offset, Length));
djasper7f663602013-03-20 09:53:23 +0000194 }
alexfh6e701792013-07-18 22:54:56 +0000195 return false;
196}
197
klimek82392d72013-12-03 09:46:06 +0000198static void outputReplacementXML(StringRef Text) {
199 size_t From = 0;
200 size_t Index;
201 while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
202 llvm::outs() << Text.substr(From, Index - From);
203 switch (Text[Index]) {
204 case '\n':
205 llvm::outs() << "&#10;";
206 break;
207 case '\r':
208 llvm::outs() << "&#13;";
209 break;
210 default:
211 llvm_unreachable("Unexpected character encountered!");
212 }
213 From = Index + 1;
214 }
215 llvm::outs() << Text.substr(From);
216}
217
djasper578d2032015-09-23 08:30:47 +0000218static void outputReplacementsXML(const Replacements &Replaces) {
219 for (const auto &R : Replaces) {
220 outs() << "<replacement "
221 << "offset='" << R.getOffset() << "' "
222 << "length='" << R.getLength() << "'>";
223 outputReplacementXML(R.getReplacementText());
224 outs() << "</replacement>\n";
225 }
226}
227
alexfh6e701792013-07-18 22:54:56 +0000228// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000229static bool format(StringRef FileName) {
rafael54c71a82014-07-06 17:43:24 +0000230 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
231 MemoryBuffer::getFileOrSTDIN(FileName);
232 if (std::error_code EC = CodeOrErr.getError()) {
233 llvm::errs() << EC.message() << "\n";
alexfh6e701792013-07-18 22:54:56 +0000234 return true;
235 }
rafael54c71a82014-07-06 17:43:24 +0000236 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
alexfh6e701792013-07-18 22:54:56 +0000237 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000238 return false; // Empty files are formatted correctly.
djasper578d2032015-09-23 08:30:47 +0000239 std::vector<tooling::Range> Ranges;
240 if (fillRanges(Code.get(), Ranges))
alexfh6e701792013-07-18 22:54:56 +0000241 return true;
djasper262cb332015-09-29 07:53:08 +0000242 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
243 FormatStyle FormatStyle = getStyle(Style, AssumedFileName, FallbackStyle);
djasper578d2032015-09-23 08:30:47 +0000244 Replacements Replaces;
245 std::string ChangedCode;
246 if (SortIncludes) {
247 Replaces =
djasper262cb332015-09-29 07:53:08 +0000248 sortIncludes(FormatStyle, Code->getBuffer(), Ranges, AssumedFileName);
djasper578d2032015-09-23 08:30:47 +0000249 ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
250 for (const auto &R : Replaces)
251 Ranges.push_back({R.getOffset(), R.getLength()});
252 } else {
253 ChangedCode = Code->getBuffer().str();
254 }
255
djasper0c6c9472015-05-10 07:47:19 +0000256 bool IncompleteFormat = false;
djasper578d2032015-09-23 08:30:47 +0000257 Replaces = tooling::mergeReplacements(
258 Replaces,
259 reformat(FormatStyle, ChangedCode, Ranges, FileName, &IncompleteFormat));
djasper7f663602013-03-20 09:53:23 +0000260 if (OutputXML) {
djasper0c6c9472015-05-10 07:47:19 +0000261 llvm::outs() << "<?xml version='1.0'?>\n<replacements "
262 "xml:space='preserve' incomplete_format='"
263 << (IncompleteFormat ? "true" : "false") << "'>\n";
klimekbf977882015-01-09 10:03:47 +0000264 if (Cursor.getNumOccurrences() != 0)
265 llvm::outs() << "<cursor>"
266 << tooling::shiftedCodePosition(Replaces, Cursor)
267 << "</cursor>\n";
djasper0c6c9472015-05-10 07:47:19 +0000268
djasper578d2032015-09-23 08:30:47 +0000269 outputReplacementsXML(Replaces);
djasper7f663602013-03-20 09:53:23 +0000270 llvm::outs() << "</replacements>\n";
271 } else {
djasper578d2032015-09-23 08:30:47 +0000272 std::string FormattedCode =
273 applyAllReplacements(Code->getBuffer(), Replaces);
djasper7f663602013-03-20 09:53:23 +0000274 if (Inplace) {
djasper529feb12015-05-06 11:56:54 +0000275 if (FileName == "-")
276 llvm::errs() << "error: cannot use -i when reading from stdin.\n";
djasper578d2032015-09-23 08:30:47 +0000277 else {
278 std::error_code EC;
279 raw_fd_ostream FileOut(FileName, EC, llvm::sys::fs::F_Text);
280 if (EC) {
281 llvm::errs() << EC.message() << "\n";
282 return true;
283 }
284 FileOut << FormattedCode;
285 }
djasper7f663602013-03-20 09:53:23 +0000286 } else {
djasper898b4f72013-05-21 14:21:46 +0000287 if (Cursor.getNumOccurrences() != 0)
grosser7e070d52015-05-08 21:34:09 +0000288 outs() << "{ \"Cursor\": "
djasper0c6c9472015-05-10 07:47:19 +0000289 << tooling::shiftedCodePosition(Replaces, Cursor)
290 << ", \"IncompleteFormat\": "
291 << (IncompleteFormat ? "true" : "false") << " }\n";
djasper578d2032015-09-23 08:30:47 +0000292 outs() << FormattedCode;
djasper7f663602013-03-20 09:53:23 +0000293 }
294 }
alexfh4df43642013-04-24 12:46:44 +0000295 return false;
djasper7f663602013-03-20 09:53:23 +0000296}
297
298} // namespace format
299} // namespace clang
300
nico436d02f2014-01-07 16:27:35 +0000301static void PrintVersion() {
302 raw_ostream &OS = outs();
303 OS << clang::getClangToolFullVersion("clang-format") << '\n';
304}
305
djasper7f663602013-03-20 09:53:23 +0000306int main(int argc, const char **argv) {
307 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000308
cbienemanc9f3db62015-01-21 23:26:11 +0000309 cl::HideUnrelatedOptions(ClangFormatCategory);
alexfh725a9f72013-05-10 18:12:00 +0000310
nico436d02f2014-01-07 16:27:35 +0000311 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000312 cl::ParseCommandLineOptions(
313 argc, argv,
314 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000315 "If no arguments are specified, it formats the code from standard input\n"
316 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000317 "If <file>s are given, it reformats the files. If -i is specified\n"
318 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000319 "result is written to the standard output.\n");
320
djasper7f663602013-03-20 09:53:23 +0000321 if (Help)
322 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000323
alexfh59883452013-05-10 11:56:10 +0000324 if (DumpConfig) {
revane4d118692013-09-30 13:31:48 +0000325 std::string Config =
326 clang::format::configurationAsText(clang::format::getStyle(
djasper262cb332015-09-29 07:53:08 +0000327 Style, FileNames.empty() ? AssumeFileName : FileNames[0],
alexfh7e0adcf2013-12-02 15:21:38 +0000328 FallbackStyle));
alexfh59883452013-05-10 11:56:10 +0000329 llvm::outs() << Config << "\n";
330 return 0;
331 }
332
alexfh4df43642013-04-24 12:46:44 +0000333 bool Error = false;
334 switch (FileNames.size()) {
335 case 0:
336 Error = clang::format::format("-");
337 break;
338 case 1:
339 Error = clang::format::format(FileNames[0]);
340 break;
341 default:
alexfh6e701792013-07-18 22:54:56 +0000342 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
343 llvm::errs() << "error: -offset, -length and -lines can only be used for "
alexfh4df43642013-04-24 12:46:44 +0000344 "single file.\n";
345 return 1;
346 }
347 for (unsigned i = 0; i < FileNames.size(); ++i)
348 Error |= clang::format::format(FileNames[i]);
349 break;
350 }
351 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000352}