blob: 741bac603f80e369c0ab967bf9eb609e9f1c7a7c [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
Alexander Kornienko21375182017-05-17 14:39:47 +0000217bool ClangTidyContext::isCheckEnabled(StringRef CheckName) const {
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000218 assert(CheckFilter != nullptr);
Alexander Kornienko21375182017-05-17 14:39:47 +0000219 return CheckFilter->contains(CheckName);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000220}
221
Alexander Kornienko21375182017-05-17 14:39:47 +0000222bool ClangTidyContext::treatAsError(StringRef CheckName) const {
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000223 assert(WarningAsErrorFilter != nullptr);
Alexander Kornienko21375182017-05-17 14:39:47 +0000224 return WarningAsErrorFilter->contains(CheckName);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000225}
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();
Alexander Kornienko21375182017-05-17 14:39:47 +0000255 if (!Context.isCheckEnabled(Error.DiagnosticName) &&
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000256 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 }
Alexander Kornienko21375182017-05-17 14:39:47 +0000387 bool IsWarningAsError = DiagLevel == DiagnosticsEngine::Warning &&
388 Context.treatAsError(CheckName);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000389 Errors.emplace_back(CheckName, Level, Context.getCurrentBuildDirectory(),
390 IsWarningAsError);
391 }
392
393 ClangTidyDiagnosticRenderer Converter(
394 Context.getLangOpts(), &Context.DiagEngine->getDiagnosticOptions(),
395 Errors.back());
396 SmallString<100> Message;
397 Info.FormatDiagnostic(Message);
398 SourceManager *Sources = nullptr;
399 if (Info.hasSourceManager())
400 Sources = &Info.getSourceManager();
401 Converter.emitDiagnostic(Info.getLocation(), DiagLevel, Message,
402 Info.getRanges(), Info.getFixItHints(), Sources);
403
404 checkFilters(Info.getLocation());
405}
406
407bool ClangTidyDiagnosticConsumer::passesLineFilter(StringRef FileName,
408 unsigned LineNumber) const {
409 if (Context.getGlobalOptions().LineFilter.empty())
410 return true;
411 for (const FileFilter &Filter : Context.getGlobalOptions().LineFilter) {
412 if (FileName.endswith(Filter.Name)) {
413 if (Filter.LineRanges.empty())
414 return true;
415 for (const FileFilter::LineRange &Range : Filter.LineRanges) {
416 if (Range.first <= LineNumber && LineNumber <= Range.second)
417 return true;
418 }
419 return false;
420 }
421 }
422 return false;
423}
424
425void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location) {
426 // Invalid location may mean a diagnostic in a command line, don't skip these.
427 if (!Location.isValid()) {
428 LastErrorRelatesToUserCode = true;
429 LastErrorPassesLineFilter = true;
430 return;
431 }
432
433 const SourceManager &Sources = Diags->getSourceManager();
434 if (!*Context.getOptions().SystemHeaders &&
435 Sources.isInSystemHeader(Location))
436 return;
437
438 // FIXME: We start with a conservative approach here, but the actual type of
439 // location needed depends on the check (in particular, where this check wants
440 // to apply fixes).
441 FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
442 const FileEntry *File = Sources.getFileEntryForID(FID);
443
444 // -DMACRO definitions on the command line have locations in a virtual buffer
445 // that doesn't have a FileEntry. Don't skip these as well.
446 if (!File) {
447 LastErrorRelatesToUserCode = true;
448 LastErrorPassesLineFilter = true;
449 return;
450 }
451
452 StringRef FileName(File->getName());
453 LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
454 Sources.isInMainFile(Location) ||
455 getHeaderFilter()->match(FileName);
456
457 unsigned LineNumber = Sources.getExpansionLineNumber(Location);
458 LastErrorPassesLineFilter =
459 LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
460}
461
462llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() {
463 if (!HeaderFilter)
464 HeaderFilter.reset(
465 new llvm::Regex(*Context.getOptions().HeaderFilterRegex));
466 return HeaderFilter.get();
467}
468
469void ClangTidyDiagnosticConsumer::removeIncompatibleErrors(
470 SmallVectorImpl<ClangTidyError> &Errors) const {
471 // Each error is modelled as the set of intervals in which it applies
472 // replacements. To detect overlapping replacements, we use a sweep line
473 // algorithm over these sets of intervals.
474 // An event here consists of the opening or closing of an interval. During the
475 // process, we maintain a counter with the amount of open intervals. If we
476 // find an endpoint of an interval and this counter is different from 0, it
477 // means that this interval overlaps with another one, so we set it as
478 // inapplicable.
479 struct Event {
480 // An event can be either the begin or the end of an interval.
481 enum EventType {
482 ET_Begin = 1,
483 ET_End = -1,
484 };
485
486 Event(unsigned Begin, unsigned End, EventType Type, unsigned ErrorId,
487 unsigned ErrorSize)
488 : Type(Type), ErrorId(ErrorId) {
489 // The events are going to be sorted by their position. In case of draw:
490 //
491 // * If an interval ends at the same position at which other interval
492 // begins, this is not an overlapping, so we want to remove the ending
493 // interval before adding the starting one: end events have higher
494 // priority than begin events.
495 //
496 // * If we have several begin points at the same position, we will mark as
497 // inapplicable the ones that we process later, so the first one has to
498 // be the one with the latest end point, because this one will contain
499 // all the other intervals. For the same reason, if we have several end
500 // points in the same position, the last one has to be the one with the
501 // earliest begin point. In both cases, we sort non-increasingly by the
502 // position of the complementary.
503 //
504 // * In case of two equal intervals, the one whose error is bigger can
505 // potentially contain the other one, so we want to process its begin
506 // points before and its end points later.
507 //
508 // * Finally, if we have two equal intervals whose errors have the same
509 // size, none of them will be strictly contained inside the other.
510 // Sorting by ErrorId will guarantee that the begin point of the first
511 // one will be processed before, disallowing the second one, and the
512 // end point of the first one will also be processed before,
513 // disallowing the first one.
514 if (Type == ET_Begin)
515 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
516 else
517 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
518 }
519
520 bool operator<(const Event &Other) const {
521 return Priority < Other.Priority;
522 }
523
524 // Determines if this event is the begin or the end of an interval.
525 EventType Type;
526 // The index of the error to which the interval that generated this event
527 // belongs.
528 unsigned ErrorId;
529 // The events will be sorted based on this field.
530 std::tuple<unsigned, EventType, int, int, unsigned> Priority;
531 };
532
533 // Compute error sizes.
534 std::vector<int> Sizes;
535 for (const auto &Error : Errors) {
536 int Size = 0;
537 for (const auto &FileAndReplaces : Error.Fix) {
538 for (const auto &Replace : FileAndReplaces.second)
539 Size += Replace.getLength();
540 }
541 Sizes.push_back(Size);
542 }
543
544 // Build events from error intervals.
545 std::map<std::string, std::vector<Event>> FileEvents;
546 for (unsigned I = 0; I < Errors.size(); ++I) {
547 for (const auto &FileAndReplace : Errors[I].Fix) {
548 for (const auto &Replace : FileAndReplace.second) {
549 unsigned Begin = Replace.getOffset();
550 unsigned End = Begin + Replace.getLength();
551 const std::string &FilePath = Replace.getFilePath();
552 // FIXME: Handle empty intervals, such as those from insertions.
553 if (Begin == End)
554 continue;
555 auto &Events = FileEvents[FilePath];
556 Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
557 Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
558 }
559 }
560 }
561
562 std::vector<bool> Apply(Errors.size(), true);
563 for (auto &FileAndEvents : FileEvents) {
564 std::vector<Event> &Events = FileAndEvents.second;
565 // Sweep.
566 std::sort(Events.begin(), Events.end());
567 int OpenIntervals = 0;
568 for (const auto &Event : Events) {
569 if (Event.Type == Event::ET_End)
570 --OpenIntervals;
571 // This has to be checked after removing the interval from the count if it
572 // is an end event, or before adding it if it is a begin event.
573 if (OpenIntervals != 0)
574 Apply[Event.ErrorId] = false;
575 if (Event.Type == Event::ET_Begin)
576 ++OpenIntervals;
577 }
578 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
579 }
580
581 for (unsigned I = 0; I < Errors.size(); ++I) {
582 if (!Apply[I]) {
583 Errors[I].Fix.clear();
584 Errors[I].Notes.emplace_back(
585 "this fix will not be applied because it overlaps with another fix");
586 }
587 }
588}
589
590namespace {
591struct LessClangTidyError {
592 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
593 const tooling::DiagnosticMessage &M1 = LHS.Message;
594 const tooling::DiagnosticMessage &M2 = RHS.Message;
595
596 return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
597 std::tie(M2.FilePath, M2.FileOffset, M2.Message);
598 }
599};
600struct EqualClangTidyError {
601 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
602 LessClangTidyError Less;
603 return !Less(LHS, RHS) && !Less(RHS, LHS);
604 }
605};
606} // end anonymous namespace
607
608// Flushes the internal diagnostics buffer to the ClangTidyContext.
609void ClangTidyDiagnosticConsumer::finish() {
610 finalizeLastError();
611
612 std::sort(Errors.begin(), Errors.end(), LessClangTidyError());
613 Errors.erase(std::unique(Errors.begin(), Errors.end(), EqualClangTidyError()),
614 Errors.end());
Alexander Kornienko9660d4d2017-05-09 15:10:26 +0000615
616 if (RemoveIncompatibleErrors)
617 removeIncompatibleErrors(Errors);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000618
619 for (const ClangTidyError &Error : Errors)
620 Context.storeError(Error);
621 Errors.clear();
622}