blob: 592d46a530c3363c178cfd7e174a8dcc29d60530 [file] [log] [blame]
Daniel Jasper7c4a9a02013-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"
20#include "clang/Format/Format.h"
21#include "clang/Lex/Lexer.h"
22#include "clang/Rewrite/Core/Rewriter.h"
Alexander Kornienkodd256312013-05-10 11:56:10 +000023#include "llvm/Support/Debug.h"
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000024#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Signals.h"
Alexander Kornienko46529e52013-05-10 18:12:00 +000026#include "llvm/ADT/StringMap.h"
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000027
28using namespace llvm;
29
Chandler Carruth439fc852013-09-02 07:42:02 +000030// Fallback style when no style specified or found in a .clang-format file.
31static const char FallbackStyle[] = "LLVM";
Alexander Kornienko885f87b2013-05-19 00:53:30 +000032
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000033static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
34
Alexander Kornienko46529e52013-05-10 18:12:00 +000035// Mark all our options with this category, everything else (except for -version
36// and -help) will be hidden.
37cl::OptionCategory ClangFormatCategory("Clang-format options");
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000038
Alexander Kornienko46529e52013-05-10 18:12:00 +000039static cl::list<unsigned>
40 Offsets("offset",
41 cl::desc("Format a range starting at this byte offset.\n"
42 "Multiple ranges can be formatted by specifying\n"
43 "several -offset and -length pairs.\n"
44 "Can only be used with one input file."),
45 cl::cat(ClangFormatCategory));
46static cl::list<unsigned>
47 Lengths("length",
48 cl::desc("Format a range of this length (in bytes).\n"
49 "Multiple ranges can be formatted by specifying\n"
50 "several -offset and -length pairs.\n"
51 "When only a single -offset is specified without\n"
52 "-length, clang-format will format up to the end\n"
53 "of the file.\n"
54 "Can only be used with one input file."),
55 cl::cat(ClangFormatCategory));
Alexander Kornienkod95f88a2013-07-18 22:54:56 +000056static cl::list<std::string>
57LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
58 "lines (both 1-based).\n"
59 "Multiple ranges can be formatted by specifying\n"
60 "several -lines arguments.\n"
61 "Can't be used with -offset and -length.\n"
62 "Can only be used with one input file."),
63 cl::cat(ClangFormatCategory));
Alexander Kornienko46529e52013-05-10 18:12:00 +000064static cl::opt<std::string>
65 Style("style",
66 cl::desc("Coding style, currently supports:\n"
Alexander Kornienko4e65c982013-09-02 16:39:23 +000067 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
Alexander Kornienko885f87b2013-05-19 00:53:30 +000068 "Use -style=file to load style configuration from\n"
Alexander Kornienko46529e52013-05-10 18:12:00 +000069 ".clang-format file located in one of the parent\n"
70 "directories of the source file (or current\n"
Alexander Kornienko885f87b2013-05-19 00:53:30 +000071 "directory for stdin).\n"
72 "Use -style=\"{key: value, ...}\" to set specific\n"
73 "parameters, e.g.:\n"
74 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""),
Chandler Carruth439fc852013-09-02 07:42:02 +000075 cl::init("file"), cl::cat(ClangFormatCategory));
Alexander Kornienko46529e52013-05-10 18:12:00 +000076static cl::opt<bool> Inplace("i",
77 cl::desc("Inplace edit <file>s, if specified."),
78 cl::cat(ClangFormatCategory));
79
80static cl::opt<bool> OutputXML("output-replacements-xml",
81 cl::desc("Output replacements as XML."),
82 cl::cat(ClangFormatCategory));
Alexander Kornienkodd256312013-05-10 11:56:10 +000083static cl::opt<bool>
84 DumpConfig("dump-config",
Alexander Kornienko46529e52013-05-10 18:12:00 +000085 cl::desc("Dump configuration options to stdout and exit.\n"
86 "Can be used with -style option."),
87 cl::cat(ClangFormatCategory));
Daniel Jasper6bd3b932013-05-21 12:21:39 +000088static cl::opt<unsigned>
89 Cursor("cursor",
Alexander Kornienko7de13bb2013-09-02 15:30:26 +000090 cl::desc("The position of the cursor when invoking\n"
91 "clang-format from an editor integration"),
Daniel Jasper6bd3b932013-05-21 12:21:39 +000092 cl::init(0), cl::cat(ClangFormatCategory));
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000093
Alexander Kornienko46529e52013-05-10 18:12:00 +000094static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
95 cl::cat(ClangFormatCategory));
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000096
97namespace clang {
98namespace format {
99
100static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
101 SourceManager &Sources, FileManager &Files) {
102 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
103 FileName,
104 Source->getBufferSize(), 0);
105 Sources.overrideFileContents(Entry, Source, true);
106 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
107}
108
Alexander Kornienkodd256312013-05-10 11:56:10 +0000109FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000110 FormatStyle Style;
Chandler Carruth439fc852013-09-02 07:42:02 +0000111 getPredefinedStyle(FallbackStyle, &Style);
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000112
113 if (StyleName.startswith("{")) {
114 // Parse YAML/JSON style from the command line.
115 if (error_code ec = parseConfiguration(StyleName, &Style)) {
116 llvm::errs() << "Error parsing -style: " << ec.message()
Chandler Carruth439fc852013-09-02 07:42:02 +0000117 << ", using " << FallbackStyle << " style\n";
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000118 }
119 return Style;
120 }
121
122 if (!StyleName.equals_lower("file")) {
123 if (!getPredefinedStyle(StyleName, &Style))
Chandler Carruth439fc852013-09-02 07:42:02 +0000124 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000125 << " style\n";
126 return Style;
127 }
Alexander Kornienkofb594862013-05-06 14:11:27 +0000128
Alexander Kornienkodd256312013-05-10 11:56:10 +0000129 SmallString<128> Path(FileName);
130 llvm::sys::fs::make_absolute(Path);
131 for (StringRef Directory = llvm::sys::path::parent_path(Path);
132 !Directory.empty();
133 Directory = llvm::sys::path::parent_path(Directory)) {
134 SmallString<128> ConfigFile(Directory);
Hans Wennborg9a7a50e2013-09-10 15:41:12 +0000135
Alexander Kornienkodd256312013-05-10 11:56:10 +0000136 llvm::sys::path::append(ConfigFile, ".clang-format");
137 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
138 bool IsFile = false;
Alexander Kornienko0ca318b2013-05-10 13:04:20 +0000139 // Ignore errors from is_regular_file: we only need to know if we can read
140 // the file or not.
Alexander Kornienkodd256312013-05-10 11:56:10 +0000141 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
Hans Wennborg9a7a50e2013-09-10 15:41:12 +0000142
143 if (!IsFile) {
144 // Try _clang-format too, since dotfiles are not commonly used on Windows.
145 ConfigFile = Directory;
146 llvm::sys::path::append(ConfigFile, "_clang-format");
147 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
148 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
149 }
150
Alexander Kornienkodd256312013-05-10 11:56:10 +0000151 if (IsFile) {
152 OwningPtr<MemoryBuffer> Text;
153 if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) {
154 llvm::errs() << ec.message() << "\n";
155 continue;
156 }
Alexander Kornienkodd256312013-05-10 11:56:10 +0000157 if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
158 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
159 << "\n";
160 continue;
161 }
162 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
163 return Style;
164 }
165 }
Chandler Carruth439fc852013-09-02 07:42:02 +0000166 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000167 << " style\n";
168 return Style;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000169}
170
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000171// Parses <start line>:<end line> input to a pair of line numbers.
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000172// Returns true on error.
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000173static bool parseLineRange(StringRef Input, unsigned &FromLine,
174 unsigned &ToLine) {
175 std::pair<StringRef, StringRef> LineRange = Input.split(':');
176 return LineRange.first.getAsInteger(0, FromLine) ||
177 LineRange.second.getAsInteger(0, ToLine);
178}
179
180static bool fillRanges(SourceManager &Sources, FileID ID,
181 const MemoryBuffer *Code,
182 std::vector<CharSourceRange> &Ranges) {
183 if (!LineRanges.empty()) {
184 if (!Offsets.empty() || !Lengths.empty()) {
185 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
186 return true;
187 }
188
189 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
190 unsigned FromLine, ToLine;
191 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
192 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
193 return true;
194 }
195 if (FromLine > ToLine) {
196 llvm::errs() << "error: start line should be less than end line\n";
197 return true;
198 }
199 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
200 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
201 if (Start.isInvalid() || End.isInvalid())
202 return true;
203 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
204 }
205 return false;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000206 }
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000207
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000208 if (Offsets.empty())
209 Offsets.push_back(0);
210 if (Offsets.size() != Lengths.size() &&
211 !(Offsets.size() == 1 && Lengths.empty())) {
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000212 llvm::errs()
213 << "error: number of -offset and -length arguments must match.\n";
214 return true;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000215 }
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000216 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
217 if (Offsets[i] >= Code->getBufferSize()) {
218 llvm::errs() << "error: offset " << Offsets[i]
219 << " is outside the file\n";
220 return true;
221 }
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000222 SourceLocation Start =
223 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
224 SourceLocation End;
225 if (i < Lengths.size()) {
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000226 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
227 llvm::errs() << "error: invalid length " << Lengths[i]
228 << ", offset + length (" << Offsets[i] + Lengths[i]
229 << ") is outside the file.\n";
230 return true;
231 }
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000232 End = Start.getLocWithOffset(Lengths[i]);
233 } else {
234 End = Sources.getLocForEndOfFile(ID);
235 }
236 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
237 }
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000238 return false;
239}
240
241// Returns true on error.
242static bool format(std::string FileName) {
243 FileManager Files((FileSystemOptions()));
244 DiagnosticsEngine Diagnostics(
245 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
246 new DiagnosticOptions);
247 SourceManager Sources(Diagnostics, Files);
248 OwningPtr<MemoryBuffer> Code;
249 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
250 llvm::errs() << ec.message() << "\n";
251 return true;
252 }
253 if (Code->getBufferSize() == 0)
254 return true; // Empty files are formatted correctly.
255 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
256 std::vector<CharSourceRange> Ranges;
257 if (fillRanges(Sources, ID, Code.get(), Ranges))
258 return true;
259
Alexander Kornienkoa1753f42013-06-28 12:51:24 +0000260 FormatStyle FormatStyle = getStyle(Style, FileName);
261 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
262 getFormattingLangOpts(FormatStyle.Standard));
263 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000264 if (OutputXML) {
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000265 llvm::outs()
266 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000267 for (tooling::Replacements::const_iterator I = Replaces.begin(),
268 E = Replaces.end();
269 I != E; ++I) {
270 llvm::outs() << "<replacement "
271 << "offset='" << I->getOffset() << "' "
272 << "length='" << I->getLength() << "'>"
273 << I->getReplacementText() << "</replacement>\n";
274 }
275 llvm::outs() << "</replacements>\n";
276 } else {
277 Rewriter Rewrite(Sources, LangOptions());
278 tooling::applyAllReplacements(Replaces, Rewrite);
279 if (Inplace) {
280 if (Replaces.size() == 0)
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000281 return false; // Nothing changed, don't touch the file.
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000282
283 std::string ErrorInfo;
284 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
Rafael Espindolad965f952013-07-16 19:44:23 +0000285 llvm::sys::fs::F_Binary);
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000286 if (!ErrorInfo.empty()) {
287 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000288 return true;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000289 }
290 Rewrite.getEditBuffer(ID).write(FileStream);
291 FileStream.flush();
292 } else {
Daniel Jasper33886c72013-05-21 14:21:46 +0000293 if (Cursor.getNumOccurrences() != 0)
Daniel Jasper6bd3b932013-05-21 12:21:39 +0000294 outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
295 Replaces, Cursor) << " }\n";
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000296 Rewrite.getEditBuffer(ID).write(outs());
297 }
298 }
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000299 return false;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000300}
301
302} // namespace format
303} // namespace clang
304
305int main(int argc, const char **argv) {
306 llvm::sys::PrintStackTraceOnErrorSignal();
Alexander Kornienko46529e52013-05-10 18:12:00 +0000307
308 // Hide unrelated options.
309 StringMap<cl::Option*> Options;
310 cl::getRegisteredOptions(Options);
311 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
312 I != E; ++I) {
313 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
314 I->first() != "version")
315 I->second->setHiddenFlag(cl::ReallyHidden);
316 }
317
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000318 cl::ParseCommandLineOptions(
319 argc, argv,
320 "A tool to format C/C++/Obj-C code.\n\n"
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000321 "If no arguments are specified, it formats the code from standard input\n"
322 "and writes the result to the standard output.\n"
Alexander Kornienko7de13bb2013-09-02 15:30:26 +0000323 "If <file>s are given, it reformats the files. If -i is specified\n"
324 "together with <file>s, the files are edited in-place. Otherwise, the\n"
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000325 "result is written to the standard output.\n");
326
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000327 if (Help)
328 cl::PrintHelpMessage();
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000329
Alexander Kornienkodd256312013-05-10 11:56:10 +0000330 if (DumpConfig) {
331 std::string Config = clang::format::configurationAsText(
332 clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0]));
333 llvm::outs() << Config << "\n";
334 return 0;
335 }
336
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000337 bool Error = false;
338 switch (FileNames.size()) {
339 case 0:
340 Error = clang::format::format("-");
341 break;
342 case 1:
343 Error = clang::format::format(FileNames[0]);
344 break;
345 default:
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000346 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
347 llvm::errs() << "error: -offset, -length and -lines can only be used for "
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000348 "single file.\n";
349 return 1;
350 }
351 for (unsigned i = 0; i < FileNames.size(); ++i)
352 Error |= clang::format::format(FileNames[i]);
353 break;
354 }
355 return Error ? 1 : 0;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000356}