blob: 340ef5587ff9263957824eb1fd515b83dade7af6 [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
alexfh76e9dd02013-05-19 00:53:30 +000030// Default style to use when no style specified or specified style not found.
31static const char *DefaultStyle = "LLVM";
32
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));
56static cl::opt<std::string>
57 Style("style",
58 cl::desc("Coding style, currently supports:\n"
59 " LLVM, Google, Chromium, Mozilla.\n"
alexfh76e9dd02013-05-19 00:53:30 +000060 "Use -style=file to load style configuration from\n"
alexfh725a9f72013-05-10 18:12:00 +000061 ".clang-format file located in one of the parent\n"
62 "directories of the source file (or current\n"
alexfh76e9dd02013-05-19 00:53:30 +000063 "directory for stdin).\n"
64 "Use -style=\"{key: value, ...}\" to set specific\n"
65 "parameters, e.g.:\n"
66 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""),
67 cl::init(DefaultStyle), cl::cat(ClangFormatCategory));
alexfh725a9f72013-05-10 18:12:00 +000068static cl::opt<bool> Inplace("i",
69 cl::desc("Inplace edit <file>s, if specified."),
70 cl::cat(ClangFormatCategory));
71
72static cl::opt<bool> OutputXML("output-replacements-xml",
73 cl::desc("Output replacements as XML."),
74 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000075static cl::opt<bool>
76 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000077 cl::desc("Dump configuration options to stdout and exit.\n"
78 "Can be used with -style option."),
79 cl::cat(ClangFormatCategory));
djasperd0252b72013-05-21 12:21:39 +000080static cl::opt<unsigned>
81 Cursor("cursor",
82 cl::desc("The position of the cursor when invoking clang-format from"
83 " an editor integration"),
84 cl::init(0), cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000085
alexfh725a9f72013-05-10 18:12:00 +000086static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
87 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000088
89namespace clang {
90namespace format {
91
92static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
93 SourceManager &Sources, FileManager &Files) {
94 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
95 FileName,
96 Source->getBufferSize(), 0);
97 Sources.overrideFileContents(Entry, Source, true);
98 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
99}
100
alexfh59883452013-05-10 11:56:10 +0000101FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
alexfh76e9dd02013-05-19 00:53:30 +0000102 FormatStyle Style;
103 getPredefinedStyle(DefaultStyle, &Style);
104
105 if (StyleName.startswith("{")) {
106 // Parse YAML/JSON style from the command line.
107 if (error_code ec = parseConfiguration(StyleName, &Style)) {
108 llvm::errs() << "Error parsing -style: " << ec.message()
109 << ", using " << DefaultStyle << " style\n";
110 }
111 return Style;
112 }
113
114 if (!StyleName.equals_lower("file")) {
115 if (!getPredefinedStyle(StyleName, &Style))
116 llvm::errs() << "Invalid value for -style, using " << DefaultStyle
117 << " style\n";
118 return Style;
119 }
alexfh2d776172013-05-06 14:11:27 +0000120
alexfh59883452013-05-10 11:56:10 +0000121 SmallString<128> Path(FileName);
122 llvm::sys::fs::make_absolute(Path);
123 for (StringRef Directory = llvm::sys::path::parent_path(Path);
124 !Directory.empty();
125 Directory = llvm::sys::path::parent_path(Directory)) {
126 SmallString<128> ConfigFile(Directory);
127 llvm::sys::path::append(ConfigFile, ".clang-format");
128 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
129 bool IsFile = false;
alexfh870fb7c2013-05-10 13:04:20 +0000130 // Ignore errors from is_regular_file: we only need to know if we can read
131 // the file or not.
alexfh59883452013-05-10 11:56:10 +0000132 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
133 if (IsFile) {
134 OwningPtr<MemoryBuffer> Text;
135 if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) {
136 llvm::errs() << ec.message() << "\n";
137 continue;
138 }
alexfh59883452013-05-10 11:56:10 +0000139 if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
140 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
141 << "\n";
142 continue;
143 }
144 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
145 return Style;
146 }
147 }
alexfh76e9dd02013-05-19 00:53:30 +0000148 llvm::errs() << "Can't find usable .clang-format, using " << DefaultStyle
149 << " style\n";
150 return Style;
djasper7f663602013-03-20 09:53:23 +0000151}
152
alexfh4df43642013-04-24 12:46:44 +0000153// Returns true on error.
154static bool format(std::string FileName) {
djasper7f663602013-03-20 09:53:23 +0000155 FileManager Files((FileSystemOptions()));
156 DiagnosticsEngine Diagnostics(
157 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
158 new DiagnosticOptions);
159 SourceManager Sources(Diagnostics, Files);
160 OwningPtr<MemoryBuffer> Code;
161 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
162 llvm::errs() << ec.message() << "\n";
alexfh4df43642013-04-24 12:46:44 +0000163 return true;
djasper7f663602013-03-20 09:53:23 +0000164 }
165 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
166 Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
167 if (Offsets.empty())
168 Offsets.push_back(0);
169 if (Offsets.size() != Lengths.size() &&
170 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000171 llvm::errs()
172 << "error: number of -offset and -length arguments must match.\n";
173 return true;
djasper7f663602013-03-20 09:53:23 +0000174 }
175 std::vector<CharSourceRange> Ranges;
alexfh4df43642013-04-24 12:46:44 +0000176 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
177 if (Offsets[i] >= Code->getBufferSize()) {
178 llvm::errs() << "error: offset " << Offsets[i]
179 << " is outside the file\n";
180 return true;
181 }
djasper7f663602013-03-20 09:53:23 +0000182 SourceLocation Start =
183 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
184 SourceLocation End;
185 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000186 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
187 llvm::errs() << "error: invalid length " << Lengths[i]
188 << ", offset + length (" << Offsets[i] + Lengths[i]
189 << ") is outside the file.\n";
190 return true;
191 }
djasper7f663602013-03-20 09:53:23 +0000192 End = Start.getLocWithOffset(Lengths[i]);
193 } else {
194 End = Sources.getLocForEndOfFile(ID);
195 }
196 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
197 }
alexfh59883452013-05-10 11:56:10 +0000198 tooling::Replacements Replaces =
199 reformat(getStyle(Style, FileName), Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000200 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000201 llvm::outs()
202 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000203 for (tooling::Replacements::const_iterator I = Replaces.begin(),
204 E = Replaces.end();
205 I != E; ++I) {
206 llvm::outs() << "<replacement "
207 << "offset='" << I->getOffset() << "' "
208 << "length='" << I->getLength() << "'>"
209 << I->getReplacementText() << "</replacement>\n";
210 }
211 llvm::outs() << "</replacements>\n";
212 } else {
213 Rewriter Rewrite(Sources, LangOptions());
214 tooling::applyAllReplacements(Replaces, Rewrite);
215 if (Inplace) {
216 if (Replaces.size() == 0)
alexfh4df43642013-04-24 12:46:44 +0000217 return false; // Nothing changed, don't touch the file.
djasper7f663602013-03-20 09:53:23 +0000218
219 std::string ErrorInfo;
220 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
221 llvm::raw_fd_ostream::F_Binary);
222 if (!ErrorInfo.empty()) {
223 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
alexfh4df43642013-04-24 12:46:44 +0000224 return true;
djasper7f663602013-03-20 09:53:23 +0000225 }
226 Rewrite.getEditBuffer(ID).write(FileStream);
227 FileStream.flush();
228 } else {
djasperd0252b72013-05-21 12:21:39 +0000229 if (Cursor != 0)
230 outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
231 Replaces, Cursor) << " }\n";
djasper7f663602013-03-20 09:53:23 +0000232 Rewrite.getEditBuffer(ID).write(outs());
233 }
234 }
alexfh4df43642013-04-24 12:46:44 +0000235 return false;
djasper7f663602013-03-20 09:53:23 +0000236}
237
238} // namespace format
239} // namespace clang
240
241int main(int argc, const char **argv) {
242 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000243
244 // Hide unrelated options.
245 StringMap<cl::Option*> Options;
246 cl::getRegisteredOptions(Options);
247 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
248 I != E; ++I) {
249 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
250 I->first() != "version")
251 I->second->setHiddenFlag(cl::ReallyHidden);
252 }
253
djasper7f663602013-03-20 09:53:23 +0000254 cl::ParseCommandLineOptions(
255 argc, argv,
256 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000257 "If no arguments are specified, it formats the code from standard input\n"
258 "and writes the result to the standard output.\n"
alexfh4df43642013-04-24 12:46:44 +0000259 "If <file>s are given, it reformats the files. If -i is specified \n"
260 "together with <file>s, the files are edited in-place. Otherwise, the \n"
261 "result is written to the standard output.\n");
262
djasper7f663602013-03-20 09:53:23 +0000263 if (Help)
264 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000265
alexfh59883452013-05-10 11:56:10 +0000266 if (DumpConfig) {
267 std::string Config = clang::format::configurationAsText(
268 clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0]));
269 llvm::outs() << Config << "\n";
270 return 0;
271 }
272
alexfh4df43642013-04-24 12:46:44 +0000273 bool Error = false;
274 switch (FileNames.size()) {
275 case 0:
276 Error = clang::format::format("-");
277 break;
278 case 1:
279 Error = clang::format::format(FileNames[0]);
280 break;
281 default:
282 if (!Offsets.empty() || !Lengths.empty()) {
283 llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
284 "single file.\n";
285 return 1;
286 }
287 for (unsigned i = 0; i < FileNames.size(); ++i)
288 Error |= clang::format::format(FileNames[i]);
289 break;
290 }
291 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000292}