blob: f779348f0fcc79cae175761d49e9a98bef79af86 [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
30static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
31
alexfh725a9f72013-05-10 18:12:00 +000032// Mark all our options with this category, everything else (except for -version
33// and -help) will be hidden.
34cl::OptionCategory ClangFormatCategory("Clang-format options");
djasper7f663602013-03-20 09:53:23 +000035
alexfh725a9f72013-05-10 18:12:00 +000036static cl::list<unsigned>
37 Offsets("offset",
38 cl::desc("Format a range starting at this byte offset.\n"
39 "Multiple ranges can be formatted by specifying\n"
40 "several -offset and -length pairs.\n"
41 "Can only be used with one input file."),
42 cl::cat(ClangFormatCategory));
43static cl::list<unsigned>
44 Lengths("length",
45 cl::desc("Format a range of this length (in bytes).\n"
46 "Multiple ranges can be formatted by specifying\n"
47 "several -offset and -length pairs.\n"
48 "When only a single -offset is specified without\n"
49 "-length, clang-format will format up to the end\n"
50 "of the file.\n"
51 "Can only be used with one input file."),
52 cl::cat(ClangFormatCategory));
53static cl::opt<std::string>
54 Style("style",
55 cl::desc("Coding style, currently supports:\n"
56 " LLVM, Google, Chromium, Mozilla.\n"
57 "Use '-style file' to load style configuration from\n"
58 ".clang-format file located in one of the parent\n"
59 "directories of the source file (or current\n"
60 "directory for stdin)."),
61 cl::init("LLVM"), cl::cat(ClangFormatCategory));
62static cl::opt<bool> Inplace("i",
63 cl::desc("Inplace edit <file>s, if specified."),
64 cl::cat(ClangFormatCategory));
65
66static cl::opt<bool> OutputXML("output-replacements-xml",
67 cl::desc("Output replacements as XML."),
68 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000069static cl::opt<bool>
70 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000071 cl::desc("Dump configuration options to stdout and exit.\n"
72 "Can be used with -style option."),
73 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000074
alexfh725a9f72013-05-10 18:12:00 +000075static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
76 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000077
78namespace clang {
79namespace format {
80
81static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
82 SourceManager &Sources, FileManager &Files) {
83 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
84 FileName,
85 Source->getBufferSize(), 0);
86 Sources.overrideFileContents(Entry, Source, true);
87 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
88}
89
alexfh59883452013-05-10 11:56:10 +000090FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
91 if (!StyleName.equals_lower("file"))
92 return getPredefinedStyle(StyleName);
alexfh2d776172013-05-06 14:11:27 +000093
alexfh59883452013-05-10 11:56:10 +000094 SmallString<128> Path(FileName);
95 llvm::sys::fs::make_absolute(Path);
96 for (StringRef Directory = llvm::sys::path::parent_path(Path);
97 !Directory.empty();
98 Directory = llvm::sys::path::parent_path(Directory)) {
99 SmallString<128> ConfigFile(Directory);
100 llvm::sys::path::append(ConfigFile, ".clang-format");
101 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
102 bool IsFile = false;
alexfh870fb7c2013-05-10 13:04:20 +0000103 // Ignore errors from is_regular_file: we only need to know if we can read
104 // the file or not.
alexfh59883452013-05-10 11:56:10 +0000105 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
106 if (IsFile) {
107 OwningPtr<MemoryBuffer> Text;
108 if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) {
109 llvm::errs() << ec.message() << "\n";
110 continue;
111 }
112 FormatStyle Style;
113 if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
114 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
115 << "\n";
116 continue;
117 }
118 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
119 return Style;
120 }
121 }
122 llvm::errs() << "Can't find usable .clang-format, using LLVM style\n";
123 return getLLVMStyle();
djasper7f663602013-03-20 09:53:23 +0000124}
125
alexfh4df43642013-04-24 12:46:44 +0000126// Returns true on error.
127static bool format(std::string FileName) {
djasper7f663602013-03-20 09:53:23 +0000128 FileManager Files((FileSystemOptions()));
129 DiagnosticsEngine Diagnostics(
130 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
131 new DiagnosticOptions);
132 SourceManager Sources(Diagnostics, Files);
133 OwningPtr<MemoryBuffer> Code;
134 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
135 llvm::errs() << ec.message() << "\n";
alexfh4df43642013-04-24 12:46:44 +0000136 return true;
djasper7f663602013-03-20 09:53:23 +0000137 }
138 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
139 Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
140 if (Offsets.empty())
141 Offsets.push_back(0);
142 if (Offsets.size() != Lengths.size() &&
143 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000144 llvm::errs()
145 << "error: number of -offset and -length arguments must match.\n";
146 return true;
djasper7f663602013-03-20 09:53:23 +0000147 }
148 std::vector<CharSourceRange> Ranges;
alexfh4df43642013-04-24 12:46:44 +0000149 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
150 if (Offsets[i] >= Code->getBufferSize()) {
151 llvm::errs() << "error: offset " << Offsets[i]
152 << " is outside the file\n";
153 return true;
154 }
djasper7f663602013-03-20 09:53:23 +0000155 SourceLocation Start =
156 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
157 SourceLocation End;
158 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000159 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
160 llvm::errs() << "error: invalid length " << Lengths[i]
161 << ", offset + length (" << Offsets[i] + Lengths[i]
162 << ") is outside the file.\n";
163 return true;
164 }
djasper7f663602013-03-20 09:53:23 +0000165 End = Start.getLocWithOffset(Lengths[i]);
166 } else {
167 End = Sources.getLocForEndOfFile(ID);
168 }
169 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
170 }
alexfh59883452013-05-10 11:56:10 +0000171 tooling::Replacements Replaces =
172 reformat(getStyle(Style, FileName), Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000173 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000174 llvm::outs()
175 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000176 for (tooling::Replacements::const_iterator I = Replaces.begin(),
177 E = Replaces.end();
178 I != E; ++I) {
179 llvm::outs() << "<replacement "
180 << "offset='" << I->getOffset() << "' "
181 << "length='" << I->getLength() << "'>"
182 << I->getReplacementText() << "</replacement>\n";
183 }
184 llvm::outs() << "</replacements>\n";
185 } else {
186 Rewriter Rewrite(Sources, LangOptions());
187 tooling::applyAllReplacements(Replaces, Rewrite);
188 if (Inplace) {
189 if (Replaces.size() == 0)
alexfh4df43642013-04-24 12:46:44 +0000190 return false; // Nothing changed, don't touch the file.
djasper7f663602013-03-20 09:53:23 +0000191
192 std::string ErrorInfo;
193 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
194 llvm::raw_fd_ostream::F_Binary);
195 if (!ErrorInfo.empty()) {
196 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
alexfh4df43642013-04-24 12:46:44 +0000197 return true;
djasper7f663602013-03-20 09:53:23 +0000198 }
199 Rewrite.getEditBuffer(ID).write(FileStream);
200 FileStream.flush();
201 } else {
202 Rewrite.getEditBuffer(ID).write(outs());
203 }
204 }
alexfh4df43642013-04-24 12:46:44 +0000205 return false;
djasper7f663602013-03-20 09:53:23 +0000206}
207
208} // namespace format
209} // namespace clang
210
211int main(int argc, const char **argv) {
212 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000213
214 // Hide unrelated options.
215 StringMap<cl::Option*> Options;
216 cl::getRegisteredOptions(Options);
217 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
218 I != E; ++I) {
219 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
220 I->first() != "version")
221 I->second->setHiddenFlag(cl::ReallyHidden);
222 }
223
djasper7f663602013-03-20 09:53:23 +0000224 cl::ParseCommandLineOptions(
225 argc, argv,
226 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000227 "If no arguments are specified, it formats the code from standard input\n"
228 "and writes the result to the standard output.\n"
alexfh4df43642013-04-24 12:46:44 +0000229 "If <file>s are given, it reformats the files. If -i is specified \n"
230 "together with <file>s, the files are edited in-place. Otherwise, the \n"
231 "result is written to the standard output.\n");
232
djasper7f663602013-03-20 09:53:23 +0000233 if (Help)
234 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000235
alexfh59883452013-05-10 11:56:10 +0000236 if (DumpConfig) {
237 std::string Config = clang::format::configurationAsText(
238 clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0]));
239 llvm::outs() << Config << "\n";
240 return 0;
241 }
242
alexfh4df43642013-04-24 12:46:44 +0000243 bool Error = false;
244 switch (FileNames.size()) {
245 case 0:
246 Error = clang::format::format("-");
247 break;
248 case 1:
249 Error = clang::format::format(FileNames[0]);
250 break;
251 default:
252 if (!Offsets.empty() || !Lengths.empty()) {
253 llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
254 "single file.\n";
255 return 1;
256 }
257 for (unsigned i = 0; i < FileNames.size(); ++i)
258 Error |= clang::format::format(FileNames[i]);
259 break;
260 }
261 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000262}