blob: 513439649d282c94591e78556701d4224b2522ce [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));
alexfh6e701792013-07-18 22:54:56 +000053static cl::list<std::string>
54LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
55 "lines (both 1-based).\n"
56 "Multiple ranges can be formatted by specifying\n"
57 "several -lines arguments.\n"
58 "Can't be used with -offset and -length.\n"
59 "Can only be used with one input file."),
60 cl::cat(ClangFormatCategory));
alexfh725a9f72013-05-10 18:12:00 +000061static cl::opt<std::string>
62 Style("style",
revane4d118692013-09-30 13:31:48 +000063 cl::desc(clang::format::StyleOptionHelpDescription),
chandlerce6992fd2013-09-02 07:42:02 +000064 cl::init("file"), cl::cat(ClangFormatCategory));
alexfh7e0adcf2013-12-02 15:21:38 +000065static cl::opt<std::string>
66FallbackStyle("fallback-style",
67 cl::desc("The name of the predefined style used as a fallback in "
68 "case clang-format is invoked with -style=file, but can "
69 "not find the .clang-format file to use."),
70 cl::init("LLVM"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000071
72static cl::opt<std::string>
73AssumeFilename("assume-filename",
74 cl::desc("When reading from stdin, clang-format assumes this\n"
75 "filename to look for a style config file (with\n"
76 "-style=file)."),
77 cl::cat(ClangFormatCategory));
78
alexfh725a9f72013-05-10 18:12:00 +000079static cl::opt<bool> Inplace("i",
80 cl::desc("Inplace edit <file>s, if specified."),
81 cl::cat(ClangFormatCategory));
82
83static cl::opt<bool> OutputXML("output-replacements-xml",
84 cl::desc("Output replacements as XML."),
85 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000086static cl::opt<bool>
87 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000088 cl::desc("Dump configuration options to stdout and exit.\n"
89 "Can be used with -style option."),
90 cl::cat(ClangFormatCategory));
djasperd0252b72013-05-21 12:21:39 +000091static cl::opt<unsigned>
92 Cursor("cursor",
alexfhb5b43022013-09-02 15:30:26 +000093 cl::desc("The position of the cursor when invoking\n"
94 "clang-format from an editor integration"),
djasperd0252b72013-05-21 12:21:39 +000095 cl::init(0), cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000096
alexfh725a9f72013-05-10 18:12:00 +000097static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
98 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +000099
100namespace clang {
101namespace format {
102
103static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
104 SourceManager &Sources, FileManager &Files) {
105 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
106 FileName,
107 Source->getBufferSize(), 0);
108 Sources.overrideFileContents(Entry, Source, true);
109 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
110}
111
alexfh6e701792013-07-18 22:54:56 +0000112// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000113// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000114static bool parseLineRange(StringRef Input, unsigned &FromLine,
115 unsigned &ToLine) {
116 std::pair<StringRef, StringRef> LineRange = Input.split(':');
117 return LineRange.first.getAsInteger(0, FromLine) ||
118 LineRange.second.getAsInteger(0, ToLine);
119}
120
121static bool fillRanges(SourceManager &Sources, FileID ID,
122 const MemoryBuffer *Code,
123 std::vector<CharSourceRange> &Ranges) {
124 if (!LineRanges.empty()) {
125 if (!Offsets.empty() || !Lengths.empty()) {
126 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
127 return true;
128 }
129
130 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
131 unsigned FromLine, ToLine;
132 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
133 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
134 return true;
135 }
136 if (FromLine > ToLine) {
137 llvm::errs() << "error: start line should be less than end line\n";
138 return true;
139 }
140 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
141 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
142 if (Start.isInvalid() || End.isInvalid())
143 return true;
144 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
145 }
146 return false;
djasper7f663602013-03-20 09:53:23 +0000147 }
alexfh6e701792013-07-18 22:54:56 +0000148
djasper7f663602013-03-20 09:53:23 +0000149 if (Offsets.empty())
150 Offsets.push_back(0);
151 if (Offsets.size() != Lengths.size() &&
152 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000153 llvm::errs()
154 << "error: number of -offset and -length arguments must match.\n";
155 return true;
djasper7f663602013-03-20 09:53:23 +0000156 }
alexfh4df43642013-04-24 12:46:44 +0000157 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
158 if (Offsets[i] >= Code->getBufferSize()) {
159 llvm::errs() << "error: offset " << Offsets[i]
160 << " is outside the file\n";
161 return true;
162 }
djasper7f663602013-03-20 09:53:23 +0000163 SourceLocation Start =
164 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
165 SourceLocation End;
166 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000167 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
168 llvm::errs() << "error: invalid length " << Lengths[i]
169 << ", offset + length (" << Offsets[i] + Lengths[i]
170 << ") is outside the file.\n";
171 return true;
172 }
djasper7f663602013-03-20 09:53:23 +0000173 End = Start.getLocWithOffset(Lengths[i]);
174 } else {
175 End = Sources.getLocForEndOfFile(ID);
176 }
177 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
178 }
alexfh6e701792013-07-18 22:54:56 +0000179 return false;
180}
181
182// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000183static bool format(StringRef FileName) {
alexfh6e701792013-07-18 22:54:56 +0000184 FileManager Files((FileSystemOptions()));
185 DiagnosticsEngine Diagnostics(
186 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
187 new DiagnosticOptions);
188 SourceManager Sources(Diagnostics, Files);
189 OwningPtr<MemoryBuffer> Code;
190 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
191 llvm::errs() << ec.message() << "\n";
192 return true;
193 }
194 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000195 return false; // Empty files are formatted correctly.
alexfh6e701792013-07-18 22:54:56 +0000196 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
197 std::vector<CharSourceRange> Ranges;
198 if (fillRanges(Sources, ID, Code.get(), Ranges))
199 return true;
200
alexfh7e0adcf2013-12-02 15:21:38 +0000201 FormatStyle FormatStyle = getStyle(
202 Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
alexfh943428e2013-06-28 12:51:24 +0000203 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
204 getFormattingLangOpts(FormatStyle.Standard));
205 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000206 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000207 llvm::outs()
208 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000209 for (tooling::Replacements::const_iterator I = Replaces.begin(),
210 E = Replaces.end();
211 I != E; ++I) {
212 llvm::outs() << "<replacement "
213 << "offset='" << I->getOffset() << "' "
214 << "length='" << I->getLength() << "'>"
215 << I->getReplacementText() << "</replacement>\n";
216 }
217 llvm::outs() << "</replacements>\n";
218 } else {
219 Rewriter Rewrite(Sources, LangOptions());
220 tooling::applyAllReplacements(Replaces, Rewrite);
221 if (Inplace) {
alp8d1b4dd2013-11-08 08:07:19 +0000222 if (Rewrite.overwriteChangedFiles())
alexfh4df43642013-04-24 12:46:44 +0000223 return true;
djasper7f663602013-03-20 09:53:23 +0000224 } else {
djasper898b4f72013-05-21 14:21:46 +0000225 if (Cursor.getNumOccurrences() != 0)
djasperd0252b72013-05-21 12:21:39 +0000226 outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
227 Replaces, Cursor) << " }\n";
djasper7f663602013-03-20 09:53:23 +0000228 Rewrite.getEditBuffer(ID).write(outs());
229 }
230 }
alexfh4df43642013-04-24 12:46:44 +0000231 return false;
djasper7f663602013-03-20 09:53:23 +0000232}
233
234} // namespace format
235} // namespace clang
236
237int main(int argc, const char **argv) {
238 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000239
240 // Hide unrelated options.
241 StringMap<cl::Option*> Options;
242 cl::getRegisteredOptions(Options);
243 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
244 I != E; ++I) {
245 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
246 I->first() != "version")
247 I->second->setHiddenFlag(cl::ReallyHidden);
248 }
249
djasper7f663602013-03-20 09:53:23 +0000250 cl::ParseCommandLineOptions(
251 argc, argv,
252 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000253 "If no arguments are specified, it formats the code from standard input\n"
254 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000255 "If <file>s are given, it reformats the files. If -i is specified\n"
256 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000257 "result is written to the standard output.\n");
258
djasper7f663602013-03-20 09:53:23 +0000259 if (Help)
260 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000261
alexfh59883452013-05-10 11:56:10 +0000262 if (DumpConfig) {
revane4d118692013-09-30 13:31:48 +0000263 std::string Config =
264 clang::format::configurationAsText(clang::format::getStyle(
alexfh7e0adcf2013-12-02 15:21:38 +0000265 Style, FileNames.empty() ? AssumeFilename : FileNames[0],
266 FallbackStyle));
alexfh59883452013-05-10 11:56:10 +0000267 llvm::outs() << Config << "\n";
268 return 0;
269 }
270
alexfh4df43642013-04-24 12:46:44 +0000271 bool Error = false;
272 switch (FileNames.size()) {
273 case 0:
274 Error = clang::format::format("-");
275 break;
276 case 1:
277 Error = clang::format::format(FileNames[0]);
278 break;
279 default:
alexfh6e701792013-07-18 22:54:56 +0000280 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
281 llvm::errs() << "error: -offset, -length and -lines can only be used for "
alexfh4df43642013-04-24 12:46:44 +0000282 "single file.\n";
283 return 1;
284 }
285 for (unsigned i = 0; i < FileNames.size(); ++i)
286 Error |= clang::format::format(FileNames[i]);
287 break;
288 }
289 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000290}