Clang Project

clang_source_code/tools/clang-format/ClangFormat.cpp
1//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a clang-format tool that automatically formats
11/// (fragments of) C++ code.
12///
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Basic/DiagnosticOptions.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/Version.h"
20#include "clang/Format/Format.h"
21#include "clang/Rewrite/Core/Rewriter.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/FileSystem.h"
24#include "llvm/Support/InitLLVM.h"
25#include "llvm/Support/Process.h"
26
27using namespace llvm;
28using clang::tooling::Replacements;
29
30static cl::opt<boolHelp("h", cl::desc("Alias for -help"), cl::Hidden);
31
32// Mark all our options with this category, everything else (except for -version
33// and -help) will be hidden.
34static cl::OptionCategory ClangFormatCategory("Clang-format options");
35
36static cl::list<unsigned>
37    Offsets("offset",
38            cl::desc("Format a range starting at this byte offset.\n"
39                     "Multiple ranges can be formatted by specifying\n"
40                     "several -offset and -length pairs.\n"
41                     "Can only be used with one input file."),
42            cl::cat(ClangFormatCategory));
43static cl::list<unsigned>
44    Lengths("length",
45            cl::desc("Format a range of this length (in bytes).\n"
46                     "Multiple ranges can be formatted by specifying\n"
47                     "several -offset and -length pairs.\n"
48                     "When only a single -offset is specified without\n"
49                     "-length, clang-format will format up to the end\n"
50                     "of the file.\n"
51                     "Can only be used with one input file."),
52            cl::cat(ClangFormatCategory));
53static cl::list<std::string>
54LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
55                             "lines (both 1-based).\n"
56                             "Multiple ranges can be formatted by specifying\n"
57                             "several -lines arguments.\n"
58                             "Can't be used with -offset and -length.\n"
59                             "Can only be used with one input file."),
60           cl::cat(ClangFormatCategory));
61static cl::opt<std::string>
62    Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
63          cl::init(clang::format::DefaultFormatStyle),
64          cl::cat(ClangFormatCategory));
65static cl::opt<std::string>
66    FallbackStyle("fallback-style",
67                  cl::desc("The name of the predefined style used as a\n"
68                           "fallback in case clang-format is invoked with\n"
69                           "-style=file, but can not find the .clang-format\n"
70                           "file to use.\n"
71                           "Use -fallback-style=none to skip formatting."),
72                  cl::init(clang::format::DefaultFallbackStyle),
73                  cl::cat(ClangFormatCategory));
74
75static cl::opt<std::string>
76AssumeFileName("assume-filename",
77               cl::desc("When reading from stdin, clang-format assumes this\n"
78                        "filename to look for a style config file (with\n"
79                        "-style=file) and to determine the language."),
80               cl::init("<stdin>"), cl::cat(ClangFormatCategory));
81
82static cl::opt<boolInplace("i",
83                             cl::desc("Inplace edit <file>s, if specified."),
84                             cl::cat(ClangFormatCategory));
85
86static cl::opt<boolOutputXML("output-replacements-xml",
87                               cl::desc("Output replacements as XML."),
88                               cl::cat(ClangFormatCategory));
89static cl::opt<bool>
90    DumpConfig("dump-config",
91               cl::desc("Dump configuration options to stdout and exit.\n"
92                        "Can be used with -style option."),
93               cl::cat(ClangFormatCategory));
94static cl::opt<unsigned>
95    Cursor("cursor",
96           cl::desc("The position of the cursor when invoking\n"
97                    "clang-format from an editor integration"),
98           cl::init(0), cl::cat(ClangFormatCategory));
99
100static cl::opt<boolSortIncludes(
101    "sort-includes",
102    cl::desc("If set, overrides the include sorting behavior determined by the "
103             "SortIncludes style flag"),
104    cl::cat(ClangFormatCategory));
105
106static cl::opt<bool>
107    Verbose("verbose", cl::desc("If set, shows the list of processed files"),
108            cl::cat(ClangFormatCategory));
109
110static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
111                                       cl::cat(ClangFormatCategory));
112
113namespace clang {
114namespace format {
115
116static FileID createInMemoryFile(StringRef FileNameMemoryBuffer *Source,
117                                 SourceManager &SourcesFileManager &Files,
118                                 llvm::vfs::InMemoryFileSystem *MemFS) {
119  MemFS->addFileNoOwn(FileName, 0, Source);
120  return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
121                              SrcMgr::C_User);
122}
123
124// Parses <start line>:<end line> input to a pair of line numbers.
125// Returns true on error.
126static bool parseLineRange(StringRef Inputunsigned &FromLine,
127                           unsigned &ToLine) {
128  std::pair<StringRefStringRefLineRange = Input.split(':');
129  return LineRange.first.getAsInteger(0, FromLine) ||
130         LineRange.second.getAsInteger(0, ToLine);
131}
132
133static bool fillRanges(MemoryBuffer *Code,
134                       std::vector<tooling::Range> &Ranges) {
135  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
136      new llvm::vfs::InMemoryFileSystem);
137  FileManager Files(FileSystemOptions(), InMemoryFileSystem);
138  DiagnosticsEngine Diagnostics(
139      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
140      new DiagnosticOptions);
141  SourceManager Sources(Diagnostics, Files);
142  FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
143                                 InMemoryFileSystem.get());
144  if (!LineRanges.empty()) {
145    if (!Offsets.empty() || !Lengths.empty()) {
146      errs() << "error: cannot use -lines with -offset/-length\n";
147      return true;
148    }
149
150    for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
151      unsigned FromLine, ToLine;
152      if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
153        errs() << "error: invalid <start line>:<end line> pair\n";
154        return true;
155      }
156      if (FromLine > ToLine) {
157        errs() << "error: start line should be less than end line\n";
158        return true;
159      }
160      SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
161      SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
162      if (Start.isInvalid() || End.isInvalid())
163        return true;
164      unsigned Offset = Sources.getFileOffset(Start);
165      unsigned Length = Sources.getFileOffset(End) - Offset;
166      Ranges.push_back(tooling::Range(Offset, Length));
167    }
168    return false;
169  }
170
171  if (Offsets.empty())
172    Offsets.push_back(0);
173  if (Offsets.size() != Lengths.size() &&
174      !(Offsets.size() == 1 && Lengths.empty())) {
175    errs() << "error: number of -offset and -length arguments must match.\n";
176    return true;
177  }
178  for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
179    if (Offsets[i] >= Code->getBufferSize()) {
180      errs() << "error: offset " << Offsets[i] << " 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        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    unsigned Offset = Sources.getFileOffset(Start);
198    unsigned Length = Sources.getFileOffset(End) - Offset;
199    Ranges.push_back(tooling::Range(Offset, Length));
200  }
201  return false;
202}
203
204static void outputReplacementXML(StringRef Text) {
205  // FIXME: When we sort includes, we need to make sure the stream is correct
206  // utf-8.
207  size_t From = 0;
208  size_t Index;
209  while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
210    outs() << Text.substr(From, Index - From);
211    switch (Text[Index]) {
212    case '\n':
213      outs() << "&#10;";
214      break;
215    case '\r':
216      outs() << "&#13;";
217      break;
218    case '<':
219      outs() << "&lt;";
220      break;
221    case '&':
222      outs() << "&amp;";
223      break;
224    default:
225      llvm_unreachable("Unexpected character encountered!");
226    }
227    From = Index + 1;
228  }
229  outs() << Text.substr(From);
230}
231
232static void outputReplacementsXML(const Replacements &Replaces) {
233  for (const auto &R : Replaces) {
234    outs() << "<replacement "
235           << "offset='" << R.getOffset() << "' "
236           << "length='" << R.getLength() << "'>";
237    outputReplacementXML(R.getReplacementText());
238    outs() << "</replacement>\n";
239  }
240}
241
242// Returns true on error.
243static bool format(StringRef FileName) {
244  if (!OutputXML && Inplace && FileName == "-") {
245    errs() << "error: cannot use -i when reading from stdin.\n";
246    return false;
247  }
248  // On Windows, overwriting a file with an open file mapping doesn't work,
249  // so read the whole file into memory when formatting in-place.
250  ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
251      !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
252                              MemoryBuffer::getFileOrSTDIN(FileName);
253  if (std::error_code EC = CodeOrErr.getError()) {
254    errs() << EC.message() << "\n";
255    return true;
256  }
257  std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
258  if (Code->getBufferSize() == 0)
259    return false// Empty files are formatted correctly.
260  std::vector<tooling::Range> Ranges;
261  if (fillRanges(Code.get(), Ranges))
262    return true;
263  StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
264
265  llvm::Expected<FormatStyle> FormatStyle =
266      getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
267  if (!FormatStyle) {
268    llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
269    return true;
270  }
271
272  if (SortIncludes.getNumOccurrences() != 0)
273    FormatStyle->SortIncludes = SortIncludes;
274  unsigned CursorPosition = Cursor;
275  Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
276                                       AssumedFileName, &CursorPosition);
277  auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
278  if (!ChangedCode) {
279    llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
280    return true;
281  }
282  // Get new affected ranges after sorting `#includes`.
283  Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
284  FormattingAttemptStatus Status;
285  Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
286                                        AssumedFileName, &Status);
287  Replaces = Replaces.merge(FormatChanges);
288  if (OutputXML) {
289    outs() << "<?xml version='1.0'?>\n<replacements "
290              "xml:space='preserve' incomplete_format='"
291           << (Status.FormatComplete ? "false" : "true") << "'";
292    if (!Status.FormatComplete)
293      outs() << " line='" << Status.Line << "'";
294    outs() << ">\n";
295    if (Cursor.getNumOccurrences() != 0)
296      outs() << "<cursor>"
297             << FormatChanges.getShiftedCodePosition(CursorPosition)
298             << "</cursor>\n";
299
300    outputReplacementsXML(Replaces);
301    outs() << "</replacements>\n";
302  } else {
303    IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
304        new llvm::vfs::InMemoryFileSystem);
305    FileManager Files(FileSystemOptions(), InMemoryFileSystem);
306    DiagnosticsEngine Diagnostics(
307        IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
308        new DiagnosticOptions);
309    SourceManager Sources(Diagnostics, Files);
310    FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
311                                   InMemoryFileSystem.get());
312    Rewriter Rewrite(Sources, LangOptions());
313    tooling::applyAllReplacements(Replaces, Rewrite);
314    if (Inplace) {
315      if (Rewrite.overwriteChangedFiles())
316        return true;
317    } else {
318      if (Cursor.getNumOccurrences() != 0) {
319        outs() << "{ \"Cursor\": "
320               << FormatChanges.getShiftedCodePosition(CursorPosition)
321               << ", \"IncompleteFormat\": "
322               << (Status.FormatComplete ? "false" : "true");
323        if (!Status.FormatComplete)
324          outs() << ", \"Line\": " << Status.Line;
325        outs() << " }\n";
326      }
327      Rewrite.getEditBuffer(ID).write(outs());
328    }
329  }
330  return false;
331}
332
333}  // namespace format
334}  // namespace clang
335
336static void PrintVersion(raw_ostream &OS) {
337  OS << clang::getClangToolFullVersion("clang-format") << '\n';
338}
339
340int main(int argcconst char **argv) {
341  llvm::InitLLVM X(argc, argv);
342
343  cl::HideUnrelatedOptions(ClangFormatCategory);
344
345  cl::SetVersionPrinter(PrintVersion);
346  cl::ParseCommandLineOptions(
347      argc, argv,
348      "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n"
349      "If no arguments are specified, it formats the code from standard input\n"
350      "and writes the result to the standard output.\n"
351      "If <file>s are given, it reformats the files. If -i is specified\n"
352      "together with <file>s, the files are edited in-place. Otherwise, the\n"
353      "result is written to the standard output.\n");
354
355  if (Help) {
356    cl::PrintHelpMessage();
357    return 0;
358  }
359
360  if (DumpConfig) {
361    StringRef FileName;
362    std::unique_ptr<llvm::MemoryBufferCode;
363    if (FileNames.empty()) {
364      // We can't read the code to detect the language if there's no
365      // file name, so leave Code empty here.
366      FileName = AssumeFileName;
367    } else {
368      // Read in the code in case the filename alone isn't enough to
369      // detect the language.
370      ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
371          MemoryBuffer::getFileOrSTDIN(FileNames[0]);
372      if (std::error_code EC = CodeOrErr.getError()) {
373        llvm::errs() << EC.message() << "\n";
374        return 1;
375      }
376      FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
377      Code = std::move(CodeOrErr.get());
378    }
379    llvm::Expected<clang::format::FormatStyle> FormatStyle =
380        clang::format::getStyle(Style, FileName, FallbackStyle,
381                                Code ? Code->getBuffer() : "");
382    if (!FormatStyle) {
383      llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
384      return 1;
385    }
386    std::string Config = clang::format::configurationAsText(*FormatStyle);
387    outs() << Config << "\n";
388    return 0;
389  }
390
391  bool Error = false;
392  if (FileNames.empty()) {
393    Error = clang::format::format("-");
394    return Error ? 1 : 0;
395  }
396  if (FileNames.size() != 1 && (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
397    errs() << "error: -offset, -length and -lines can only be used for "
398              "single file.\n";
399    return 1;
400  }
401  for (const auto &FileName : FileNames) {
402    if (Verbose)
403      errs() << "Formatting " << FileName << "\n";
404    Error |= clang::format::format(FileName);
405  }
406  return Error ? 1 : 0;
407}
408