blob: 575ac7a93d8ce8ea131ebb6e2cf49312affb4dbb [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"
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>
76AssumeFilename("assume-filename",
77 cl::desc("When reading from stdin, clang-format assumes this\n"
78 "filename to look for a style config file (with\n"
79 "-style=file)."),
80 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
alexfh725a9f72013-05-10 18:12:00 +0000100static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
101 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000102
103namespace clang {
104namespace format {
105
dblaikieaa159c52014-06-27 17:40:03 +0000106static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
djasper7f663602013-03-20 09:53:23 +0000107 SourceManager &Sources, FileManager &Files) {
108 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
109 FileName,
110 Source->getBufferSize(), 0);
111 Sources.overrideFileContents(Entry, Source, true);
112 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
113}
114
alexfh6e701792013-07-18 22:54:56 +0000115// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000116// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000117static bool parseLineRange(StringRef Input, unsigned &FromLine,
118 unsigned &ToLine) {
119 std::pair<StringRef, StringRef> LineRange = Input.split(':');
120 return LineRange.first.getAsInteger(0, FromLine) ||
121 LineRange.second.getAsInteger(0, ToLine);
122}
123
124static bool fillRanges(SourceManager &Sources, FileID ID,
125 const MemoryBuffer *Code,
126 std::vector<CharSourceRange> &Ranges) {
127 if (!LineRanges.empty()) {
128 if (!Offsets.empty() || !Lengths.empty()) {
129 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
130 return true;
131 }
132
133 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
134 unsigned FromLine, ToLine;
135 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
136 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
137 return true;
138 }
139 if (FromLine > ToLine) {
140 llvm::errs() << "error: start line should be less than end line\n";
141 return true;
142 }
143 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
144 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
145 if (Start.isInvalid() || End.isInvalid())
146 return true;
147 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
148 }
149 return false;
djasper7f663602013-03-20 09:53:23 +0000150 }
alexfh6e701792013-07-18 22:54:56 +0000151
djasper7f663602013-03-20 09:53:23 +0000152 if (Offsets.empty())
153 Offsets.push_back(0);
154 if (Offsets.size() != Lengths.size() &&
155 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000156 llvm::errs()
157 << "error: number of -offset and -length arguments must match.\n";
158 return true;
djasper7f663602013-03-20 09:53:23 +0000159 }
alexfh4df43642013-04-24 12:46:44 +0000160 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
161 if (Offsets[i] >= Code->getBufferSize()) {
162 llvm::errs() << "error: offset " << Offsets[i]
163 << " is outside the file\n";
164 return true;
165 }
djasper7f663602013-03-20 09:53:23 +0000166 SourceLocation Start =
167 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
168 SourceLocation End;
169 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000170 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
171 llvm::errs() << "error: invalid length " << Lengths[i]
172 << ", offset + length (" << Offsets[i] + Lengths[i]
173 << ") is outside the file.\n";
174 return true;
175 }
djasper7f663602013-03-20 09:53:23 +0000176 End = Start.getLocWithOffset(Lengths[i]);
177 } else {
178 End = Sources.getLocForEndOfFile(ID);
179 }
180 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
181 }
alexfh6e701792013-07-18 22:54:56 +0000182 return false;
183}
184
klimek82392d72013-12-03 09:46:06 +0000185static void outputReplacementXML(StringRef Text) {
186 size_t From = 0;
187 size_t Index;
188 while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
189 llvm::outs() << Text.substr(From, Index - From);
190 switch (Text[Index]) {
191 case '\n':
192 llvm::outs() << "&#10;";
193 break;
194 case '\r':
195 llvm::outs() << "&#13;";
196 break;
197 default:
198 llvm_unreachable("Unexpected character encountered!");
199 }
200 From = Index + 1;
201 }
202 llvm::outs() << Text.substr(From);
203}
204
alexfh6e701792013-07-18 22:54:56 +0000205// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000206static bool format(StringRef FileName) {
alexfh6e701792013-07-18 22:54:56 +0000207 FileManager Files((FileSystemOptions()));
208 DiagnosticsEngine Diagnostics(
209 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
210 new DiagnosticOptions);
211 SourceManager Sources(Diagnostics, Files);
ace2001ac65b3e492014-03-07 20:03:18 +0000212 std::unique_ptr<MemoryBuffer> Code;
rafaeld94e9a62014-06-12 20:37:59 +0000213 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
alexfh6e701792013-07-18 22:54:56 +0000214 llvm::errs() << ec.message() << "\n";
215 return true;
216 }
217 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000218 return false; // Empty files are formatted correctly.
alexfh6e701792013-07-18 22:54:56 +0000219 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
220 std::vector<CharSourceRange> Ranges;
221 if (fillRanges(Sources, ID, Code.get(), Ranges))
222 return true;
223
alexfh7e0adcf2013-12-02 15:21:38 +0000224 FormatStyle FormatStyle = getStyle(
225 Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
alexfh943428e2013-06-28 12:51:24 +0000226 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
227 getFormattingLangOpts(FormatStyle.Standard));
228 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000229 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000230 llvm::outs()
231 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000232 for (tooling::Replacements::const_iterator I = Replaces.begin(),
233 E = Replaces.end();
234 I != E; ++I) {
235 llvm::outs() << "<replacement "
236 << "offset='" << I->getOffset() << "' "
klimek82392d72013-12-03 09:46:06 +0000237 << "length='" << I->getLength() << "'>";
238 outputReplacementXML(I->getReplacementText());
239 llvm::outs() << "</replacement>\n";
djasper7f663602013-03-20 09:53:23 +0000240 }
241 llvm::outs() << "</replacements>\n";
242 } else {
243 Rewriter Rewrite(Sources, LangOptions());
244 tooling::applyAllReplacements(Replaces, Rewrite);
245 if (Inplace) {
alp8d1b4dd2013-11-08 08:07:19 +0000246 if (Rewrite.overwriteChangedFiles())
alexfh4df43642013-04-24 12:46:44 +0000247 return true;
djasper7f663602013-03-20 09:53:23 +0000248 } else {
djasper898b4f72013-05-21 14:21:46 +0000249 if (Cursor.getNumOccurrences() != 0)
nikolaa7180442014-05-08 00:05:13 +0000250 outs() << "{ \"Cursor\": "
251 << tooling::shiftedCodePosition(Replaces, Cursor) << " }\n";
djasper7f663602013-03-20 09:53:23 +0000252 Rewrite.getEditBuffer(ID).write(outs());
253 }
254 }
alexfh4df43642013-04-24 12:46:44 +0000255 return false;
djasper7f663602013-03-20 09:53:23 +0000256}
257
258} // namespace format
259} // namespace clang
260
nico436d02f2014-01-07 16:27:35 +0000261static void PrintVersion() {
262 raw_ostream &OS = outs();
263 OS << clang::getClangToolFullVersion("clang-format") << '\n';
264}
265
djasper7f663602013-03-20 09:53:23 +0000266int main(int argc, const char **argv) {
267 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000268
269 // Hide unrelated options.
270 StringMap<cl::Option*> Options;
271 cl::getRegisteredOptions(Options);
272 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
273 I != E; ++I) {
274 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
275 I->first() != "version")
276 I->second->setHiddenFlag(cl::ReallyHidden);
277 }
278
nico436d02f2014-01-07 16:27:35 +0000279 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000280 cl::ParseCommandLineOptions(
281 argc, argv,
282 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000283 "If no arguments are specified, it formats the code from standard input\n"
284 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000285 "If <file>s are given, it reformats the files. If -i is specified\n"
286 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000287 "result is written to the standard output.\n");
288
djasper7f663602013-03-20 09:53:23 +0000289 if (Help)
290 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000291
alexfh59883452013-05-10 11:56:10 +0000292 if (DumpConfig) {
revane4d118692013-09-30 13:31:48 +0000293 std::string Config =
294 clang::format::configurationAsText(clang::format::getStyle(
alexfh7e0adcf2013-12-02 15:21:38 +0000295 Style, FileNames.empty() ? AssumeFilename : FileNames[0],
296 FallbackStyle));
alexfh59883452013-05-10 11:56:10 +0000297 llvm::outs() << Config << "\n";
298 return 0;
299 }
300
alexfh4df43642013-04-24 12:46:44 +0000301 bool Error = false;
302 switch (FileNames.size()) {
303 case 0:
304 Error = clang::format::format("-");
305 break;
306 case 1:
307 Error = clang::format::format(FileNames[0]);
308 break;
309 default:
alexfh6e701792013-07-18 22:54:56 +0000310 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
311 llvm::errs() << "error: -offset, -length and -lines can only be used for "
alexfh4df43642013-04-24 12:46:44 +0000312 "single file.\n";
313 return 1;
314 }
315 for (unsigned i = 0; i < FileNames.size(); ++i)
316 Error |= clang::format::format(FileNames[i]);
317 break;
318 }
319 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000320}