clang-tools 24.0.0git
Diagnostics.cpp
Go to the documentation of this file.
1//===--- Diagnostics.cpp -----------------------------------------*- C++-*-===//
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#include "Diagnostics.h"
11#include "Compiler.h"
12#include "Config.h"
13#include "Protocol.h"
14#include "SourceCode.h"
15#include "support/Logger.h"
16#include "clang/Basic/AllDiagnostics.h" // IWYU pragma: keep
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/DiagnosticIDs.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TokenKinds.h"
23#include "clang/Edit/EditedSource.h"
24#include "clang/Lex/Lexer.h"
25#include "clang/Lex/Token.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseSet.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/STLFunctionalExtras.h"
30#include "llvm/ADT/ScopeExit.h"
31#include "llvm/ADT/SmallString.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/StringSet.h"
36#include "llvm/ADT/Twine.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FormatVariadic.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/SourceMgr.h"
41#include "llvm/Support/raw_ostream.h"
42#include <algorithm>
43#include <cassert>
44#include <optional>
45#include <set>
46#include <string>
47#include <tuple>
48#include <utility>
49#include <vector>
50
51namespace clang {
52namespace clangd {
53namespace {
54
55const char *getDiagnosticCode(unsigned ID) {
56 switch (ID) {
57#define DIAG(ENUM, CLASS, DEFAULT_MAPPING, DESC, GROPU, SFINAE, NOWERROR, \
58 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY, STABLE_ID, \
59 LEGACY_STABLE_IDS) \
60 case clang::diag::ENUM: \
61 return #ENUM;
62#include "clang/Basic/DiagnosticASTKinds.inc"
63#include "clang/Basic/DiagnosticAnalysisKinds.inc"
64#include "clang/Basic/DiagnosticCommentKinds.inc"
65#include "clang/Basic/DiagnosticCommonKinds.inc"
66#include "clang/Basic/DiagnosticDriverKinds.inc"
67#include "clang/Basic/DiagnosticFrontendKinds.inc"
68#include "clang/Basic/DiagnosticLexKinds.inc"
69#include "clang/Basic/DiagnosticParseKinds.inc"
70#include "clang/Basic/DiagnosticRefactoringKinds.inc"
71#include "clang/Basic/DiagnosticSemaKinds.inc"
72#include "clang/Basic/DiagnosticSerializationKinds.inc"
73#undef DIAG
74 default:
75 return nullptr;
76 }
77}
78
79bool mentionsMainFile(const Diag &D) {
80 if (D.InsideMainFile)
81 return true;
82 // Fixes are always in the main file.
83 if (!D.Fixes.empty())
84 return true;
85 for (auto &N : D.Notes) {
86 if (N.InsideMainFile)
87 return true;
88 }
89 return false;
90}
91
92bool isExcluded(unsigned DiagID) {
93 // clang will always fail parsing MS ASM, we don't link in desc + asm parser.
94 if (DiagID == clang::diag::err_msasm_unable_to_create_target ||
95 DiagID == clang::diag::err_msasm_unsupported_arch)
96 return true;
97 return false;
98}
99
100// Checks whether a location is within a half-open range.
101// Note that clang also uses closed source ranges, which this can't handle!
102bool locationInRange(SourceLocation L, CharSourceRange R,
103 const SourceManager &M) {
104 assert(R.isCharRange());
105 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
106 M.getFileID(R.getBegin()) != M.getFileID(L))
107 return false;
108 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
109}
110
111// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
112// LSP needs a single range.
113std::optional<Range> diagnosticRange(const clang::Diagnostic &D,
114 const LangOptions &L) {
115 auto &M = D.getSourceManager();
116 auto PatchedRange = [&M](CharSourceRange &R) {
117 R.setBegin(translatePreamblePatchLocation(R.getBegin(), M));
118 R.setEnd(translatePreamblePatchLocation(R.getEnd(), M));
119 return R;
120 };
121 auto Loc = M.getFileLoc(D.getLocation());
122 for (const auto &CR : D.getRanges()) {
123 auto R = Lexer::makeFileCharRange(CR, M, L);
124 if (locationInRange(Loc, R, M))
125 return halfOpenToRange(M, PatchedRange(R));
126 }
127 // The range may be given as a fixit hint instead.
128 for (const auto &F : D.getFixItHints()) {
129 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
130 if (locationInRange(Loc, R, M))
131 return halfOpenToRange(M, PatchedRange(R));
132 }
133 // Source locations from stale preambles might become OOB.
134 // FIXME: These diagnostics might point to wrong locations even when they're
135 // not OOB.
136 auto [FID, Offset] = M.getDecomposedLoc(Loc);
137 if (Offset > M.getBufferData(FID).size())
138 return std::nullopt;
139 // If the token at the location is not a comment, we use the token.
140 // If we can't get the token at the location, fall back to using the location
141 auto R = CharSourceRange::getCharRange(Loc);
142 Token Tok;
143 if (!Lexer::getRawToken(Loc, Tok, M, L, true) && Tok.isNot(tok::comment))
144 R = CharSourceRange::getTokenRange(Tok.getLocation(), Tok.getEndLoc());
145 return halfOpenToRange(M, PatchedRange(R));
146}
147
148// Try to find a location in the main-file to report the diagnostic D.
149// Returns a description like "in included file", or nullptr on failure.
150const char *getMainFileRange(const Diag &D, const SourceManager &SM,
151 SourceLocation DiagLoc, Range &R) {
152 // Look for a note in the main file indicating template instantiation.
153 for (const auto &N : D.Notes) {
154 if (N.InsideMainFile) {
155 switch (N.ID) {
156 case diag::note_template_class_instantiation_was_here:
157 case diag::note_template_class_explicit_specialization_was_here:
158 case diag::note_template_class_instantiation_here:
159 case diag::note_template_member_class_here:
160 case diag::note_template_member_function_here:
161 case diag::note_function_template_spec_here:
162 case diag::note_template_static_data_member_def_here:
163 case diag::note_template_variable_def_here:
164 case diag::note_template_enum_def_here:
165 case diag::note_template_nsdmi_here:
166 case diag::note_template_type_alias_instantiation_here:
167 case diag::note_template_exception_spec_instantiation_here:
168 case diag::note_template_requirement_instantiation_here:
169 case diag::note_evaluating_exception_spec_here:
170 case diag::note_default_arg_instantiation_here:
171 case diag::note_default_function_arg_instantiation_here:
172 case diag::note_explicit_template_arg_substitution_here:
173 case diag::note_function_template_deduction_instantiation_here:
174 case diag::note_deduced_template_arg_substitution_here:
175 case diag::note_prior_template_arg_substitution:
176 case diag::note_template_default_arg_checking:
177 case diag::note_concept_specialization_here:
178 case diag::note_nested_requirement_here:
179 case diag::note_checking_constraints_for_template_id_here:
180 case diag::note_checking_constraints_for_var_spec_id_here:
181 case diag::note_checking_constraints_for_class_spec_id_here:
182 case diag::note_checking_constraints_for_function_here:
183 case diag::note_constraint_substitution_here:
184 case diag::note_parameter_mapping_substitution_here:
185 R = N.Range;
186 return "in template";
187 default:
188 break;
189 }
190 }
191 }
192 // Look for where the file with the error was #included.
193 auto GetIncludeLoc = [&SM](SourceLocation SLoc) {
194 return SM.getIncludeLoc(SM.getFileID(SLoc));
195 };
196 for (auto IncludeLocation = GetIncludeLoc(SM.getExpansionLoc(DiagLoc));
197 IncludeLocation.isValid();
198 IncludeLocation = GetIncludeLoc(IncludeLocation)) {
199 if (clangd::isInsideMainFile(IncludeLocation, SM)) {
200 R.start = sourceLocToPosition(SM, IncludeLocation);
201 R.end = sourceLocToPosition(
202 SM,
203 Lexer::getLocForEndOfToken(IncludeLocation, 0, SM, LangOptions()));
204 return "in included file";
205 }
206 }
207 return nullptr;
208}
209
210// Place the diagnostic the main file, rather than the header, if possible:
211// - for errors in included files, use the #include location
212// - for errors in template instantiation, use the instantiation location
213// In both cases, add the original header location as a note.
214bool tryMoveToMainFile(Diag &D, FullSourceLoc DiagLoc) {
215 const SourceManager &SM = DiagLoc.getManager();
216 DiagLoc = DiagLoc.getExpansionLoc();
217 Range R;
218 const char *Prefix = getMainFileRange(D, SM, DiagLoc, R);
219 if (!Prefix)
220 return false;
221
222 // Add a note that will point to real diagnostic.
223 auto FE = *SM.getFileEntryRefForID(SM.getFileID(DiagLoc));
224 D.Notes.emplace(D.Notes.begin());
225 Note &N = D.Notes.front();
226 N.AbsFile = std::string(FE.getFileEntry().tryGetRealPathName());
227 N.File = std::string(FE.getName());
228 N.Message = "error occurred here";
229 N.Range = D.Range;
230
231 // Update diag to point at include inside main file.
232 D.File = SM.getFileEntryRefForID(SM.getMainFileID())->getName().str();
233 D.Range = std::move(R);
234 D.InsideMainFile = true;
235 // Update message to mention original file.
236 D.Message = llvm::formatv("{0}: {1}", Prefix, D.Message);
237 return true;
238}
239
240bool isNote(DiagnosticsEngine::Level L) {
241 return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
242}
243
244llvm::StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
245 switch (Lvl) {
246 case DiagnosticsEngine::Ignored:
247 return "ignored";
248 case DiagnosticsEngine::Note:
249 return "note";
250 case DiagnosticsEngine::Remark:
251 return "remark";
252 case DiagnosticsEngine::Warning:
253 return "warning";
254 case DiagnosticsEngine::Error:
255 return "error";
256 case DiagnosticsEngine::Fatal:
257 return "fatal error";
258 }
259 llvm_unreachable("unhandled DiagnosticsEngine::Level");
260}
261
262/// Prints a single diagnostic in a clang-like manner, the output includes
263/// location, severity and error message. An example of the output message is:
264///
265/// main.cpp:12:23: error: undeclared identifier
266///
267/// For main file we only print the basename and for all other files we print
268/// the filename on a separate line to provide a slightly more readable output
269/// in the editors:
270///
271/// dir1/dir2/dir3/../../dir4/header.h:12:23
272/// error: undeclared identifier
273void printDiag(llvm::raw_string_ostream &OS, const DiagBase &D) {
274 if (D.InsideMainFile) {
275 // Paths to main files are often taken from compile_command.json, where they
276 // are typically absolute. To reduce noise we print only basename for them,
277 // it should not be confusing and saves space.
278 OS << llvm::sys::path::filename(D.File) << ":";
279 } else {
280 OS << D.File << ":";
281 }
282 // Note +1 to line and character. clangd::Range is zero-based, but when
283 // printing for users we want one-based indexes.
284 auto Pos = D.Range.start;
285 OS << (Pos.line + 1) << ":" << (Pos.character + 1) << ":";
286 // The non-main-file paths are often too long, putting them on a separate
287 // line improves readability.
288 if (D.InsideMainFile)
289 OS << " ";
290 else
291 OS << "\n";
292 OS << diagLeveltoString(D.Severity) << ": " << D.Message;
293}
294
295/// Capitalizes the first word in the diagnostic's message.
296std::string capitalize(std::string Message) {
297 if (!Message.empty())
298 Message[0] = llvm::toUpper(Message[0]);
299 return Message;
300}
301
302/// Returns a message sent to LSP for the main diagnostic in \p D.
303/// This message may include notes, if they're not emitted in some other way.
304/// Example output:
305///
306/// no matching function for call to 'foo'
307///
308/// main.cpp:3:5: note: candidate function not viable: requires 2 arguments
309///
310/// dir1/dir2/dir3/../../dir4/header.h:12:23
311/// note: candidate function not viable: requires 3 arguments
312std::string mainMessage(const Diag &D, const ClangdDiagnosticOptions &Opts) {
313 std::string Result;
314 llvm::raw_string_ostream OS(Result);
315 OS << D.Message;
316 if (Opts.DisplayFixesCount && !D.Fixes.empty())
317 OS << " (" << (D.Fixes.size() > 1 ? "fixes" : "fix") << " available)";
318 // If notes aren't emitted as structured info, add them to the message.
319 if (!Opts.EmitRelatedLocations)
320 for (auto &Note : D.Notes) {
321 OS << "\n\n";
322 printDiag(OS, Note);
323 }
324 return capitalize(std::move(Result));
325}
326
327/// Returns a message sent to LSP for the note of the main diagnostic.
328std::string noteMessage(const Diag &Main, const DiagBase &Note,
329 const ClangdDiagnosticOptions &Opts) {
330 std::string Result;
331 llvm::raw_string_ostream OS(Result);
332 OS << Note.Message;
333 // If the client doesn't support structured links between the note and the
334 // original diagnostic, then emit the main diagnostic to give context.
335 if (!Opts.EmitRelatedLocations) {
336 OS << "\n\n";
337 printDiag(OS, Main);
338 }
339 return capitalize(std::move(Result));
340}
341
342void setTags(clangd::Diag &D) {
343 static const auto *DeprecatedDiags = new llvm::DenseSet<unsigned>{
344 diag::warn_access_decl_deprecated,
345 diag::warn_atl_uuid_deprecated,
346 diag::warn_deprecated,
347 diag::warn_deprecated_altivec_src_compat,
348 diag::warn_deprecated_comma_subscript,
349 diag::warn_deprecated_copy,
350 diag::warn_deprecated_copy_with_dtor,
351 diag::warn_deprecated_copy_with_user_provided_copy,
352 diag::warn_deprecated_copy_with_user_provided_dtor,
353 diag::warn_deprecated_def,
354 diag::warn_deprecated_increment_decrement_volatile,
355 diag::warn_deprecated_message,
356 diag::warn_deprecated_redundant_constexpr_static_def,
357 diag::warn_deprecated_register,
358 diag::warn_deprecated_simple_assign_volatile,
359 diag::warn_deprecated_string_literal_conversion,
360 diag::warn_deprecated_this_capture,
361 diag::warn_deprecated_volatile_param,
362 diag::warn_deprecated_volatile_return,
363 diag::warn_deprecated_volatile_structured_binding,
364 diag::warn_opencl_attr_deprecated_ignored,
365 diag::warn_property_method_deprecated,
366 diag::warn_vector_mode_deprecated,
367 };
368 static const auto *UnusedDiags = new llvm::DenseSet<unsigned>{
369 diag::warn_opencl_attr_deprecated_ignored,
370 diag::warn_pragma_attribute_unused,
371 diag::warn_unused_but_set_parameter,
372 diag::warn_unused_but_set_variable,
373 diag::warn_unused_comparison,
374 diag::warn_unused_const_variable,
375 diag::warn_unused_exception_param,
376 diag::warn_unused_function,
377 diag::warn_unused_label,
378 diag::warn_unused_lambda_capture,
379 diag::warn_unused_local_typedef,
380 diag::warn_unused_member_function,
381 diag::warn_unused_parameter,
382 diag::warn_unused_private_field,
383 diag::warn_unused_property_backing_ivar,
384 diag::warn_unused_template,
385 diag::warn_unused_variable,
386 };
387 if (DeprecatedDiags->contains(D.ID)) {
388 D.Tags.push_back(DiagnosticTag::Deprecated);
389 } else if (UnusedDiags->contains(D.ID)) {
390 D.Tags.push_back(DiagnosticTag::Unnecessary);
391 }
392 if (D.Source == Diag::ClangTidy) {
393 if (llvm::StringRef(D.Name).starts_with("misc-unused-"))
394 D.Tags.push_back(DiagnosticTag::Unnecessary);
395 if (llvm::StringRef(D.Name).starts_with("modernize-"))
396 D.Tags.push_back(DiagnosticTag::Deprecated);
397 }
398}
399} // namespace
400
401llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const DiagBase &D) {
402 OS << "[";
403 if (!D.InsideMainFile)
404 OS << D.File << ":";
405 OS << D.Range.start << "-" << D.Range.end << "] ";
406
407 return OS << D.Message;
408}
409
410llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Fix &F) {
411 OS << F.Message << " {";
412 const char *Sep = "";
413 for (const auto &Edit : F.Edits) {
414 OS << Sep << Edit;
415 Sep = ", ";
416 }
417 return OS << "}";
418}
419
420llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diag &D) {
421 OS << static_cast<const DiagBase &>(D);
422 if (!D.Notes.empty()) {
423 OS << ", notes: {";
424 const char *Sep = "";
425 for (auto &Note : D.Notes) {
426 OS << Sep << Note;
427 Sep = ", ";
428 }
429 OS << "}";
430 }
431 if (!D.Fixes.empty()) {
432 OS << ", fixes: {";
433 const char *Sep = "";
434 for (auto &Fix : D.Fixes) {
435 OS << Sep << Fix;
436 Sep = ", ";
437 }
438 OS << "}";
439 }
440 return OS;
441}
442
443Diag toDiag(const llvm::SMDiagnostic &D, Diag::DiagSource Source) {
444 Diag Result;
445 Result.Message = D.getMessage().str();
446 switch (D.getKind()) {
447 case llvm::SourceMgr::DK_Error:
448 Result.Severity = DiagnosticsEngine::Error;
449 break;
450 case llvm::SourceMgr::DK_Warning:
451 Result.Severity = DiagnosticsEngine::Warning;
452 break;
453 default:
454 break;
455 }
456 Result.Source = Source;
457 Result.AbsFile = D.getFilename().str();
458 Result.InsideMainFile = D.getSourceMgr()->FindBufferContainingLoc(
459 D.getLoc()) == D.getSourceMgr()->getMainFileID();
460 if (D.getRanges().empty())
461 Result.Range = {{D.getLineNo() - 1, D.getColumnNo()},
462 {D.getLineNo() - 1, D.getColumnNo()}};
463 else
464 Result.Range = {{D.getLineNo() - 1, (int)D.getRanges().front().first},
465 {D.getLineNo() - 1, (int)D.getRanges().front().second}};
466 return Result;
467}
468
470 const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts,
471 llvm::function_ref<void(clangd::Diagnostic, llvm::ArrayRef<Fix>)> OutFn) {
473 Main.severity = getSeverity(D.Severity);
474 // We downgrade severity for certain noisy warnings, like deprecated
475 // declartions. These already have visible decorations inside the editor and
476 // most users find the extra clutter in the UI (gutter, minimap, diagnostics
477 // views) overwhelming.
478 if (D.Severity == DiagnosticsEngine::Warning) {
479 if (llvm::is_contained(D.Tags, DiagnosticTag::Deprecated))
480 Main.severity = getSeverity(DiagnosticsEngine::Remark);
481 }
482
483 // Main diagnostic should always refer to a range inside main file. If a
484 // diagnostic made it so for, it means either itself or one of its notes is
485 // inside main file. It's also possible that there's a fix in the main file,
486 // but we preserve fixes iff primary diagnostic is in the main file.
487 if (D.InsideMainFile) {
488 Main.range = D.Range;
489 } else {
490 auto It =
491 llvm::find_if(D.Notes, [](const Note &N) { return N.InsideMainFile; });
492 assert(It != D.Notes.end() &&
493 "neither the main diagnostic nor notes are inside main file");
494 Main.range = It->Range;
495 }
496
497 Main.code = D.Name;
498 if (auto URI = getDiagnosticDocURI(D.Source, D.ID, D.Name)) {
499 Main.codeDescription.emplace();
500 Main.codeDescription->href = std::move(*URI);
501 }
502 switch (D.Source) {
503 case Diag::Clang:
504 Main.source = "clang";
505 break;
506 case Diag::ClangTidy:
507 Main.source = "clang-tidy";
508 break;
509 case Diag::Clangd:
510 Main.source = "clangd";
511 break;
513 Main.source = "clangd-config";
514 break;
515 case Diag::Unknown:
516 break;
517 }
518 if (Opts.SendDiagnosticCategory && !D.Category.empty())
519 Main.category = D.Category;
520
521 Main.message = mainMessage(D, Opts);
522 if (Opts.EmitRelatedLocations) {
523 Main.relatedInformation.emplace();
524 for (auto &Note : D.Notes) {
525 if (!Note.AbsFile) {
526 vlog("Dropping note from unknown file: {0}", Note);
527 continue;
528 }
530 RelInfo.location.range = Note.Range;
531 RelInfo.location.uri =
533 RelInfo.message = noteMessage(D, Note, Opts);
534 Main.relatedInformation->push_back(std::move(RelInfo));
535 }
536 }
537 Main.tags = D.Tags;
538 // FIXME: Get rid of the copies here by taking in a mutable clangd::Diag.
539 for (auto &Entry : D.OpaqueData)
540 Main.data.insert({Entry.first, Entry.second});
541 OutFn(std::move(Main), D.Fixes);
542
543 // If we didn't emit the notes as relatedLocations, emit separate diagnostics
544 // so the user can find the locations easily.
545 if (!Opts.EmitRelatedLocations)
546 for (auto &Note : D.Notes) {
547 if (!Note.InsideMainFile)
548 continue;
551 Res.range = Note.Range;
552 Res.message = noteMessage(D, Note, Opts);
553 OutFn(std::move(Res), llvm::ArrayRef<Fix>());
554 }
555}
556
557int getSeverity(DiagnosticsEngine::Level L) {
558 switch (L) {
559 case DiagnosticsEngine::Remark:
560 return 4;
561 case DiagnosticsEngine::Note:
562 return 3;
563 case DiagnosticsEngine::Warning:
564 return 2;
565 case DiagnosticsEngine::Fatal:
566 case DiagnosticsEngine::Error:
567 return 1;
568 case DiagnosticsEngine::Ignored:
569 return 0;
570 }
571 llvm_unreachable("Unknown diagnostic level!");
572}
573
574std::vector<Diag> StoreDiags::take(const clang::tidy::ClangTidyContext *Tidy) {
575 // Do not forget to emit a pending diagnostic if there is one.
576 flushLastDiag();
577
578 // Fill in name/source now that we have all the context needed to map them.
579 for (auto &Diag : Output) {
580 if (const char *ClangDiag = getDiagnosticCode(Diag.ID)) {
581 // Warnings controlled by -Wfoo are better recognized by that name.
582 StringRef Warning = [&] {
583 if (OrigSrcMgr) {
584 return OrigSrcMgr->getDiagnostics()
585 .getDiagnosticIDs()
586 ->getWarningOptionForDiag(Diag.ID);
587 }
588 if (!DiagnosticIDs::IsCustomDiag(Diag.ID))
589 return DiagnosticIDs{}.getWarningOptionForDiag(Diag.ID);
590 return StringRef{};
591 }();
592
593 if (!Warning.empty()) {
594 Diag.Name = ("-W" + Warning).str();
595 } else {
596 StringRef Name(ClangDiag);
597 // Almost always an error, with a name like err_enum_class_reference.
598 // Drop the err_ prefix for brevity.
599 Name.consume_front("err_");
600 Diag.Name = std::string(Name);
601 }
603 } else if (Tidy != nullptr) {
604 std::string TidyDiag = Tidy->getCheckName(Diag.ID);
605 if (!TidyDiag.empty()) {
606 Diag.Name = std::move(TidyDiag);
608 // clang-tidy bakes the name into diagnostic messages. Strip it out.
609 // It would be much nicer to make clang-tidy not do this.
610 auto CleanMessage = [&](std::string &Msg) {
611 StringRef Rest(Msg);
612 if (Rest.consume_back("]") && Rest.consume_back(Diag.Name) &&
613 Rest.consume_back(" ["))
614 Msg.resize(Rest.size());
615 };
616 CleanMessage(Diag.Message);
617 for (auto &Note : Diag.Notes)
618 CleanMessage(Note.Message);
619 for (auto &Fix : Diag.Fixes)
620 CleanMessage(Fix.Message);
621 }
622 }
623 setTags(Diag);
624 }
625 if (Finalizer)
626 for (auto &Diag : Output)
627 Finalizer(Diag);
628 // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
629 // duplicated messages due to various reasons (e.g. the check doesn't handle
630 // template instantiations well; clang-tidy alias checks).
631 std::set<std::pair<Range, std::string>> SeenDiags;
632 llvm::erase_if(Output, [&](const Diag &D) {
633 return !SeenDiags.emplace(D.Range, D.Message).second;
634 });
635 return std::move(Output);
636}
637
638void StoreDiags::BeginSourceFile(const LangOptions &Opts,
639 const Preprocessor *PP) {
640 LangOpts = Opts;
641 if (PP) {
642 OrigSrcMgr = &PP->getSourceManager();
643 }
644}
645
647 flushLastDiag();
648 LangOpts = std::nullopt;
649 OrigSrcMgr = nullptr;
650}
651
652/// Sanitizes a piece for presenting it in a synthesized fix message. Ensures
653/// the result is not too large and does not contain newlines.
654static void writeCodeToFixMessage(llvm::raw_ostream &OS, llvm::StringRef Code) {
655 constexpr unsigned MaxLen = 50;
656 if (Code == "\n") {
657 OS << "\\n";
658 return;
659 }
660 // Only show the first line if there are many.
661 llvm::StringRef R = Code.split('\n').first;
662 // Shorten the message if it's too long.
663 R = R.take_front(MaxLen);
664
665 OS << R;
666 if (R.size() != Code.size())
667 OS << "…";
668}
669
670/// Fills \p D with all information, except the location-related bits.
671/// Also note that ID and Name are not part of clangd::DiagBase and should be
672/// set elsewhere.
673static void fillNonLocationData(DiagnosticsEngine::Level DiagLevel,
674 const clang::Diagnostic &Info,
675 clangd::DiagBase &D) {
676 llvm::SmallString<64> Message;
677 Info.FormatDiagnostic(Message);
678
679 D.Message = std::string(Message);
680 D.Severity = DiagLevel;
681 D.Category = DiagnosticIDs::getCategoryNameFromID(
682 DiagnosticIDs::getCategoryNumberForDiag(Info.getID()))
683 .str();
684}
685
686static bool isDiagnosticSuppressed(const clang::Diagnostic &Diag,
687 const llvm::StringSet<> &Suppress,
688 const std::optional<LangOptions> &LangOpts) {
689 // Don't complain about header-only stuff in mainfiles if it's a header.
690 // FIXME: would be cleaner to suppress in clang, once we decide whether the
691 // behavior should be to silently-ignore or respect the pragma.
692 if (LangOpts && Diag.getID() == diag::pp_pragma_sysheader_in_main_file &&
693 LangOpts->IsHeaderFile)
694 return true;
695
696 if (const char *CodePtr = getDiagnosticCode(Diag.getID())) {
697 if (Suppress.contains(normalizeSuppressedCode(CodePtr)))
698 return true;
699 }
700 StringRef Warning =
701 Diag.getDiags()->getDiagnosticIDs()->getWarningOptionForDiag(
702 Diag.getID());
703 if (!Warning.empty() && Suppress.contains(Warning))
704 return true;
705 return false;
706}
707
708void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
709 const clang::Diagnostic &Info) {
710 // If the diagnostic was generated for a different SourceManager, skip it.
711 // This happens when a module is imported and needs to be implicitly built.
712 // The compilation of that module will use the same StoreDiags, but different
713 // SourceManager.
714 if (OrigSrcMgr && Info.hasSourceManager() &&
715 OrigSrcMgr != &Info.getSourceManager()) {
716 IgnoreDiagnostics::log(DiagLevel, Info);
717 return;
718 }
719
720 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
721 bool OriginallyError =
722 Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
723 Info.getID());
724
725 if (!isNote(DiagLevel)) {
726 const Config &Cfg = Config::current();
727 // Check if diagnostics is suppressed (possibly by user), before doing any
728 // adjustments.
729 if (Cfg.Diagnostics.SuppressAll ||
731 DiagLevel = DiagnosticsEngine::Ignored;
732 } else if (Adjuster) {
733 // FIXME: Merge with feature modules.
734 DiagLevel = Adjuster(DiagLevel, Info);
735 }
736 }
737
738 if (Info.getLocation().isInvalid()) {
739 // Handle diagnostics coming from command-line arguments. The source manager
740 // is *not* available at this point, so we cannot use it.
741 if (!OriginallyError) {
742 IgnoreDiagnostics::log(DiagLevel, Info);
743 return; // non-errors add too much noise, do not show them.
744 }
745
746 flushLastDiag();
747
748 LastDiag = Diag();
749 LastDiagLoc.reset();
750 LastDiagOriginallyError = OriginallyError;
751 LastDiag->ID = Info.getID();
752 fillNonLocationData(DiagLevel, Info, *LastDiag);
753 LastDiag->InsideMainFile = true;
754 // Put it at the start of the main file, for a lack of a better place.
755 LastDiag->Range.start = Position{0, 0};
756 LastDiag->Range.end = Position{0, 0};
757 return;
758 }
759
760 if (!LangOpts || !Info.hasSourceManager()) {
761 IgnoreDiagnostics::log(DiagLevel, Info);
762 return;
763 }
764
765 SourceManager &SM = Info.getSourceManager();
766
767 auto FillDiagBase = [&](DiagBase &D) {
768 fillNonLocationData(DiagLevel, Info, D);
769
770 SourceLocation PatchLoc =
771 translatePreamblePatchLocation(Info.getLocation(), SM);
772 D.InsideMainFile = isInsideMainFile(PatchLoc, SM);
773 if (auto DRange = diagnosticRange(Info, *LangOpts))
774 D.Range = *DRange;
775 else
776 D.Severity = DiagnosticsEngine::Ignored;
777 auto FID = SM.getFileID(Info.getLocation());
778 if (const auto FE = SM.getFileEntryRefForID(FID)) {
779 D.File = FE->getName().str();
780 D.AbsFile = getCanonicalPath(*FE, SM.getFileManager());
781 }
782 D.ID = Info.getID();
783 return D;
784 };
785
786 auto AddFix = [&](bool SyntheticMessage) -> bool {
787 assert(!Info.getFixItHints().empty() &&
788 "diagnostic does not have attached fix-its");
789 // No point in generating fixes, if the diagnostic is for a different file.
790 if (!LastDiag->InsideMainFile)
791 return false;
792 // Copy as we may modify the ranges.
793 auto FixIts = Info.getFixItHints().vec();
794 for (auto &FixIt : FixIts) {
795 // Allow fixits within a single macro-arg expansion to be applied.
796 // This can be incorrect if the argument is expanded multiple times in
797 // different contexts. Hopefully this is rare!
798 if (FixIt.RemoveRange.getBegin().isMacroID() &&
799 FixIt.RemoveRange.getEnd().isMacroID() &&
800 SM.getFileID(FixIt.RemoveRange.getBegin()) ==
801 SM.getFileID(FixIt.RemoveRange.getEnd())) {
802 FixIt.RemoveRange = CharSourceRange(
803 {SM.getTopMacroCallerLoc(FixIt.RemoveRange.getBegin()),
804 SM.getTopMacroCallerLoc(FixIt.RemoveRange.getEnd())},
805 FixIt.RemoveRange.isTokenRange());
806 }
807 // Otherwise, follow clang's behavior: no fixits in macros.
808 if (FixIt.RemoveRange.getBegin().isMacroID() ||
809 FixIt.RemoveRange.getEnd().isMacroID())
810 return false;
811 }
812 llvm::SmallVector<FixItHint> MergedFixIts;
813 clang::edit::mergeFixits(FixIts, SM, *LangOpts, MergedFixIts);
814 if (MergedFixIts.empty())
815 return false;
816 llvm::SmallVector<TextEdit> Edits;
817 Edits.reserve(MergedFixIts.size());
818 for (const auto &FixIt : MergedFixIts) {
819 if (!isInsideMainFile(FixIt.RemoveRange.getBegin(), SM))
820 return false;
821 Edits.push_back(toTextEdit(FixIt, SM, *LangOpts));
822 }
823
824 llvm::SmallString<64> Message;
825 // If requested and possible, create a message like "change 'foo' to 'bar'".
826 if (SyntheticMessage && MergedFixIts.size() == 1) {
827 const auto &FixIt = MergedFixIts.front();
828 bool Invalid = false;
829 llvm::StringRef Remove =
830 Lexer::getSourceText(FixIt.RemoveRange, SM, *LangOpts, &Invalid);
831 llvm::StringRef Insert = FixIt.CodeToInsert;
832 if (!Invalid) {
833 llvm::raw_svector_ostream M(Message);
834 if (!Remove.empty() && !Insert.empty()) {
835 M << "change '";
836 writeCodeToFixMessage(M, Remove);
837 M << "' to '";
838 writeCodeToFixMessage(M, Insert);
839 M << "'";
840 } else if (!Remove.empty()) {
841 M << "remove '";
842 writeCodeToFixMessage(M, Remove);
843 M << "'";
844 } else if (!Insert.empty()) {
845 M << "insert '";
846 writeCodeToFixMessage(M, Insert);
847 M << "'";
848 }
849 // Don't allow source code to inject newlines into diagnostics.
850 llvm::replace(Message, '\n', ' ');
851 }
852 }
853 if (Message.empty()) // either !SyntheticMessage, or we failed to make one.
854 Info.FormatDiagnostic(Message);
855 LastDiag->Fixes.push_back(Fix{std::string(Message), std::move(Edits), {}});
856 return true;
857 };
858
859 if (!isNote(DiagLevel)) {
860 // Handle the new main diagnostic.
861 flushLastDiag();
862
863 LastDiag = Diag();
864
865 FillDiagBase(*LastDiag);
866 if (isExcluded(LastDiag->ID))
867 LastDiag->Severity = DiagnosticsEngine::Ignored;
868 if (DiagCB)
869 DiagCB(Info, *LastDiag);
870 // Don't bother filling in the rest if diag is going to be dropped.
871 if (LastDiag->Severity == DiagnosticsEngine::Ignored)
872 return;
873
874 LastDiagLoc.emplace(Info.getLocation(), Info.getSourceManager());
875 LastDiagOriginallyError = OriginallyError;
876 if (!Info.getFixItHints().empty())
877 AddFix(true /* try to invent a message instead of repeating the diag */);
878 if (Fixer) {
879 auto ExtraFixes = Fixer(LastDiag->Severity, Info);
880 LastDiag->Fixes.insert(LastDiag->Fixes.end(), ExtraFixes.begin(),
881 ExtraFixes.end());
882 }
883 } else {
884 // Handle a note to an existing diagnostic.
885 if (!LastDiag) {
886 assert(false && "Adding a note without main diagnostic");
887 IgnoreDiagnostics::log(DiagLevel, Info);
888 return;
889 }
890
891 // If a diagnostic was suppressed due to the suppression filter,
892 // also suppress notes associated with it.
893 if (LastDiag->Severity == DiagnosticsEngine::Ignored)
894 return;
895
896 // Give include-fixer a chance to replace a note with a fix.
897 if (Fixer) {
898 auto ReplacementFixes = Fixer(LastDiag->Severity, Info);
899 if (!ReplacementFixes.empty()) {
900 assert(Info.getNumFixItHints() == 0 &&
901 "Include-fixer replaced a note with clang fix-its attached!");
902 LastDiag->Fixes.insert(LastDiag->Fixes.end(), ReplacementFixes.begin(),
903 ReplacementFixes.end());
904 return;
905 }
906 }
907
908 if (!Info.getFixItHints().empty()) {
909 // A clang note with fix-it is not a separate diagnostic in clangd. We
910 // attach it as a Fix to the main diagnostic instead.
911 if (!AddFix(false /* use the note as the message */))
912 IgnoreDiagnostics::log(DiagLevel, Info);
913 } else {
914 // A clang note without fix-its corresponds to clangd::Note.
915 Note N;
916 FillDiagBase(N);
917
918 LastDiag->Notes.push_back(std::move(N));
919 }
920 }
921}
922
923void StoreDiags::flushLastDiag() {
924 if (!LastDiag)
925 return;
926 llvm::scope_exit Finish([&, NDiags(Output.size())] {
927 if (Output.size() == NDiags) // No new diag emitted.
928 vlog("Dropped diagnostic: {0}: {1}", LastDiag->File, LastDiag->Message);
929 LastDiag.reset();
930 });
931
932 if (LastDiag->Severity == DiagnosticsEngine::Ignored)
933 return;
934 // Move errors that occur from headers into main file.
935 if (!LastDiag->InsideMainFile && LastDiagLoc && LastDiagOriginallyError) {
936 if (tryMoveToMainFile(*LastDiag, *LastDiagLoc)) {
937 // Suppress multiple errors from the same inclusion.
938 if (!IncludedErrorLocations
939 .insert({LastDiag->Range.start.line,
940 LastDiag->Range.start.character})
941 .second)
942 return;
943 }
944 }
945 if (!mentionsMainFile(*LastDiag))
946 return;
947 Output.push_back(std::move(*LastDiag));
948}
949
950llvm::StringRef normalizeSuppressedCode(llvm::StringRef Code) {
951 Code.consume_front("err_");
952 Code.consume_front("-W");
953 return Code;
954}
955
956std::optional<std::string> getDiagnosticDocURI(Diag::DiagSource Source,
957 unsigned ID,
958 llvm::StringRef Name) {
959 switch (Source) {
960 case Diag::Unknown:
961 break;
962 case Diag::Clang:
963 // There is a page listing many warning flags, but it provides too little
964 // information to be worth linking.
965 // https://clang.llvm.org/docs/DiagnosticsReference.html
966 break;
967 case Diag::ClangTidy: {
968 StringRef Module, Check;
969 // This won't correctly get the module for clang-analyzer checks, but as we
970 // don't link in the analyzer that shouldn't be an issue.
971 // This would also need updating if anyone decides to create a module with a
972 // '-' in the name.
973 std::tie(Module, Check) = Name.split('-');
974 if (Module.empty() || Check.empty())
975 return std::nullopt;
976 return ("https://clang.llvm.org/extra/clang-tidy/checks/" + Module + "/" +
977 Check + ".html")
978 .str();
979 }
980 case Diag::Clangd:
981 if (Name == "unused-includes" || Name == "missing-includes")
982 return {"https://clangd.llvm.org/guides/include-cleaner"};
983 break;
985 // FIXME: we should link to https://clangd.llvm.org/config
986 // However we have no diagnostic codes, which the link should describe!
987 break;
988 }
989 return std::nullopt;
990}
991
992} // namespace clangd
993} // namespace clang
static void log(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info)
Definition Compiler.cpp:21
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) override
std::vector< Diag > take(const clang::tidy::ClangTidyContext *Tidy=nullptr)
void BeginSourceFile(const LangOptions &Opts, const Preprocessor *PP) override
void EndSourceFile() override
A URI describes the location of a source file.
Definition URI.h:28
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
std::string getCheckName(unsigned DiagnosticID) const
Returns the name of the clang-tidy check which produced this diagnostic ID.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
static void writeCodeToFixMessage(llvm::raw_ostream &OS, llvm::StringRef Code)
Sanitizes a piece for presenting it in a synthesized fix message.
@ Warning
A warning message.
Definition Protocol.h:753
@ Info
An information message.
Definition Protocol.h:755
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
static void fillNonLocationData(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info, clangd::DiagBase &D)
Fills D with all information, except the location-related bits.
void toLSPDiags(const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts, llvm::function_ref< void(clangd::Diagnostic, llvm::ArrayRef< Fix >)> OutFn)
Conversion to LSP diagnostics.
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
void vlog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:72
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
SourceLocation translatePreamblePatchLocation(SourceLocation Loc, const SourceManager &SM)
Translates locations inside preamble patch to their main-file equivalent using presumed locations.
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
std::optional< std::string > getCanonicalPath(const FileEntryRef F, FileManager &FileMgr)
Get the canonical path of F.
llvm::StringRef normalizeSuppressedCode(llvm::StringRef Code)
Take a user-specified diagnostic code, and convert it to a normalized form stored in the config and c...
static bool isDiagnosticSuppressed(const clang::Diagnostic &Diag, const llvm::StringSet<> &Suppress, const std::optional< LangOptions > &LangOpts)
Diag toDiag(const llvm::SMDiagnostic &D, Diag::DiagSource Source)
int getSeverity(DiagnosticsEngine::Level L)
Convert from clang diagnostic level to LSP severity.
@ Deprecated
Deprecated or obsolete code.
Definition Protocol.h:936
@ Unnecessary
Unused or unnecessary code.
Definition Protocol.h:932
std::optional< std::string > getDiagnosticDocURI(Diag::DiagSource Source, unsigned ID, llvm::StringRef Name)
Returns a URI providing more information about a particular diagnostic.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
bool SendDiagnosticCategory
If true, Clangd uses an LSP extension to send the diagnostic's category to the client.
Definition Diagnostics.h:50
bool EmitRelatedLocations
If true, Clangd uses the relatedInformation field to include other locations (in particular attached ...
Definition Diagnostics.h:44
Settings that express user/project preferences and control clangd behavior.
Definition Config.h:45
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition Config.cpp:17
struct clang::clangd::Config::@343034053122374337352226322054223376344037116252 Diagnostics
Controls warnings and errors when parsing code.
llvm::StringSet Suppress
Definition Config.h:106
Contains basic information about a diagnostic.
Definition Diagnostics.h:58
DiagnosticsEngine::Level Severity
Definition Diagnostics.h:67
std::optional< std::string > AbsFile
Definition Diagnostics.h:64
A top-level diagnostic that may have Notes and Fixes.
Definition Diagnostics.h:98
std::vector< Fix > Fixes
Alternative fixes for this diagnostic, one should be chosen.
enum clang::clangd::Diag::DiagSource Source
std::vector< Note > Notes
Elaborate on the problem, usually pointing to a related piece of code.
Represents a related message and source code location for a diagnostic.
Definition Protocol.h:919
std::string message
The message of this related diagnostic information.
Definition Protocol.h:923
Location location
The location of this related diagnostic information.
Definition Protocol.h:921
std::optional< CodeDescription > codeDescription
An optional property to describe the error code.
Definition Protocol.h:960
llvm::json::Object data
A data entry field that is preserved between a textDocument/publishDiagnostics notification and textD...
Definition Protocol.h:992
std::optional< std::vector< DiagnosticRelatedInformation > > relatedInformation
An array of related diagnostic information, e.g.
Definition Protocol.h:974
std::string code
The diagnostic's code. Can be omitted.
Definition Protocol.h:957
Range range
The range at which the message applies.
Definition Protocol.h:950
std::string source
A human-readable string describing the source of this diagnostic, e.g.
Definition Protocol.h:964
std::string message
The diagnostic's message.
Definition Protocol.h:967
int severity
The diagnostic's severity.
Definition Protocol.h:954
std::optional< std::string > category
The diagnostic's category.
Definition Protocol.h:980
llvm::SmallVector< DiagnosticTag, 1 > tags
Additional metadata about the diagnostic.
Definition Protocol.h:970
A set of edits generated for a single file.
Definition SourceCode.h:189
Represents a single fix-it that editor can apply to fix the error.
Definition Diagnostics.h:81
std::string Message
Message for the fix-it.
Definition Diagnostics.h:83
llvm::SmallVector< TextEdit, 1 > Edits
TextEdits from clang's fix-its. Must be non-empty.
Definition Diagnostics.h:85
URIForFile uri
The text document's URI.
Definition Protocol.h:214
Represents a note for the diagnostic.
Definition Diagnostics.h:95
A single C++ or preprocessor token.
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition Protocol.cpp:46