blob: 1477e9347d0c5118462fc3205519e23668f73af0 [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"
23#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/Signals.h"
25
26using namespace llvm;
27
28static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
29
alexfh4df43642013-04-24 12:46:44 +000030static cl::list<unsigned>
31Offsets("offset", cl::desc("Format a range starting at this file offset. Can "
32 "only be used with one input file."));
33static cl::list<unsigned>
34Lengths("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."));
djasper7f663602013-03-20 09:53:23 +000037static cl::opt<std::string> Style(
38 "style",
39 cl::desc("Coding style, currently supports: LLVM, Google, Chromium."),
40 cl::init("LLVM"));
41static cl::opt<bool> Inplace("i",
alexfh4df43642013-04-24 12:46:44 +000042 cl::desc("Inplace edit <file>s, if specified."));
djasper7f663602013-03-20 09:53:23 +000043
44static cl::opt<bool> OutputXML(
45 "output-replacements-xml", cl::desc("Output replacements as XML."));
46
alexfh4df43642013-04-24 12:46:44 +000047static cl::list<std::string> FileNames(cl::Positional,
48 cl::desc("[<file> ...]"));
djasper7f663602013-03-20 09:53:23 +000049
50namespace clang {
51namespace format {
52
53static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
54 SourceManager &Sources, FileManager &Files) {
55 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
56 FileName,
57 Source->getBufferSize(), 0);
58 Sources.overrideFileContents(Entry, Source, true);
59 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
60}
61
62static FormatStyle getStyle() {
63 FormatStyle TheStyle = getGoogleStyle();
64 if (Style == "LLVM")
65 TheStyle = getLLVMStyle();
66 if (Style == "Chromium")
67 TheStyle = getChromiumStyle();
68 return TheStyle;
69}
70
alexfh4df43642013-04-24 12:46:44 +000071// Returns true on error.
72static bool format(std::string FileName) {
djasper7f663602013-03-20 09:53:23 +000073 FileManager Files((FileSystemOptions()));
74 DiagnosticsEngine Diagnostics(
75 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
76 new DiagnosticOptions);
77 SourceManager Sources(Diagnostics, Files);
78 OwningPtr<MemoryBuffer> Code;
79 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
80 llvm::errs() << ec.message() << "\n";
alexfh4df43642013-04-24 12:46:44 +000081 return true;
djasper7f663602013-03-20 09:53:23 +000082 }
83 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
84 Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
85 if (Offsets.empty())
86 Offsets.push_back(0);
87 if (Offsets.size() != Lengths.size() &&
88 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +000089 llvm::errs()
90 << "error: number of -offset and -length arguments must match.\n";
91 return true;
djasper7f663602013-03-20 09:53:23 +000092 }
93 std::vector<CharSourceRange> Ranges;
alexfh4df43642013-04-24 12:46:44 +000094 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
95 if (Offsets[i] >= Code->getBufferSize()) {
96 llvm::errs() << "error: offset " << Offsets[i]
97 << " is outside the file\n";
98 return true;
99 }
djasper7f663602013-03-20 09:53:23 +0000100 SourceLocation Start =
101 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
102 SourceLocation End;
103 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000104 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
105 llvm::errs() << "error: invalid length " << Lengths[i]
106 << ", offset + length (" << Offsets[i] + Lengths[i]
107 << ") is outside the file.\n";
108 return true;
109 }
djasper7f663602013-03-20 09:53:23 +0000110 End = Start.getLocWithOffset(Lengths[i]);
111 } else {
112 End = Sources.getLocForEndOfFile(ID);
113 }
114 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
115 }
116 tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges);
117 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000118 llvm::outs()
119 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000120 for (tooling::Replacements::const_iterator I = Replaces.begin(),
121 E = Replaces.end();
122 I != E; ++I) {
123 llvm::outs() << "<replacement "
124 << "offset='" << I->getOffset() << "' "
125 << "length='" << I->getLength() << "'>"
126 << I->getReplacementText() << "</replacement>\n";
127 }
128 llvm::outs() << "</replacements>\n";
129 } else {
130 Rewriter Rewrite(Sources, LangOptions());
131 tooling::applyAllReplacements(Replaces, Rewrite);
132 if (Inplace) {
133 if (Replaces.size() == 0)
alexfh4df43642013-04-24 12:46:44 +0000134 return false; // Nothing changed, don't touch the file.
djasper7f663602013-03-20 09:53:23 +0000135
136 std::string ErrorInfo;
137 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
138 llvm::raw_fd_ostream::F_Binary);
139 if (!ErrorInfo.empty()) {
140 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
alexfh4df43642013-04-24 12:46:44 +0000141 return true;
djasper7f663602013-03-20 09:53:23 +0000142 }
143 Rewrite.getEditBuffer(ID).write(FileStream);
144 FileStream.flush();
145 } else {
146 Rewrite.getEditBuffer(ID).write(outs());
147 }
148 }
alexfh4df43642013-04-24 12:46:44 +0000149 return false;
djasper7f663602013-03-20 09:53:23 +0000150}
151
152} // namespace format
153} // namespace clang
154
155int main(int argc, const char **argv) {
156 llvm::sys::PrintStackTraceOnErrorSignal();
157 cl::ParseCommandLineOptions(
158 argc, argv,
159 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000160 "If no arguments are specified, it formats the code from standard input\n"
161 "and writes the result to the standard output.\n"
alexfh4df43642013-04-24 12:46:44 +0000162 "If <file>s are given, it reformats the files. If -i is specified \n"
163 "together with <file>s, the files are edited in-place. Otherwise, the \n"
164 "result is written to the standard output.\n");
165
djasper7f663602013-03-20 09:53:23 +0000166 if (Help)
167 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000168
169 bool Error = false;
170 switch (FileNames.size()) {
171 case 0:
172 Error = clang::format::format("-");
173 break;
174 case 1:
175 Error = clang::format::format(FileNames[0]);
176 break;
177 default:
178 if (!Offsets.empty() || !Lengths.empty()) {
179 llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
180 "single file.\n";
181 return 1;
182 }
183 for (unsigned i = 0; i < FileNames.size(); ++i)
184 Error |= clang::format::format(FileNames[i]);
185 break;
186 }
187 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000188}