clang-tools  10.0.0svn
ClangTidyDiagnosticConsumer.cpp
Go to the documentation of this file.
1 //===--- tools/extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp ----------=== //
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 This file implements ClangTidyDiagnosticConsumer, ClangTidyContext
10 /// and ClangTidyError classes.
11 ///
12 /// This tool uses the Clang Tooling infrastructure, see
13 /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
14 /// for details on setting it up with LLVM source tree.
15 ///
16 //===----------------------------------------------------------------------===//
17 
19 #include "ClangTidyOptions.h"
20 #include "GlobList.h"
21 #include "clang/AST/ASTDiagnostic.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Frontend/DiagnosticRenderer.h"
25 #include "clang/Tooling/Core/Diagnostic.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallString.h"
28 #include <tuple>
29 #include <vector>
30 using namespace clang;
31 using namespace tidy;
32 
33 namespace {
34 class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
35 public:
36  ClangTidyDiagnosticRenderer(const LangOptions &LangOpts,
37  DiagnosticOptions *DiagOpts,
38  ClangTidyError &Error)
39  : DiagnosticRenderer(LangOpts, DiagOpts), Error(Error) {}
40 
41 protected:
42  void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc,
43  DiagnosticsEngine::Level Level, StringRef Message,
44  ArrayRef<CharSourceRange> Ranges,
45  DiagOrStoredDiag Info) override {
46  // Remove check name from the message.
47  // FIXME: Remove this once there's a better way to pass check names than
48  // appending the check name to the message in ClangTidyContext::diag and
49  // using getCustomDiagID.
50  std::string CheckNameInMessage = " [" + Error.DiagnosticName + "]";
51  if (Message.endswith(CheckNameInMessage))
52  Message = Message.substr(0, Message.size() - CheckNameInMessage.size());
53 
54  auto TidyMessage =
55  Loc.isValid()
56  ? tooling::DiagnosticMessage(Message, Loc.getManager(), Loc)
57  : tooling::DiagnosticMessage(Message);
58  if (Level == DiagnosticsEngine::Note) {
59  Error.Notes.push_back(TidyMessage);
60  return;
61  }
62  assert(Error.Message.Message.empty() && "Overwriting a diagnostic message");
63  Error.Message = TidyMessage;
64  }
65 
66  void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
67  DiagnosticsEngine::Level Level,
68  ArrayRef<CharSourceRange> Ranges) override {}
69 
70  void emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level,
71  SmallVectorImpl<CharSourceRange> &Ranges,
72  ArrayRef<FixItHint> Hints) override {
73  assert(Loc.isValid());
74  tooling::DiagnosticMessage *DiagWithFix =
75  Level == DiagnosticsEngine::Note ? &Error.Notes.back() : &Error.Message;
76 
77  for (const auto &FixIt : Hints) {
78  CharSourceRange Range = FixIt.RemoveRange;
79  assert(Range.getBegin().isValid() && Range.getEnd().isValid() &&
80  "Invalid range in the fix-it hint.");
81  assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
82  "Only file locations supported in fix-it hints.");
83 
84  tooling::Replacement Replacement(Loc.getManager(), Range,
85  FixIt.CodeToInsert);
86  llvm::Error Err =
87  DiagWithFix->Fix[Replacement.getFilePath()].add(Replacement);
88  // FIXME: better error handling (at least, don't let other replacements be
89  // applied).
90  if (Err) {
91  llvm::errs() << "Fix conflicts with existing fix! "
92  << llvm::toString(std::move(Err)) << "\n";
93  assert(false && "Fix conflicts with existing fix!");
94  }
95  }
96  }
97 
98  void emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) override {}
99 
100  void emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
101  StringRef ModuleName) override {}
102 
103  void emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc,
104  StringRef ModuleName) override {}
105 
106  void endDiagnostic(DiagOrStoredDiag D,
107  DiagnosticsEngine::Level Level) override {
108  assert(!Error.Message.Message.empty() && "Message has not been set");
109  }
110 
111 private:
113 };
114 } // end anonymous namespace
115 
116 ClangTidyError::ClangTidyError(StringRef CheckName,
117  ClangTidyError::Level DiagLevel,
118  StringRef BuildDirectory, bool IsWarningAsError)
119  : tooling::Diagnostic(CheckName, DiagLevel, BuildDirectory),
120  IsWarningAsError(IsWarningAsError) {}
121 
122 
124 public:
125  CachedGlobList(StringRef Globs) : Globs(Globs) {}
126 
127  bool contains(StringRef S) {
128  switch (auto &Result = Cache[S]) {
129  case Yes:
130  return true;
131  case No:
132  return false;
133  case None:
134  Result = Globs.contains(S) ? Yes : No;
135  return Result == Yes;
136  }
137  llvm_unreachable("invalid enum");
138  }
139 
140 private:
141  GlobList Globs;
142  enum Tristate { None, Yes, No };
143  llvm::StringMap<Tristate> Cache;
144 };
145 
147  std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider,
149  : DiagEngine(nullptr), OptionsProvider(std::move(OptionsProvider)),
150  Profile(false),
151  AllowEnablingAnalyzerAlphaCheckers(AllowEnablingAnalyzerAlphaCheckers) {
152  // Before the first translation unit we can get errors related to command-line
153  // parsing, use empty string for the file name in this case.
154  setCurrentFile("");
155 }
156 
158 
159 DiagnosticBuilder ClangTidyContext::diag(
160  StringRef CheckName, SourceLocation Loc, StringRef Description,
161  DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
162  assert(Loc.isValid());
163  unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
164  Level, (Description + " [" + CheckName + "]").str());
165  CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
166  return DiagEngine->Report(Loc, ID);
167 }
168 
169 void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
170  DiagEngine->setSourceManager(SourceMgr);
171 }
172 
173 void ClangTidyContext::setCurrentFile(StringRef File) {
174  CurrentFile = File;
175  CurrentOptions = getOptionsForFile(CurrentFile);
176  CheckFilter = std::make_unique<CachedGlobList>(*getOptions().Checks);
177  WarningAsErrorFilter =
178  std::make_unique<CachedGlobList>(*getOptions().WarningsAsErrors);
179 }
180 
181 void ClangTidyContext::setASTContext(ASTContext *Context) {
182  DiagEngine->SetArgToStringFn(&FormatASTNodeDiagnosticArgument, Context);
183  LangOpts = Context->getLangOpts();
184 }
185 
187  return OptionsProvider->getGlobalOptions();
188 }
189 
191  return CurrentOptions;
192 }
193 
195  // Merge options on top of getDefaults() as a safeguard against options with
196  // unset values.
198  OptionsProvider->getOptions(File));
199 }
200 
201 void ClangTidyContext::setEnableProfiling(bool P) { Profile = P; }
202 
204  ProfilePrefix = Prefix;
205 }
206 
207 llvm::Optional<ClangTidyProfiling::StorageParams>
209  if (ProfilePrefix.empty())
210  return llvm::None;
211 
212  return ClangTidyProfiling::StorageParams(ProfilePrefix, CurrentFile);
213 }
214 
215 bool ClangTidyContext::isCheckEnabled(StringRef CheckName) const {
216  assert(CheckFilter != nullptr);
217  return CheckFilter->contains(CheckName);
218 }
219 
220 bool ClangTidyContext::treatAsError(StringRef CheckName) const {
221  assert(WarningAsErrorFilter != nullptr);
222  return WarningAsErrorFilter->contains(CheckName);
223 }
224 
225 std::string ClangTidyContext::getCheckName(unsigned DiagnosticID) const {
226  std::string ClangWarningOption =
227  DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(DiagnosticID);
228  if (!ClangWarningOption.empty())
229  return "clang-diagnostic-" + ClangWarningOption;
230  llvm::DenseMap<unsigned, std::string>::const_iterator I =
231  CheckNamesByDiagnosticID.find(DiagnosticID);
232  if (I != CheckNamesByDiagnosticID.end())
233  return I->second;
234  return "";
235 }
236 
238  ClangTidyContext &Ctx, DiagnosticsEngine *ExternalDiagEngine,
239  bool RemoveIncompatibleErrors)
240  : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine),
241  RemoveIncompatibleErrors(RemoveIncompatibleErrors),
242  LastErrorRelatesToUserCode(false), LastErrorPassesLineFilter(false),
243  LastErrorWasIgnored(false) {}
244 
245 void ClangTidyDiagnosticConsumer::finalizeLastError() {
246  if (!Errors.empty()) {
247  ClangTidyError &Error = Errors.back();
248  if (!Context.isCheckEnabled(Error.DiagnosticName) &&
249  Error.DiagLevel != ClangTidyError::Error) {
250  ++Context.Stats.ErrorsIgnoredCheckFilter;
251  Errors.pop_back();
252  } else if (!LastErrorRelatesToUserCode) {
253  ++Context.Stats.ErrorsIgnoredNonUserCode;
254  Errors.pop_back();
255  } else if (!LastErrorPassesLineFilter) {
256  ++Context.Stats.ErrorsIgnoredLineFilter;
257  Errors.pop_back();
258  } else {
259  ++Context.Stats.ErrorsDisplayed;
260  }
261  }
262  LastErrorRelatesToUserCode = false;
263  LastErrorPassesLineFilter = false;
264 }
265 
266 static bool IsNOLINTFound(StringRef NolintDirectiveText, StringRef Line,
267  unsigned DiagID, const ClangTidyContext &Context) {
268  const size_t NolintIndex = Line.find(NolintDirectiveText);
269  if (NolintIndex == StringRef::npos)
270  return false;
271 
272  size_t BracketIndex = NolintIndex + NolintDirectiveText.size();
273  // Check if the specific checks are specified in brackets.
274  if (BracketIndex < Line.size() && Line[BracketIndex] == '(') {
275  ++BracketIndex;
276  const size_t BracketEndIndex = Line.find(')', BracketIndex);
277  if (BracketEndIndex != StringRef::npos) {
278  StringRef ChecksStr =
279  Line.substr(BracketIndex, BracketEndIndex - BracketIndex);
280  // Allow disabling all the checks with "*".
281  if (ChecksStr != "*") {
282  std::string CheckName = Context.getCheckName(DiagID);
283  // Allow specifying a few check names, delimited with comma.
284  SmallVector<StringRef, 1> Checks;
285  ChecksStr.split(Checks, ',', -1, false);
286  llvm::transform(Checks, Checks.begin(),
287  [](StringRef S) { return S.trim(); });
288  return llvm::find(Checks, CheckName) != Checks.end();
289  }
290  }
291  }
292  return true;
293 }
294 
295 static bool LineIsMarkedWithNOLINT(const SourceManager &SM, SourceLocation Loc,
296  unsigned DiagID,
297  const ClangTidyContext &Context) {
298  bool Invalid;
299  const char *CharacterData = SM.getCharacterData(Loc, &Invalid);
300  if (Invalid)
301  return false;
302 
303  // Check if there's a NOLINT on this line.
304  const char *P = CharacterData;
305  while (*P != '\0' && *P != '\r' && *P != '\n')
306  ++P;
307  StringRef RestOfLine(CharacterData, P - CharacterData + 1);
308  if (IsNOLINTFound("NOLINT", RestOfLine, DiagID, Context))
309  return true;
310 
311  // Check if there's a NOLINTNEXTLINE on the previous line.
312  const char *BufBegin =
313  SM.getCharacterData(SM.getLocForStartOfFile(SM.getFileID(Loc)), &Invalid);
314  if (Invalid || P == BufBegin)
315  return false;
316 
317  // Scan backwards over the current line.
318  P = CharacterData;
319  while (P != BufBegin && *P != '\n')
320  --P;
321 
322  // If we reached the begin of the file there is no line before it.
323  if (P == BufBegin)
324  return false;
325 
326  // Skip over the newline.
327  --P;
328  const char *LineEnd = P;
329 
330  // Now we're on the previous line. Skip to the beginning of it.
331  while (P != BufBegin && *P != '\n')
332  --P;
333 
334  RestOfLine = StringRef(P, LineEnd - P + 1);
335  if (IsNOLINTFound("NOLINTNEXTLINE", RestOfLine, DiagID, Context))
336  return true;
337 
338  return false;
339 }
340 
341 static bool LineIsMarkedWithNOLINTinMacro(const SourceManager &SM,
342  SourceLocation Loc, unsigned DiagID,
343  const ClangTidyContext &Context) {
344  while (true) {
345  if (LineIsMarkedWithNOLINT(SM, Loc, DiagID, Context))
346  return true;
347  if (!Loc.isMacroID())
348  return false;
349  Loc = SM.getImmediateExpansionRange(Loc).getBegin();
350  }
351  return false;
352 }
353 
354 namespace clang {
355 namespace tidy {
356 
357 bool ShouldSuppressDiagnostic(DiagnosticsEngine::Level DiagLevel,
358  const Diagnostic &Info, ClangTidyContext &Context,
359  bool CheckMacroExpansion) {
360  return Info.getLocation().isValid() &&
361  DiagLevel != DiagnosticsEngine::Error &&
362  DiagLevel != DiagnosticsEngine::Fatal &&
363  (CheckMacroExpansion ? LineIsMarkedWithNOLINTinMacro
364  : LineIsMarkedWithNOLINT)(Info.getSourceManager(),
365  Info.getLocation(),
366  Info.getID(), Context);
367 }
368 
369 } // namespace tidy
370 } // namespace clang
371 
373  DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
374  if (LastErrorWasIgnored && DiagLevel == DiagnosticsEngine::Note)
375  return;
376 
377  if (ShouldSuppressDiagnostic(DiagLevel, Info, Context)) {
378  ++Context.Stats.ErrorsIgnoredNOLINT;
379  // Ignored a warning, should ignore related notes as well
380  LastErrorWasIgnored = true;
381  return;
382  }
383 
384  LastErrorWasIgnored = false;
385  // Count warnings/errors.
386  DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
387 
388  if (DiagLevel == DiagnosticsEngine::Note) {
389  assert(!Errors.empty() &&
390  "A diagnostic note can only be appended to a message.");
391  } else {
392  finalizeLastError();
393  std::string CheckName = Context.getCheckName(Info.getID());
394  if (CheckName.empty()) {
395  // This is a compiler diagnostic without a warning option. Assign check
396  // name based on its level.
397  switch (DiagLevel) {
398  case DiagnosticsEngine::Error:
399  case DiagnosticsEngine::Fatal:
400  CheckName = "clang-diagnostic-error";
401  break;
402  case DiagnosticsEngine::Warning:
403  CheckName = "clang-diagnostic-warning";
404  break;
405  default:
406  CheckName = "clang-diagnostic-unknown";
407  break;
408  }
409  }
410 
411  ClangTidyError::Level Level = ClangTidyError::Warning;
412  if (DiagLevel == DiagnosticsEngine::Error ||
413  DiagLevel == DiagnosticsEngine::Fatal) {
414  // Force reporting of Clang errors regardless of filters and non-user
415  // code.
416  Level = ClangTidyError::Error;
417  LastErrorRelatesToUserCode = true;
418  LastErrorPassesLineFilter = true;
419  }
420  bool IsWarningAsError = DiagLevel == DiagnosticsEngine::Warning &&
421  Context.treatAsError(CheckName);
422  Errors.emplace_back(CheckName, Level, Context.getCurrentBuildDirectory(),
423  IsWarningAsError);
424  }
425 
426  if (ExternalDiagEngine) {
427  // If there is an external diagnostics engine, like in the
428  // ClangTidyPluginAction case, forward the diagnostics to it.
429  forwardDiagnostic(Info);
430  } else {
431  ClangTidyDiagnosticRenderer Converter(
432  Context.getLangOpts(), &Context.DiagEngine->getDiagnosticOptions(),
433  Errors.back());
434  SmallString<100> Message;
435  Info.FormatDiagnostic(Message);
436  FullSourceLoc Loc;
437  if (Info.getLocation().isValid() && Info.hasSourceManager())
438  Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
439  Converter.emitDiagnostic(Loc, DiagLevel, Message, Info.getRanges(),
440  Info.getFixItHints());
441  }
442 
443  if (Info.hasSourceManager())
444  checkFilters(Info.getLocation(), Info.getSourceManager());
445 }
446 
447 bool ClangTidyDiagnosticConsumer::passesLineFilter(StringRef FileName,
448  unsigned LineNumber) const {
449  if (Context.getGlobalOptions().LineFilter.empty())
450  return true;
451  for (const FileFilter &Filter : Context.getGlobalOptions().LineFilter) {
452  if (FileName.endswith(Filter.Name)) {
453  if (Filter.LineRanges.empty())
454  return true;
455  for (const FileFilter::LineRange &Range : Filter.LineRanges) {
456  if (Range.first <= LineNumber && LineNumber <= Range.second)
457  return true;
458  }
459  return false;
460  }
461  }
462  return false;
463 }
464 
465 void ClangTidyDiagnosticConsumer::forwardDiagnostic(const Diagnostic &Info) {
466  // Acquire a diagnostic ID also in the external diagnostics engine.
467  auto DiagLevelAndFormatString =
468  Context.getDiagLevelAndFormatString(Info.getID(), Info.getLocation());
469  unsigned ExternalID = ExternalDiagEngine->getDiagnosticIDs()->getCustomDiagID(
470  DiagLevelAndFormatString.first, DiagLevelAndFormatString.second);
471 
472  // Forward the details.
473  auto builder = ExternalDiagEngine->Report(Info.getLocation(), ExternalID);
474  for (auto Hint : Info.getFixItHints())
475  builder << Hint;
476  for (auto Range : Info.getRanges())
477  builder << Range;
478  for (unsigned Index = 0; Index < Info.getNumArgs(); ++Index) {
479  DiagnosticsEngine::ArgumentKind kind = Info.getArgKind(Index);
480  switch (kind) {
481  case clang::DiagnosticsEngine::ak_std_string:
482  builder << Info.getArgStdStr(Index);
483  break;
484  case clang::DiagnosticsEngine::ak_c_string:
485  builder << Info.getArgCStr(Index);
486  break;
487  case clang::DiagnosticsEngine::ak_sint:
488  builder << Info.getArgSInt(Index);
489  break;
490  case clang::DiagnosticsEngine::ak_uint:
491  builder << Info.getArgUInt(Index);
492  break;
493  case clang::DiagnosticsEngine::ak_tokenkind:
494  builder << static_cast<tok::TokenKind>(Info.getRawArg(Index));
495  break;
496  case clang::DiagnosticsEngine::ak_identifierinfo:
497  builder << Info.getArgIdentifier(Index);
498  break;
499  case clang::DiagnosticsEngine::ak_qual:
500  builder << Qualifiers::fromOpaqueValue(Info.getRawArg(Index));
501  break;
502  case clang::DiagnosticsEngine::ak_qualtype:
503  builder << QualType::getFromOpaquePtr((void *)Info.getRawArg(Index));
504  break;
505  case clang::DiagnosticsEngine::ak_declarationname:
506  builder << DeclarationName::getFromOpaqueInteger(Info.getRawArg(Index));
507  break;
508  case clang::DiagnosticsEngine::ak_nameddecl:
509  builder << reinterpret_cast<const NamedDecl *>(Info.getRawArg(Index));
510  break;
511  case clang::DiagnosticsEngine::ak_nestednamespec:
512  builder << reinterpret_cast<NestedNameSpecifier *>(Info.getRawArg(Index));
513  break;
514  case clang::DiagnosticsEngine::ak_declcontext:
515  builder << reinterpret_cast<DeclContext *>(Info.getRawArg(Index));
516  break;
517  case clang::DiagnosticsEngine::ak_qualtype_pair:
518  assert(false); // This one is not passed around.
519  break;
520  case clang::DiagnosticsEngine::ak_attr:
521  builder << reinterpret_cast<Attr *>(Info.getRawArg(Index));
522  break;
523  }
524  }
525 }
526 
527 void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
528  const SourceManager &Sources) {
529  // Invalid location may mean a diagnostic in a command line, don't skip these.
530  if (!Location.isValid()) {
531  LastErrorRelatesToUserCode = true;
532  LastErrorPassesLineFilter = true;
533  return;
534  }
535 
536  if (!*Context.getOptions().SystemHeaders &&
537  Sources.isInSystemHeader(Location))
538  return;
539 
540  // FIXME: We start with a conservative approach here, but the actual type of
541  // location needed depends on the check (in particular, where this check wants
542  // to apply fixes).
543  FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
544  const FileEntry *File = Sources.getFileEntryForID(FID);
545 
546  // -DMACRO definitions on the command line have locations in a virtual buffer
547  // that doesn't have a FileEntry. Don't skip these as well.
548  if (!File) {
549  LastErrorRelatesToUserCode = true;
550  LastErrorPassesLineFilter = true;
551  return;
552  }
553 
554  StringRef FileName(File->getName());
555  LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
556  Sources.isInMainFile(Location) ||
557  getHeaderFilter()->match(FileName);
558 
559  unsigned LineNumber = Sources.getExpansionLineNumber(Location);
560  LastErrorPassesLineFilter =
561  LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
562 }
563 
564 llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() {
565  if (!HeaderFilter)
566  HeaderFilter =
567  std::make_unique<llvm::Regex>(*Context.getOptions().HeaderFilterRegex);
568  return HeaderFilter.get();
569 }
570 
571 void ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
572  // Each error is modelled as the set of intervals in which it applies
573  // replacements. To detect overlapping replacements, we use a sweep line
574  // algorithm over these sets of intervals.
575  // An event here consists of the opening or closing of an interval. During the
576  // process, we maintain a counter with the amount of open intervals. If we
577  // find an endpoint of an interval and this counter is different from 0, it
578  // means that this interval overlaps with another one, so we set it as
579  // inapplicable.
580  struct Event {
581  // An event can be either the begin or the end of an interval.
582  enum EventType {
583  ET_Begin = 1,
584  ET_End = -1,
585  };
586 
587  Event(unsigned Begin, unsigned End, EventType Type, unsigned ErrorId,
588  unsigned ErrorSize)
589  : Type(Type), ErrorId(ErrorId) {
590  // The events are going to be sorted by their position. In case of draw:
591  //
592  // * If an interval ends at the same position at which other interval
593  // begins, this is not an overlapping, so we want to remove the ending
594  // interval before adding the starting one: end events have higher
595  // priority than begin events.
596  //
597  // * If we have several begin points at the same position, we will mark as
598  // inapplicable the ones that we process later, so the first one has to
599  // be the one with the latest end point, because this one will contain
600  // all the other intervals. For the same reason, if we have several end
601  // points in the same position, the last one has to be the one with the
602  // earliest begin point. In both cases, we sort non-increasingly by the
603  // position of the complementary.
604  //
605  // * In case of two equal intervals, the one whose error is bigger can
606  // potentially contain the other one, so we want to process its begin
607  // points before and its end points later.
608  //
609  // * Finally, if we have two equal intervals whose errors have the same
610  // size, none of them will be strictly contained inside the other.
611  // Sorting by ErrorId will guarantee that the begin point of the first
612  // one will be processed before, disallowing the second one, and the
613  // end point of the first one will also be processed before,
614  // disallowing the first one.
615  if (Type == ET_Begin)
616  Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
617  else
618  Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
619  }
620 
621  bool operator<(const Event &Other) const {
622  return Priority < Other.Priority;
623  }
624 
625  // Determines if this event is the begin or the end of an interval.
626  EventType Type;
627  // The index of the error to which the interval that generated this event
628  // belongs.
629  unsigned ErrorId;
630  // The events will be sorted based on this field.
631  std::tuple<unsigned, EventType, int, int, unsigned> Priority;
632  };
633 
634  // Compute error sizes.
635  std::vector<int> Sizes;
636  std::vector<
637  std::pair<ClangTidyError *, llvm::StringMap<tooling::Replacements> *>>
638  ErrorFixes;
639  for (auto &Error : Errors) {
640  if (const auto *Fix = tooling::selectFirstFix(Error))
641  ErrorFixes.emplace_back(
642  &Error, const_cast<llvm::StringMap<tooling::Replacements> *>(Fix));
643  }
644  for (const auto &ErrorAndFix : ErrorFixes) {
645  int Size = 0;
646  for (const auto &FileAndReplaces : *ErrorAndFix.second) {
647  for (const auto &Replace : FileAndReplaces.second)
648  Size += Replace.getLength();
649  }
650  Sizes.push_back(Size);
651  }
652 
653  // Build events from error intervals.
654  std::map<std::string, std::vector<Event>> FileEvents;
655  for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
656  for (const auto &FileAndReplace : *ErrorFixes[I].second) {
657  for (const auto &Replace : FileAndReplace.second) {
658  unsigned Begin = Replace.getOffset();
659  unsigned End = Begin + Replace.getLength();
660  const std::string &FilePath = Replace.getFilePath();
661  // FIXME: Handle empty intervals, such as those from insertions.
662  if (Begin == End)
663  continue;
664  auto &Events = FileEvents[FilePath];
665  Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
666  Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
667  }
668  }
669  }
670 
671  std::vector<bool> Apply(ErrorFixes.size(), true);
672  for (auto &FileAndEvents : FileEvents) {
673  std::vector<Event> &Events = FileAndEvents.second;
674  // Sweep.
675  std::sort(Events.begin(), Events.end());
676  int OpenIntervals = 0;
677  for (const auto &Event : Events) {
678  if (Event.Type == Event::ET_End)
679  --OpenIntervals;
680  // This has to be checked after removing the interval from the count if it
681  // is an end event, or before adding it if it is a begin event.
682  if (OpenIntervals != 0)
683  Apply[Event.ErrorId] = false;
684  if (Event.Type == Event::ET_Begin)
685  ++OpenIntervals;
686  }
687  assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
688  }
689 
690  for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
691  if (!Apply[I]) {
692  ErrorFixes[I].second->clear();
693  ErrorFixes[I].first->Notes.emplace_back(
694  "this fix will not be applied because it overlaps with another fix");
695  }
696  }
697 }
698 
699 namespace {
700 struct LessClangTidyError {
701  bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
702  const tooling::DiagnosticMessage &M1 = LHS.Message;
703  const tooling::DiagnosticMessage &M2 = RHS.Message;
704 
705  return
706  std::tie(M1.FilePath, M1.FileOffset, LHS.DiagnosticName, M1.Message) <
707  std::tie(M2.FilePath, M2.FileOffset, RHS.DiagnosticName, M2.Message);
708  }
709 };
710 struct EqualClangTidyError {
711  bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
712  LessClangTidyError Less;
713  return !Less(LHS, RHS) && !Less(RHS, LHS);
714  }
715 };
716 } // end anonymous namespace
717 
718 std::vector<ClangTidyError> ClangTidyDiagnosticConsumer::take() {
719  finalizeLastError();
720 
721  std::sort(Errors.begin(), Errors.end(), LessClangTidyError());
722  Errors.erase(std::unique(Errors.begin(), Errors.end(), EqualClangTidyError()),
723  Errors.end());
724  if (RemoveIncompatibleErrors)
725  removeIncompatibleErrors();
726  return std::move(Errors);
727 }
llvm::Optional< std::string > Checks
Checks filter.
SourceLocation Loc
&#39;#&#39; location in the include directive
ClangTidyOptions mergeWith(const ClangTidyOptions &Other) const
Creates a new ClangTidyOptions instance combined from all fields of this instance overridden by the f...
bool ShouldSuppressDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info, ClangTidyContext &Context, bool CheckMacroExpansion)
Check whether a given diagnostic should be suppressed due to the presence of a "NOLINT" suppression c...
Read-only set of strings represented as a list of positive and negative globs.
Definition: GlobList.h:25
const ClangTidyGlobalOptions & getGlobalOptions() const
Returns global options.
static bool LineIsMarkedWithNOLINTinMacro(const SourceManager &SM, SourceLocation Loc, unsigned DiagID, const ClangTidyContext &Context)
bool isCheckEnabled(StringRef CheckName) const
Returns true if the check is enabled for the CurrentFile.
constexpr llvm::StringLiteral Message
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
Contains options for clang-tidy.
Context Ctx
std::pair< unsigned, unsigned > LineRange
LineRange is a pair<start, end> (inclusive).
void setCurrentFile(StringRef File)
Should be called when starting to process new translation unit.
static cl::opt< bool > AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers", cl::init(false), cl::Hidden, cl::cat(ClangTidyCategory))
This option allows enabling the experimental alpha checkers from the static analyzer.
DiagnosticBuilder diag(StringRef CheckName, SourceLocation Loc, StringRef Message, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Report any errors detected using this method.
bool operator<(const Ref &L, const Ref &R)
Definition: Ref.h:58
llvm::Optional< ClangTidyProfiling::StorageParams > getProfileStorageParams() const
ClangTidyDiagnosticConsumer(ClangTidyContext &Ctx, DiagnosticsEngine *ExternalDiagEngine=nullptr, bool RemoveIncompatibleErrors=true)
ClangTidyError(StringRef CheckName, Level DiagLevel, StringRef BuildDirectory, bool IsWarningAsError)
ClangTidyOptions getOptionsForFile(StringRef File) const
Returns options for File.
const ClangTidyOptions & getOptions() const
Returns options for CurrentFile.
void setASTContext(ASTContext *Context)
Sets ASTContext for the current translation unit.
const Decl * D
Definition: XRefs.cpp:849
void setProfileStoragePrefix(StringRef ProfilePrefix)
Control storage of profile date.
PathRef FileName
llvm::Optional< std::string > WarningsAsErrors
WarningsAsErrors filter.
void setSourceManager(SourceManager *SourceMgr)
Sets the SourceManager of the used DiagnosticsEngine.
Contains a list of line ranges in a single file.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
ClangTidyContext(std::unique_ptr< ClangTidyOptionsProvider > OptionsProvider, bool AllowEnablingAnalyzerAlphaCheckers=false)
Initializes ClangTidyContext instance.
static bool IsNOLINTFound(StringRef NolintDirectiveText, StringRef Line, unsigned DiagID, const ClangTidyContext &Context)
std::vector< FixItHint > Hints
CharSourceRange Range
SourceRange for the file name.
A detected error complete with information to display diagnostic and automatic fix.
std::string getCheckName(unsigned DiagnosticID) const
Returns the name of the clang-tidy check which produced this diagnostic ID.
static cl::opt< std::string > Checks("checks", cl::desc(R"( Comma-separated list of globs with optional '-' prefix. Globs are processed in order of appearance in the list. Globs without '-' prefix add checks with matching names to the set, globs with the '-' prefix remove checks with matching names from the set of enabled checks. This option's value is appended to the value of the 'Checks' option in .clang-tidy file, if any. )"), cl::init(""), cl::cat(ClangTidyCategory))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
llvm::Optional< FixItHint > FixIt
static ClangTidyOptions getDefaults()
These options are used for all settings that haven&#39;t been overridden by the OptionsProvider.
const char * Description
Definition: Dexp.cpp:257
static cl::opt< bool > Fix("fix", cl::desc(R"( Apply suggested fixes. Without -fix-errors clang-tidy will bail out if any compilation errors were found. )"), cl::init(false), cl::cat(ClangTidyCategory))
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) override
bool treatAsError(StringRef CheckName) const
Returns true if the check should be upgraded to error for the CurrentFile.
void setEnableProfiling(bool Profile)
Control profile collection in clang-tidy.
static bool LineIsMarkedWithNOLINT(const SourceManager &SM, SourceLocation Loc, unsigned DiagID, const ClangTidyContext &Context)
NodeType Type
const SymbolIndex * Index
Definition: Dexp.cpp:84