blob: 9334bb5e8ed69f20267e5419f243d9a17b367825 [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",
Edwin Vanef4e12c82013-09-30 13:31:48 +000066 cl::desc(clang::format::StyleOptionHelpDescription),
Chandler Carruth439fc852013-09-02 07:42:02 +000067 cl::init("file"), cl::cat(ClangFormatCategory));
Daniel Jasper62df7ef2013-09-13 13:40:24 +000068
69static cl::opt<std::string>
70AssumeFilename("assume-filename",
71 cl::desc("When reading from stdin, clang-format assumes this\n"
72 "filename to look for a style config file (with\n"
73 "-style=file)."),
74 cl::cat(ClangFormatCategory));
75
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 Kornienkod95f88a2013-07-18 22:54:56 +0000109// Parses <start line>:<end line> input to a pair of line numbers.
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000110// Returns true on error.
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000111static bool parseLineRange(StringRef Input, unsigned &FromLine,
112 unsigned &ToLine) {
113 std::pair<StringRef, StringRef> LineRange = Input.split(':');
114 return LineRange.first.getAsInteger(0, FromLine) ||
115 LineRange.second.getAsInteger(0, ToLine);
116}
117
118static bool fillRanges(SourceManager &Sources, FileID ID,
119 const MemoryBuffer *Code,
120 std::vector<CharSourceRange> &Ranges) {
121 if (!LineRanges.empty()) {
122 if (!Offsets.empty() || !Lengths.empty()) {
123 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
124 return true;
125 }
126
127 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
128 unsigned FromLine, ToLine;
129 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
130 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
131 return true;
132 }
133 if (FromLine > ToLine) {
134 llvm::errs() << "error: start line should be less than end line\n";
135 return true;
136 }
137 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
138 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
139 if (Start.isInvalid() || End.isInvalid())
140 return true;
141 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
142 }
143 return false;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000144 }
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000145
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000146 if (Offsets.empty())
147 Offsets.push_back(0);
148 if (Offsets.size() != Lengths.size() &&
149 !(Offsets.size() == 1 && Lengths.empty())) {
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000150 llvm::errs()
151 << "error: number of -offset and -length arguments must match.\n";
152 return true;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000153 }
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000154 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
155 if (Offsets[i] >= Code->getBufferSize()) {
156 llvm::errs() << "error: offset " << Offsets[i]
157 << " is outside the file\n";
158 return true;
159 }
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000160 SourceLocation Start =
161 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
162 SourceLocation End;
163 if (i < Lengths.size()) {
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000164 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
165 llvm::errs() << "error: invalid length " << Lengths[i]
166 << ", offset + length (" << Offsets[i] + Lengths[i]
167 << ") is outside the file.\n";
168 return true;
169 }
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000170 End = Start.getLocWithOffset(Lengths[i]);
171 } else {
172 End = Sources.getLocForEndOfFile(ID);
173 }
174 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
175 }
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000176 return false;
177}
178
179// Returns true on error.
180static bool format(std::string FileName) {
181 FileManager Files((FileSystemOptions()));
182 DiagnosticsEngine Diagnostics(
183 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
184 new DiagnosticOptions);
185 SourceManager Sources(Diagnostics, Files);
186 OwningPtr<MemoryBuffer> Code;
187 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
188 llvm::errs() << ec.message() << "\n";
189 return true;
190 }
191 if (Code->getBufferSize() == 0)
192 return true; // Empty files are formatted correctly.
193 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
194 std::vector<CharSourceRange> Ranges;
195 if (fillRanges(Sources, ID, Code.get(), Ranges))
196 return true;
197
Edwin Vanef4e12c82013-09-30 13:31:48 +0000198 FormatStyle FormatStyle =
199 getStyle(Style, (FileName == "-") ? AssumeFilename : FileName);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +0000200 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
201 getFormattingLangOpts(FormatStyle.Standard));
202 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000203 if (OutputXML) {
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000204 llvm::outs()
205 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000206 for (tooling::Replacements::const_iterator I = Replaces.begin(),
207 E = Replaces.end();
208 I != E; ++I) {
209 llvm::outs() << "<replacement "
210 << "offset='" << I->getOffset() << "' "
211 << "length='" << I->getLength() << "'>"
212 << I->getReplacementText() << "</replacement>\n";
213 }
214 llvm::outs() << "</replacements>\n";
215 } else {
216 Rewriter Rewrite(Sources, LangOptions());
217 tooling::applyAllReplacements(Replaces, Rewrite);
218 if (Inplace) {
219 if (Replaces.size() == 0)
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000220 return false; // Nothing changed, don't touch the file.
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000221
222 std::string ErrorInfo;
223 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
Rafael Espindolad965f952013-07-16 19:44:23 +0000224 llvm::sys::fs::F_Binary);
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000225 if (!ErrorInfo.empty()) {
226 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000227 return true;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000228 }
229 Rewrite.getEditBuffer(ID).write(FileStream);
230 FileStream.flush();
231 } else {
Daniel Jasper33886c72013-05-21 14:21:46 +0000232 if (Cursor.getNumOccurrences() != 0)
Daniel Jasper6bd3b932013-05-21 12:21:39 +0000233 outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
234 Replaces, Cursor) << " }\n";
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000235 Rewrite.getEditBuffer(ID).write(outs());
236 }
237 }
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000238 return false;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000239}
240
241} // namespace format
242} // namespace clang
243
244int main(int argc, const char **argv) {
245 llvm::sys::PrintStackTraceOnErrorSignal();
Alexander Kornienko46529e52013-05-10 18:12:00 +0000246
247 // Hide unrelated options.
248 StringMap<cl::Option*> Options;
249 cl::getRegisteredOptions(Options);
250 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
251 I != E; ++I) {
252 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
253 I->first() != "version")
254 I->second->setHiddenFlag(cl::ReallyHidden);
255 }
256
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000257 cl::ParseCommandLineOptions(
258 argc, argv,
259 "A tool to format C/C++/Obj-C code.\n\n"
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000260 "If no arguments are specified, it formats the code from standard input\n"
261 "and writes the result to the standard output.\n"
Alexander Kornienko7de13bb2013-09-02 15:30:26 +0000262 "If <file>s are given, it reformats the files. If -i is specified\n"
263 "together with <file>s, the files are edited in-place. Otherwise, the\n"
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000264 "result is written to the standard output.\n");
265
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000266 if (Help)
267 cl::PrintHelpMessage();
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000268
Alexander Kornienkodd256312013-05-10 11:56:10 +0000269 if (DumpConfig) {
Edwin Vanef4e12c82013-09-30 13:31:48 +0000270 std::string Config =
271 clang::format::configurationAsText(clang::format::getStyle(
272 Style, FileNames.empty() ? AssumeFilename : FileNames[0]));
Alexander Kornienkodd256312013-05-10 11:56:10 +0000273 llvm::outs() << Config << "\n";
274 return 0;
275 }
276
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000277 bool Error = false;
278 switch (FileNames.size()) {
279 case 0:
280 Error = clang::format::format("-");
281 break;
282 case 1:
283 Error = clang::format::format(FileNames[0]);
284 break;
285 default:
Alexander Kornienkod95f88a2013-07-18 22:54:56 +0000286 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
287 llvm::errs() << "error: -offset, -length and -lines can only be used for "
Alexander Kornienko4cdc0cd2013-04-24 12:46:44 +0000288 "single file.\n";
289 return 1;
290 }
291 for (unsigned i = 0; i < FileNames.size(); ++i)
292 Error |= clang::format::format(FileNames[i]);
293 break;
294 }
295 return Error ? 1 : 0;
Daniel Jasper7c4a9a02013-03-20 09:53:23 +0000296}