blob: d26659d12776a86f761c1bd430ccef408c6a3d44 [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"
22#include "clang/Lex/Lexer.h"
23#include "clang/Rewrite/Core/Rewriter.h"
chandlercd56704b2014-01-07 11:51:46 +000024#include "llvm/ADT/StringMap.h"
alexfh59883452013-05-10 11:56:10 +000025#include "llvm/Support/Debug.h"
djasper7f663602013-03-20 09:53:23 +000026#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/Signals.h"
28
29using namespace llvm;
30
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"
71 "file to use."),
alexfh7e0adcf2013-12-02 15:21:38 +000072 cl::init("LLVM"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000073
74static cl::opt<std::string>
75AssumeFilename("assume-filename",
76 cl::desc("When reading from stdin, clang-format assumes this\n"
77 "filename to look for a style config file (with\n"
78 "-style=file)."),
79 cl::cat(ClangFormatCategory));
80
alexfh725a9f72013-05-10 18:12:00 +000081static cl::opt<bool> Inplace("i",
82 cl::desc("Inplace edit <file>s, if specified."),
83 cl::cat(ClangFormatCategory));
84
85static cl::opt<bool> OutputXML("output-replacements-xml",
86 cl::desc("Output replacements as XML."),
87 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000088static cl::opt<bool>
89 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000090 cl::desc("Dump configuration options to stdout and exit.\n"
91 "Can be used with -style option."),
92 cl::cat(ClangFormatCategory));
djasperd0252b72013-05-21 12:21:39 +000093static cl::opt<unsigned>
94 Cursor("cursor",
alexfhb5b43022013-09-02 15:30:26 +000095 cl::desc("The position of the cursor when invoking\n"
96 "clang-format from an editor integration"),
djasperd0252b72013-05-21 12:21:39 +000097 cl::init(0), cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000098
alexfh725a9f72013-05-10 18:12:00 +000099static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
100 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000101
102namespace clang {
103namespace format {
104
105static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
106 SourceManager &Sources, FileManager &Files) {
107 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
108 FileName,
109 Source->getBufferSize(), 0);
110 Sources.overrideFileContents(Entry, Source, true);
111 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
112}
113
alexfh6e701792013-07-18 22:54:56 +0000114// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000115// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000116static bool parseLineRange(StringRef Input, unsigned &FromLine,
117 unsigned &ToLine) {
118 std::pair<StringRef, StringRef> LineRange = Input.split(':');
119 return LineRange.first.getAsInteger(0, FromLine) ||
120 LineRange.second.getAsInteger(0, ToLine);
121}
122
123static bool fillRanges(SourceManager &Sources, FileID ID,
124 const MemoryBuffer *Code,
125 std::vector<CharSourceRange> &Ranges) {
126 if (!LineRanges.empty()) {
127 if (!Offsets.empty() || !Lengths.empty()) {
128 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
129 return true;
130 }
131
132 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
133 unsigned FromLine, ToLine;
134 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
135 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
136 return true;
137 }
138 if (FromLine > ToLine) {
139 llvm::errs() << "error: start line should be less than end line\n";
140 return true;
141 }
142 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
143 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
144 if (Start.isInvalid() || End.isInvalid())
145 return true;
146 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
147 }
148 return false;
djasper7f663602013-03-20 09:53:23 +0000149 }
alexfh6e701792013-07-18 22:54:56 +0000150
djasper7f663602013-03-20 09:53:23 +0000151 if (Offsets.empty())
152 Offsets.push_back(0);
153 if (Offsets.size() != Lengths.size() &&
154 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000155 llvm::errs()
156 << "error: number of -offset and -length arguments must match.\n";
157 return true;
djasper7f663602013-03-20 09:53:23 +0000158 }
alexfh4df43642013-04-24 12:46:44 +0000159 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
160 if (Offsets[i] >= Code->getBufferSize()) {
161 llvm::errs() << "error: offset " << Offsets[i]
162 << " is outside the file\n";
163 return true;
164 }
djasper7f663602013-03-20 09:53:23 +0000165 SourceLocation Start =
166 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
167 SourceLocation End;
168 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000169 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
170 llvm::errs() << "error: invalid length " << Lengths[i]
171 << ", offset + length (" << Offsets[i] + Lengths[i]
172 << ") is outside the file.\n";
173 return true;
174 }
djasper7f663602013-03-20 09:53:23 +0000175 End = Start.getLocWithOffset(Lengths[i]);
176 } else {
177 End = Sources.getLocForEndOfFile(ID);
178 }
179 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
180 }
alexfh6e701792013-07-18 22:54:56 +0000181 return false;
182}
183
klimek82392d72013-12-03 09:46:06 +0000184static void outputReplacementXML(StringRef Text) {
185 size_t From = 0;
186 size_t Index;
187 while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
188 llvm::outs() << Text.substr(From, Index - From);
189 switch (Text[Index]) {
190 case '\n':
191 llvm::outs() << "&#10;";
192 break;
193 case '\r':
194 llvm::outs() << "&#13;";
195 break;
196 default:
197 llvm_unreachable("Unexpected character encountered!");
198 }
199 From = Index + 1;
200 }
201 llvm::outs() << Text.substr(From);
202}
203
alexfh6e701792013-07-18 22:54:56 +0000204// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000205static bool format(StringRef FileName) {
alexfh6e701792013-07-18 22:54:56 +0000206 FileManager Files((FileSystemOptions()));
207 DiagnosticsEngine Diagnostics(
208 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
209 new DiagnosticOptions);
210 SourceManager Sources(Diagnostics, Files);
ace2001ac65b3e492014-03-07 20:03:18 +0000211 std::unique_ptr<MemoryBuffer> Code;
alexfh6e701792013-07-18 22:54:56 +0000212 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
213 llvm::errs() << ec.message() << "\n";
214 return true;
215 }
216 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000217 return false; // Empty files are formatted correctly.
alexfh6e701792013-07-18 22:54:56 +0000218 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
219 std::vector<CharSourceRange> Ranges;
220 if (fillRanges(Sources, ID, Code.get(), Ranges))
221 return true;
222
alexfh7e0adcf2013-12-02 15:21:38 +0000223 FormatStyle FormatStyle = getStyle(
224 Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
alexfh943428e2013-06-28 12:51:24 +0000225 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
226 getFormattingLangOpts(FormatStyle.Standard));
227 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000228 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000229 llvm::outs()
230 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000231 for (tooling::Replacements::const_iterator I = Replaces.begin(),
232 E = Replaces.end();
233 I != E; ++I) {
234 llvm::outs() << "<replacement "
235 << "offset='" << I->getOffset() << "' "
klimek82392d72013-12-03 09:46:06 +0000236 << "length='" << I->getLength() << "'>";
237 outputReplacementXML(I->getReplacementText());
238 llvm::outs() << "</replacement>\n";
djasper7f663602013-03-20 09:53:23 +0000239 }
240 llvm::outs() << "</replacements>\n";
241 } else {
242 Rewriter Rewrite(Sources, LangOptions());
243 tooling::applyAllReplacements(Replaces, Rewrite);
244 if (Inplace) {
alp8d1b4dd2013-11-08 08:07:19 +0000245 if (Rewrite.overwriteChangedFiles())
alexfh4df43642013-04-24 12:46:44 +0000246 return true;
djasper7f663602013-03-20 09:53:23 +0000247 } else {
djasper898b4f72013-05-21 14:21:46 +0000248 if (Cursor.getNumOccurrences() != 0)
nikolaa7180442014-05-08 00:05:13 +0000249 outs() << "{ \"Cursor\": "
250 << tooling::shiftedCodePosition(Replaces, Cursor) << " }\n";
djasper7f663602013-03-20 09:53:23 +0000251 Rewrite.getEditBuffer(ID).write(outs());
252 }
253 }
alexfh4df43642013-04-24 12:46:44 +0000254 return false;
djasper7f663602013-03-20 09:53:23 +0000255}
256
257} // namespace format
258} // namespace clang
259
nico436d02f2014-01-07 16:27:35 +0000260static void PrintVersion() {
261 raw_ostream &OS = outs();
262 OS << clang::getClangToolFullVersion("clang-format") << '\n';
263}
264
djasper7f663602013-03-20 09:53:23 +0000265int main(int argc, const char **argv) {
266 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000267
268 // Hide unrelated options.
269 StringMap<cl::Option*> Options;
270 cl::getRegisteredOptions(Options);
271 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
272 I != E; ++I) {
273 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
274 I->first() != "version")
275 I->second->setHiddenFlag(cl::ReallyHidden);
276 }
277
nico436d02f2014-01-07 16:27:35 +0000278 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000279 cl::ParseCommandLineOptions(
280 argc, argv,
281 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000282 "If no arguments are specified, it formats the code from standard input\n"
283 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000284 "If <file>s are given, it reformats the files. If -i is specified\n"
285 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000286 "result is written to the standard output.\n");
287
djasper7f663602013-03-20 09:53:23 +0000288 if (Help)
289 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000290
alexfh59883452013-05-10 11:56:10 +0000291 if (DumpConfig) {
revane4d118692013-09-30 13:31:48 +0000292 std::string Config =
293 clang::format::configurationAsText(clang::format::getStyle(
alexfh7e0adcf2013-12-02 15:21:38 +0000294 Style, FileNames.empty() ? AssumeFilename : FileNames[0],
295 FallbackStyle));
alexfh59883452013-05-10 11:56:10 +0000296 llvm::outs() << Config << "\n";
297 return 0;
298 }
299
alexfh4df43642013-04-24 12:46:44 +0000300 bool Error = false;
301 switch (FileNames.size()) {
302 case 0:
303 Error = clang::format::format("-");
304 break;
305 case 1:
306 Error = clang::format::format(FileNames[0]);
307 break;
308 default:
alexfh6e701792013-07-18 22:54:56 +0000309 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
310 llvm::errs() << "error: -offset, -length and -lines can only be used for "
alexfh4df43642013-04-24 12:46:44 +0000311 "single file.\n";
312 return 1;
313 }
314 for (unsigned i = 0; i < FileNames.size(); ++i)
315 Error |= clang::format::format(FileNames[i]);
316 break;
317 }
318 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000319}