blob: ca3494fd2a95de8b600b663196290834cb360941 [file] [log] [blame]
Alexander Kornienkod0488d42017-05-09 14:56:28 +00001//===--- tools/extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp ----------=== //
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 This file implements ClangTidyDiagnosticConsumer, ClangTidyContext
11/// and ClangTidyError classes.
12///
13/// This tool uses the Clang Tooling infrastructure, see
14/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
15/// for details on setting it up with LLVM source tree.
16///
17//===----------------------------------------------------------------------===//
18
19#include "ClangTidyDiagnosticConsumer.h"
20#include "ClangTidyOptions.h"
21#include "clang/AST/ASTDiagnostic.h"
22#include "clang/Basic/DiagnosticOptions.h"
23#include "clang/Frontend/DiagnosticRenderer.h"
24#include "llvm/ADT/SmallString.h"
25#include <tuple>
26#include <vector>
27using namespace clang;
28using namespace tidy;
29
30namespace {
31class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
32public:
33 ClangTidyDiagnosticRenderer(const LangOptions &LangOpts,
34 DiagnosticOptions *DiagOpts,
35 ClangTidyError &Error)
36 : DiagnosticRenderer(LangOpts, DiagOpts), Error(Error) {}
37
38protected:
39 void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc,
40 DiagnosticsEngine::Level Level, StringRef Message,
41 ArrayRef<CharSourceRange> Ranges,
42 const SourceManager *SM,
43 DiagOrStoredDiag Info) override {
44 // Remove check name from the message.
45 // FIXME: Remove this once there's a better way to pass check names than
46 // appending the check name to the message in ClangTidyContext::diag and
47 // using getCustomDiagID.
48 std::string CheckNameInMessage = " [" + Error.DiagnosticName + "]";
49 if (Message.endswith(CheckNameInMessage))
50 Message = Message.substr(0, Message.size() - CheckNameInMessage.size());
51
52 auto TidyMessage = Loc.isValid()
53 ? tooling::DiagnosticMessage(Message, *SM, Loc)
54 : tooling::DiagnosticMessage(Message);
55 if (Level == DiagnosticsEngine::Note) {
56 Error.Notes.push_back(TidyMessage);
57 return;
58 }
59 assert(Error.Message.Message.empty() && "Overwriting a diagnostic message");
60 Error.Message = TidyMessage;
61 }
62
63 void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
64 DiagnosticsEngine::Level Level,
65 ArrayRef<CharSourceRange> Ranges,
66 const SourceManager &SM) override {}
67
68 void emitCodeContext(SourceLocation Loc, DiagnosticsEngine::Level Level,
69 SmallVectorImpl<CharSourceRange> &Ranges,
70 ArrayRef<FixItHint> Hints,
71 const SourceManager &SM) override {
72 assert(Loc.isValid());
73 for (const auto &FixIt : Hints) {
74 CharSourceRange Range = FixIt.RemoveRange;
75 assert(Range.getBegin().isValid() && Range.getEnd().isValid() &&
76 "Invalid range in the fix-it hint.");
77 assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
78 "Only file locations supported in fix-it hints.");
79
80 tooling::Replacement Replacement(SM, Range, FixIt.CodeToInsert);
81 llvm::Error Err = Error.Fix[Replacement.getFilePath()].add(Replacement);
82 // FIXME: better error handling (at least, don't let other replacements be
83 // applied).
84 if (Err) {
85 llvm::errs() << "Fix conflicts with existing fix! "
86 << llvm::toString(std::move(Err)) << "\n";
87 assert(false && "Fix conflicts with existing fix!");
88 }
89 }
90 }
91
92 void emitIncludeLocation(SourceLocation Loc, PresumedLoc PLoc,
93 const SourceManager &SM) override {}
94
95 void emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
96 StringRef ModuleName,
97 const SourceManager &SM) override {}
98
99 void emitBuildingModuleLocation(SourceLocation Loc, PresumedLoc PLoc,
100 StringRef ModuleName,
101 const SourceManager &SM) override {}
102
103 void endDiagnostic(DiagOrStoredDiag D,
104 DiagnosticsEngine::Level Level) override {
105 assert(!Error.Message.Message.empty() && "Message has not been set");
106 }
107
108private:
109 ClangTidyError &Error;
110};
111} // end anonymous namespace
112
113ClangTidyError::ClangTidyError(StringRef CheckName,
114 ClangTidyError::Level DiagLevel,
115 StringRef BuildDirectory, bool IsWarningAsError)
116 : tooling::Diagnostic(CheckName, DiagLevel, BuildDirectory),
117 IsWarningAsError(IsWarningAsError) {}
118
119// Returns true if GlobList starts with the negative indicator ('-'), removes it
120// from the GlobList.
121static bool ConsumeNegativeIndicator(StringRef &GlobList) {
122 GlobList = GlobList.trim(' ');
123 if (GlobList.startswith("-")) {
124 GlobList = GlobList.substr(1);
125 return true;
126 }
127 return false;
128}
129// Converts first glob from the comma-separated list of globs to Regex and
130// removes it and the trailing comma from the GlobList.
131static llvm::Regex ConsumeGlob(StringRef &GlobList) {
132 StringRef UntrimmedGlob = GlobList.substr(0, GlobList.find(','));
133 StringRef Glob = UntrimmedGlob.trim(' ');
134 GlobList = GlobList.substr(UntrimmedGlob.size() + 1);
135 SmallString<128> RegexText("^");
136 StringRef MetaChars("()^$|*+?.[]\\{}");
137 for (char C : Glob) {
138 if (C == '*')
139 RegexText.push_back('.');
140 else if (MetaChars.find(C) != StringRef::npos)
141 RegexText.push_back('\\');
142 RegexText.push_back(C);
143 }
144 RegexText.push_back('$');
145 return llvm::Regex(RegexText);
146}
147
148GlobList::GlobList(StringRef Globs)
149 : Positive(!ConsumeNegativeIndicator(Globs)), Regex(ConsumeGlob(Globs)),
150 NextGlob(Globs.empty() ? nullptr : new GlobList(Globs)) {}
151
152bool GlobList::contains(StringRef S, bool Contains) {
153 if (Regex.match(S))
154 Contains = Positive;
155
156 if (NextGlob)
157 Contains = NextGlob->contains(S, Contains);
158 return Contains;
159}
160
161ClangTidyContext::ClangTidyContext(
162 std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider)
163 : DiagEngine(nullptr), OptionsProvider(std::move(OptionsProvider)),
164 Profile(nullptr) {
165 // Before the first translation unit we can get errors related to command-line
166 // parsing, use empty string for the file name in this case.
167 setCurrentFile("");
168}
169
170DiagnosticBuilder ClangTidyContext::diag(
171 StringRef CheckName, SourceLocation Loc, StringRef Description,
172 DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
173 assert(Loc.isValid());
174 unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
175 Level, (Description + " [" + CheckName + "]").str());
176 CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
177 return DiagEngine->Report(Loc, ID);
178}
179
180void ClangTidyContext::setDiagnosticsEngine(DiagnosticsEngine *Engine) {
181 DiagEngine = Engine;
182}
183
184void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
185 DiagEngine->setSourceManager(SourceMgr);
186}
187
188void ClangTidyContext::setCurrentFile(StringRef File) {
189 CurrentFile = File;
190 CurrentOptions = getOptionsForFile(CurrentFile);
191 CheckFilter.reset(new GlobList(*getOptions().Checks));
192 WarningAsErrorFilter.reset(new GlobList(*getOptions().WarningsAsErrors));
193}
194
195void ClangTidyContext::setASTContext(ASTContext *Context) {
196 DiagEngine->SetArgToStringFn(&FormatASTNodeDiagnosticArgument, Context);
197 LangOpts = Context->getLangOpts();
198}
199
200const ClangTidyGlobalOptions &ClangTidyContext::getGlobalOptions() const {
201 return OptionsProvider->getGlobalOptions();
202}
203
204const ClangTidyOptions &ClangTidyContext::getOptions() const {
205 return CurrentOptions;
206}
207
208ClangTidyOptions ClangTidyContext::getOptionsForFile(StringRef File) const {
209 // Merge options on top of getDefaults() as a safeguard against options with
210 // unset values.
211 return ClangTidyOptions::getDefaults().mergeWith(
212 OptionsProvider->getOptions(File));
213}
214
215void ClangTidyContext::setCheckProfileData(ProfileData *P) { Profile = P; }
216
217GlobList &ClangTidyContext::getChecksFilter() {
218 assert(CheckFilter != nullptr);
219 return *CheckFilter;
220}
221
222GlobList &ClangTidyContext::getWarningAsErrorFilter() {
223 assert(WarningAsErrorFilter != nullptr);
224 return *WarningAsErrorFilter;
225}
226
227/// \brief Store a \c ClangTidyError.
228void ClangTidyContext::storeError(const ClangTidyError &Error) {
229 Errors.push_back(Error);
230}
231
232StringRef ClangTidyContext::getCheckName(unsigned DiagnosticID) const {
233 llvm::DenseMap<unsigned, std::string>::const_iterator I =
234 CheckNamesByDiagnosticID.find(DiagnosticID);
235 if (I != CheckNamesByDiagnosticID.end())
236 return I->second;
237 return "";
238}
239
Alexander Kornienko9660d4d2017-05-09 15:10:26 +0000240ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
241 ClangTidyContext &Ctx, bool RemoveIncompatibleErrors)
242 : Context(Ctx), RemoveIncompatibleErrors(RemoveIncompatibleErrors),
243 LastErrorRelatesToUserCode(false), LastErrorPassesLineFilter(false),
244 LastErrorWasIgnored(false) {
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000245 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
246 Diags.reset(new DiagnosticsEngine(
247 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts, this,
248 /*ShouldOwnClient=*/false));
249 Context.setDiagnosticsEngine(Diags.get());
250}
251
252void ClangTidyDiagnosticConsumer::finalizeLastError() {
253 if (!Errors.empty()) {
254 ClangTidyError &Error = Errors.back();
255 if (!Context.getChecksFilter().contains(Error.DiagnosticName) &&
256 Error.DiagLevel != ClangTidyError::Error) {
257 ++Context.Stats.ErrorsIgnoredCheckFilter;
258 Errors.pop_back();
259 } else if (!LastErrorRelatesToUserCode) {
260 ++Context.Stats.ErrorsIgnoredNonUserCode;
261 Errors.pop_back();
262 } else if (!LastErrorPassesLineFilter) {
263 ++Context.Stats.ErrorsIgnoredLineFilter;
264 Errors.pop_back();
265 } else {
266 ++Context.Stats.ErrorsDisplayed;
267 }
268 }
269 LastErrorRelatesToUserCode = false;
270 LastErrorPassesLineFilter = false;
271}
272
273static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
274 bool Invalid;
275 const char *CharacterData = SM.getCharacterData(Loc, &Invalid);
276 if (Invalid)
277 return false;
278
279 // Check if there's a NOLINT on this line.
280 const char *P = CharacterData;
281 while (*P != '\0' && *P != '\r' && *P != '\n')
282 ++P;
283 StringRef RestOfLine(CharacterData, P - CharacterData + 1);
284 // FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
285 if (RestOfLine.find("NOLINT") != StringRef::npos)
286 return true;
287
288 // Check if there's a NOLINTNEXTLINE on the previous line.
289 const char *BufBegin =
290 SM.getCharacterData(SM.getLocForStartOfFile(SM.getFileID(Loc)), &Invalid);
291 if (Invalid || P == BufBegin)
292 return false;
293
294 // Scan backwards over the current line.
295 P = CharacterData;
296 while (P != BufBegin && *P != '\n')
297 --P;
298
299 // If we reached the begin of the file there is no line before it.
300 if (P == BufBegin)
301 return false;
302
303 // Skip over the newline.
304 --P;
305 const char *LineEnd = P;
306
307 // Now we're on the previous line. Skip to the beginning of it.
308 while (P != BufBegin && *P != '\n')
309 --P;
310
311 RestOfLine = StringRef(P, LineEnd - P + 1);
312 if (RestOfLine.find("NOLINTNEXTLINE") != StringRef::npos)
313 return true;
314
315 return false;
316}
317
318static bool LineIsMarkedWithNOLINTinMacro(SourceManager &SM,
319 SourceLocation Loc) {
320 while (true) {
321 if (LineIsMarkedWithNOLINT(SM, Loc))
322 return true;
323 if (!Loc.isMacroID())
324 return false;
325 Loc = SM.getImmediateExpansionRange(Loc).first;
326 }
327 return false;
328}
329
330void ClangTidyDiagnosticConsumer::HandleDiagnostic(
331 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
332 if (LastErrorWasIgnored && DiagLevel == DiagnosticsEngine::Note)
333 return;
334
335 if (Info.getLocation().isValid() && DiagLevel != DiagnosticsEngine::Error &&
336 DiagLevel != DiagnosticsEngine::Fatal &&
337 LineIsMarkedWithNOLINTinMacro(Diags->getSourceManager(),
338 Info.getLocation())) {
339 ++Context.Stats.ErrorsIgnoredNOLINT;
340 // Ignored a warning, should ignore related notes as well
341 LastErrorWasIgnored = true;
342 return;
343 }
344
345 LastErrorWasIgnored = false;
346 // Count warnings/errors.
347 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
348
349 if (DiagLevel == DiagnosticsEngine::Note) {
350 assert(!Errors.empty() &&
351 "A diagnostic note can only be appended to a message.");
352 } else {
353 finalizeLastError();
354 StringRef WarningOption =
355 Context.DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(
356 Info.getID());
357 std::string CheckName = !WarningOption.empty()
358 ? ("clang-diagnostic-" + WarningOption).str()
359 : Context.getCheckName(Info.getID()).str();
360
361 if (CheckName.empty()) {
362 // This is a compiler diagnostic without a warning option. Assign check
363 // name based on its level.
364 switch (DiagLevel) {
365 case DiagnosticsEngine::Error:
366 case DiagnosticsEngine::Fatal:
367 CheckName = "clang-diagnostic-error";
368 break;
369 case DiagnosticsEngine::Warning:
370 CheckName = "clang-diagnostic-warning";
371 break;
372 default:
373 CheckName = "clang-diagnostic-unknown";
374 break;
375 }
376 }
377
378 ClangTidyError::Level Level = ClangTidyError::Warning;
379 if (DiagLevel == DiagnosticsEngine::Error ||
380 DiagLevel == DiagnosticsEngine::Fatal) {
381 // Force reporting of Clang errors regardless of filters and non-user
382 // code.
383 Level = ClangTidyError::Error;
384 LastErrorRelatesToUserCode = true;
385 LastErrorPassesLineFilter = true;
386 }
387 bool IsWarningAsError =
388 DiagLevel == DiagnosticsEngine::Warning &&
389 Context.getWarningAsErrorFilter().contains(CheckName);
390 Errors.emplace_back(CheckName, Level, Context.getCurrentBuildDirectory(),
391 IsWarningAsError);
392 }
393
394 ClangTidyDiagnosticRenderer Converter(
395 Context.getLangOpts(), &Context.DiagEngine->getDiagnosticOptions(),
396 Errors.back());
397 SmallString<100> Message;
398 Info.FormatDiagnostic(Message);
399 SourceManager *Sources = nullptr;
400 if (Info.hasSourceManager())
401 Sources = &Info.getSourceManager();
402 Converter.emitDiagnostic(Info.getLocation(), DiagLevel, Message,
403 Info.getRanges(), Info.getFixItHints(), Sources);
404
405 checkFilters(Info.getLocation());
406}
407
408bool ClangTidyDiagnosticConsumer::passesLineFilter(StringRef FileName,
409 unsigned LineNumber) const {
410 if (Context.getGlobalOptions().LineFilter.empty())
411 return true;
412 for (const FileFilter &Filter : Context.getGlobalOptions().LineFilter) {
413 if (FileName.endswith(Filter.Name)) {
414 if (Filter.LineRanges.empty())
415 return true;
416 for (const FileFilter::LineRange &Range : Filter.LineRanges) {
417 if (Range.first <= LineNumber && LineNumber <= Range.second)
418 return true;
419 }
420 return false;
421 }
422 }
423 return false;
424}
425
426void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location) {
427 // Invalid location may mean a diagnostic in a command line, don't skip these.
428 if (!Location.isValid()) {
429 LastErrorRelatesToUserCode = true;
430 LastErrorPassesLineFilter = true;
431 return;
432 }
433
434 const SourceManager &Sources = Diags->getSourceManager();
435 if (!*Context.getOptions().SystemHeaders &&
436 Sources.isInSystemHeader(Location))
437 return;
438
439 // FIXME: We start with a conservative approach here, but the actual type of
440 // location needed depends on the check (in particular, where this check wants
441 // to apply fixes).
442 FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
443 const FileEntry *File = Sources.getFileEntryForID(FID);
444
445 // -DMACRO definitions on the command line have locations in a virtual buffer
446 // that doesn't have a FileEntry. Don't skip these as well.
447 if (!File) {
448 LastErrorRelatesToUserCode = true;
449 LastErrorPassesLineFilter = true;
450 return;
451 }
452
453 StringRef FileName(File->getName());
454 LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
455 Sources.isInMainFile(Location) ||
456 getHeaderFilter()->match(FileName);
457
458 unsigned LineNumber = Sources.getExpansionLineNumber(Location);
459 LastErrorPassesLineFilter =
460 LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
461}
462
463llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() {
464 if (!HeaderFilter)
465 HeaderFilter.reset(
466 new llvm::Regex(*Context.getOptions().HeaderFilterRegex));
467 return HeaderFilter.get();
468}
469
470void ClangTidyDiagnosticConsumer::removeIncompatibleErrors(
471 SmallVectorImpl<ClangTidyError> &Errors) const {
472 // Each error is modelled as the set of intervals in which it applies
473 // replacements. To detect overlapping replacements, we use a sweep line
474 // algorithm over these sets of intervals.
475 // An event here consists of the opening or closing of an interval. During the
476 // process, we maintain a counter with the amount of open intervals. If we
477 // find an endpoint of an interval and this counter is different from 0, it
478 // means that this interval overlaps with another one, so we set it as
479 // inapplicable.
480 struct Event {
481 // An event can be either the begin or the end of an interval.
482 enum EventType {
483 ET_Begin = 1,
484 ET_End = -1,
485 };
486
487 Event(unsigned Begin, unsigned End, EventType Type, unsigned ErrorId,
488 unsigned ErrorSize)
489 : Type(Type), ErrorId(ErrorId) {
490 // The events are going to be sorted by their position. In case of draw:
491 //
492 // * If an interval ends at the same position at which other interval
493 // begins, this is not an overlapping, so we want to remove the ending
494 // interval before adding the starting one: end events have higher
495 // priority than begin events.
496 //
497 // * If we have several begin points at the same position, we will mark as
498 // inapplicable the ones that we process later, so the first one has to
499 // be the one with the latest end point, because this one will contain
500 // all the other intervals. For the same reason, if we have several end
501 // points in the same position, the last one has to be the one with the
502 // earliest begin point. In both cases, we sort non-increasingly by the
503 // position of the complementary.
504 //
505 // * In case of two equal intervals, the one whose error is bigger can
506 // potentially contain the other one, so we want to process its begin
507 // points before and its end points later.
508 //
509 // * Finally, if we have two equal intervals whose errors have the same
510 // size, none of them will be strictly contained inside the other.
511 // Sorting by ErrorId will guarantee that the begin point of the first
512 // one will be processed before, disallowing the second one, and the
513 // end point of the first one will also be processed before,
514 // disallowing the first one.
515 if (Type == ET_Begin)
516 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
517 else
518 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
519 }
520
521 bool operator<(const Event &Other) const {
522 return Priority < Other.Priority;
523 }
524
525 // Determines if this event is the begin or the end of an interval.
526 EventType Type;
527 // The index of the error to which the interval that generated this event
528 // belongs.
529 unsigned ErrorId;
530 // The events will be sorted based on this field.
531 std::tuple<unsigned, EventType, int, int, unsigned> Priority;
532 };
533
534 // Compute error sizes.
535 std::vector<int> Sizes;
536 for (const auto &Error : Errors) {
537 int Size = 0;
538 for (const auto &FileAndReplaces : Error.Fix) {
539 for (const auto &Replace : FileAndReplaces.second)
540 Size += Replace.getLength();
541 }
542 Sizes.push_back(Size);
543 }
544
545 // Build events from error intervals.
546 std::map<std::string, std::vector<Event>> FileEvents;
547 for (unsigned I = 0; I < Errors.size(); ++I) {
548 for (const auto &FileAndReplace : Errors[I].Fix) {
549 for (const auto &Replace : FileAndReplace.second) {
550 unsigned Begin = Replace.getOffset();
551 unsigned End = Begin + Replace.getLength();
552 const std::string &FilePath = Replace.getFilePath();
553 // FIXME: Handle empty intervals, such as those from insertions.
554 if (Begin == End)
555 continue;
556 auto &Events = FileEvents[FilePath];
557 Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
558 Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
559 }
560 }
561 }
562
563 std::vector<bool> Apply(Errors.size(), true);
564 for (auto &FileAndEvents : FileEvents) {
565 std::vector<Event> &Events = FileAndEvents.second;
566 // Sweep.
567 std::sort(Events.begin(), Events.end());
568 int OpenIntervals = 0;
569 for (const auto &Event : Events) {
570 if (Event.Type == Event::ET_End)
571 --OpenIntervals;
572 // This has to be checked after removing the interval from the count if it
573 // is an end event, or before adding it if it is a begin event.
574 if (OpenIntervals != 0)
575 Apply[Event.ErrorId] = false;
576 if (Event.Type == Event::ET_Begin)
577 ++OpenIntervals;
578 }
579 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
580 }
581
582 for (unsigned I = 0; I < Errors.size(); ++I) {
583 if (!Apply[I]) {
584 Errors[I].Fix.clear();
585 Errors[I].Notes.emplace_back(
586 "this fix will not be applied because it overlaps with another fix");
587 }
588 }
589}
590
591namespace {
592struct LessClangTidyError {
593 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
594 const tooling::DiagnosticMessage &M1 = LHS.Message;
595 const tooling::DiagnosticMessage &M2 = RHS.Message;
596
597 return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
598 std::tie(M2.FilePath, M2.FileOffset, M2.Message);
599 }
600};
601struct EqualClangTidyError {
602 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
603 LessClangTidyError Less;
604 return !Less(LHS, RHS) && !Less(RHS, LHS);
605 }
606};
607} // end anonymous namespace
608
609// Flushes the internal diagnostics buffer to the ClangTidyContext.
610void ClangTidyDiagnosticConsumer::finish() {
611 finalizeLastError();
612
613 std::sort(Errors.begin(), Errors.end(), LessClangTidyError());
614 Errors.erase(std::unique(Errors.begin(), Errors.end(), EqualClangTidyError()),
615 Errors.end());
Alexander Kornienko9660d4d2017-05-09 15:10:26 +0000616
617 if (RemoveIncompatibleErrors)
618 removeIncompatibleErrors(Errors);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000619
620 for (const ClangTidyError &Error : Errors)
621 Context.storeError(Error);
622 Errors.clear();
623}