blob: d8c0b51ee1c2bad3f07ee5825c9e21d05f0ad85d [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
klimek82392d72013-12-03 09:46:06 +0000182static void outputReplacementXML(StringRef Text) {
183 size_t From = 0;
184 size_t Index;
185 while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
186 llvm::outs() << Text.substr(From, Index - From);
187 switch (Text[Index]) {
188 case '\n':
189 llvm::outs() << "&#10;";
190 break;
191 case '\r':
192 llvm::outs() << "&#13;";
193 break;
194 default:
195 llvm_unreachable("Unexpected character encountered!");
196 }
197 From = Index + 1;
198 }
199 llvm::outs() << Text.substr(From);
200}
201
alexfh6e701792013-07-18 22:54:56 +0000202// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000203static bool format(StringRef FileName) {
alexfh6e701792013-07-18 22:54:56 +0000204 FileManager Files((FileSystemOptions()));
205 DiagnosticsEngine Diagnostics(
206 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
207 new DiagnosticOptions);
208 SourceManager Sources(Diagnostics, Files);
209 OwningPtr<MemoryBuffer> Code;
210 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
211 llvm::errs() << ec.message() << "\n";
212 return true;
213 }
214 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000215 return false; // Empty files are formatted correctly.
alexfh6e701792013-07-18 22:54:56 +0000216 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
217 std::vector<CharSourceRange> Ranges;
218 if (fillRanges(Sources, ID, Code.get(), Ranges))
219 return true;
220
alexfh7e0adcf2013-12-02 15:21:38 +0000221 FormatStyle FormatStyle = getStyle(
222 Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
alexfh943428e2013-06-28 12:51:24 +0000223 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
224 getFormattingLangOpts(FormatStyle.Standard));
225 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000226 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000227 llvm::outs()
228 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000229 for (tooling::Replacements::const_iterator I = Replaces.begin(),
230 E = Replaces.end();
231 I != E; ++I) {
232 llvm::outs() << "<replacement "
233 << "offset='" << I->getOffset() << "' "
klimek82392d72013-12-03 09:46:06 +0000234 << "length='" << I->getLength() << "'>";
235 outputReplacementXML(I->getReplacementText());
236 llvm::outs() << "</replacement>\n";
djasper7f663602013-03-20 09:53:23 +0000237 }
238 llvm::outs() << "</replacements>\n";
239 } else {
240 Rewriter Rewrite(Sources, LangOptions());
241 tooling::applyAllReplacements(Replaces, Rewrite);
242 if (Inplace) {
alp8d1b4dd2013-11-08 08:07:19 +0000243 if (Rewrite.overwriteChangedFiles())
alexfh4df43642013-04-24 12:46:44 +0000244 return true;
djasper7f663602013-03-20 09:53:23 +0000245 } else {
djasper898b4f72013-05-21 14:21:46 +0000246 if (Cursor.getNumOccurrences() != 0)
djasperd0252b72013-05-21 12:21:39 +0000247 outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
248 Replaces, Cursor) << " }\n";
djasper7f663602013-03-20 09:53:23 +0000249 Rewrite.getEditBuffer(ID).write(outs());
250 }
251 }
alexfh4df43642013-04-24 12:46:44 +0000252 return false;
djasper7f663602013-03-20 09:53:23 +0000253}
254
255} // namespace format
256} // namespace clang
257
258int main(int argc, const char **argv) {
259 llvm::sys::PrintStackTraceOnErrorSignal();
alexfh725a9f72013-05-10 18:12:00 +0000260
261 // Hide unrelated options.
262 StringMap<cl::Option*> Options;
263 cl::getRegisteredOptions(Options);
264 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
265 I != E; ++I) {
266 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
267 I->first() != "version")
268 I->second->setHiddenFlag(cl::ReallyHidden);
269 }
270
djasper7f663602013-03-20 09:53:23 +0000271 cl::ParseCommandLineOptions(
272 argc, argv,
273 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000274 "If no arguments are specified, it formats the code from standard input\n"
275 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000276 "If <file>s are given, it reformats the files. If -i is specified\n"
277 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000278 "result is written to the standard output.\n");
279
djasper7f663602013-03-20 09:53:23 +0000280 if (Help)
281 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000282
alexfh59883452013-05-10 11:56:10 +0000283 if (DumpConfig) {
revane4d118692013-09-30 13:31:48 +0000284 std::string Config =
285 clang::format::configurationAsText(clang::format::getStyle(
alexfh7e0adcf2013-12-02 15:21:38 +0000286 Style, FileNames.empty() ? AssumeFilename : FileNames[0],
287 FallbackStyle));
alexfh59883452013-05-10 11:56:10 +0000288 llvm::outs() << Config << "\n";
289 return 0;
290 }
291
alexfh4df43642013-04-24 12:46:44 +0000292 bool Error = false;
293 switch (FileNames.size()) {
294 case 0:
295 Error = clang::format::format("-");
296 break;
297 case 1:
298 Error = clang::format::format(FileNames[0]);
299 break;
300 default:
alexfh6e701792013-07-18 22:54:56 +0000301 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
302 llvm::errs() << "error: -offset, -length and -lines can only be used for "
alexfh4df43642013-04-24 12:46:44 +0000303 "single file.\n";
304 return 1;
305 }
306 for (unsigned i = 0; i < FileNames.size(); ++i)
307 Error |= clang::format::format(FileNames[i]);
308 break;
309 }
310 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000311}