blob: fccd6bf2571400697716b7336f77d88a0f3e1359 [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));
djasper7f663602013-03-20 09:53:23 +000080
alexfh725a9f72013-05-10 18:12:00 +000081static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
82 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000083
84namespace clang {
85namespace format {
86
87static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
88 SourceManager &Sources, FileManager &Files) {
89 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
90 FileName,
91 Source->getBufferSize(), 0);
92 Sources.overrideFileContents(Entry, Source, true);
93 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
94}
95
alexfh59883452013-05-10 11:56:10 +000096FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
alexfh76e9dd02013-05-19 00:53:30 +000097 FormatStyle Style;
98 getPredefinedStyle(DefaultStyle, &Style);
99
100 if (StyleName.startswith("{")) {
101 // Parse YAML/JSON style from the command line.
102 if (error_code ec = parseConfiguration(StyleName, &Style)) {
103 llvm::errs() << "Error parsing -style: " << ec.message()
104 << ", using " << DefaultStyle << " style\n";
105 }
106 return Style;
107 }
108
109 if (!StyleName.equals_lower("file")) {
110 if (!getPredefinedStyle(StyleName, &Style))
111 llvm::errs() << "Invalid value for -style, using " << DefaultStyle
112 << " style\n";
113 return Style;
114 }
alexfh2d776172013-05-06 14:11:27 +0000115
alexfh59883452013-05-10 11:56:10 +0000116 SmallString<128> Path(FileName);
117 llvm::sys::fs::make_absolute(Path);
118 for (StringRef Directory = llvm::sys::path::parent_path(Path);
119 !Directory.empty();
120 Directory = llvm::sys::path::parent_path(Directory)) {
121 SmallString<128> ConfigFile(Directory);
122 llvm::sys::path::append(ConfigFile, ".clang-format");
123 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
124 bool IsFile = false;
alexfh870fb7c2013-05-10 13:04:20 +0000125 // Ignore errors from is_regular_file: we only need to know if we can read
126 // the file or not.
alexfh59883452013-05-10 11:56:10 +0000127 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
128 if (IsFile) {
129 OwningPtr<MemoryBuffer> Text;
130 if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) {
131 llvm::errs() << ec.message() << "\n";
132 continue;
133 }
alexfh59883452013-05-10 11:56:10 +0000134 if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
135 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
136 << "\n";
137 continue;
138 }
139 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
140 return Style;
141 }
142 }
alexfh76e9dd02013-05-19 00:53:30 +0000143 llvm::errs() << "Can't find usable .clang-format, using " << DefaultStyle
144 << " style\n";
145 return Style;
djasper7f663602013-03-20 09:53:23 +0000146}
147
alexfh4df43642013-04-24 12:46:44 +0000148// Returns true on error.
149static bool format(std::string FileName) {
djasper7f663602013-03-20 09:53:23 +0000150 FileManager Files((FileSystemOptions()));
151 DiagnosticsEngine Diagnostics(
152 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
153 new DiagnosticOptions);
154 SourceManager Sources(Diagnostics, Files);
155 OwningPtr<MemoryBuffer> Code;
156 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
157 llvm::errs() << ec.message() << "\n";
alexfh4df43642013-04-24 12:46:44 +0000158 return true;
djasper7f663602013-03-20 09:53:23 +0000159 }
160 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
161 Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
162 if (Offsets.empty())
163 Offsets.push_back(0);
164 if (Offsets.size() != Lengths.size() &&
165 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000166 llvm::errs()
167 << "error: number of -offset and -length arguments must match.\n";
168 return true;
djasper7f663602013-03-20 09:53:23 +0000169 }
170 std::vector<CharSourceRange> Ranges;
alexfh4df43642013-04-24 12:46:44 +0000171 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
172 if (Offsets[i] >= Code->getBufferSize()) {
173 llvm::errs() << "error: offset " << Offsets[i]
174 << " is outside the file\n";
175 return true;
176 }
djasper7f663602013-03-20 09:53:23 +0000177 SourceLocation Start =
178 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
179 SourceLocation End;
180 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000181 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
182 llvm::errs() << "error: invalid length " << Lengths[i]
183 << ", offset + length (" << Offsets[i] + Lengths[i]
184 << ") is outside the file.\n";
185 return true;
186 }
djasper7f663602013-03-20 09:53:23 +0000187 End = Start.getLocWithOffset(Lengths[i]);
188 } else {
189 End = Sources.getLocForEndOfFile(ID);
190 }
191 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
192 }
alexfh59883452013-05-10 11:56:10 +0000193 tooling::Replacements Replaces =
194 reformat(getStyle(Style, FileName), Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000195 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000196 llvm::outs()
197 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000198 for (tooling::Replacements::const_iterator I = Replaces.begin(),
199 E = Replaces.end();
200 I != E; ++I) {
201 llvm::outs() << "<replacement "
202 << "offset='" << I->getOffset() << "' "
203 << "length='" << I->getLength() << "'>"
204 << I->getReplacementText() << "</replacement>\n";
205 }
206 llvm::outs() << "</replacements>\n";
207 } else {
208 Rewriter Rewrite(Sources, LangOptions());
209 tooling::applyAllReplacements(Replaces, Rewrite);
210 if (Inplace) {
211 if (Replaces.size() == 0)
alexfh4df43642013-04-24 12:46:44 +0000212 return false; // Nothing changed, don't touch the file.
djasper7f663602013-03-20 09:53:23 +0000213
214 std::string ErrorInfo;
215 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
216 llvm::raw_fd_ostream::F_Binary);
217 if (!ErrorInfo.empty()) {
218 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
alexfh4df43642013-04-24 12:46:44 +0000219 return true;
djasper7f663602013-03-20 09:53:23 +0000220 }
221 Rewrite.getEditBuffer(ID).write(FileStream);
222 FileStream.flush();
223 } else {
224 Rewrite.getEditBuffer(ID).write(outs());
225 }
226 }
alexfh4df43642013-04-24 12:46:44 +0000227 return false;
djasper7f663602013-03-20 09:53:23 +0000228}
229
230} // namespace format
231} // namespace clang
232
233int main(int argc, const char **argv) {
234 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000235
236 // Hide unrelated options.
237 StringMap<cl::Option*> Options;
238 cl::getRegisteredOptions(Options);
239 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
240 I != E; ++I) {
241 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
242 I->first() != "version")
243 I->second->setHiddenFlag(cl::ReallyHidden);
244 }
245
djasper7f663602013-03-20 09:53:23 +0000246 cl::ParseCommandLineOptions(
247 argc, argv,
248 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000249 "If no arguments are specified, it formats the code from standard input\n"
250 "and writes the result to the standard output.\n"
alexfh4df43642013-04-24 12:46:44 +0000251 "If <file>s are given, it reformats the files. If -i is specified \n"
252 "together with <file>s, the files are edited in-place. Otherwise, the \n"
253 "result is written to the standard output.\n");
254
djasper7f663602013-03-20 09:53:23 +0000255 if (Help)
256 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000257
alexfh59883452013-05-10 11:56:10 +0000258 if (DumpConfig) {
259 std::string Config = clang::format::configurationAsText(
260 clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0]));
261 llvm::outs() << Config << "\n";
262 return 0;
263 }
264
alexfh4df43642013-04-24 12:46:44 +0000265 bool Error = false;
266 switch (FileNames.size()) {
267 case 0:
268 Error = clang::format::format("-");
269 break;
270 case 1:
271 Error = clang::format::format(FileNames[0]);
272 break;
273 default:
274 if (!Offsets.empty() || !Lengths.empty()) {
275 llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
276 "single file.\n";
277 return 1;
278 }
279 for (unsigned i = 0; i < FileNames.size(); ++i)
280 Error |= clang::format::format(FileNames[i]);
281 break;
282 }
283 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000284}