Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/clang-format/ClangFormat.cpp
Line
Count
Source (jump to first uncovered line)
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
27
using namespace llvm;
28
using clang::tooling::Replacements;
29
30
static cl::opt<bool> Help("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.
34
static cl::OptionCategory ClangFormatCategory("Clang-format options");
35
36
static 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));
43
static 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));
53
static cl::list<std::string>
54
    LineRanges("lines",
55
               cl::desc("<start line>:<end line> - format a range of\n"
56
                        "lines (both 1-based).\n"
57
                        "Multiple ranges can be formatted by specifying\n"
58
                        "several -lines arguments.\n"
59
                        "Can't be used with -offset and -length.\n"
60
                        "Can only be used with one input file."),
61
               cl::cat(ClangFormatCategory));
62
static cl::opt<std::string>
63
    Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
64
          cl::init(clang::format::DefaultFormatStyle),
65
          cl::cat(ClangFormatCategory));
66
static cl::opt<std::string>
67
    FallbackStyle("fallback-style",
68
                  cl::desc("The name of the predefined style used as a\n"
69
                           "fallback in case clang-format is invoked with\n"
70
                           "-style=file, but can not find the .clang-format\n"
71
                           "file to use.\n"
72
                           "Use -fallback-style=none to skip formatting."),
73
                  cl::init(clang::format::DefaultFallbackStyle),
74
                  cl::cat(ClangFormatCategory));
75
76
static cl::opt<std::string> AssumeFileName(
77
    "assume-filename",
78
    cl::desc("Override filename used to determine the language.\n"
79
             "When reading from stdin, clang-format assumes this\n"
80
             "filename to determine the language."),
81
    cl::init("<stdin>"), cl::cat(ClangFormatCategory));
82
83
static cl::opt<bool> Inplace("i",
84
                             cl::desc("Inplace edit <file>s, if specified."),
85
                             cl::cat(ClangFormatCategory));
86
87
static cl::opt<bool> OutputXML("output-replacements-xml",
88
                               cl::desc("Output replacements as XML."),
89
                               cl::cat(ClangFormatCategory));
90
static cl::opt<bool>
91
    DumpConfig("dump-config",
92
               cl::desc("Dump configuration options to stdout and exit.\n"
93
                        "Can be used with -style option."),
94
               cl::cat(ClangFormatCategory));
95
static cl::opt<unsigned>
96
    Cursor("cursor",
97
           cl::desc("The position of the cursor when invoking\n"
98
                    "clang-format from an editor integration"),
99
           cl::init(0), cl::cat(ClangFormatCategory));
100
101
static cl::opt<bool> SortIncludes(
102
    "sort-includes",
103
    cl::desc("If set, overrides the include sorting behavior determined by the "
104
             "SortIncludes style flag"),
105
    cl::cat(ClangFormatCategory));
106
107
static cl::opt<bool>
108
    Verbose("verbose", cl::desc("If set, shows the list of processed files"),
109
            cl::cat(ClangFormatCategory));
110
111
// Use --dry-run to match other LLVM tools when you mean do it but don't
112
// actually do it
113
static cl::opt<bool>
114
    DryRun("dry-run",
115
           cl::desc("If set, do not actually make the formatting changes"),
116
           cl::cat(ClangFormatCategory));
117
118
// Use -n as a common command as an alias for --dry-run. (git and make use -n)
119
static cl::alias DryRunShort("n", cl::desc("Alias for --dry-run"),
120
                             cl::cat(ClangFormatCategory), cl::aliasopt(DryRun),
121
                             cl::NotHidden);
122
123
// Emulate being able to turn on/off the warning.
124
static cl::opt<bool>
125
    WarnFormat("Wclang-format-violations",
126
               cl::desc("Warnings about individual formatting changes needed. "
127
                        "Used only with --dry-run or -n"),
128
               cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
129
130
static cl::opt<bool>
131
    NoWarnFormat("Wno-clang-format-violations",
132
                 cl::desc("Do not warn about individual formatting changes "
133
                          "needed. Used only with --dry-run or -n"),
134
                 cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
135
136
static cl::opt<unsigned> ErrorLimit(
137
    "ferror-limit",
138
    cl::desc("Set the maximum number of clang-format errors to emit before "
139
             "stopping (0 = no limit). Used only with --dry-run or -n"),
140
    cl::init(0), cl::cat(ClangFormatCategory));
141
142
static cl::opt<bool>
143
    WarningsAsErrors("Werror",
144
                     cl::desc("If set, changes formatting warnings to errors"),
145
                     cl::cat(ClangFormatCategory));
146
147
static cl::opt<bool>
148
    ShowColors("fcolor-diagnostics",
149
               cl::desc("If set, and on a color-capable terminal controls "
150
                        "whether or not to print diagnostics in color"),
151
               cl::init(true), cl::cat(ClangFormatCategory), cl::Hidden);
152
153
static cl::opt<bool>
154
    NoShowColors("fno-color-diagnostics",
155
                 cl::desc("If set, and on a color-capable terminal controls "
156
                          "whether or not to print diagnostics in color"),
157
                 cl::init(false), cl::cat(ClangFormatCategory), cl::Hidden);
158
159
static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
160
                                       cl::cat(ClangFormatCategory));
161
162
namespace clang {
163
namespace format {
164
165
static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
166
                                 SourceManager &Sources, FileManager &Files,
167
70
                                 llvm::vfs::InMemoryFileSystem *MemFS) {
168
70
  MemFS->addFileNoOwn(FileName, 0, Source);
169
70
  auto File = Files.getFile(FileName);
170
70
  return Sources.createFileID(File ? *File : 
nullptr0
, SourceLocation(),
171
70
                              SrcMgr::C_User);
172
70
}
173
174
// Parses <start line>:<end line> input to a pair of line numbers.
175
// Returns true on error.
176
static bool parseLineRange(StringRef Input, unsigned &FromLine,
177
4
                           unsigned &ToLine) {
178
4
  std::pair<StringRef, StringRef> LineRange = Input.split(':');
179
4
  return LineRange.first.getAsInteger(0, FromLine) ||
180
4
         LineRange.second.getAsInteger(0, ToLine);
181
4
}
182
183
static bool fillRanges(MemoryBuffer *Code,
184
38
                       std::vector<tooling::Range> &Ranges) {
185
38
  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
186
38
      new llvm::vfs::InMemoryFileSystem);
187
38
  FileManager Files(FileSystemOptions(), InMemoryFileSystem);
188
38
  DiagnosticsEngine Diagnostics(
189
38
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
190
38
      new DiagnosticOptions);
191
38
  SourceManager Sources(Diagnostics, Files);
192
38
  FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
193
38
                                 InMemoryFileSystem.get());
194
38
  if (!LineRanges.empty()) {
195
3
    if (!Offsets.empty() || !Lengths.empty()) {
196
0
      errs() << "error: cannot use -lines with -offset/-length\n";
197
0
      return true;
198
0
    }
199
3
200
7
    
for (unsigned i = 0, e = LineRanges.size(); 3
i < e;
++i4
) {
201
4
      unsigned FromLine, ToLine;
202
4
      if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
203
0
        errs() << "error: invalid <start line>:<end line> pair\n";
204
0
        return true;
205
0
      }
206
4
      if (FromLine > ToLine) {
207
0
        errs() << "error: start line should be less than end line\n";
208
0
        return true;
209
0
      }
210
4
      SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
211
4
      SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
212
4
      if (Start.isInvalid() || End.isInvalid())
213
0
        return true;
214
4
      unsigned Offset = Sources.getFileOffset(Start);
215
4
      unsigned Length = Sources.getFileOffset(End) - Offset;
216
4
      Ranges.push_back(tooling::Range(Offset, Length));
217
4
    }
218
3
    return false;
219
35
  }
220
35
221
35
  if (Offsets.empty())
222
32
    Offsets.push_back(0);
223
35
  if (Offsets.size() != Lengths.size() &&
224
35
      
!(34
Offsets.size() == 134
&&
Lengths.empty()34
)) {
225
0
    errs() << "error: number of -offset and -length arguments must match.\n";
226
0
    return true;
227
0
  }
228
71
  
for (unsigned i = 0, e = Offsets.size(); 35
i != e;
++i36
) {
229
36
    if (Offsets[i] >= Code->getBufferSize()) {
230
0
      errs() << "error: offset " << Offsets[i] << " is outside the file\n";
231
0
      return true;
232
0
    }
233
36
    SourceLocation Start =
234
36
        Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
235
36
    SourceLocation End;
236
36
    if (i < Lengths.size()) {
237
2
      if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
238
0
        errs() << "error: invalid length " << Lengths[i]
239
0
               << ", offset + length (" << Offsets[i] + Lengths[i]
240
0
               << ") is outside the file.\n";
241
0
        return true;
242
0
      }
243
2
      End = Start.getLocWithOffset(Lengths[i]);
244
34
    } else {
245
34
      End = Sources.getLocForEndOfFile(ID);
246
34
    }
247
36
    unsigned Offset = Sources.getFileOffset(Start);
248
36
    unsigned Length = Sources.getFileOffset(End) - Offset;
249
36
    Ranges.push_back(tooling::Range(Offset, Length));
250
36
  }
251
35
  return false;
252
35
}
253
254
3
static void outputReplacementXML(StringRef Text) {
255
3
  // FIXME: When we sort includes, we need to make sure the stream is correct
256
3
  // utf-8.
257
3
  size_t From = 0;
258
3
  size_t Index;
259
7
  while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
260
4
    outs() << Text.substr(From, Index - From);
261
4
    switch (Text[Index]) {
262
2
    case '\n':
263
2
      outs() << "&#10;";
264
2
      break;
265
0
    case '\r':
266
0
      outs() << "&#13;";
267
0
      break;
268
2
    case '<':
269
2
      outs() << "&lt;";
270
2
      break;
271
0
    case '&':
272
0
      outs() << "&amp;";
273
0
      break;
274
0
    default:
275
0
      llvm_unreachable("Unexpected character encountered!");
276
4
    }
277
4
    From = Index + 1;
278
4
  }
279
3
  outs() << Text.substr(From);
280
3
}
281
282
1
static void outputReplacementsXML(const Replacements &Replaces) {
283
3
  for (const auto &R : Replaces) {
284
3
    outs() << "<replacement "
285
3
           << "offset='" << R.getOffset() << "' "
286
3
           << "length='" << R.getLength() << "'>";
287
3
    outputReplacementXML(R.getReplacementText());
288
3
    outs() << "</replacement>\n";
289
3
  }
290
1
}
291
292
static bool
293
emitReplacementWarnings(const Replacements &Replaces, StringRef AssumedFileName,
294
2
                        const std::unique_ptr<llvm::MemoryBuffer> &Code) {
295
2
  if (Replaces.empty())
296
0
    return false;
297
2
298
2
  unsigned Errors = 0;
299
2
  if (WarnFormat && !NoWarnFormat) {
300
2
    llvm::SourceMgr Mgr;
301
2
    const char *StartBuf = Code->getBufferStart();
302
2
303
2
    Mgr.AddNewSourceBuffer(
304
2
        MemoryBuffer::getMemBuffer(StartBuf, AssumedFileName), SMLoc());
305
2
    for (const auto &R : Replaces) {
306
2
      SMDiagnostic Diag = Mgr.GetMessage(
307
2
          SMLoc::getFromPointer(StartBuf + R.getOffset()),
308
2
          WarningsAsErrors ? 
SourceMgr::DiagKind::DK_Error0
309
2
                           : SourceMgr::DiagKind::DK_Warning,
310
2
          "code should be clang-formatted [-Wclang-format-violations]");
311
2
312
2
      Diag.print(nullptr, llvm::errs(), (ShowColors && !NoShowColors));
313
2
      if (ErrorLimit && 
++Errors >= ErrorLimit0
)
314
0
        break;
315
2
    }
316
2
  }
317
2
  return WarningsAsErrors;
318
2
}
319
320
static void outputXML(const Replacements &Replaces,
321
                      const Replacements &FormatChanges,
322
                      const FormattingAttemptStatus &Status,
323
                      const cl::opt<unsigned> &Cursor,
324
1
                      unsigned CursorPosition) {
325
1
  outs() << "<?xml version='1.0'?>\n<replacements "
326
1
            "xml:space='preserve' incomplete_format='"
327
1
         << (Status.FormatComplete ? "false" : 
"true"0
) << "'";
328
1
  if (!Status.FormatComplete)
329
0
    outs() << " line='" << Status.Line << "'";
330
1
  outs() << ">\n";
331
1
  if (Cursor.getNumOccurrences() != 0)
332
0
    outs() << "<cursor>" << FormatChanges.getShiftedCodePosition(CursorPosition)
333
0
           << "</cursor>\n";
334
1
335
1
  outputReplacementsXML(Replaces);
336
1
  outs() << "</replacements>\n";
337
1
}
338
339
// Returns true on error.
340
38
static bool format(StringRef FileName) {
341
38
  if (!OutputXML && 
Inplace37
&&
FileName == "-"5
) {
342
0
    errs() << "error: cannot use -i when reading from stdin.\n";
343
0
    return false;
344
0
  }
345
38
  // On Windows, overwriting a file with an open file mapping doesn't work,
346
38
  // so read the whole file into memory when formatting in-place.
347
38
  ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
348
38
      !OutputXML && 
Inplace37
?
MemoryBuffer::getFileAsStream(FileName)5
349
38
                            : 
MemoryBuffer::getFileOrSTDIN(FileName)33
;
350
38
  if (std::error_code EC = CodeOrErr.getError()) {
351
0
    errs() << EC.message() << "\n";
352
0
    return true;
353
0
  }
354
38
  std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
355
38
  if (Code->getBufferSize() == 0)
356
0
    return false; // Empty files are formatted correctly.
357
38
358
38
  StringRef BufStr = Code->getBuffer();
359
38
360
38
  const char *InvalidBOM = SrcMgr::ContentCache::getInvalidBOM(BufStr);
361
38
362
38
  if (InvalidBOM) {
363
0
    errs() << "error: encoding with unsupported byte order mark \""
364
0
           << InvalidBOM << "\" detected";
365
0
    if (FileName != "-")
366
0
      errs() << " in file '" << FileName << "'";
367
0
    errs() << ".\n";
368
0
    return true;
369
0
  }
370
38
371
38
  std::vector<tooling::Range> Ranges;
372
38
  if (fillRanges(Code.get(), Ranges))
373
0
    return true;
374
38
  StringRef AssumedFileName = (FileName == "-") ? 
AssumeFileName14
:
FileName24
;
375
38
  if (AssumedFileName.empty()) {
376
0
    llvm::errs() << "error: empty filenames are not allowed\n";
377
0
    return true;
378
0
  }
379
38
380
38
  llvm::Expected<FormatStyle> FormatStyle =
381
38
      getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
382
38
  if (!FormatStyle) {
383
3
    llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
384
3
    return true;
385
3
  }
386
35
387
35
  if (SortIncludes.getNumOccurrences() != 0)
388
3
    FormatStyle->SortIncludes = SortIncludes;
389
35
  unsigned CursorPosition = Cursor;
390
35
  Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
391
35
                                       AssumedFileName, &CursorPosition);
392
35
  auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
393
35
  if (!ChangedCode) {
394
0
    llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
395
0
    return true;
396
0
  }
397
35
  // Get new affected ranges after sorting `#includes`.
398
35
  Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
399
35
  FormattingAttemptStatus Status;
400
35
  Replacements FormatChanges =
401
35
      reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status);
402
35
  Replaces = Replaces.merge(FormatChanges);
403
35
  if (OutputXML || 
DryRun34
) {
404
3
    if (DryRun) {
405
2
      return emitReplacementWarnings(Replaces, AssumedFileName, Code);
406
2
    } else {
407
1
      outputXML(Replaces, FormatChanges, Status, Cursor, CursorPosition);
408
1
    }
409
32
  } else {
410
32
    IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
411
32
        new llvm::vfs::InMemoryFileSystem);
412
32
    FileManager Files(FileSystemOptions(), InMemoryFileSystem);
413
32
    DiagnosticsEngine Diagnostics(
414
32
        IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
415
32
        new DiagnosticOptions);
416
32
    SourceManager Sources(Diagnostics, Files);
417
32
    FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
418
32
                                   InMemoryFileSystem.get());
419
32
    Rewriter Rewrite(Sources, LangOptions());
420
32
    tooling::applyAllReplacements(Replaces, Rewrite);
421
32
    if (Inplace) {
422
3
      if (Rewrite.overwriteChangedFiles())
423
0
        return true;
424
29
    } else {
425
29
      if (Cursor.getNumOccurrences() != 0) {
426
2
        outs() << "{ \"Cursor\": "
427
2
               << FormatChanges.getShiftedCodePosition(CursorPosition)
428
2
               << ", \"IncompleteFormat\": "
429
2
               << (Status.FormatComplete ? 
"false"1
:
"true"1
);
430
2
        if (!Status.FormatComplete)
431
1
          outs() << ", \"Line\": " << Status.Line;
432
2
        outs() << " }\n";
433
2
      }
434
29
      Rewrite.getEditBuffer(ID).write(outs());
435
29
    }
436
32
  }
437
35
  
return false33
;
438
35
}
439
440
} // namespace format
441
} // namespace clang
442
443
0
static void PrintVersion(raw_ostream &OS) {
444
0
  OS << clang::getClangToolFullVersion("clang-format") << '\n';
445
0
}
446
447
// Dump the configuration.
448
2
static int dumpConfig() {
449
2
  StringRef FileName;
450
2
  std::unique_ptr<llvm::MemoryBuffer> Code;
451
2
  if (FileNames.empty()) {
452
0
    // We can't read the code to detect the language if there's no
453
0
    // file name, so leave Code empty here.
454
0
    FileName = AssumeFileName;
455
2
  } else {
456
2
    // Read in the code in case the filename alone isn't enough to
457
2
    // detect the language.
458
2
    ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
459
2
        MemoryBuffer::getFileOrSTDIN(FileNames[0]);
460
2
    if (std::error_code EC = CodeOrErr.getError()) {
461
0
      llvm::errs() << EC.message() << "\n";
462
0
      return 1;
463
0
    }
464
2
    FileName = (FileNames[0] == "-") ? 
AssumeFileName0
: FileNames[0];
465
2
    Code = std::move(CodeOrErr.get());
466
2
  }
467
2
  llvm::Expected<clang::format::FormatStyle> FormatStyle =
468
2
      clang::format::getStyle(Style, FileName, FallbackStyle,
469
2
                              Code ? Code->getBuffer() : 
""0
);
470
2
  if (!FormatStyle) {
471
0
    llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
472
0
    return 1;
473
0
  }
474
2
  std::string Config = clang::format::configurationAsText(*FormatStyle);
475
2
  outs() << Config << "\n";
476
2
  return 0;
477
2
}
478
479
40
int main(int argc, const char **argv) {
480
40
  llvm::InitLLVM X(argc, argv);
481
40
482
40
  cl::HideUnrelatedOptions(ClangFormatCategory);
483
40
484
40
  cl::SetVersionPrinter(PrintVersion);
485
40
  cl::ParseCommandLineOptions(
486
40
      argc, argv,
487
40
      "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.\n\n"
488
40
      "If no arguments are specified, it formats the code from standard input\n"
489
40
      "and writes the result to the standard output.\n"
490
40
      "If <file>s are given, it reformats the files. If -i is specified\n"
491
40
      "together with <file>s, the files are edited in-place. Otherwise, the\n"
492
40
      "result is written to the standard output.\n");
493
40
494
40
  if (Help) {
495
0
    cl::PrintHelpMessage();
496
0
    return 0;
497
0
  }
498
40
499
40
  if (DumpConfig) {
500
2
    return dumpConfig();
501
2
  }
502
38
503
38
  bool Error = false;
504
38
  if (FileNames.empty()) {
505
14
    Error = clang::format::format("-");
506
14
    return Error ? 
11
:
013
;
507
14
  }
508
24
  if (FileNames.size() != 1 &&
509
24
      
(4
!Offsets.empty()4
||
!Lengths.empty()3
||
!LineRanges.empty()3
)) {
510
2
    errs() << "error: -offset, -length and -lines can only be used for "
511
2
              "single file.\n";
512
2
    return 1;
513
2
  }
514
24
  
for (const auto &FileName : FileNames)22
{
515
24
    if (Verbose)
516
2
      errs() << "Formatting " << FileName << "\n";
517
24
    Error |= clang::format::format(FileName);
518
24
  }
519
22
  return Error ? 
12
:
020
;
520
22
}