blob: 5ae95781fb11ecc4749d94212ebe32d4d84e178e [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"
alexfh59883452013-05-10 11:56:10 +000023#include "llvm/Support/Debug.h"
djasper7f663602013-03-20 09:53:23 +000024#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Signals.h"
26
27using namespace llvm;
28
29static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
30
alexfh4df43642013-04-24 12:46:44 +000031static cl::list<unsigned>
32Offsets("offset", cl::desc("Format a range starting at this file offset. Can "
33 "only be used with one input file."));
34static cl::list<unsigned>
35Lengths("length", cl::desc("Format a range of this length. "
36 "When it's not specified, end of file is used. "
37 "Can only be used with one input file."));
djasper7f663602013-03-20 09:53:23 +000038static cl::opt<std::string> Style(
39 "style",
alexfh59883452013-05-10 11:56:10 +000040 cl::desc(
41 "Coding style, currently supports: LLVM, Google, Chromium, Mozilla. "
42 "Use '-style file' to load style configuration from .clang-format file "
43 "located in one of the parent directories of the source file (or "
44 "current directory for stdin)."),
djasper7f663602013-03-20 09:53:23 +000045 cl::init("LLVM"));
46static cl::opt<bool> Inplace("i",
alexfh4df43642013-04-24 12:46:44 +000047 cl::desc("Inplace edit <file>s, if specified."));
djasper7f663602013-03-20 09:53:23 +000048
49static cl::opt<bool> OutputXML(
50 "output-replacements-xml", cl::desc("Output replacements as XML."));
alexfh59883452013-05-10 11:56:10 +000051static cl::opt<bool>
52 DumpConfig("dump-config",
53 cl::desc("Dump configuration options to stdout and exit. Can be used with -style option."));
djasper7f663602013-03-20 09:53:23 +000054
alexfh4df43642013-04-24 12:46:44 +000055static cl::list<std::string> FileNames(cl::Positional,
56 cl::desc("[<file> ...]"));
djasper7f663602013-03-20 09:53:23 +000057
58namespace clang {
59namespace format {
60
61static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
62 SourceManager &Sources, FileManager &Files) {
63 const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
64 FileName,
65 Source->getBufferSize(), 0);
66 Sources.overrideFileContents(Entry, Source, true);
67 return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
68}
69
alexfh59883452013-05-10 11:56:10 +000070FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
71 if (!StyleName.equals_lower("file"))
72 return getPredefinedStyle(StyleName);
alexfh2d776172013-05-06 14:11:27 +000073
alexfh59883452013-05-10 11:56:10 +000074 SmallString<128> Path(FileName);
75 llvm::sys::fs::make_absolute(Path);
76 for (StringRef Directory = llvm::sys::path::parent_path(Path);
77 !Directory.empty();
78 Directory = llvm::sys::path::parent_path(Directory)) {
79 SmallString<128> ConfigFile(Directory);
80 llvm::sys::path::append(ConfigFile, ".clang-format");
81 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
82 bool IsFile = false;
83 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
84 if (IsFile) {
85 OwningPtr<MemoryBuffer> Text;
86 if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) {
87 llvm::errs() << ec.message() << "\n";
88 continue;
89 }
90 FormatStyle Style;
91 if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
92 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
93 << "\n";
94 continue;
95 }
96 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
97 return Style;
98 }
99 }
100 llvm::errs() << "Can't find usable .clang-format, using LLVM style\n";
101 return getLLVMStyle();
djasper7f663602013-03-20 09:53:23 +0000102}
103
alexfh4df43642013-04-24 12:46:44 +0000104// Returns true on error.
105static bool format(std::string FileName) {
djasper7f663602013-03-20 09:53:23 +0000106 FileManager Files((FileSystemOptions()));
107 DiagnosticsEngine Diagnostics(
108 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
109 new DiagnosticOptions);
110 SourceManager Sources(Diagnostics, Files);
111 OwningPtr<MemoryBuffer> Code;
112 if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
113 llvm::errs() << ec.message() << "\n";
alexfh4df43642013-04-24 12:46:44 +0000114 return true;
djasper7f663602013-03-20 09:53:23 +0000115 }
116 FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
117 Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
118 if (Offsets.empty())
119 Offsets.push_back(0);
120 if (Offsets.size() != Lengths.size() &&
121 !(Offsets.size() == 1 && Lengths.empty())) {
alexfh4df43642013-04-24 12:46:44 +0000122 llvm::errs()
123 << "error: number of -offset and -length arguments must match.\n";
124 return true;
djasper7f663602013-03-20 09:53:23 +0000125 }
126 std::vector<CharSourceRange> Ranges;
alexfh4df43642013-04-24 12:46:44 +0000127 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
128 if (Offsets[i] >= Code->getBufferSize()) {
129 llvm::errs() << "error: offset " << Offsets[i]
130 << " is outside the file\n";
131 return true;
132 }
djasper7f663602013-03-20 09:53:23 +0000133 SourceLocation Start =
134 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
135 SourceLocation End;
136 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000137 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
138 llvm::errs() << "error: invalid length " << Lengths[i]
139 << ", offset + length (" << Offsets[i] + Lengths[i]
140 << ") is outside the file.\n";
141 return true;
142 }
djasper7f663602013-03-20 09:53:23 +0000143 End = Start.getLocWithOffset(Lengths[i]);
144 } else {
145 End = Sources.getLocForEndOfFile(ID);
146 }
147 Ranges.push_back(CharSourceRange::getCharRange(Start, End));
148 }
alexfh59883452013-05-10 11:56:10 +0000149 tooling::Replacements Replaces =
150 reformat(getStyle(Style, FileName), Lex, Sources, Ranges);
djasper7f663602013-03-20 09:53:23 +0000151 if (OutputXML) {
alexfh4df43642013-04-24 12:46:44 +0000152 llvm::outs()
153 << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
djasper7f663602013-03-20 09:53:23 +0000154 for (tooling::Replacements::const_iterator I = Replaces.begin(),
155 E = Replaces.end();
156 I != E; ++I) {
157 llvm::outs() << "<replacement "
158 << "offset='" << I->getOffset() << "' "
159 << "length='" << I->getLength() << "'>"
160 << I->getReplacementText() << "</replacement>\n";
161 }
162 llvm::outs() << "</replacements>\n";
163 } else {
164 Rewriter Rewrite(Sources, LangOptions());
165 tooling::applyAllReplacements(Replaces, Rewrite);
166 if (Inplace) {
167 if (Replaces.size() == 0)
alexfh4df43642013-04-24 12:46:44 +0000168 return false; // Nothing changed, don't touch the file.
djasper7f663602013-03-20 09:53:23 +0000169
170 std::string ErrorInfo;
171 llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
172 llvm::raw_fd_ostream::F_Binary);
173 if (!ErrorInfo.empty()) {
174 llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
alexfh4df43642013-04-24 12:46:44 +0000175 return true;
djasper7f663602013-03-20 09:53:23 +0000176 }
177 Rewrite.getEditBuffer(ID).write(FileStream);
178 FileStream.flush();
179 } else {
180 Rewrite.getEditBuffer(ID).write(outs());
181 }
182 }
alexfh4df43642013-04-24 12:46:44 +0000183 return false;
djasper7f663602013-03-20 09:53:23 +0000184}
185
186} // namespace format
187} // namespace clang
188
189int main(int argc, const char **argv) {
190 llvm::sys::PrintStackTraceOnErrorSignal();
191 cl::ParseCommandLineOptions(
192 argc, argv,
193 "A tool to format C/C++/Obj-C code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000194 "If no arguments are specified, it formats the code from standard input\n"
195 "and writes the result to the standard output.\n"
alexfh4df43642013-04-24 12:46:44 +0000196 "If <file>s are given, it reformats the files. If -i is specified \n"
197 "together with <file>s, the files are edited in-place. Otherwise, the \n"
198 "result is written to the standard output.\n");
199
djasper7f663602013-03-20 09:53:23 +0000200 if (Help)
201 cl::PrintHelpMessage();
alexfh4df43642013-04-24 12:46:44 +0000202
alexfh59883452013-05-10 11:56:10 +0000203 if (DumpConfig) {
204 std::string Config = clang::format::configurationAsText(
205 clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0]));
206 llvm::outs() << Config << "\n";
207 return 0;
208 }
209
alexfh4df43642013-04-24 12:46:44 +0000210 bool Error = false;
211 switch (FileNames.size()) {
212 case 0:
213 Error = clang::format::format("-");
214 break;
215 case 1:
216 Error = clang::format::format(FileNames[0]);
217 break;
218 default:
219 if (!Offsets.empty() || !Lengths.empty()) {
220 llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
221 "single file.\n";
222 return 1;
223 }
224 for (unsigned i = 0; i < FileNames.size(); ++i)
225 Error |= clang::format::format(FileNames[i]);
226 break;
227 }
228 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000229}