1 //===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements a clang-format tool that automatically formats
12 /// (fragments of) C++ code.
14 //===----------------------------------------------------------------------===//
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/Basic/Version.h"
21 #include "clang/Format/Format.h"
22 #include "clang/Lex/Lexer.h"
23 #include "clang/Rewrite/Core/Rewriter.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Signals.h"
31 static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
33 // Mark all our options with this category, everything else (except for -version
34 // and -help) will be hidden.
35 static cl::OptionCategory ClangFormatCategory("Clang-format options");
37 static cl::list<unsigned>
39 cl::desc("Format a range starting at this byte offset.\n"
40 "Multiple ranges can be formatted by specifying\n"
41 "several -offset and -length pairs.\n"
42 "Can only be used with one input file."),
43 cl::cat(ClangFormatCategory));
44 static cl::list<unsigned>
46 cl::desc("Format a range of this length (in bytes).\n"
47 "Multiple ranges can be formatted by specifying\n"
48 "several -offset and -length pairs.\n"
49 "When only a single -offset is specified without\n"
50 "-length, clang-format will format up to the end\n"
52 "Can only be used with one input file."),
53 cl::cat(ClangFormatCategory));
54 static cl::list<std::string>
55 LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
56 "lines (both 1-based).\n"
57 "Multiple ranges can be formatted by specifying\n"
58 "several -lines arguments.\n"
59 "Can't be used with -offset and -length.\n"
60 "Can only be used with one input file."),
61 cl::cat(ClangFormatCategory));
62 static cl::opt<std::string>
64 cl::desc(clang::format::StyleOptionHelpDescription),
65 cl::init("file"), cl::cat(ClangFormatCategory));
66 static cl::opt<std::string>
67 FallbackStyle("fallback-style",
68 cl::desc("The name of the predefined style used as a\n"
69 "fallback in case clang-format is invoked with\n"
70 "-style=file, but can not find the .clang-format\n"
72 cl::init("LLVM"), cl::cat(ClangFormatCategory));
74 static cl::opt<std::string>
75 AssumeFilename("assume-filename",
76 cl::desc("When reading from stdin, clang-format assumes this\n"
77 "filename to look for a style config file (with\n"
79 cl::cat(ClangFormatCategory));
81 static cl::opt<bool> Inplace("i",
82 cl::desc("Inplace edit <file>s, if specified."),
83 cl::cat(ClangFormatCategory));
85 static cl::opt<bool> OutputXML("output-replacements-xml",
86 cl::desc("Output replacements as XML."),
87 cl::cat(ClangFormatCategory));
89 DumpConfig("dump-config",
90 cl::desc("Dump configuration options to stdout and exit.\n"
91 "Can be used with -style option."),
92 cl::cat(ClangFormatCategory));
93 static cl::opt<unsigned>
95 cl::desc("The position of the cursor when invoking\n"
96 "clang-format from an editor integration"),
97 cl::init(0), cl::cat(ClangFormatCategory));
99 static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
100 cl::cat(ClangFormatCategory));
105 static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
106 SourceManager &Sources, FileManager &Files) {
107 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
109 Source->getBufferSize(), 0);
110 Sources.overrideFileContents(Entry, Source, true);
111 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
114 // Parses <start line>:<end line> input to a pair of line numbers.
115 // Returns true on error.
116 static bool parseLineRange(StringRef Input, unsigned &FromLine,
118 std::pair<StringRef, StringRef> LineRange = Input.split(':');
119 return LineRange.first.getAsInteger(0, FromLine) ||
120 LineRange.second.getAsInteger(0, ToLine);
123 static bool fillRanges(SourceManager &Sources, FileID ID,
124 const MemoryBuffer *Code,
125 std::vector<CharSourceRange> &Ranges) {
126 if (!LineRanges.empty()) {
127 if (!Offsets.empty() || !Lengths.empty()) {
128 llvm::errs() << "error: cannot use -lines with -offset/-length\n";
132 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
133 unsigned FromLine, ToLine;
134 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
135 llvm::errs() << "error: invalid <start line>:<end line> pair\n";
138 if (FromLine > ToLine) {
139 llvm::errs() << "error: start line should be less than end line\n";
142 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
143 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
144 if (Start.isInvalid() || End.isInvalid())
146 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
152 Offsets.push_back(0);
153 if (Offsets.size() != Lengths.size() &&
154 !(Offsets.size() == 1 && Lengths.empty())) {
156 << "error: number of -offset and -length arguments must match.\n";
159 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
160 if (Offsets[i] >= Code->getBufferSize()) {
161 llvm::errs() << "error: offset " << Offsets[i]
162 << " is outside the file\n";
165 SourceLocation Start =
166 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
168 if (i < Lengths.size()) {
169 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
170 llvm::errs() << "error: invalid length " << Lengths[i]
171 << ", offset + length (" << Offsets[i] + Lengths[i]
172 << ") is outside the file.\n";
175 End = Start.getLocWithOffset(Lengths[i]);
177 End = Sources.getLocForEndOfFile(ID);
179 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
184 static void outputReplacementXML(StringRef Text) {
187 while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
188 llvm::outs() << Text.substr(From, Index - From);
189 switch (Text[Index]) {
191 llvm::outs() << " ";
194 llvm::outs() << " ";
197 llvm_unreachable("Unexpected character encountered!");
201 llvm::outs() << Text.substr(From);
204 // Returns true on error.
205 static bool format(StringRef FileName) {
206 FileManager Files((FileSystemOptions()));
207 DiagnosticsEngine Diagnostics(
208 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
209 new DiagnosticOptions);
210 SourceManager Sources(Diagnostics, Files);
211 std::unique_ptr<MemoryBuffer> Code;
212 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
213 llvm::errs() << ec.message() << "\n";
216 if (Code->getBufferSize() == 0)
217 return false; // Empty files are formatted correctly.
218 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
219 std::vector<CharSourceRange> Ranges;
220 if (fillRanges(Sources, ID, Code.get(), Ranges))
223 FormatStyle FormatStyle = getStyle(
224 Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
225 Lexer Lex(ID, Sources.getBuffer(ID), Sources,
226 getFormattingLangOpts(FormatStyle.Standard));
227 tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
230 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
231 for (tooling::Replacements::const_iterator I = Replaces.begin(),
234 llvm::outs() << "<replacement "
235 << "offset='" << I->getOffset() << "' "
236 << "length='" << I->getLength() << "'>";
237 outputReplacementXML(I->getReplacementText());
238 llvm::outs() << "</replacement>\n";
240 llvm::outs() << "</replacements>\n";
242 Rewriter Rewrite(Sources, LangOptions());
243 tooling::applyAllReplacements(Replaces, Rewrite);
245 if (Rewrite.overwriteChangedFiles())
248 if (Cursor.getNumOccurrences() != 0)
249 outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
250 Replaces, Cursor) << " }\n";
251 Rewrite.getEditBuffer(ID).write(outs());
257 } // namespace format
260 static void PrintVersion() {
261 raw_ostream &OS = outs();
262 OS << clang::getClangToolFullVersion("clang-format") << '\n';
265 int main(int argc, const char **argv) {
266 llvm::sys::PrintStackTraceOnErrorSignal();
268 // Hide unrelated options.
269 StringMap<cl::Option*> Options;
270 cl::getRegisteredOptions(Options);
271 for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
273 if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
274 I->first() != "version")
275 I->second->setHiddenFlag(cl::ReallyHidden);
278 cl::SetVersionPrinter(PrintVersion);
279 cl::ParseCommandLineOptions(
281 "A tool to format C/C++/Obj-C code.\n\n"
282 "If no arguments are specified, it formats the code from standard input\n"
283 "and writes the result to the standard output.\n"
284 "If <file>s are given, it reformats the files. If -i is specified\n"
285 "together with <file>s, the files are edited in-place. Otherwise, the\n"
286 "result is written to the standard output.\n");
289 cl::PrintHelpMessage();
293 clang::format::configurationAsText(clang::format::getStyle(
294 Style, FileNames.empty() ? AssumeFilename : FileNames[0],
296 llvm::outs() << Config << "\n";
301 switch (FileNames.size()) {
303 Error = clang::format::format("-");
306 Error = clang::format::format(FileNames[0]);
309 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
310 llvm::errs() << "error: -offset, -length and -lines can only be used for "
314 for (unsigned i = 0; i < FileNames.size(); ++i)
315 Error |= clang::format::format(FileNames[i]);
318 return Error ? 1 : 0;