ClangFormat.cpp revision c1baef687bd2e53aa5ac54b825d66eda86c9e408
1//===-- 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/Debug.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Signals.h"
26#include "llvm/ADT/StringMap.h"
27
28using namespace llvm;
29
30// Default style to use when no style specified or specified style not found.
31static const char *DefaultStyle = "LLVM";
32
33static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
34
35// Mark all our options with this category, everything else (except for -version
36// and -help) will be hidden.
37cl::OptionCategory ClangFormatCategory("Clang-format options");
38
39static cl::list<unsigned>
40    Offsets("offset",
41            cl::desc("Format a range starting at this byte offset.\n"
42                     "Multiple ranges can be formatted by specifying\n"
43                     "several -offset and -length pairs.\n"
44                     "Can only be used with one input file."),
45            cl::cat(ClangFormatCategory));
46static cl::list<unsigned>
47    Lengths("length",
48            cl::desc("Format a range of this length (in bytes).\n"
49                     "Multiple ranges can be formatted by specifying\n"
50                     "several -offset and -length pairs.\n"
51                     "When only a single -offset is specified without\n"
52                     "-length, clang-format will format up to the end\n"
53                     "of the file.\n"
54                     "Can only be used with one input file."),
55            cl::cat(ClangFormatCategory));
56static cl::opt<std::string>
57    Style("style",
58          cl::desc("Coding style, currently supports:\n"
59                   "  LLVM, Google, Chromium, Mozilla.\n"
60                   "Use -style=file to load style configuration from\n"
61                   ".clang-format file located in one of the parent\n"
62                   "directories of the source file (or current\n"
63                   "directory for stdin).\n"
64                   "Use -style=\"{key: value, ...}\" to set specific\n"
65                   "parameters, e.g.:\n"
66                   "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""),
67          cl::init(DefaultStyle), cl::cat(ClangFormatCategory));
68static cl::opt<bool> Inplace("i",
69                             cl::desc("Inplace edit <file>s, if specified."),
70                             cl::cat(ClangFormatCategory));
71
72static cl::opt<bool> OutputXML("output-replacements-xml",
73                               cl::desc("Output replacements as XML."),
74                               cl::cat(ClangFormatCategory));
75static cl::opt<bool>
76    DumpConfig("dump-config",
77               cl::desc("Dump configuration options to stdout and exit.\n"
78                        "Can be used with -style option."),
79               cl::cat(ClangFormatCategory));
80static cl::opt<unsigned>
81    Cursor("cursor",
82           cl::desc("The position of the cursor when invoking clang-format from"
83                    " an editor integration"),
84           cl::init(0), cl::cat(ClangFormatCategory));
85
86static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
87                                       cl::cat(ClangFormatCategory));
88
89namespace clang {
90namespace format {
91
92static FileID createInMemoryFile(StringRef FileName, const MemoryBuffer *Source,
93                                 SourceManager &Sources, FileManager &Files) {
94  const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
95                                                    FileName,
96                                                Source->getBufferSize(), 0);
97  Sources.overrideFileContents(Entry, Source, true);
98  return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
99}
100
101FormatStyle getStyle(StringRef StyleName, StringRef FileName) {
102  FormatStyle Style;
103  getPredefinedStyle(DefaultStyle, &Style);
104
105  if (StyleName.startswith("{")) {
106    // Parse YAML/JSON style from the command line.
107    if (error_code ec = parseConfiguration(StyleName, &Style)) {
108      llvm::errs() << "Error parsing -style: " << ec.message()
109                   << ", using " << DefaultStyle << " style\n";
110    }
111    return Style;
112  }
113
114  if (!StyleName.equals_lower("file")) {
115    if (!getPredefinedStyle(StyleName, &Style))
116      llvm::errs() << "Invalid value for -style, using " << DefaultStyle
117                   << " style\n";
118    return Style;
119  }
120
121  SmallString<128> Path(FileName);
122  llvm::sys::fs::make_absolute(Path);
123  for (StringRef Directory = llvm::sys::path::parent_path(Path);
124       !Directory.empty();
125       Directory = llvm::sys::path::parent_path(Directory)) {
126    SmallString<128> ConfigFile(Directory);
127    llvm::sys::path::append(ConfigFile, ".clang-format");
128    DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
129    bool IsFile = false;
130    // Ignore errors from is_regular_file: we only need to know if we can read
131    // the file or not.
132    llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
133    if (IsFile) {
134      OwningPtr<MemoryBuffer> Text;
135      if (error_code ec = MemoryBuffer::getFile(ConfigFile, Text)) {
136        llvm::errs() << ec.message() << "\n";
137        continue;
138      }
139      if (error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
140        llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
141                     << "\n";
142        continue;
143      }
144      DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
145      return Style;
146    }
147  }
148  llvm::errs() << "Can't find usable .clang-format, using " << DefaultStyle
149               << " style\n";
150  return Style;
151}
152
153// Returns true on error.
154static bool format(std::string FileName) {
155  FileManager Files((FileSystemOptions()));
156  DiagnosticsEngine Diagnostics(
157      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
158      new DiagnosticOptions);
159  SourceManager Sources(Diagnostics, Files);
160  OwningPtr<MemoryBuffer> Code;
161  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
162    llvm::errs() << ec.message() << "\n";
163    return true;
164  }
165  if (Code->getBufferSize() == 0)
166    return true; // Empty files are formatted correctly.
167  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
168  if (Offsets.empty())
169    Offsets.push_back(0);
170  if (Offsets.size() != Lengths.size() &&
171      !(Offsets.size() == 1 && Lengths.empty())) {
172    llvm::errs()
173        << "error: number of -offset and -length arguments must match.\n";
174    return true;
175  }
176  std::vector<CharSourceRange> Ranges;
177  for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
178    if (Offsets[i] >= Code->getBufferSize()) {
179      llvm::errs() << "error: offset " << Offsets[i]
180                   << " is outside the file\n";
181      return true;
182    }
183    SourceLocation Start =
184        Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
185    SourceLocation End;
186    if (i < Lengths.size()) {
187      if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
188        llvm::errs() << "error: invalid length " << Lengths[i]
189                     << ", offset + length (" << Offsets[i] + Lengths[i]
190                     << ") is outside the file.\n";
191        return true;
192      }
193      End = Start.getLocWithOffset(Lengths[i]);
194    } else {
195      End = Sources.getLocForEndOfFile(ID);
196    }
197    Ranges.push_back(CharSourceRange::getCharRange(Start, End));
198  }
199  FormatStyle FormatStyle = getStyle(Style, FileName);
200  Lexer Lex(ID, Sources.getBuffer(ID), Sources,
201            getFormattingLangOpts(FormatStyle.Standard));
202  tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
203  if (OutputXML) {
204    llvm::outs()
205        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
206    for (tooling::Replacements::const_iterator I = Replaces.begin(),
207                                               E = Replaces.end();
208         I != E; ++I) {
209      llvm::outs() << "<replacement "
210                   << "offset='" << I->getOffset() << "' "
211                   << "length='" << I->getLength() << "'>"
212                   << I->getReplacementText() << "</replacement>\n";
213    }
214    llvm::outs() << "</replacements>\n";
215  } else {
216    Rewriter Rewrite(Sources, LangOptions());
217    tooling::applyAllReplacements(Replaces, Rewrite);
218    if (Inplace) {
219      if (Replaces.size() == 0)
220        return false; // Nothing changed, don't touch the file.
221
222      std::string ErrorInfo;
223      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
224                                      llvm::raw_fd_ostream::F_Binary);
225      if (!ErrorInfo.empty()) {
226        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
227        return true;
228      }
229      Rewrite.getEditBuffer(ID).write(FileStream);
230      FileStream.flush();
231    } else {
232      if (Cursor.getNumOccurrences() != 0)
233        outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
234                                          Replaces, Cursor) << " }\n";
235      Rewrite.getEditBuffer(ID).write(outs());
236    }
237  }
238  return false;
239}
240
241}  // namespace format
242}  // namespace clang
243
244int main(int argc, const char **argv) {
245  llvm::sys::PrintStackTraceOnErrorSignal();
246
247  // Hide unrelated options.
248  StringMap<cl::Option*> Options;
249  cl::getRegisteredOptions(Options);
250  for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
251       I != E; ++I) {
252    if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
253        I->first() != "version")
254      I->second->setHiddenFlag(cl::ReallyHidden);
255  }
256
257  cl::ParseCommandLineOptions(
258      argc, argv,
259      "A tool to format C/C++/Obj-C code.\n\n"
260      "If no arguments are specified, it formats the code from standard input\n"
261      "and writes the result to the standard output.\n"
262      "If <file>s are given, it reformats the files. If -i is specified \n"
263      "together with <file>s, the files are edited in-place. Otherwise, the \n"
264      "result is written to the standard output.\n");
265
266  if (Help)
267    cl::PrintHelpMessage();
268
269  if (DumpConfig) {
270    std::string Config = clang::format::configurationAsText(
271        clang::format::getStyle(Style, FileNames.empty() ? "-" : FileNames[0]));
272    llvm::outs() << Config << "\n";
273    return 0;
274  }
275
276  bool Error = false;
277  switch (FileNames.size()) {
278  case 0:
279    Error = clang::format::format("-");
280    break;
281  case 1:
282    Error = clang::format::format(FileNames[0]);
283    break;
284  default:
285    if (!Offsets.empty() || !Lengths.empty()) {
286      llvm::errs() << "error: \"-offset\" and \"-length\" can only be used for "
287                      "single file.\n";
288      return 1;
289    }
290    for (unsigned i = 0; i < FileNames.size(); ++i)
291      Error |= clang::format::format(FileNames[i]);
292    break;
293  }
294  return Error ? 1 : 0;
295}
296