blob: 71dcfc5640bf864d348e77b761cf930d12bf0821 [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"
20#include "clang/Format/Format.h"
21#include "clang/Lex/Lexer.h"
22#include "clang/Rewrite/Core/Rewriter.h"
alexfh59883452013-05-10 11:56:10 +000023#include "llvm/Support/Debug.h"
djasper7f663602013-03-20 09:53:23 +000024#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Signals.h"
alexfh725a9f72013-05-10 18:12:00 +000026#include "llvm/ADT/StringMap.h"
djasper7f663602013-03-20 09:53:23 +000027
28using namespace llvm;
29
chandlerce6992fd2013-09-02 07:42:02 +000030// Fallback style when no style specified or found in a .clang-format file.
31static const char FallbackStyle[] = "LLVM";
alexfh76e9dd02013-05-19 00:53:30 +000032
djasper7f663602013-03-20 09:53:23 +000033static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
34
alexfh725a9f72013-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");
djasper7f663602013-03-20 09:53:23 +000038
alexfh725a9f72013-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));
alexfh6e701792013-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));
alexfh725a9f72013-05-10 18:12:00 +000064static cl::opt<std::string>
65 Style("style",
66 cl::desc("Coding style, currently supports:\n"
alexfh39293052013-09-02 16:39:23 +000067 " LLVM, Google, Chromium, Mozilla, WebKit.\n"
alexfh76e9dd02013-05-19 00:53:30 +000068 "Use -style=file to load style configuration from\n"
alexfh725a9f72013-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"
alexfh76e9dd02013-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}\""),
chandlerce6992fd2013-09-02 07:42:02 +000075 cl::init("file"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000076
77static cl::opt<std::string>
78AssumeFilename("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)."),
82 cl::cat(ClangFormatCategory));
83
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
alexfh725a9f72013-05-10 18:12:00 +0000102static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
103 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000104
105namespace clang {
106namespace format {
107
108static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
109 SourceManager &Sources, FileManager &Files) {
110 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
111 FileName,
112 Source->getBufferSize(), 0);
113 Sources.overrideFileContents(Entry, Source, true);
114 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
115}
116
alexfh59883452013-05-10 11:56:10 +0000117FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
alexfh76e9dd02013-05-19 00:53:30 +0000118 FormatStyle Style;
chandlerce6992fd2013-09-02 07:42:02 +0000119 getPredefinedStyle(FallbackStyle, &Style);
alexfh76e9dd02013-05-19 00:53:30 +0000120
121 if (StyleName.startswith("{")) {
122 // Parse YAML/JSON style from the command line.
123 if (error_code ec = parseConfiguration(StyleName, &Style)) {
124 llvm::errs() << "Error parsing -style: " << ec.message()
chandlerce6992fd2013-09-02 07:42:02 +0000125 << ", using " << FallbackStyle << " style\n";
alexfh76e9dd02013-05-19 00:53:30 +0000126 }
127 return Style;
128 }
129
130 if (!StyleName.equals_lower("file")) {
131 if (!getPredefinedStyle(StyleName, &Style))
chandlerce6992fd2013-09-02 07:42:02 +0000132 llvm::errs() << "Invalid value for -style, using " << FallbackStyle
alexfh76e9dd02013-05-19 00:53:30 +0000133 << " style\n";
134 return Style;
135 }
alexfh2d776172013-05-06 14:11:27 +0000136
djasper05848282013-09-13 13:40:24 +0000137 if (FileName == "-")
138 FileName = AssumeFilename;
alexfh59883452013-05-10 11:56:10 +0000139 SmallString<128> Path(FileName);
140 llvm::sys::fs::make_absolute(Path);
djasper05848282013-09-13 13:40:24 +0000141 for (StringRef Directory = Path;
alexfh59883452013-05-10 11:56:10 +0000142 !Directory.empty();
143 Directory = llvm::sys::path::parent_path(Directory)) {
djasper05848282013-09-13 13:40:24 +0000144 if (!llvm::sys::fs::is_directory(Directory))
145 continue;
alexfh59883452013-05-10 11:56:10 +0000146 SmallString<128> ConfigFile(Directory);
hans79a882f2013-09-10 15:41:12 +0000147
alexfh59883452013-05-10 11:56:10 +0000148 llvm::sys::path::append(ConfigFile, ".clang-format");
149 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
150 bool IsFile = false;
alexfh870fb7c2013-05-10 13:04:20 +0000151 // Ignore errors from is_regular_file: we only need to know if we can read
152 // the file or not.
alexfh59883452013-05-10 11:56:10 +0000153 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
hans79a882f2013-09-10 15:41:12 +0000154
155 if (!IsFile) {
156 // Try _clang-format too, since dotfiles are not commonly used on Windows.
157 ConfigFile = Directory;
158 llvm::sys::path::append(ConfigFile, "_clang-format");
159 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
160 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
161 }
162
alexfh59883452013-05-10 11:56:10 +0000163 if (IsFile) {
164 OwningPtr<MemoryBuffer> Text;
165 if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) {
166 llvm::errs() << ec.message() << "\n";
167 continue;
168 }
alexfh59883452013-05-10 11:56:10 +0000169 if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
170 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
171 << "\n";
172 continue;
173 }
174 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
175 return Style;
176 }
177 }
chandlerce6992fd2013-09-02 07:42:02 +0000178 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
alexfh76e9dd02013-05-19 00:53:30 +0000179 << " style\n";
180 return Style;
djasper7f663602013-03-20 09:53:23 +0000181}
182
alexfh6e701792013-07-18 22:54:56 +0000183// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000184// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000185static bool parseLineRange(StringRef Input, unsigned &FromLine,
186 unsigned &ToLine) {
187 std::pair<StringRef, StringRef> LineRange = Input.split(':');
188 return LineRange.first.getAsInteger(0, FromLine) ||
189 LineRange.second.getAsInteger(0, ToLine);
190}
191
192static bool fillRanges(SourceManager &Sources, FileID ID,
193 const MemoryBuffer *Code,
194 std::vector<CharSourceRange> &Ranges) {
195 if (!LineRanges.empty()) {
196 if (!Offsets.empty() || !Lengths.empty()) {
197 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
198 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)) {
204 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
205 return true;
206 }
207 if (FromLine > ToLine) {
208 llvm::errs() << "error: start line should be less than end line\n";
209 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;
215 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
216 }
217 return false;
djasper7f663602013-03-20 09:53:23 +0000218 }
alexfh6e701792013-07-18 22:54:56 +0000219
djasper7f663602013-03-20 09:53:23 +0000220 if (Offsets.empty())
221 Offsets.push_back(0);
222 if (Offsets.size() != Lengths.size() &&
223 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000224 llvm::errs()
225 << "error: number of -offset and -length arguments must match.\n";
226 return true;
djasper7f663602013-03-20 09:53:23 +0000227 }
alexfh4df43642013-04-24 12:46:44 +0000228 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
229 if (Offsets[i] >= Code->getBufferSize()) {
230 llvm::errs() << "error: offset " << Offsets[i]
231 << " is outside the file\n";
232 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()) {
239 llvm::errs() << "error: invalid length " << Lengths[i]
240 << ", offset + length (" << Offsets[i] + Lengths[i]
241 << ") is outside the file.\n";
242 return true;
243 }
djasper7f663602013-03-20 09:53:23 +0000244 End = Start.getLocWithOffset(Lengths[i]);
245 } else {
246 End = Sources.getLocForEndOfFile(ID);
247 }
248 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
249 }
alexfh6e701792013-07-18 22:54:56 +0000250 return false;
251}
252
253// Returns true on error.
254static bool format(std::string FileName) {
255 FileManager Files((FileSystemOptions()));
256 DiagnosticsEngine Diagnostics(
257 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
258 new DiagnosticOptions);
259 SourceManager Sources(Diagnostics, Files);
260 OwningPtr<MemoryBuffer> Code;
261 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
262 llvm::errs() << ec.message() << "\n";
263 return true;
264 }
265 if (Code->getBufferSize() == 0)
266 return true; // Empty files are formatted correctly.
267 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
268 std::vector<CharSourceRange> Ranges;
269 if (fillRanges(Sources, ID, Code.get(), Ranges))
270 return true;
271
alexfh943428e2013-06-28 12:51:24 +0000272 FormatStyle FormatStyle = getStyle(Style, FileName);
273 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
274 getFormattingLangOpts(FormatStyle.Standard));
275 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000276 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000277 llvm::outs()
278 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000279 for (tooling::Replacements::const_iterator I = Replaces.begin(),
280 E = Replaces.end();
281 I != E; ++I) {
282 llvm::outs() << "<replacement "
283 << "offset='" << I->getOffset() << "' "
284 << "length='" << I->getLength() << "'>"
285 << I->getReplacementText() << "</replacement>\n";
286 }
287 llvm::outs() << "</replacements>\n";
288 } else {
289 Rewriter Rewrite(Sources, LangOptions());
290 tooling::applyAllReplacements(Replaces, Rewrite);
291 if (Inplace) {
292 if (Replaces.size() == 0)
alexfh4df43642013-04-24 12:46:44 +0000293 return false; // Nothing changed, don't touch the file.
djasper7f663602013-03-20 09:53:23 +0000294
295 std::string ErrorInfo;
296 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
rafaelea77cf82013-07-16 19:44:23 +0000297 llvm::sys::fs::F_Binary);
djasper7f663602013-03-20 09:53:23 +0000298 if (!ErrorInfo.empty()) {
299 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
alexfh4df43642013-04-24 12:46:44 +0000300 return true;
djasper7f663602013-03-20 09:53:23 +0000301 }
302 Rewrite.getEditBuffer(ID).write(FileStream);
303 FileStream.flush();
304 } else {
djasper898b4f72013-05-21 14:21:46 +0000305 if (Cursor.getNumOccurrences() != 0)
djasperd0252b72013-05-21 12:21:39 +0000306 outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
307 Replaces, Cursor) << " }\n";
djasper7f663602013-03-20 09:53:23 +0000308 Rewrite.getEditBuffer(ID).write(outs());
309 }
310 }
alexfh4df43642013-04-24 12:46:44 +0000311 return false;
djasper7f663602013-03-20 09:53:23 +0000312}
313
314} // namespace format
315} // namespace clang
316
317int main(int argc, const char **argv) {
318 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000319
320 // Hide unrelated options.
321 StringMap<cl::Option*> Options;
322 cl::getRegisteredOptions(Options);
323 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
324 I != E; ++I) {
325 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
326 I->first() != "version")
327 I->second->setHiddenFlag(cl::ReallyHidden);
328 }
329
djasper7f663602013-03-20 09:53:23 +0000330 cl::ParseCommandLineOptions(
331 argc, argv,
332 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000333 "If no arguments are specified, it formats the code from standard input\n"
334 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000335 "If <file>s are given, it reformats the files. If -i is specified\n"
336 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000337 "result is written to the standard output.\n");
338
djasper7f663602013-03-20 09:53:23 +0000339 if (Help)
340 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000341
alexfh59883452013-05-10 11:56:10 +0000342 if (DumpConfig) {
343 std::string Config = clang::format::configurationAsText(
344 clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0]));
345 llvm::outs() << Config << "\n";
346 return 0;
347 }
348
alexfh4df43642013-04-24 12:46:44 +0000349 bool Error = false;
350 switch (FileNames.size()) {
351 case 0:
352 Error = clang::format::format("-");
353 break;
354 case 1:
355 Error = clang::format::format(FileNames[0]);
356 break;
357 default:
alexfh6e701792013-07-18 22:54:56 +0000358 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
359 llvm::errs() << "error: -offset, -length and -lines can only be used for "
alexfh4df43642013-04-24 12:46:44 +0000360 "single file.\n";
361 return 1;
362 }
363 for (unsigned i = 0; i < FileNames.size(); ++i)
364 Error |= clang::format::format(FileNames[i]);
365 break;
366 }
367 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000368}