blob: 3a3aa01dac1f9d8759149b0de4be4f97e62fddce [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
Alexander Kornienko61803372017-05-18 01:13:51 +0000161class ClangTidyContext::CachedGlobList {
162public:
163 CachedGlobList(StringRef Globs) : Globs(Globs) {}
164
165 bool contains(StringRef S) {
166 switch (auto &Result = Cache[S]) {
167 case Yes: return true;
168 case No: return false;
169 case None:
170 Result = Globs.contains(S) ? Yes : No;
171 return Result == Yes;
172 }
173 }
174
175private:
176 GlobList Globs;
177 enum Tristate { None, Yes, No };
178 llvm::StringMap<Tristate> Cache;
179};
180
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000181ClangTidyContext::ClangTidyContext(
182 std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider)
183 : DiagEngine(nullptr), OptionsProvider(std::move(OptionsProvider)),
184 Profile(nullptr) {
185 // Before the first translation unit we can get errors related to command-line
186 // parsing, use empty string for the file name in this case.
187 setCurrentFile("");
188}
189
Alexander Kornienko61803372017-05-18 01:13:51 +0000190ClangTidyContext::~ClangTidyContext() = default;
191
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000192DiagnosticBuilder ClangTidyContext::diag(
193 StringRef CheckName, SourceLocation Loc, StringRef Description,
194 DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
195 assert(Loc.isValid());
196 unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
197 Level, (Description + " [" + CheckName + "]").str());
198 CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
199 return DiagEngine->Report(Loc, ID);
200}
201
202void ClangTidyContext::setDiagnosticsEngine(DiagnosticsEngine *Engine) {
203 DiagEngine = Engine;
204}
205
206void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
207 DiagEngine->setSourceManager(SourceMgr);
208}
209
210void ClangTidyContext::setCurrentFile(StringRef File) {
211 CurrentFile = File;
212 CurrentOptions = getOptionsForFile(CurrentFile);
Alexander Kornienko61803372017-05-18 01:13:51 +0000213 CheckFilter = llvm::make_unique<CachedGlobList>(*getOptions().Checks);
214 WarningAsErrorFilter =
215 llvm::make_unique<CachedGlobList>(*getOptions().WarningsAsErrors);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000216}
217
218void ClangTidyContext::setASTContext(ASTContext *Context) {
219 DiagEngine->SetArgToStringFn(&FormatASTNodeDiagnosticArgument, Context);
220 LangOpts = Context->getLangOpts();
221}
222
223const ClangTidyGlobalOptions &ClangTidyContext::getGlobalOptions() const {
224 return OptionsProvider->getGlobalOptions();
225}
226
227const ClangTidyOptions &ClangTidyContext::getOptions() const {
228 return CurrentOptions;
229}
230
231ClangTidyOptions ClangTidyContext::getOptionsForFile(StringRef File) const {
232 // Merge options on top of getDefaults() as a safeguard against options with
233 // unset values.
234 return ClangTidyOptions::getDefaults().mergeWith(
235 OptionsProvider->getOptions(File));
236}
237
238void ClangTidyContext::setCheckProfileData(ProfileData *P) { Profile = P; }
239
Alexander Kornienko21375182017-05-17 14:39:47 +0000240bool ClangTidyContext::isCheckEnabled(StringRef CheckName) const {
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000241 assert(CheckFilter != nullptr);
Alexander Kornienko21375182017-05-17 14:39:47 +0000242 return CheckFilter->contains(CheckName);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000243}
244
Alexander Kornienko21375182017-05-17 14:39:47 +0000245bool ClangTidyContext::treatAsError(StringRef CheckName) const {
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000246 assert(WarningAsErrorFilter != nullptr);
Alexander Kornienko21375182017-05-17 14:39:47 +0000247 return WarningAsErrorFilter->contains(CheckName);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000248}
249
250/// \brief Store a \c ClangTidyError.
251void ClangTidyContext::storeError(const ClangTidyError &Error) {
252 Errors.push_back(Error);
253}
254
255StringRef ClangTidyContext::getCheckName(unsigned DiagnosticID) const {
256 llvm::DenseMap<unsigned, std::string>::const_iterator I =
257 CheckNamesByDiagnosticID.find(DiagnosticID);
258 if (I != CheckNamesByDiagnosticID.end())
259 return I->second;
260 return "";
261}
262
Alexander Kornienko9660d4d2017-05-09 15:10:26 +0000263ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
264 ClangTidyContext &Ctx, bool RemoveIncompatibleErrors)
265 : Context(Ctx), RemoveIncompatibleErrors(RemoveIncompatibleErrors),
266 LastErrorRelatesToUserCode(false), LastErrorPassesLineFilter(false),
267 LastErrorWasIgnored(false) {
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000268 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko61803372017-05-18 01:13:51 +0000269 Diags = llvm::make_unique<DiagnosticsEngine>(
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000270 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts, this,
Alexander Kornienko61803372017-05-18 01:13:51 +0000271 /*ShouldOwnClient=*/false);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000272 Context.setDiagnosticsEngine(Diags.get());
273}
274
275void ClangTidyDiagnosticConsumer::finalizeLastError() {
276 if (!Errors.empty()) {
277 ClangTidyError &Error = Errors.back();
Alexander Kornienko21375182017-05-17 14:39:47 +0000278 if (!Context.isCheckEnabled(Error.DiagnosticName) &&
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000279 Error.DiagLevel != ClangTidyError::Error) {
280 ++Context.Stats.ErrorsIgnoredCheckFilter;
281 Errors.pop_back();
282 } else if (!LastErrorRelatesToUserCode) {
283 ++Context.Stats.ErrorsIgnoredNonUserCode;
284 Errors.pop_back();
285 } else if (!LastErrorPassesLineFilter) {
286 ++Context.Stats.ErrorsIgnoredLineFilter;
287 Errors.pop_back();
288 } else {
289 ++Context.Stats.ErrorsDisplayed;
290 }
291 }
292 LastErrorRelatesToUserCode = false;
293 LastErrorPassesLineFilter = false;
294}
295
296static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
297 bool Invalid;
298 const char *CharacterData = SM.getCharacterData(Loc, &Invalid);
299 if (Invalid)
300 return false;
301
302 // Check if there's a NOLINT on this line.
303 const char *P = CharacterData;
304 while (*P != '\0' && *P != '\r' && *P != '\n')
305 ++P;
306 StringRef RestOfLine(CharacterData, P - CharacterData + 1);
307 // FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
308 if (RestOfLine.find("NOLINT") != StringRef::npos)
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 (RestOfLine.find("NOLINTNEXTLINE") != StringRef::npos)
336 return true;
337
338 return false;
339}
340
341static bool LineIsMarkedWithNOLINTinMacro(SourceManager &SM,
342 SourceLocation Loc) {
343 while (true) {
344 if (LineIsMarkedWithNOLINT(SM, Loc))
345 return true;
346 if (!Loc.isMacroID())
347 return false;
348 Loc = SM.getImmediateExpansionRange(Loc).first;
349 }
350 return false;
351}
352
353void ClangTidyDiagnosticConsumer::HandleDiagnostic(
354 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
355 if (LastErrorWasIgnored && DiagLevel == DiagnosticsEngine::Note)
356 return;
357
358 if (Info.getLocation().isValid() && DiagLevel != DiagnosticsEngine::Error &&
359 DiagLevel != DiagnosticsEngine::Fatal &&
360 LineIsMarkedWithNOLINTinMacro(Diags->getSourceManager(),
361 Info.getLocation())) {
362 ++Context.Stats.ErrorsIgnoredNOLINT;
363 // Ignored a warning, should ignore related notes as well
364 LastErrorWasIgnored = true;
365 return;
366 }
367
368 LastErrorWasIgnored = false;
369 // Count warnings/errors.
370 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
371
372 if (DiagLevel == DiagnosticsEngine::Note) {
373 assert(!Errors.empty() &&
374 "A diagnostic note can only be appended to a message.");
375 } else {
376 finalizeLastError();
377 StringRef WarningOption =
378 Context.DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(
379 Info.getID());
380 std::string CheckName = !WarningOption.empty()
381 ? ("clang-diagnostic-" + WarningOption).str()
382 : Context.getCheckName(Info.getID()).str();
383
384 if (CheckName.empty()) {
385 // This is a compiler diagnostic without a warning option. Assign check
386 // name based on its level.
387 switch (DiagLevel) {
388 case DiagnosticsEngine::Error:
389 case DiagnosticsEngine::Fatal:
390 CheckName = "clang-diagnostic-error";
391 break;
392 case DiagnosticsEngine::Warning:
393 CheckName = "clang-diagnostic-warning";
394 break;
395 default:
396 CheckName = "clang-diagnostic-unknown";
397 break;
398 }
399 }
400
401 ClangTidyError::Level Level = ClangTidyError::Warning;
402 if (DiagLevel == DiagnosticsEngine::Error ||
403 DiagLevel == DiagnosticsEngine::Fatal) {
404 // Force reporting of Clang errors regardless of filters and non-user
405 // code.
406 Level = ClangTidyError::Error;
407 LastErrorRelatesToUserCode = true;
408 LastErrorPassesLineFilter = true;
409 }
Alexander Kornienko21375182017-05-17 14:39:47 +0000410 bool IsWarningAsError = DiagLevel == DiagnosticsEngine::Warning &&
411 Context.treatAsError(CheckName);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000412 Errors.emplace_back(CheckName, Level, Context.getCurrentBuildDirectory(),
413 IsWarningAsError);
414 }
415
416 ClangTidyDiagnosticRenderer Converter(
417 Context.getLangOpts(), &Context.DiagEngine->getDiagnosticOptions(),
418 Errors.back());
419 SmallString<100> Message;
420 Info.FormatDiagnostic(Message);
421 SourceManager *Sources = nullptr;
422 if (Info.hasSourceManager())
423 Sources = &Info.getSourceManager();
424 Converter.emitDiagnostic(Info.getLocation(), DiagLevel, Message,
425 Info.getRanges(), Info.getFixItHints(), Sources);
426
427 checkFilters(Info.getLocation());
428}
429
430bool ClangTidyDiagnosticConsumer::passesLineFilter(StringRef FileName,
431 unsigned LineNumber) const {
432 if (Context.getGlobalOptions().LineFilter.empty())
433 return true;
434 for (const FileFilter &Filter : Context.getGlobalOptions().LineFilter) {
435 if (FileName.endswith(Filter.Name)) {
436 if (Filter.LineRanges.empty())
437 return true;
438 for (const FileFilter::LineRange &Range : Filter.LineRanges) {
439 if (Range.first <= LineNumber && LineNumber <= Range.second)
440 return true;
441 }
442 return false;
443 }
444 }
445 return false;
446}
447
448void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location) {
449 // Invalid location may mean a diagnostic in a command line, don't skip these.
450 if (!Location.isValid()) {
451 LastErrorRelatesToUserCode = true;
452 LastErrorPassesLineFilter = true;
453 return;
454 }
455
456 const SourceManager &Sources = Diags->getSourceManager();
457 if (!*Context.getOptions().SystemHeaders &&
458 Sources.isInSystemHeader(Location))
459 return;
460
461 // FIXME: We start with a conservative approach here, but the actual type of
462 // location needed depends on the check (in particular, where this check wants
463 // to apply fixes).
464 FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
465 const FileEntry *File = Sources.getFileEntryForID(FID);
466
467 // -DMACRO definitions on the command line have locations in a virtual buffer
468 // that doesn't have a FileEntry. Don't skip these as well.
469 if (!File) {
470 LastErrorRelatesToUserCode = true;
471 LastErrorPassesLineFilter = true;
472 return;
473 }
474
475 StringRef FileName(File->getName());
476 LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
477 Sources.isInMainFile(Location) ||
478 getHeaderFilter()->match(FileName);
479
480 unsigned LineNumber = Sources.getExpansionLineNumber(Location);
481 LastErrorPassesLineFilter =
482 LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
483}
484
485llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() {
486 if (!HeaderFilter)
Alexander Kornienko61803372017-05-18 01:13:51 +0000487 HeaderFilter =
488 llvm::make_unique<llvm::Regex>(*Context.getOptions().HeaderFilterRegex);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000489 return HeaderFilter.get();
490}
491
492void ClangTidyDiagnosticConsumer::removeIncompatibleErrors(
493 SmallVectorImpl<ClangTidyError> &Errors) const {
494 // Each error is modelled as the set of intervals in which it applies
495 // replacements. To detect overlapping replacements, we use a sweep line
496 // algorithm over these sets of intervals.
497 // An event here consists of the opening or closing of an interval. During the
498 // process, we maintain a counter with the amount of open intervals. If we
499 // find an endpoint of an interval and this counter is different from 0, it
500 // means that this interval overlaps with another one, so we set it as
501 // inapplicable.
502 struct Event {
503 // An event can be either the begin or the end of an interval.
504 enum EventType {
505 ET_Begin = 1,
506 ET_End = -1,
507 };
508
509 Event(unsigned Begin, unsigned End, EventType Type, unsigned ErrorId,
510 unsigned ErrorSize)
511 : Type(Type), ErrorId(ErrorId) {
512 // The events are going to be sorted by their position. In case of draw:
513 //
514 // * If an interval ends at the same position at which other interval
515 // begins, this is not an overlapping, so we want to remove the ending
516 // interval before adding the starting one: end events have higher
517 // priority than begin events.
518 //
519 // * If we have several begin points at the same position, we will mark as
520 // inapplicable the ones that we process later, so the first one has to
521 // be the one with the latest end point, because this one will contain
522 // all the other intervals. For the same reason, if we have several end
523 // points in the same position, the last one has to be the one with the
524 // earliest begin point. In both cases, we sort non-increasingly by the
525 // position of the complementary.
526 //
527 // * In case of two equal intervals, the one whose error is bigger can
528 // potentially contain the other one, so we want to process its begin
529 // points before and its end points later.
530 //
531 // * Finally, if we have two equal intervals whose errors have the same
532 // size, none of them will be strictly contained inside the other.
533 // Sorting by ErrorId will guarantee that the begin point of the first
534 // one will be processed before, disallowing the second one, and the
535 // end point of the first one will also be processed before,
536 // disallowing the first one.
537 if (Type == ET_Begin)
538 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
539 else
540 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
541 }
542
543 bool operator<(const Event &Other) const {
544 return Priority < Other.Priority;
545 }
546
547 // Determines if this event is the begin or the end of an interval.
548 EventType Type;
549 // The index of the error to which the interval that generated this event
550 // belongs.
551 unsigned ErrorId;
552 // The events will be sorted based on this field.
553 std::tuple<unsigned, EventType, int, int, unsigned> Priority;
554 };
555
556 // Compute error sizes.
557 std::vector<int> Sizes;
558 for (const auto &Error : Errors) {
559 int Size = 0;
560 for (const auto &FileAndReplaces : Error.Fix) {
561 for (const auto &Replace : FileAndReplaces.second)
562 Size += Replace.getLength();
563 }
564 Sizes.push_back(Size);
565 }
566
567 // Build events from error intervals.
568 std::map<std::string, std::vector<Event>> FileEvents;
569 for (unsigned I = 0; I < Errors.size(); ++I) {
570 for (const auto &FileAndReplace : Errors[I].Fix) {
571 for (const auto &Replace : FileAndReplace.second) {
572 unsigned Begin = Replace.getOffset();
573 unsigned End = Begin + Replace.getLength();
574 const std::string &FilePath = Replace.getFilePath();
575 // FIXME: Handle empty intervals, such as those from insertions.
576 if (Begin == End)
577 continue;
578 auto &Events = FileEvents[FilePath];
579 Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
580 Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
581 }
582 }
583 }
584
585 std::vector<bool> Apply(Errors.size(), true);
586 for (auto &FileAndEvents : FileEvents) {
587 std::vector<Event> &Events = FileAndEvents.second;
588 // Sweep.
589 std::sort(Events.begin(), Events.end());
590 int OpenIntervals = 0;
591 for (const auto &Event : Events) {
592 if (Event.Type == Event::ET_End)
593 --OpenIntervals;
594 // This has to be checked after removing the interval from the count if it
595 // is an end event, or before adding it if it is a begin event.
596 if (OpenIntervals != 0)
597 Apply[Event.ErrorId] = false;
598 if (Event.Type == Event::ET_Begin)
599 ++OpenIntervals;
600 }
601 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
602 }
603
604 for (unsigned I = 0; I < Errors.size(); ++I) {
605 if (!Apply[I]) {
606 Errors[I].Fix.clear();
607 Errors[I].Notes.emplace_back(
608 "this fix will not be applied because it overlaps with another fix");
609 }
610 }
611}
612
613namespace {
614struct LessClangTidyError {
615 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
616 const tooling::DiagnosticMessage &M1 = LHS.Message;
617 const tooling::DiagnosticMessage &M2 = RHS.Message;
618
619 return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
620 std::tie(M2.FilePath, M2.FileOffset, M2.Message);
621 }
622};
623struct EqualClangTidyError {
624 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
625 LessClangTidyError Less;
626 return !Less(LHS, RHS) && !Less(RHS, LHS);
627 }
628};
629} // end anonymous namespace
630
631// Flushes the internal diagnostics buffer to the ClangTidyContext.
632void ClangTidyDiagnosticConsumer::finish() {
633 finalizeLastError();
634
635 std::sort(Errors.begin(), Errors.end(), LessClangTidyError());
636 Errors.erase(std::unique(Errors.begin(), Errors.end(), EqualClangTidyError()),
637 Errors.end());
Alexander Kornienko9660d4d2017-05-09 15:10:26 +0000638
639 if (RemoveIncompatibleErrors)
640 removeIncompatibleErrors(Errors);
Alexander Kornienkod0488d42017-05-09 14:56:28 +0000641
642 for (const ClangTidyError &Error : Errors)
643 Context.storeError(Error);
644 Errors.clear();
645}