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/Format/Format.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Rewrite/Core/Rewriter.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Signals.h"
28 static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
30 static cl::list<unsigned>
31 Offsets("offset", cl::desc("Format a range starting at this file offset. Can "
32 "only be used with one input file."));
33 static cl::list<unsigned>
34 Lengths("length", cl::desc("Format a range of this length. "
35 "When it's not specified, end of file is used. "
36 "Can only be used with one input file."));
37 static cl::opt<std::string> Style(
39 cl::desc("Coding style, currently supports: LLVM, Google, Chromium, Mozilla."),
41 static cl::opt<bool> Inplace("i",
42 cl::desc("Inplace edit <file>s, if specified."));
44 static cl::opt<bool> OutputXML(
45 "output-replacements-xml", cl::desc("Output replacements as XML."));
47 static cl::list<std::string> FileNames(cl::Positional,
48 cl::desc("[<file> ...]"));
53 static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
54 SourceManager &Sources, FileManager &Files) {
55 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
57 Source->getBufferSize(), 0);
58 Sources.overrideFileContents(Entry, Source, true);
59 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
62 static FormatStyle getStyle() {
63 FormatStyle TheStyle = getGoogleStyle();
65 TheStyle = getLLVMStyle();
66 else if (Style == "Chromium")
67 TheStyle = getChromiumStyle();
68 else if (Style == "Mozilla")
69 TheStyle = getMozillaStyle();
70 else if (Style != "Google")
71 llvm::errs() << "Unknown style " << Style << ", using Google style.\n";
76 // Returns true on error.
77 static bool format(std::string FileName) {
78 FileManager Files((FileSystemOptions()));
79 DiagnosticsEngine Diagnostics(
80 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
81 new DiagnosticOptions);
82 SourceManager Sources(Diagnostics, Files);
83 OwningPtr<MemoryBuffer> Code;
84 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
85 llvm::errs() << ec.message() << "\n";
88 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
89 Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
92 if (Offsets.size() != Lengths.size() &&
93 !(Offsets.size() == 1 && Lengths.empty())) {
95 << "error: number of -offset and -length arguments must match.\n";
98 std::vector<CharSourceRange> Ranges;
99 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
100 if (Offsets[i] >= Code->getBufferSize()) {
101 llvm::errs() << "error: offset " << Offsets[i]
102 << " is outside the file\n";
105 SourceLocation Start =
106 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
108 if (i < Lengths.size()) {
109 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
110 llvm::errs() << "error: invalid length " << Lengths[i]
111 << ", offset + length (" << Offsets[i] + Lengths[i]
112 << ") is outside the file.\n";
115 End = Start.getLocWithOffset(Lengths[i]);
117 End = Sources.getLocForEndOfFile(ID);
119 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
121 tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges);
124 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
125 for (tooling::Replacements::const_iterator I = Replaces.begin(),
128 llvm::outs() << "<replacement "
129 << "offset='" << I->getOffset() << "' "
130 << "length='" << I->getLength() << "'>"
131 << I->getReplacementText() << "</replacement>\n";
133 llvm::outs() << "</replacements>\n";
135 Rewriter Rewrite(Sources, LangOptions());
136 tooling::applyAllReplacements(Replaces, Rewrite);
138 if (Replaces.size() == 0)
139 return false; // Nothing changed, don't touch the file.
141 std::string ErrorInfo;
142 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
143 llvm::raw_fd_ostream::F_Binary);
144 if (!ErrorInfo.empty()) {
145 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
148 Rewrite.getEditBuffer(ID).write(FileStream);
151 Rewrite.getEditBuffer(ID).write(outs());
157 } // namespace format
160 int main(int argc, const char **argv) {
161 llvm::sys::PrintStackTraceOnErrorSignal();
162 cl::ParseCommandLineOptions(
164 "A tool to format C/C++/Obj-C code.\n\n"
165 "If no arguments are specified, it formats the code from standard input\n"
166 "and writes the result to the standard output.\n"
167 "If <file>s are given, it reformats the files. If -i is specified \n"
168 "together with <file>s, the files are edited in-place. Otherwise, the \n"
169 "result is written to the standard output.\n");
172 cl::PrintHelpMessage();
175 switch (FileNames.size()) {
177 Error = clang::format::format("-");
180 Error = clang::format::format(FileNames[0]);
183 if (!Offsets.empty() || !Lengths.empty()) {
184 llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
188 for (unsigned i = 0; i < FileNames.size(); ++i)
189 Error |= clang::format::format(FileNames[i]);
192 return Error ? 1 : 0;