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/Rewrite/Core/Rewriter.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Signals.h"
28 using clang::tooling::Replacements;
30 static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
32 // Mark all our options with this category, everything else (except for -version
33 // and -help) will be hidden.
34 static cl::OptionCategory ClangFormatCategory("Clang-format options");
36 static cl::list<unsigned>
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));
43 static cl::list<unsigned>
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"
51 "Can only be used with one input file."),
52 cl::cat(ClangFormatCategory));
53 static cl::list<std::string>
54 LineRanges("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));
61 static cl::opt<std::string>
63 cl::desc(clang::format::StyleOptionHelpDescription),
64 cl::init("file"), cl::cat(ClangFormatCategory));
65 static cl::opt<std::string>
66 FallbackStyle("fallback-style",
67 cl::desc("The name of the predefined style used as a\n"
68 "fallback in case clang-format is invoked with\n"
69 "-style=file, but can not find the .clang-format\n"
71 "Use -fallback-style=none to skip formatting."),
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"
78 "-style=file) and to determine the language."),
79 cl::init("<stdin>"), 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::opt<bool> SortIncludes(
101 cl::desc("If set, overrides the include sorting behavior determined by the "
102 "SortIncludes style flag"),
103 cl::cat(ClangFormatCategory));
105 static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
106 cl::cat(ClangFormatCategory));
111 static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
112 SourceManager &Sources, FileManager &Files,
113 vfs::InMemoryFileSystem *MemFS) {
114 MemFS->addFileNoOwn(FileName, 0, Source);
115 return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
119 // Parses <start line>:<end line> input to a pair of line numbers.
120 // Returns true on error.
121 static bool parseLineRange(StringRef Input, unsigned &FromLine,
123 std::pair<StringRef, StringRef> LineRange = Input.split(':');
124 return LineRange.first.getAsInteger(0, FromLine) ||
125 LineRange.second.getAsInteger(0, ToLine);
128 static bool fillRanges(MemoryBuffer *Code,
129 std::vector<tooling::Range> &Ranges) {
130 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
131 new vfs::InMemoryFileSystem);
132 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
133 DiagnosticsEngine Diagnostics(
134 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
135 new DiagnosticOptions);
136 SourceManager Sources(Diagnostics, Files);
137 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
138 InMemoryFileSystem.get());
139 if (!LineRanges.empty()) {
140 if (!Offsets.empty() || !Lengths.empty()) {
141 errs() << "error: cannot use -lines with -offset/-length\n";
145 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
146 unsigned FromLine, ToLine;
147 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
148 errs() << "error: invalid <start line>:<end line> pair\n";
151 if (FromLine > ToLine) {
152 errs() << "error: start line should be less than end line\n";
155 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
156 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
157 if (Start.isInvalid() || End.isInvalid())
159 unsigned Offset = Sources.getFileOffset(Start);
160 unsigned Length = Sources.getFileOffset(End) - Offset;
161 Ranges.push_back(tooling::Range(Offset, Length));
167 Offsets.push_back(0);
168 if (Offsets.size() != Lengths.size() &&
169 !(Offsets.size() == 1 && Lengths.empty())) {
170 errs() << "error: number of -offset and -length arguments must match.\n";
173 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
174 if (Offsets[i] >= Code->getBufferSize()) {
175 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
178 SourceLocation Start =
179 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
181 if (i < Lengths.size()) {
182 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
183 errs() << "error: invalid length " << Lengths[i]
184 << ", offset + length (" << Offsets[i] + Lengths[i]
185 << ") is outside the file.\n";
188 End = Start.getLocWithOffset(Lengths[i]);
190 End = Sources.getLocForEndOfFile(ID);
192 unsigned Offset = Sources.getFileOffset(Start);
193 unsigned Length = Sources.getFileOffset(End) - Offset;
194 Ranges.push_back(tooling::Range(Offset, Length));
199 static void outputReplacementXML(StringRef Text) {
200 // FIXME: When we sort includes, we need to make sure the stream is correct
204 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
205 outs() << Text.substr(From, Index - From);
206 switch (Text[Index]) {
220 llvm_unreachable("Unexpected character encountered!");
224 outs() << Text.substr(From);
227 static void outputReplacementsXML(const Replacements &Replaces) {
228 for (const auto &R : Replaces) {
229 outs() << "<replacement "
230 << "offset='" << R.getOffset() << "' "
231 << "length='" << R.getLength() << "'>";
232 outputReplacementXML(R.getReplacementText());
233 outs() << "</replacement>\n";
237 // Returns true on error.
238 static bool format(StringRef FileName) {
239 if (!OutputXML && Inplace && FileName == "-") {
240 errs() << "error: cannot use -i when reading from stdin.\n";
243 // On Windows, overwriting a file with an open file mapping doesn't work,
244 // so read the whole file into memory when formatting in-place.
245 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
246 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
247 MemoryBuffer::getFileOrSTDIN(FileName);
248 if (std::error_code EC = CodeOrErr.getError()) {
249 errs() << EC.message() << "\n";
252 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
253 if (Code->getBufferSize() == 0)
254 return false; // Empty files are formatted correctly.
255 std::vector<tooling::Range> Ranges;
256 if (fillRanges(Code.get(), Ranges))
258 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
260 llvm::Expected<FormatStyle> FormatStyle =
261 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
263 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
267 if (SortIncludes.getNumOccurrences() != 0)
268 FormatStyle->SortIncludes = SortIncludes;
269 unsigned CursorPosition = Cursor;
270 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
271 AssumedFileName, &CursorPosition);
272 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
274 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
277 // Get new affected ranges after sorting `#includes`.
278 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
279 FormattingAttemptStatus Status;
280 Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
281 AssumedFileName, &Status);
282 Replaces = Replaces.merge(FormatChanges);
284 outs() << "<?xml version='1.0'?>\n<replacements "
285 "xml:space='preserve' incomplete_format='"
286 << (Status.FormatComplete ? "false" : "true") << "'";
287 if (!Status.FormatComplete)
288 outs() << " line=" << Status.Line;
290 if (Cursor.getNumOccurrences() != 0)
292 << FormatChanges.getShiftedCodePosition(CursorPosition)
295 outputReplacementsXML(Replaces);
296 outs() << "</replacements>\n";
298 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
299 new vfs::InMemoryFileSystem);
300 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
301 DiagnosticsEngine Diagnostics(
302 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
303 new DiagnosticOptions);
304 SourceManager Sources(Diagnostics, Files);
305 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
306 InMemoryFileSystem.get());
307 Rewriter Rewrite(Sources, LangOptions());
308 tooling::applyAllReplacements(Replaces, Rewrite);
310 if (Rewrite.overwriteChangedFiles())
313 if (Cursor.getNumOccurrences() != 0) {
314 outs() << "{ \"Cursor\": "
315 << FormatChanges.getShiftedCodePosition(CursorPosition)
316 << ", \"IncompleteFormat\": "
317 << (Status.FormatComplete ? "false" : "true");
318 if (!Status.FormatComplete)
319 outs() << ", \"Line\": " << Status.Line;
322 Rewrite.getEditBuffer(ID).write(outs());
328 } // namespace format
331 static void PrintVersion() {
332 raw_ostream &OS = outs();
333 OS << clang::getClangToolFullVersion("clang-format") << '\n';
336 int main(int argc, const char **argv) {
337 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
339 cl::HideUnrelatedOptions(ClangFormatCategory);
341 cl::SetVersionPrinter(PrintVersion);
342 cl::ParseCommandLineOptions(
344 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf code.\n\n"
345 "If no arguments are specified, it formats the code from standard input\n"
346 "and writes the result to the standard output.\n"
347 "If <file>s are given, it reformats the files. If -i is specified\n"
348 "together with <file>s, the files are edited in-place. Otherwise, the\n"
349 "result is written to the standard output.\n");
352 cl::PrintHelpMessage();
355 llvm::Expected<clang::format::FormatStyle> FormatStyle =
356 clang::format::getStyle(
357 Style, FileNames.empty() ? AssumeFileName : FileNames[0],
360 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
363 std::string Config = clang::format::configurationAsText(*FormatStyle);
364 outs() << Config << "\n";
369 switch (FileNames.size()) {
371 Error = clang::format::format("-");
374 Error = clang::format::format(FileNames[0]);
377 if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
378 errs() << "error: -offset, -length and -lines can only be used for "
382 for (unsigned i = 0; i < FileNames.size(); ++i)
383 Error |= clang::format::format(FileNames[i]);
386 return Error ? 1 : 0;