Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp

raw
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
18 #include "ClangTidyDiagnosticConsumer.h"
19 #include "ClangTidyOptions.h"
20 #include "GlobList.h"
21 #include "NoLintDirectiveHandler.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/ASTDiagnostic.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/Basic/Diagnostic.h"
26 #include "clang/Basic/DiagnosticOptions.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Frontend/DiagnosticRenderer.h"
30 #include "clang/Lex/Lexer.h"
31 #include "clang/Tooling/Core/Diagnostic.h"
32 #include "clang/Tooling/Core/Replacement.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringMap.h"
37 #include "llvm/Support/FormatVariadic.h"
38 #include "llvm/Support/Regex.h"
39 #include <optional>
40 #include <tuple>
41 #include <utility>
42 #include <vector>
43 using namespace clang;
44 using namespace tidy;
45
46 namespace {
47 class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
48 public:
49 ClangTidyDiagnosticRenderer(const LangOptions &LangOpts,
50 DiagnosticOptions *DiagOpts,
51 ClangTidyError &Error)
52 : DiagnosticRenderer(LangOpts, DiagOpts), Error(Error) {}
53
54 protected:
55 void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc,
56 DiagnosticsEngine::Level Level, StringRef Message,
57 ArrayRef<CharSourceRange> Ranges,
58 DiagOrStoredDiag Info) override {
59 // Remove check name from the message.
60 // FIXME: Remove this once there's a better way to pass check names than
61 // appending the check name to the message in ClangTidyContext::diag and
62 // using getCustomDiagID.
63 std::string CheckNameInMessage = " [" + Error.DiagnosticName + "]";
64 if (Message.endswith(CheckNameInMessage))
65 Message = Message.substr(0, Message.size() - CheckNameInMessage.size());
66
67 auto TidyMessage =
68 Loc.isValid()
69 ? tooling::DiagnosticMessage(Message, Loc.getManager(), Loc)
70 : tooling::DiagnosticMessage(Message);
71
72 // Make sure that if a TokenRange is received from the check it is unfurled
73 // into a real CharRange for the diagnostic printer later.
74 // Whatever we store here gets decoupled from the current SourceManager, so
75 // we **have to** know the exact position and length of the highlight.
76 auto ToCharRange = [this, &Loc](const CharSourceRange &SourceRange) {
77 if (SourceRange.isCharRange())
78 return SourceRange;
79 assert(SourceRange.isTokenRange());
80 SourceLocation End = Lexer::getLocForEndOfToken(
81 SourceRange.getEnd(), 0, Loc.getManager(), LangOpts);
82 return CharSourceRange::getCharRange(SourceRange.getBegin(), End);
83 };
84
85 // We are only interested in valid ranges.
86 auto ValidRanges =
87 llvm::make_filter_range(Ranges, [](const CharSourceRange &R) {
88 return R.getAsRange().isValid();
89 });
90
91 if (Level == DiagnosticsEngine::Note) {
92 Error.Notes.push_back(TidyMessage);
93 for (const CharSourceRange &SourceRange : ValidRanges)
94 Error.Notes.back().Ranges.emplace_back(Loc.getManager(),
95 ToCharRange(SourceRange));
96 return;
97 }
98 assert(Error.Message.Message.empty() && "Overwriting a diagnostic message");
99 Error.Message = TidyMessage;
100 for (const CharSourceRange &SourceRange : ValidRanges)
101 Error.Message.Ranges.emplace_back(Loc.getManager(),
102 ToCharRange(SourceRange));
103 }
104
105 void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
106 DiagnosticsEngine::Level Level,
107 ArrayRef<CharSourceRange> Ranges) override {}
108
109 void emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level,
110 SmallVectorImpl<CharSourceRange> &Ranges,
111 ArrayRef<FixItHint> Hints) override {
112 assert(Loc.isValid());
113 tooling::DiagnosticMessage *DiagWithFix =
114 Level == DiagnosticsEngine::Note ? &Error.Notes.back() : &Error.Message;
115
116 for (const auto &FixIt : Hints) {
117 CharSourceRange Range = FixIt.RemoveRange;
118 assert(Range.getBegin().isValid() && Range.getEnd().isValid() &&
119 "Invalid range in the fix-it hint.");
120 assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
121 "Only file locations supported in fix-it hints.");
122
123 tooling::Replacement Replacement(Loc.getManager(), Range,
124 FixIt.CodeToInsert);
125 llvm::Error Err =
126 DiagWithFix->Fix[Replacement.getFilePath()].add(Replacement);
127 // FIXME: better error handling (at least, don't let other replacements be
128 // applied).
129 if (Err) {
130 llvm::errs() << "Fix conflicts with existing fix! "
131 << llvm::toString(std::move(Err)) << "\n";
132 assert(false && "Fix conflicts with existing fix!");
133 }
134 }
135 }
136
137 void emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) override {}
138
139 void emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
140 StringRef ModuleName) override {}
141
142 void emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc,
143 StringRef ModuleName) override {}
144
145 void endDiagnostic(DiagOrStoredDiag D,
146 DiagnosticsEngine::Level Level) override {
147 assert(!Error.Message.Message.empty() && "Message has not been set");
148 }
149
150 private:
151 ClangTidyError &Error;
152 };
153 } // end anonymous namespace
154
155 ClangTidyError::ClangTidyError(StringRef CheckName,
156 ClangTidyError::Level DiagLevel,
157 StringRef BuildDirectory, bool IsWarningAsError)
158 : tooling::Diagnostic(CheckName, DiagLevel, BuildDirectory),
159 IsWarningAsError(IsWarningAsError) {}
160
161 ClangTidyContext::ClangTidyContext(
162 std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider,
163 bool AllowEnablingAnalyzerAlphaCheckers)
164 : DiagEngine(nullptr), OptionsProvider(std::move(OptionsProvider)),
165 Profile(false),
166 AllowEnablingAnalyzerAlphaCheckers(AllowEnablingAnalyzerAlphaCheckers),
167 SelfContainedDiags(false) {
168 // Before the first translation unit we can get errors related to command-line
169 // parsing, use empty string for the file name in this case.
170 setCurrentFile("");
171 }
172
173 ClangTidyContext::~ClangTidyContext() = default;
174
175 DiagnosticBuilder ClangTidyContext::diag(
176 StringRef CheckName, SourceLocation Loc, StringRef Description,
177 DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
178 assert(Loc.isValid());
179 unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
180 Level, (Description + " [" + CheckName + "]").str());
181 CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
182 return DiagEngine->Report(Loc, ID);
183 }
184
185 DiagnosticBuilder ClangTidyContext::diag(
186 StringRef CheckName, StringRef Description,
187 DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
188 unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
189 Level, (Description + " [" + CheckName + "]").str());
190 CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
191 return DiagEngine->Report(ID);
192 }
193
194 DiagnosticBuilder ClangTidyContext::diag(const tooling::Diagnostic &Error) {
195 SourceManager &SM = DiagEngine->getSourceManager();
196 llvm::ErrorOr<const FileEntry *> File =
197 SM.getFileManager().getFile(Error.Message.FilePath);
198 FileID ID = SM.getOrCreateFileID(*File, SrcMgr::C_User);
199 SourceLocation FileStartLoc = SM.getLocForStartOfFile(ID);
200 SourceLocation Loc = FileStartLoc.getLocWithOffset(
201 static_cast<SourceLocation::IntTy>(Error.Message.FileOffset));
202 return diag(Error.DiagnosticName, Loc, Error.Message.Message,
203 static_cast<DiagnosticIDs::Level>(Error.DiagLevel));
204 }
205
206 DiagnosticBuilder ClangTidyContext::configurationDiag(
207 StringRef Message,
208 DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
209 return diag("clang-tidy-config", Message, Level);
210 }
211
212 bool ClangTidyContext::shouldSuppressDiagnostic(
213 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info,
214 SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, bool AllowIO,
215 bool EnableNoLintBlocks) {
216 std::string CheckName = getCheckName(Info.getID());
217 return NoLintHandler.shouldSuppress(DiagLevel, Info, CheckName, NoLintErrors,
218 AllowIO, EnableNoLintBlocks);
219 }
220
221 void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) {
222 DiagEngine->setSourceManager(SourceMgr);
223 }
224
225 void ClangTidyContext::setCurrentFile(StringRef File) {
226 CurrentFile = std::string(File);
227 CurrentOptions = getOptionsForFile(CurrentFile);
228 CheckFilter = std::make_unique<CachedGlobList>(*getOptions().Checks);
229 WarningAsErrorFilter =
230 std::make_unique<CachedGlobList>(*getOptions().WarningsAsErrors);
231 }
232
233 void ClangTidyContext::setASTContext(ASTContext *Context) {
234 DiagEngine->SetArgToStringFn(&FormatASTNodeDiagnosticArgument, Context);
235 LangOpts = Context->getLangOpts();
236 }
237
238 const ClangTidyGlobalOptions &ClangTidyContext::getGlobalOptions() const {
239 return OptionsProvider->getGlobalOptions();
240 }
241
242 const ClangTidyOptions &ClangTidyContext::getOptions() const {
243 return CurrentOptions;
244 }
245
246 ClangTidyOptions ClangTidyContext::getOptionsForFile(StringRef File) const {
247 // Merge options on top of getDefaults() as a safeguard against options with
248 // unset values.
249 return ClangTidyOptions::getDefaults().merge(
250 OptionsProvider->getOptions(File), 0);
251 }
252
253 void ClangTidyContext::setEnableProfiling(bool P) { Profile = P; }
254
255 void ClangTidyContext::setProfileStoragePrefix(StringRef Prefix) {
256 ProfilePrefix = std::string(Prefix);
257 }
258
259 std::optional<ClangTidyProfiling::StorageParams>
260 ClangTidyContext::getProfileStorageParams() const {
261 if (ProfilePrefix.empty())
262 return std::nullopt;
263
264 return ClangTidyProfiling::StorageParams(ProfilePrefix, CurrentFile);
265 }
266
267 bool ClangTidyContext::isCheckEnabled(StringRef CheckName) const {
268 assert(CheckFilter != nullptr);
269 return CheckFilter->contains(CheckName);
270 }
271
272 bool ClangTidyContext::treatAsError(StringRef CheckName) const {
273 assert(WarningAsErrorFilter != nullptr);
274 return WarningAsErrorFilter->contains(CheckName);
275 }
276
277 std::string ClangTidyContext::getCheckName(unsigned DiagnosticID) const {
278 std::string ClangWarningOption = std::string(
279 DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(DiagnosticID));
280 if (!ClangWarningOption.empty())
281 return "clang-diagnostic-" + ClangWarningOption;
282 llvm::DenseMap<unsigned, std::string>::const_iterator I =
283 CheckNamesByDiagnosticID.find(DiagnosticID);
284 if (I != CheckNamesByDiagnosticID.end())
285 return I->second;
286 return "";
287 }
288
289 ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
290 ClangTidyContext &Ctx, DiagnosticsEngine *ExternalDiagEngine,
291 bool RemoveIncompatibleErrors, bool GetFixesFromNotes,
292 bool EnableNolintBlocks)
293 : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine),
294 RemoveIncompatibleErrors(RemoveIncompatibleErrors),
295 GetFixesFromNotes(GetFixesFromNotes),
296 EnableNolintBlocks(EnableNolintBlocks), LastErrorRelatesToUserCode(false),
297 LastErrorPassesLineFilter(false), LastErrorWasIgnored(false) {}
298
299 void ClangTidyDiagnosticConsumer::finalizeLastError() {
300 if (!Errors.empty()) {
301 ClangTidyError &Error = Errors.back();
302 if (Error.DiagnosticName == "clang-tidy-config") {
303 // Never ignore these.
304 } else if (!Context.isCheckEnabled(Error.DiagnosticName) &&
305 Error.DiagLevel != ClangTidyError::Error) {
306 ++Context.Stats.ErrorsIgnoredCheckFilter;
307 Errors.pop_back();
308 } else if (!LastErrorRelatesToUserCode) {
309 ++Context.Stats.ErrorsIgnoredNonUserCode;
310 Errors.pop_back();
311 } else if (!LastErrorPassesLineFilter) {
312 ++Context.Stats.ErrorsIgnoredLineFilter;
313 Errors.pop_back();
314 } else {
315 ++Context.Stats.ErrorsDisplayed;
316 }
317 }
318 LastErrorRelatesToUserCode = false;
319 LastErrorPassesLineFilter = false;
320 }
321
322 namespace clang::tidy {
323
324 const llvm::StringMap<tooling::Replacements> *
325 getFixIt(const tooling::Diagnostic &Diagnostic, bool GetFixFromNotes) {
326 if (!Diagnostic.Message.Fix.empty())
327 return &Diagnostic.Message.Fix;
328 if (!GetFixFromNotes)
329 return nullptr;
330 const llvm::StringMap<tooling::Replacements> *Result = nullptr;
331 for (const auto &Note : Diagnostic.Notes) {
332 if (!Note.Fix.empty()) {
333 if (Result)
334 // We have 2 different fixes in notes, bail out.
335 return nullptr;
336 Result = &Note.Fix;
337 }
338 }
339 return Result;
340 }
341
342 } // namespace clang::tidy
343
344 void ClangTidyDiagnosticConsumer::HandleDiagnostic(
345 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
346 if (LastErrorWasIgnored && DiagLevel == DiagnosticsEngine::Note)
347 return;
348
349 SmallVector<tooling::Diagnostic, 1> SuppressionErrors;
350 if (Context.shouldSuppressDiagnostic(DiagLevel, Info, SuppressionErrors,
351 EnableNolintBlocks)) {
352 ++Context.Stats.ErrorsIgnoredNOLINT;
353 // Ignored a warning, should ignore related notes as well
354 LastErrorWasIgnored = true;
355 Context.DiagEngine->Clear();
356 for (const auto &Error : SuppressionErrors)
357 Context.diag(Error);
358 return;
359 }
360
361 LastErrorWasIgnored = false;
362 // Count warnings/errors.
363 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
364
365 if (DiagLevel == DiagnosticsEngine::Note) {
366 assert(!Errors.empty() &&
367 "A diagnostic note can only be appended to a message.");
368 } else {
369 finalizeLastError();
370 std::string CheckName = Context.getCheckName(Info.getID());
371 if (CheckName.empty()) {
372 // This is a compiler diagnostic without a warning option. Assign check
373 // name based on its level.
374 switch (DiagLevel) {
375 case DiagnosticsEngine::Error:
376 case DiagnosticsEngine::Fatal:
377 CheckName = "clang-diagnostic-error";
378 break;
379 case DiagnosticsEngine::Warning:
380 CheckName = "clang-diagnostic-warning";
381 break;
382 case DiagnosticsEngine::Remark:
383 CheckName = "clang-diagnostic-remark";
384 break;
385 default:
386 CheckName = "clang-diagnostic-unknown";
387 break;
388 }
389 }
390
391 ClangTidyError::Level Level = ClangTidyError::Warning;
392 if (DiagLevel == DiagnosticsEngine::Error ||
393 DiagLevel == DiagnosticsEngine::Fatal) {
394 // Force reporting of Clang errors regardless of filters and non-user
395 // code.
396 Level = ClangTidyError::Error;
397 LastErrorRelatesToUserCode = true;
398 LastErrorPassesLineFilter = true;
399 } else if (DiagLevel == DiagnosticsEngine::Remark) {
400 Level = ClangTidyError::Remark;
401 }
402
403 bool IsWarningAsError = DiagLevel == DiagnosticsEngine::Warning &&
404 Context.treatAsError(CheckName);
405 if (IsWarningAsError)
406 Level = ClangTidyError::Error;
407 Errors.emplace_back(CheckName, Level, Context.getCurrentBuildDirectory(),
408 IsWarningAsError);
409 }
410
411 if (ExternalDiagEngine) {
412 // If there is an external diagnostics engine, like in the
413 // ClangTidyPluginAction case, forward the diagnostics to it.
414 forwardDiagnostic(Info);
415 } else {
416 ClangTidyDiagnosticRenderer Converter(
417 Context.getLangOpts(), &Context.DiagEngine->getDiagnosticOptions(),
418 Errors.back());
419 SmallString<100> Message;
420 Info.FormatDiagnostic(Message);
421 FullSourceLoc Loc;
422 if (Info.getLocation().isValid() && Info.hasSourceManager())
423 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
424 Converter.emitDiagnostic(Loc, DiagLevel, Message, Info.getRanges(),
425 Info.getFixItHints());
426 }
427
428 if (Info.hasSourceManager())
429 checkFilters(Info.getLocation(), Info.getSourceManager());
430
431 Context.DiagEngine->Clear();
432 for (const auto &Error : SuppressionErrors)
433 Context.diag(Error);
434 }
435
436 bool ClangTidyDiagnosticConsumer::passesLineFilter(StringRef FileName,
437 unsigned LineNumber) const {
438 if (Context.getGlobalOptions().LineFilter.empty())
439 return true;
440 for (const FileFilter &Filter : Context.getGlobalOptions().LineFilter) {
441 if (FileName.endswith(Filter.Name)) {
442 if (Filter.LineRanges.empty())
443 return true;
444 for (const FileFilter::LineRange &Range : Filter.LineRanges) {
445 if (Range.first <= LineNumber && LineNumber <= Range.second)
446 return true;
447 }
448 return false;
449 }
450 }
451 return false;
452 }
453
454 void ClangTidyDiagnosticConsumer::forwardDiagnostic(const Diagnostic &Info) {
455 // Acquire a diagnostic ID also in the external diagnostics engine.
456 auto DiagLevelAndFormatString =
457 Context.getDiagLevelAndFormatString(Info.getID(), Info.getLocation());
458 unsigned ExternalID = ExternalDiagEngine->getDiagnosticIDs()->getCustomDiagID(
459 DiagLevelAndFormatString.first, DiagLevelAndFormatString.second);
460
461 // Forward the details.
462 auto Builder = ExternalDiagEngine->Report(Info.getLocation(), ExternalID);
463 for (auto Hint : Info.getFixItHints())
464 Builder << Hint;
465 for (auto Range : Info.getRanges())
466 Builder << Range;
467 for (unsigned Index = 0; Index < Info.getNumArgs(); ++Index) {
468 DiagnosticsEngine::ArgumentKind Kind = Info.getArgKind(Index);
469 switch (Kind) {
470 case clang::DiagnosticsEngine::ak_std_string:
471 Builder << Info.getArgStdStr(Index);
472 break;
473 case clang::DiagnosticsEngine::ak_c_string:
474 Builder << Info.getArgCStr(Index);
475 break;
476 case clang::DiagnosticsEngine::ak_sint:
477 Builder << Info.getArgSInt(Index);
478 break;
479 case clang::DiagnosticsEngine::ak_uint:
480 Builder << Info.getArgUInt(Index);
481 break;
482 case clang::DiagnosticsEngine::ak_tokenkind:
483 Builder << static_cast<tok::TokenKind>(Info.getRawArg(Index));
484 break;
485 case clang::DiagnosticsEngine::ak_identifierinfo:
486 Builder << Info.getArgIdentifier(Index);
487 break;
488 case clang::DiagnosticsEngine::ak_qual:
489 Builder << Qualifiers::fromOpaqueValue(Info.getRawArg(Index));
490 break;
491 case clang::DiagnosticsEngine::ak_qualtype:
492 Builder << QualType::getFromOpaquePtr((void *)Info.getRawArg(Index));
493 break;
494 case clang::DiagnosticsEngine::ak_declarationname:
495 Builder << DeclarationName::getFromOpaqueInteger(Info.getRawArg(Index));
496 break;
497 case clang::DiagnosticsEngine::ak_nameddecl:
498 Builder << reinterpret_cast<const NamedDecl *>(Info.getRawArg(Index));
499 break;
500 case clang::DiagnosticsEngine::ak_nestednamespec:
501 Builder << reinterpret_cast<NestedNameSpecifier *>(Info.getRawArg(Index));
502 break;
503 case clang::DiagnosticsEngine::ak_declcontext:
504 Builder << reinterpret_cast<DeclContext *>(Info.getRawArg(Index));
505 break;
506 case clang::DiagnosticsEngine::ak_qualtype_pair:
507 assert(false); // This one is not passed around.
508 break;
509 case clang::DiagnosticsEngine::ak_attr:
510 Builder << reinterpret_cast<Attr *>(Info.getRawArg(Index));
511 break;
512 case clang::DiagnosticsEngine::ak_addrspace:
513 Builder << static_cast<LangAS>(Info.getRawArg(Index));
514 break;
515 }
516 }
517 }
518
519 void ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
520 const SourceManager &Sources) {
521 // Invalid location may mean a diagnostic in a command line, don't skip these.
522 if (!Location.isValid()) {
523 LastErrorRelatesToUserCode = true;
524 LastErrorPassesLineFilter = true;
525 return;
526 }
527
528 if (!*Context.getOptions().SystemHeaders &&
529 (Sources.isInSystemHeader(Location) || Sources.isInSystemMacro(Location)))
530 return;
531
532 // FIXME: We start with a conservative approach here, but the actual type of
533 // location needed depends on the check (in particular, where this check wants
534 // to apply fixes).
535 FileID FID = Sources.getDecomposedExpansionLoc(Location).first;
536 const FileEntry *File = Sources.getFileEntryForID(FID);
537
538 // -DMACRO definitions on the command line have locations in a virtual buffer
539 // that doesn't have a FileEntry. Don't skip these as well.
540 if (!File) {
541 LastErrorRelatesToUserCode = true;
542 LastErrorPassesLineFilter = true;
543 return;
544 }
545
546 StringRef FileName(File->getName());
547 LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
548 Sources.isInMainFile(Location) ||
549 getHeaderFilter()->match(FileName);
550
551 unsigned LineNumber = Sources.getExpansionLineNumber(Location);
552 LastErrorPassesLineFilter =
553 LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
554 }
555
556 llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() {
557 if (!HeaderFilter)
558 HeaderFilter =
559 std::make_unique<llvm::Regex>(*Context.getOptions().HeaderFilterRegex);
560 return HeaderFilter.get();
561 }
562
563 void ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
564 // Each error is modelled as the set of intervals in which it applies
565 // replacements. To detect overlapping replacements, we use a sweep line
566 // algorithm over these sets of intervals.
567 // An event here consists of the opening or closing of an interval. During the
568 // process, we maintain a counter with the amount of open intervals. If we
569 // find an endpoint of an interval and this counter is different from 0, it
570 // means that this interval overlaps with another one, so we set it as
571 // inapplicable.
572 struct Event {
573 // An event can be either the begin or the end of an interval.
574 enum EventType {
575 ET_Begin = 1,
576 ET_Insert = 0,
577 ET_End = -1,
578 };
579
580 Event(unsigned Begin, unsigned End, EventType Type, unsigned ErrorId,
581 unsigned ErrorSize)
582 : Type(Type), ErrorId(ErrorId) {
583 // The events are going to be sorted by their position. In case of draw:
584 //
585 // * If an interval ends at the same position at which other interval
586 // begins, this is not an overlapping, so we want to remove the ending
587 // interval before adding the starting one: end events have higher
588 // priority than begin events.
589 //
590 // * If we have several begin points at the same position, we will mark as
591 // inapplicable the ones that we process later, so the first one has to
592 // be the one with the latest end point, because this one will contain
593 // all the other intervals. For the same reason, if we have several end
594 // points in the same position, the last one has to be the one with the
595 // earliest begin point. In both cases, we sort non-increasingly by the
596 // position of the complementary.
597 //
598 // * In case of two equal intervals, the one whose error is bigger can
599 // potentially contain the other one, so we want to process its begin
600 // points before and its end points later.
601 //
602 // * Finally, if we have two equal intervals whose errors have the same
603 // size, none of them will be strictly contained inside the other.
604 // Sorting by ErrorId will guarantee that the begin point of the first
605 // one will be processed before, disallowing the second one, and the
606 // end point of the first one will also be processed before,
607 // disallowing the first one.
608 switch (Type) {
609 case ET_Begin:
610 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
611 break;
612 case ET_Insert:
613 Priority = std::make_tuple(Begin, Type, -End, ErrorSize, ErrorId);
614 break;
615 case ET_End:
616 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
617 break;
618 }
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 removeDuplicatedDiagnosticsOfAliasCheckers();
635
636 // Compute error sizes.
637 std::vector<int> Sizes;
638 std::vector<
639 std::pair<ClangTidyError *, llvm::StringMap<tooling::Replacements> *>>
640 ErrorFixes;
641 for (auto &Error : Errors) {
642 if (const auto *Fix = getFixIt(Error, GetFixesFromNotes))
643 ErrorFixes.emplace_back(
644 &Error, const_cast<llvm::StringMap<tooling::Replacements> *>(Fix));
645 }
646 for (const auto &ErrorAndFix : ErrorFixes) {
647 int Size = 0;
648 for (const auto &FileAndReplaces : *ErrorAndFix.second) {
649 for (const auto &Replace : FileAndReplaces.second)
650 Size += Replace.getLength();
651 }
652 Sizes.push_back(Size);
653 }
654
655 // Build events from error intervals.
656 llvm::StringMap<std::vector<Event>> FileEvents;
657 for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
658 for (const auto &FileAndReplace : *ErrorFixes[I].second) {
659 for (const auto &Replace : FileAndReplace.second) {
660 unsigned Begin = Replace.getOffset();
661 unsigned End = Begin + Replace.getLength();
662 auto &Events = FileEvents[Replace.getFilePath()];
663 if (Begin == End) {
664 Events.emplace_back(Begin, End, Event::ET_Insert, I, Sizes[I]);
665 } else {
666 Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
667 Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
668 }
669 }
670 }
671 }
672
673 llvm::BitVector Apply(ErrorFixes.size(), true);
674 for (auto &FileAndEvents : FileEvents) {
675 std::vector<Event> &Events = FileAndEvents.second;
676 // Sweep.
677 llvm::sort(Events);
678 int OpenIntervals = 0;
679 for (const auto &Event : Events) {
680 switch (Event.Type) {
681 case Event::ET_Begin:
682 if (OpenIntervals++ != 0)
683 Apply[Event.ErrorId] = false;
684 break;
685 case Event::ET_Insert:
686 if (OpenIntervals != 0)
687 Apply[Event.ErrorId] = false;
688 break;
689 case Event::ET_End:
690 if (--OpenIntervals != 0)
691 Apply[Event.ErrorId] = false;
692 break;
693 }
694 }
695 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
696 }
697
698 for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
699 if (!Apply[I]) {
700 ErrorFixes[I].second->clear();
701 ErrorFixes[I].first->Notes.emplace_back(
702 "this fix will not be applied because it overlaps with another fix");
703 }
704 }
705 }
706
707 namespace {
708 struct LessClangTidyError {
709 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
710 const tooling::DiagnosticMessage &M1 = LHS.Message;
711 const tooling::DiagnosticMessage &M2 = RHS.Message;
712
713 return std::tie(M1.FilePath, M1.FileOffset, LHS.DiagnosticName,
714 M1.Message) <
715 std::tie(M2.FilePath, M2.FileOffset, RHS.DiagnosticName, M2.Message);
716 }
717 };
718 struct EqualClangTidyError {
719 bool operator()(const ClangTidyError &LHS, const ClangTidyError &RHS) const {
720 LessClangTidyError Less;
721 return !Less(LHS, RHS) && !Less(RHS, LHS);
722 }
723 };
724 } // end anonymous namespace
725
726 std::vector<ClangTidyError> ClangTidyDiagnosticConsumer::take() {
727 finalizeLastError();
728
729 llvm::stable_sort(Errors, LessClangTidyError());
730 Errors.erase(std::unique(Errors.begin(), Errors.end(), EqualClangTidyError()),
731 Errors.end());
732 if (RemoveIncompatibleErrors)
733 removeIncompatibleErrors();
734 return std::move(Errors);
735 }
736
737 namespace {
738 struct LessClangTidyErrorWithoutDiagnosticName {
739 bool operator()(const ClangTidyError *LHS, const ClangTidyError *RHS) const {
740 const tooling::DiagnosticMessage &M1 = LHS->Message;
741 const tooling::DiagnosticMessage &M2 = RHS->Message;
742
743 return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
744 std::tie(M2.FilePath, M2.FileOffset, M2.Message);
745 }
746 };
747 } // end anonymous namespace
748
749 void ClangTidyDiagnosticConsumer::removeDuplicatedDiagnosticsOfAliasCheckers() {
750 using UniqueErrorSet =
751 std::set<ClangTidyError *, LessClangTidyErrorWithoutDiagnosticName>;
752 UniqueErrorSet UniqueErrors;
753
754 auto IT = Errors.begin();
755 while (IT != Errors.end()) {
756 ClangTidyError &Error = *IT;
757 std::pair<UniqueErrorSet::iterator, bool> Inserted =
758 UniqueErrors.insert(&Error);
759
760 // Unique error, we keep it and move along.
761 if (Inserted.second) {
762 ++IT;
763 } else {
764 ClangTidyError &ExistingError = **Inserted.first;
765 const llvm::StringMap<tooling::Replacements> &CandidateFix =
766 Error.Message.Fix;
767 const llvm::StringMap<tooling::Replacements> &ExistingFix =
768 (*Inserted.first)->Message.Fix;
769
770 if (CandidateFix != ExistingFix) {
771
772 // In case of a conflict, don't suggest any fix-it.
773 ExistingError.Message.Fix.clear();
774 ExistingError.Notes.emplace_back(
775 llvm::formatv("cannot apply fix-it because an alias checker has "
776 "suggested a different fix-it; please remove one of "
777 "the checkers ('{0}', '{1}') or "
778 "ensure they are both configured the same",
779 ExistingError.DiagnosticName, Error.DiagnosticName)
780 .str());
781 }
782
783 if (Error.IsWarningAsError)
784 ExistingError.IsWarningAsError = true;
785
786 // Since it is the same error, we should take it as alias and remove it.
787 ExistingError.EnabledDiagnosticAliases.emplace_back(Error.DiagnosticName);
788 IT = Errors.erase(IT);
789 }
790 }
791 }