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 /// 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/InitLLVM.h"
26 #include "llvm/Support/Process.h"
29 using clang::tooling::Replacements;
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>
63 Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
64 cl::init(clang::format::DefaultFormatStyle),
65 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 "Use -fallback-style=none to skip formatting."),
73 cl::init(clang::format::DefaultFallbackStyle),
74 cl::cat(ClangFormatCategory));
76 static cl::opt<std::string>
77 AssumeFileName("assume-filename",
78 cl::desc("When reading from stdin, clang-format assumes this\n"
79 "filename to look for a style config file (with\n"
80 "-style=file) and to determine the language."),
81 cl::init("<stdin>"), cl::cat(ClangFormatCategory));
83 static cl::opt<bool> Inplace("i",
84 cl::desc("Inplace edit <file>s, if specified."),
85 cl::cat(ClangFormatCategory));
87 static cl::opt<bool> OutputXML("output-replacements-xml",
88 cl::desc("Output replacements as XML."),
89 cl::cat(ClangFormatCategory));
91 DumpConfig("dump-config",
92 cl::desc("Dump configuration options to stdout and exit.\n"
93 "Can be used with -style option."),
94 cl::cat(ClangFormatCategory));
95 static cl::opt<unsigned>
97 cl::desc("The position of the cursor when invoking\n"
98 "clang-format from an editor integration"),
99 cl::init(0), cl::cat(ClangFormatCategory));
101 static cl::opt<bool> SortIncludes(
103 cl::desc("If set, overrides the include sorting behavior determined by the "
104 "SortIncludes style flag"),
105 cl::cat(ClangFormatCategory));
108 Verbose("verbose", cl::desc("If set, shows the list of processed files"),
109 cl::cat(ClangFormatCategory));
111 static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
112 cl::cat(ClangFormatCategory));
117 static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
118 SourceManager &Sources, FileManager &Files,
119 vfs::InMemoryFileSystem *MemFS) {
120 MemFS->addFileNoOwn(FileName, 0, Source);
121 return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
125 // Parses <start line>:<end line> input to a pair of line numbers.
126 // Returns true on error.
127 static bool parseLineRange(StringRef Input, unsigned &FromLine,
129 std::pair<StringRef, StringRef> LineRange = Input.split(':');
130 return LineRange.first.getAsInteger(0, FromLine) ||
131 LineRange.second.getAsInteger(0, ToLine);
134 static bool fillRanges(MemoryBuffer *Code,
135 std::vector<tooling::Range> &Ranges) {
136 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
137 new vfs::InMemoryFileSystem);
138 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
139 DiagnosticsEngine Diagnostics(
140 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
141 new DiagnosticOptions);
142 SourceManager Sources(Diagnostics, Files);
143 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
144 InMemoryFileSystem.get());
145 if (!LineRanges.empty()) {
146 if (!Offsets.empty() || !Lengths.empty()) {
147 errs() << "error: cannot use -lines with -offset/-length\n";
151 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
152 unsigned FromLine, ToLine;
153 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
154 errs() << "error: invalid <start line>:<end line> pair\n";
157 if (FromLine > ToLine) {
158 errs() << "error: start line should be less than end line\n";
161 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
162 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
163 if (Start.isInvalid() || End.isInvalid())
165 unsigned Offset = Sources.getFileOffset(Start);
166 unsigned Length = Sources.getFileOffset(End) - Offset;
167 Ranges.push_back(tooling::Range(Offset, Length));
173 Offsets.push_back(0);
174 if (Offsets.size() != Lengths.size() &&
175 !(Offsets.size() == 1 && Lengths.empty())) {
176 errs() << "error: number of -offset and -length arguments must match.\n";
179 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
180 if (Offsets[i] >= Code->getBufferSize()) {
181 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
184 SourceLocation Start =
185 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
187 if (i < Lengths.size()) {
188 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
189 errs() << "error: invalid length " << Lengths[i]
190 << ", offset + length (" << Offsets[i] + Lengths[i]
191 << ") is outside the file.\n";
194 End = Start.getLocWithOffset(Lengths[i]);
196 End = Sources.getLocForEndOfFile(ID);
198 unsigned Offset = Sources.getFileOffset(Start);
199 unsigned Length = Sources.getFileOffset(End) - Offset;
200 Ranges.push_back(tooling::Range(Offset, Length));
205 static void outputReplacementXML(StringRef Text) {
206 // FIXME: When we sort includes, we need to make sure the stream is correct
210 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
211 outs() << Text.substr(From, Index - From);
212 switch (Text[Index]) {
226 llvm_unreachable("Unexpected character encountered!");
230 outs() << Text.substr(From);
233 static void outputReplacementsXML(const Replacements &Replaces) {
234 for (const auto &R : Replaces) {
235 outs() << "<replacement "
236 << "offset='" << R.getOffset() << "' "
237 << "length='" << R.getLength() << "'>";
238 outputReplacementXML(R.getReplacementText());
239 outs() << "</replacement>\n";
243 // Returns true on error.
244 static bool format(StringRef FileName) {
245 if (!OutputXML && Inplace && FileName == "-") {
246 errs() << "error: cannot use -i when reading from stdin.\n";
249 // On Windows, overwriting a file with an open file mapping doesn't work,
250 // so read the whole file into memory when formatting in-place.
251 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
252 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
253 MemoryBuffer::getFileOrSTDIN(FileName);
254 if (std::error_code EC = CodeOrErr.getError()) {
255 errs() << EC.message() << "\n";
258 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
259 if (Code->getBufferSize() == 0)
260 return false; // Empty files are formatted correctly.
261 std::vector<tooling::Range> Ranges;
262 if (fillRanges(Code.get(), Ranges))
264 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
266 llvm::Expected<FormatStyle> FormatStyle =
267 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
269 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
273 if (SortIncludes.getNumOccurrences() != 0)
274 FormatStyle->SortIncludes = SortIncludes;
275 unsigned CursorPosition = Cursor;
276 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
277 AssumedFileName, &CursorPosition);
278 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
280 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
283 // Get new affected ranges after sorting `#includes`.
284 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
285 FormattingAttemptStatus Status;
286 Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
287 AssumedFileName, &Status);
288 Replaces = Replaces.merge(FormatChanges);
290 outs() << "<?xml version='1.0'?>\n<replacements "
291 "xml:space='preserve' incomplete_format='"
292 << (Status.FormatComplete ? "false" : "true") << "'";
293 if (!Status.FormatComplete)
294 outs() << " line='" << Status.Line << "'";
296 if (Cursor.getNumOccurrences() != 0)
298 << FormatChanges.getShiftedCodePosition(CursorPosition)
301 outputReplacementsXML(Replaces);
302 outs() << "</replacements>\n";
304 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
305 new vfs::InMemoryFileSystem);
306 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
307 DiagnosticsEngine Diagnostics(
308 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
309 new DiagnosticOptions);
310 SourceManager Sources(Diagnostics, Files);
311 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
312 InMemoryFileSystem.get());
313 Rewriter Rewrite(Sources, LangOptions());
314 tooling::applyAllReplacements(Replaces, Rewrite);
316 if (Rewrite.overwriteChangedFiles())
319 if (Cursor.getNumOccurrences() != 0) {
320 outs() << "{ \"Cursor\": "
321 << FormatChanges.getShiftedCodePosition(CursorPosition)
322 << ", \"IncompleteFormat\": "
323 << (Status.FormatComplete ? "false" : "true");
324 if (!Status.FormatComplete)
325 outs() << ", \"Line\": " << Status.Line;
328 Rewrite.getEditBuffer(ID).write(outs());
334 } // namespace format
337 static void PrintVersion(raw_ostream &OS) {
338 OS << clang::getClangToolFullVersion("clang-format") << '\n';
341 int main(int argc, const char **argv) {
342 llvm::InitLLVM X(argc, argv);
344 cl::HideUnrelatedOptions(ClangFormatCategory);
346 cl::SetVersionPrinter(PrintVersion);
347 cl::ParseCommandLineOptions(
349 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf code.\n\n"
350 "If no arguments are specified, it formats the code from standard input\n"
351 "and writes the result to the standard output.\n"
352 "If <file>s are given, it reformats the files. If -i is specified\n"
353 "together with <file>s, the files are edited in-place. Otherwise, the\n"
354 "result is written to the standard output.\n");
357 cl::PrintHelpMessage();
363 std::unique_ptr<llvm::MemoryBuffer> Code;
364 if (FileNames.empty()) {
365 // We can't read the code to detect the language if there's no
366 // file name, so leave Code empty here.
367 FileName = AssumeFileName;
369 // Read in the code in case the filename alone isn't enough to
370 // detect the language.
371 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
372 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
373 if (std::error_code EC = CodeOrErr.getError()) {
374 llvm::errs() << EC.message() << "\n";
377 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
378 Code = std::move(CodeOrErr.get());
380 llvm::Expected<clang::format::FormatStyle> FormatStyle =
381 clang::format::getStyle(Style, FileName, FallbackStyle,
382 Code ? Code->getBuffer() : "");
384 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
387 std::string Config = clang::format::configurationAsText(*FormatStyle);
388 outs() << Config << "\n";
393 if (FileNames.empty()) {
394 Error = clang::format::format("-");
395 return Error ? 1 : 0;
397 if (FileNames.size() != 1 && (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
398 errs() << "error: -offset, -length and -lines can only be used for "
402 for (const auto &FileName : FileNames) {
404 errs() << "Formatting " << FileName << "\n";
405 Error |= clang::format::format(FileName);
407 return Error ? 1 : 0;