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"
10#include "../clang-tidy/ClangTidyDiagnosticConsumer.h"
11#include "Compiler.h"
12#include "Protocol.h"
13#include "SourceCode.h"
14#include "support/Logger.h"
15#include "clang/Basic/AllDiagnostics.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticIDs.h"
18#include "clang/Basic/FileManager.h"
19#include "clang/Basic/SourceLocation.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Lex/Lexer.h"
22#include "clang/Lex/Token.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/Optional.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/ScopeExit.h"
28#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/Twine.h"
31#include "llvm/Support/Capacity.h"
32#include "llvm/Support/Path.h"
33#include "llvm/Support/ScopedPrinter.h"
34#include "llvm/Support/Signals.h"
35#include "llvm/Support/raw_ostream.h"
36#include <algorithm>
37#include <cstddef>
38
39namespace clang {
40namespace clangd {
41namespace {
42
43const char *getDiagnosticCode(unsigned ID) {
44 switch (ID) {
45#define DIAG(ENUM, CLASS, DEFAULT_MAPPING, DESC, GROPU, SFINAE, NOWERROR, \
46 SHOWINSYSHEADER, DEFERRABLE, CATEGORY) \
47 case clang::diag::ENUM: \
48 return #ENUM;
49#include "clang/Basic/DiagnosticASTKinds.inc"
50#include "clang/Basic/DiagnosticAnalysisKinds.inc"
51#include "clang/Basic/DiagnosticCommentKinds.inc"
52#include "clang/Basic/DiagnosticCommonKinds.inc"
53#include "clang/Basic/DiagnosticDriverKinds.inc"
54#include "clang/Basic/DiagnosticFrontendKinds.inc"
55#include "clang/Basic/DiagnosticLexKinds.inc"
56#include "clang/Basic/DiagnosticParseKinds.inc"
57#include "clang/Basic/DiagnosticRefactoringKinds.inc"
58#include "clang/Basic/DiagnosticSemaKinds.inc"
59#include "clang/Basic/DiagnosticSerializationKinds.inc"
60#undef DIAG
61 default:
62 return nullptr;
63 }
64}
65
66bool mentionsMainFile(const Diag &D) {
67 if (D.InsideMainFile)
68 return true;
69 // Fixes are always in the main file.
70 if (!D.Fixes.empty())
71 return true;
72 for (auto &N : D.Notes) {
73 if (N.InsideMainFile)
74 return true;
75 }
76 return false;
77}
78
79bool isExcluded(const Diag &D) {
80 // clang will always fail parsing MS ASM, we don't link in desc + asm parser.
81 if (D.ID == clang::diag::err_msasm_unable_to_create_target ||
82 D.ID == clang::diag::err_msasm_unsupported_arch)
83 return true;
84 return false;
85}
86
87// Checks whether a location is within a half-open range.
88// Note that clang also uses closed source ranges, which this can't handle!
89bool locationInRange(SourceLocation L, CharSourceRange R,
90 const SourceManager &M) {
91 assert(R.isCharRange());
92 if (!R.isValid() || M.getFileID(R.getBegin()) != M.getFileID(R.getEnd()) ||
93 M.getFileID(R.getBegin()) != M.getFileID(L))
94 return false;
95 return L != R.getEnd() && M.isPointWithin(L, R.getBegin(), R.getEnd());
96}
97
98// Clang diags have a location (shown as ^) and 0 or more ranges (~~~~).
99// LSP needs a single range.
100Range diagnosticRange(const clang::Diagnostic &D, const LangOptions &L) {
101 auto &M = D.getSourceManager();
102 auto Loc = M.getFileLoc(D.getLocation());
103 for (const auto &CR : D.getRanges()) {
104 auto R = Lexer::makeFileCharRange(CR, M, L);
105 if (locationInRange(Loc, R, M))
106 return halfOpenToRange(M, R);
107 }
108 // The range may be given as a fixit hint instead.
109 for (const auto &F : D.getFixItHints()) {
110 auto R = Lexer::makeFileCharRange(F.RemoveRange, M, L);
111 if (locationInRange(Loc, R, M))
112 return halfOpenToRange(M, R);
113 }
114 // If the token at the location is not a comment, we use the token.
115 // If we can't get the token at the location, fall back to using the location
116 auto R = CharSourceRange::getCharRange(Loc);
117 Token Tok;
118 if (!Lexer::getRawToken(Loc, Tok, M, L, true) && Tok.isNot(tok::comment)) {
119 R = CharSourceRange::getTokenRange(Tok.getLocation(), Tok.getEndLoc());
120 }
121 return halfOpenToRange(M, R);
122}
123
124// Try to find a location in the main-file to report the diagnostic D.
125// Returns a description like "in included file", or nullptr on failure.
126const char *getMainFileRange(const Diag &D, const SourceManager &SM,
127 SourceLocation DiagLoc, Range &R) {
128 // Look for a note in the main file indicating template instantiation.
129 for (const auto &N : D.Notes) {
130 if (N.InsideMainFile) {
131 switch (N.ID) {
132 case diag::note_template_class_instantiation_was_here:
133 case diag::note_template_class_explicit_specialization_was_here:
134 case diag::note_template_class_instantiation_here:
135 case diag::note_template_member_class_here:
136 case diag::note_template_member_function_here:
137 case diag::note_function_template_spec_here:
138 case diag::note_template_static_data_member_def_here:
139 case diag::note_template_variable_def_here:
140 case diag::note_template_enum_def_here:
141 case diag::note_template_nsdmi_here:
142 case diag::note_template_type_alias_instantiation_here:
143 case diag::note_template_exception_spec_instantiation_here:
144 case diag::note_template_requirement_instantiation_here:
145 case diag::note_evaluating_exception_spec_here:
146 case diag::note_default_arg_instantiation_here:
147 case diag::note_default_function_arg_instantiation_here:
148 case diag::note_explicit_template_arg_substitution_here:
149 case diag::note_function_template_deduction_instantiation_here:
150 case diag::note_deduced_template_arg_substitution_here:
151 case diag::note_prior_template_arg_substitution:
152 case diag::note_template_default_arg_checking:
153 case diag::note_concept_specialization_here:
154 case diag::note_nested_requirement_here:
155 case diag::note_checking_constraints_for_template_id_here:
156 case diag::note_checking_constraints_for_var_spec_id_here:
157 case diag::note_checking_constraints_for_class_spec_id_here:
158 case diag::note_checking_constraints_for_function_here:
159 case diag::note_constraint_substitution_here:
160 case diag::note_constraint_normalization_here:
161 case diag::note_parameter_mapping_substitution_here:
162 R = N.Range;
163 return "in template";
164 default:
165 break;
166 }
167 }
168 }
169 // Look for where the file with the error was #included.
170 auto GetIncludeLoc = [&SM](SourceLocation SLoc) {
171 return SM.getIncludeLoc(SM.getFileID(SLoc));
172 };
173 for (auto IncludeLocation = GetIncludeLoc(SM.getExpansionLoc(DiagLoc));
174 IncludeLocation.isValid();
175 IncludeLocation = GetIncludeLoc(IncludeLocation)) {
176 if (clangd::isInsideMainFile(IncludeLocation, SM)) {
177 R.start = sourceLocToPosition(SM, IncludeLocation);
178 R.end = sourceLocToPosition(
179 SM,
180 Lexer::getLocForEndOfToken(IncludeLocation, 0, SM, LangOptions()));
181 return "in included file";
182 }
183 }
184 return nullptr;
185}
186
187// Place the diagnostic the main file, rather than the header, if possible:
188// - for errors in included files, use the #include location
189// - for errors in template instantiation, use the instantiation location
190// In both cases, add the original header location as a note.
191bool tryMoveToMainFile(Diag &D, FullSourceLoc DiagLoc) {
192 const SourceManager &SM = DiagLoc.getManager();
193 DiagLoc = DiagLoc.getExpansionLoc();
194 Range R;
195 const char *Prefix = getMainFileRange(D, SM, DiagLoc, R);
196 if (!Prefix)
197 return false;
198
199 // Add a note that will point to real diagnostic.
200 const auto *FE = SM.getFileEntryForID(SM.getFileID(DiagLoc));
201 D.Notes.emplace(D.Notes.begin());
202 Note &N = D.Notes.front();
203 N.AbsFile = std::string(FE->tryGetRealPathName());
204 N.File = std::string(FE->getName());
205 N.Message = "error occurred here";
206 N.Range = D.Range;
207
208 // Update diag to point at include inside main file.
209 D.File = SM.getFileEntryForID(SM.getMainFileID())->getName().str();
210 D.Range = std::move(R);
211 D.InsideMainFile = true;
212 // Update message to mention original file.
213 D.Message = llvm::formatv("{0}: {1}", Prefix, D.Message);
214 return true;
215}
216
217bool isInsideMainFile(const clang::Diagnostic &D) {
218 if (!D.hasSourceManager())
219 return false;
220
221 return clangd::isInsideMainFile(D.getLocation(), D.getSourceManager());
222}
223
224bool isNote(DiagnosticsEngine::Level L) {
225 return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
226}
227
228llvm::StringRef diagLeveltoString(DiagnosticsEngine::Level Lvl) {
229 switch (Lvl) {
230 case DiagnosticsEngine::Ignored:
231 return "ignored";
232 case DiagnosticsEngine::Note:
233 return "note";
234 case DiagnosticsEngine::Remark:
235 return "remark";
236 case DiagnosticsEngine::Warning:
237 return "warning";
238 case DiagnosticsEngine::Error:
239 return "error";
240 case DiagnosticsEngine::Fatal:
241 return "fatal error";
242 }
243 llvm_unreachable("unhandled DiagnosticsEngine::Level");
244}
245
246/// Prints a single diagnostic in a clang-like manner, the output includes
247/// location, severity and error message. An example of the output message is:
248///
249/// main.cpp:12:23: error: undeclared identifier
250///
251/// For main file we only print the basename and for all other files we print
252/// the filename on a separate line to provide a slightly more readable output
253/// in the editors:
254///
255/// dir1/dir2/dir3/../../dir4/header.h:12:23
256/// error: undeclared identifier
257void printDiag(llvm::raw_string_ostream &OS, const DiagBase &D) {
258 if (D.InsideMainFile) {
259 // Paths to main files are often taken from compile_command.json, where they
260 // are typically absolute. To reduce noise we print only basename for them,
261 // it should not be confusing and saves space.
262 OS << llvm::sys::path::filename(D.File) << ":";
263 } else {
264 OS << D.File << ":";
265 }
266 // Note +1 to line and character. clangd::Range is zero-based, but when
267 // printing for users we want one-based indexes.
268 auto Pos = D.Range.start;
269 OS << (Pos.line + 1) << ":" << (Pos.character + 1) << ":";
270 // The non-main-file paths are often too long, putting them on a separate
271 // line improves readability.
272 if (D.InsideMainFile)
273 OS << " ";
274 else
275 OS << "\n";
276 OS << diagLeveltoString(D.Severity) << ": " << D.Message;
277}
278
279/// Capitalizes the first word in the diagnostic's message.
280std::string capitalize(std::string Message) {
281 if (!Message.empty())
282 Message[0] = llvm::toUpper(Message[0]);
283 return Message;
284}
285
286/// Returns a message sent to LSP for the main diagnostic in \p D.
287/// This message may include notes, if they're not emitted in some other way.
288/// Example output:
289///
290/// no matching function for call to 'foo'
291///
292/// main.cpp:3:5: note: candidate function not viable: requires 2 arguments
293///
294/// dir1/dir2/dir3/../../dir4/header.h:12:23
295/// note: candidate function not viable: requires 3 arguments
296std::string mainMessage(const Diag &D, const ClangdDiagnosticOptions &Opts) {
297 std::string Result;
298 llvm::raw_string_ostream OS(Result);
299 OS << D.Message;
300 if (Opts.DisplayFixesCount && !D.Fixes.empty())
301 OS << " (" << (D.Fixes.size() > 1 ? "fixes" : "fix") << " available)";
302 // If notes aren't emitted as structured info, add them to the message.
303 if (!Opts.EmitRelatedLocations)
304 for (auto &Note : D.Notes) {
305 OS << "\n\n";
306 printDiag(OS, Note);
307 }
308 OS.flush();
309 return capitalize(std::move(Result));
310}
311
312/// Returns a message sent to LSP for the note of the main diagnostic.
313std::string noteMessage(const Diag &Main, const DiagBase &Note,
314 const ClangdDiagnosticOptions &Opts) {
315 std::string Result;
316 llvm::raw_string_ostream OS(Result);
317 OS << Note.Message;
318 // If the client doesn't support structured links between the note and the
319 // original diagnostic, then emit the main diagnostic to give context.
320 if (!Opts.EmitRelatedLocations) {
321 OS << "\n\n";
322 printDiag(OS, Main);
323 }
324 OS.flush();
325 return capitalize(std::move(Result));
326}
327} // namespace
328
329llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const DiagBase &D) {
330 OS << "[";
331 if (!D.InsideMainFile)
332 OS << D.File << ":";
333 OS << D.Range.start << "-" << D.Range.end << "] ";
334
335 return OS << D.Message;
336}
337
338llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Fix &F) {
339 OS << F.Message << " {";
340 const char *Sep = "";
341 for (const auto &Edit : F.Edits) {
342 OS << Sep << Edit;
343 Sep = ", ";
344 }
345 return OS << "}";
346}
347
348llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diag &D) {
349 OS << static_cast<const DiagBase &>(D);
350 if (!D.Notes.empty()) {
351 OS << ", notes: {";
352 const char *Sep = "";
353 for (auto &Note : D.Notes) {
354 OS << Sep << Note;
355 Sep = ", ";
356 }
357 OS << "}";
358 }
359 if (!D.Fixes.empty()) {
360 OS << ", fixes: {";
361 const char *Sep = "";
362 for (auto &Fix : D.Fixes) {
363 OS << Sep << Fix;
364 Sep = ", ";
365 }
366 }
367 return OS;
368}
369
370CodeAction toCodeAction(const Fix &F, const URIForFile &File) {
371 CodeAction Action;
372 Action.title = F.Message;
373 Action.kind = std::string(CodeAction::QUICKFIX_KIND);
374 Action.edit.emplace();
375 Action.edit->changes.emplace();
376 (*Action.edit->changes)[File.uri()] = {F.Edits.begin(), F.Edits.end()};
377 return Action;
378}
379
380Diag toDiag(const llvm::SMDiagnostic &D, Diag::DiagSource Source) {
381 Diag Result;
382 Result.Message = D.getMessage().str();
383 switch (D.getKind()) {
384 case llvm::SourceMgr::DK_Error:
385 Result.Severity = DiagnosticsEngine::Error;
386 break;
387 case llvm::SourceMgr::DK_Warning:
388 Result.Severity = DiagnosticsEngine::Warning;
389 break;
390 default:
391 break;
392 }
393 Result.Source = Source;
394 Result.AbsFile = D.getFilename().str();
395 Result.InsideMainFile = D.getSourceMgr()->FindBufferContainingLoc(
396 D.getLoc()) == D.getSourceMgr()->getMainFileID();
397 if (D.getRanges().empty())
398 Result.Range = {{D.getLineNo() - 1, D.getColumnNo()},
399 {D.getLineNo() - 1, D.getColumnNo()}};
400 else
401 Result.Range = {{D.getLineNo() - 1, (int)D.getRanges().front().first},
402 {D.getLineNo() - 1, (int)D.getRanges().front().second}};
403 return Result;
404}
405
406void toLSPDiags(
407 const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts,
408 llvm::function_ref<void(clangd::Diagnostic, llvm::ArrayRef<Fix>)> OutFn) {
409 clangd::Diagnostic Main;
410 Main.severity = getSeverity(D.Severity);
411
412 // Main diagnostic should always refer to a range inside main file. If a
413 // diagnostic made it so for, it means either itself or one of its notes is
414 // inside main file.
415 if (D.InsideMainFile) {
416 Main.range = D.Range;
417 } else {
418 auto It =
419 llvm::find_if(D.Notes, [](const Note &N) { return N.InsideMainFile; });
420 assert(It != D.Notes.end() &&
421 "neither the main diagnostic nor notes are inside main file");
422 Main.range = It->Range;
423 }
424
425 Main.code = D.Name;
426 switch (D.Source) {
427 case Diag::Clang:
428 Main.source = "clang";
429 break;
430 case Diag::ClangTidy:
431 Main.source = "clang-tidy";
432 break;
433 case Diag::ClangdConfig:
434 Main.source = "clangd-config";
435 break;
436 case Diag::Unknown:
437 break;
438 }
439 if (Opts.EmbedFixesInDiagnostics) {
440 Main.codeActions.emplace();
441 for (const auto &Fix : D.Fixes)
442 Main.codeActions->push_back(toCodeAction(Fix, File));
443 if (Main.codeActions->size() == 1)
444 Main.codeActions->front().isPreferred = true;
445 }
446 if (Opts.SendDiagnosticCategory && !D.Category.empty())
447 Main.category = D.Category;
448
449 Main.message = mainMessage(D, Opts);
450 if (Opts.EmitRelatedLocations) {
451 Main.relatedInformation.emplace();
452 for (auto &Note : D.Notes) {
453 if (!Note.AbsFile) {
454 vlog("Dropping note from unknown file: {0}", Note);
455 continue;
456 }
457 DiagnosticRelatedInformation RelInfo;
458 RelInfo.location.range = Note.Range;
459 RelInfo.location.uri =
460 URIForFile::canonicalize(*Note.AbsFile, File.file());
461 RelInfo.message = noteMessage(D, Note, Opts);
462 Main.relatedInformation->push_back(std::move(RelInfo));
463 }
464 }
465 OutFn(std::move(Main), D.Fixes);
466
467 // If we didn't emit the notes as relatedLocations, emit separate diagnostics
468 // so the user can find the locations easily.
469 if (!Opts.EmitRelatedLocations)
470 for (auto &Note : D.Notes) {
471 if (!Note.InsideMainFile)
472 continue;
473 clangd::Diagnostic Res;
474 Res.severity = getSeverity(Note.Severity);
475 Res.range = Note.Range;
476 Res.message = noteMessage(D, Note, Opts);
477 OutFn(std::move(Res), llvm::ArrayRef<Fix>());
478 }
479
480 // FIXME: Get rid of the copies here by taking in a mutable clangd::Diag.
481 for (auto &Entry : D.OpaqueData)
482 Main.data.insert({Entry.first, Entry.second});
483}
484
485int getSeverity(DiagnosticsEngine::Level L) {
486 switch (L) {
487 case DiagnosticsEngine::Remark:
488 return 4;
489 case DiagnosticsEngine::Note:
490 return 3;
491 case DiagnosticsEngine::Warning:
492 return 2;
493 case DiagnosticsEngine::Fatal:
494 case DiagnosticsEngine::Error:
495 return 1;
496 case DiagnosticsEngine::Ignored:
497 return 0;
498 }
499 llvm_unreachable("Unknown diagnostic level!");
500}
501
502std::vector<Diag> StoreDiags::take(const clang::tidy::ClangTidyContext *Tidy) {
503 // Do not forget to emit a pending diagnostic if there is one.
504 flushLastDiag();
505
506 // Fill in name/source now that we have all the context needed to map them.
507 for (auto &Diag : Output) {
508 if (const char *ClangDiag = getDiagnosticCode(Diag.ID)) {
509 // Warnings controlled by -Wfoo are better recognized by that name.
510 StringRef Warning = DiagnosticIDs::getWarningOptionForDiag(Diag.ID);
511 if (!Warning.empty()) {
512 Diag.Name = ("-W" + Warning).str();
513 } else {
514 StringRef Name(ClangDiag);
515 // Almost always an error, with a name like err_enum_class_reference.
516 // Drop the err_ prefix for brevity.
517 Name.consume_front("err_");
518 Diag.Name = std::string(Name);
519 }
520 Diag.Source = Diag::Clang;
521 continue;
522 }
523 if (Tidy != nullptr) {
524 std::string TidyDiag = Tidy->getCheckName(Diag.ID);
525 if (!TidyDiag.empty()) {
526 Diag.Name = std::move(TidyDiag);
527 Diag.Source = Diag::ClangTidy;
528 // clang-tidy bakes the name into diagnostic messages. Strip it out.
529 // It would be much nicer to make clang-tidy not do this.
530 auto CleanMessage = [&](std::string &Msg) {
531 StringRef Rest(Msg);
532 if (Rest.consume_back("]") && Rest.consume_back(Diag.Name) &&
533 Rest.consume_back(" ["))
534 Msg.resize(Rest.size());
535 };
536 CleanMessage(Diag.Message);
537 for (auto &Note : Diag.Notes)
538 CleanMessage(Note.Message);
539 for (auto &Fix : Diag.Fixes)
540 CleanMessage(Fix.Message);
541 continue;
542 }
543 }
544 }
545 // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
546 // duplicated messages due to various reasons (e.g. the check doesn't handle
547 // template instantiations well; clang-tidy alias checks).
548 std::set<std::pair<Range, std::string>> SeenDiags;
549 llvm::erase_if(Output, [&](const Diag& D) {
550 return !SeenDiags.emplace(D.Range, D.Message).second;
551 });
552 return std::move(Output);
553}
554
555void StoreDiags::BeginSourceFile(const LangOptions &Opts,
556 const Preprocessor *PP) {
557 LangOpts = Opts;
558 if (PP) {
559 OrigSrcMgr = &PP->getSourceManager();
560 }
561}
562
563void StoreDiags::EndSourceFile() {
564 flushLastDiag();
565 LangOpts = None;
566 OrigSrcMgr = nullptr;
567}
568
569/// Sanitizes a piece for presenting it in a synthesized fix message. Ensures
570/// the result is not too large and does not contain newlines.
571static void writeCodeToFixMessage(llvm::raw_ostream &OS, llvm::StringRef Code) {
572 constexpr unsigned MaxLen = 50;
573
574 // Only show the first line if there are many.
575 llvm::StringRef R = Code.split('\n').first;
576 // Shorten the message if it's too long.
577 R = R.take_front(MaxLen);
578
579 OS << R;
580 if (R.size() != Code.size())
581 OS << "…";
582}
583
584/// Fills \p D with all information, except the location-related bits.
585/// Also note that ID and Name are not part of clangd::DiagBase and should be
586/// set elsewhere.
587static void fillNonLocationData(DiagnosticsEngine::Level DiagLevel,
588 const clang::Diagnostic &Info,
589 clangd::DiagBase &D) {
590 llvm::SmallString<64> Message;
591 Info.FormatDiagnostic(Message);
592
593 D.Message = std::string(Message.str());
594 D.Severity = DiagLevel;
595 D.Category = DiagnosticIDs::getCategoryNameFromID(
596 DiagnosticIDs::getCategoryNumberForDiag(Info.getID()))
597 .str();
598}
599
600void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
601 const clang::Diagnostic &Info) {
602 // If the diagnostic was generated for a different SourceManager, skip it.
603 // This happens when a module is imported and needs to be implicitly built.
604 // The compilation of that module will use the same StoreDiags, but different
605 // SourceManager.
606 if (OrigSrcMgr && Info.hasSourceManager() &&
607 OrigSrcMgr != &Info.getSourceManager()) {
608 IgnoreDiagnostics::log(DiagLevel, Info);
609 return;
610 }
611
612 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
613 bool OriginallyError =
614 Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
615 Info.getID());
616
617 if (Info.getLocation().isInvalid()) {
618 // Handle diagnostics coming from command-line arguments. The source manager
619 // is *not* available at this point, so we cannot use it.
620 if (!OriginallyError) {
621 IgnoreDiagnostics::log(DiagLevel, Info);
622 return; // non-errors add too much noise, do not show them.
623 }
624
625 flushLastDiag();
626
627 LastDiag = Diag();
628 LastDiagLoc.reset();
629 LastDiagOriginallyError = OriginallyError;
630 LastDiag->ID = Info.getID();
631 fillNonLocationData(DiagLevel, Info, *LastDiag);
632 LastDiag->InsideMainFile = true;
633 // Put it at the start of the main file, for a lack of a better place.
634 LastDiag->Range.start = Position{0, 0};
635 LastDiag->Range.end = Position{0, 0};
636 return;
637 }
638
639 if (!LangOpts || !Info.hasSourceManager()) {
640 IgnoreDiagnostics::log(DiagLevel, Info);
641 return;
642 }
643
644 bool InsideMainFile = isInsideMainFile(Info);
645 SourceManager &SM = Info.getSourceManager();
646
647 auto FillDiagBase = [&](DiagBase &D) {
648 fillNonLocationData(DiagLevel, Info, D);
649
650 D.InsideMainFile = InsideMainFile;
651 D.Range = diagnosticRange(Info, *LangOpts);
652 D.File = std::string(SM.getFilename(Info.getLocation()));
653 D.AbsFile = getCanonicalPath(
654 SM.getFileEntryForID(SM.getFileID(Info.getLocation())), SM);
655 D.ID = Info.getID();
656 return D;
657 };
658
659 auto AddFix = [&](bool SyntheticMessage) -> bool {
660 assert(!Info.getFixItHints().empty() &&
661 "diagnostic does not have attached fix-its");
662 if (!InsideMainFile)
663 return false;
664
665 // Copy as we may modify the ranges.
666 auto FixIts = Info.getFixItHints().vec();
667 llvm::SmallVector<TextEdit, 1> Edits;
668 for (auto &FixIt : FixIts) {
669 // Allow fixits within a single macro-arg expansion to be applied.
670 // This can be incorrect if the argument is expanded multiple times in
671 // different contexts. Hopefully this is rare!
672 if (FixIt.RemoveRange.getBegin().isMacroID() &&
673 FixIt.RemoveRange.getEnd().isMacroID() &&
674 SM.getFileID(FixIt.RemoveRange.getBegin()) ==
675 SM.getFileID(FixIt.RemoveRange.getEnd())) {
676 FixIt.RemoveRange = CharSourceRange(
677 {SM.getTopMacroCallerLoc(FixIt.RemoveRange.getBegin()),
678 SM.getTopMacroCallerLoc(FixIt.RemoveRange.getEnd())},
679 FixIt.RemoveRange.isTokenRange());
680 }
681 // Otherwise, follow clang's behavior: no fixits in macros.
682 if (FixIt.RemoveRange.getBegin().isMacroID() ||
683 FixIt.RemoveRange.getEnd().isMacroID())
684 return false;
685 if (!isInsideMainFile(FixIt.RemoveRange.getBegin(), SM))
686 return false;
687 Edits.push_back(toTextEdit(FixIt, SM, *LangOpts));
688 }
689
690 llvm::SmallString<64> Message;
691 // If requested and possible, create a message like "change 'foo' to 'bar'".
692 if (SyntheticMessage && FixIts.size() == 1) {
693 const auto &FixIt = FixIts.front();
694 bool Invalid = false;
695 llvm::StringRef Remove =
696 Lexer::getSourceText(FixIt.RemoveRange, SM, *LangOpts, &Invalid);
697 llvm::StringRef Insert = FixIt.CodeToInsert;
698 if (!Invalid) {
699 llvm::raw_svector_ostream M(Message);
700 if (!Remove.empty() && !Insert.empty()) {
701 M << "change '";
702 writeCodeToFixMessage(M, Remove);
703 M << "' to '";
704 writeCodeToFixMessage(M, Insert);
705 M << "'";
706 } else if (!Remove.empty()) {
707 M << "remove '";
708 writeCodeToFixMessage(M, Remove);
709 M << "'";
710 } else if (!Insert.empty()) {
711 M << "insert '";
712 writeCodeToFixMessage(M, Insert);
713 M << "'";
714 }
715 // Don't allow source code to inject newlines into diagnostics.
716 std::replace(Message.begin(), Message.end(), '\n', ' ');
717 }
718 }
719 if (Message.empty()) // either !SyntheticMessage, or we failed to make one.
720 Info.FormatDiagnostic(Message);
721 LastDiag->Fixes.push_back(
722 Fix{std::string(Message.str()), std::move(Edits)});
723 return true;
724 };
725
726 if (!isNote(DiagLevel)) {
727 // Handle the new main diagnostic.
728 flushLastDiag();
729
730 if (Adjuster) {
731 DiagLevel = Adjuster(DiagLevel, Info);
732 if (DiagLevel == DiagnosticsEngine::Ignored) {
733 LastPrimaryDiagnosticWasSuppressed = true;
734 return;
735 }
736 }
737 LastPrimaryDiagnosticWasSuppressed = false;
738
739 LastDiag = Diag();
740 FillDiagBase(*LastDiag);
741 LastDiagLoc.emplace(Info.getLocation(), Info.getSourceManager());
742 LastDiagOriginallyError = OriginallyError;
743
744 if (!Info.getFixItHints().empty())
745 AddFix(true /* try to invent a message instead of repeating the diag */);
746 if (Fixer) {
747 auto ExtraFixes = Fixer(DiagLevel, Info);
748 LastDiag->Fixes.insert(LastDiag->Fixes.end(), ExtraFixes.begin(),
749 ExtraFixes.end());
750 }
751 if (DiagCB)
752 DiagCB(Info, *LastDiag);
753 } else {
754 // Handle a note to an existing diagnostic.
755
756 // If a diagnostic was suppressed due to the suppression filter,
757 // also suppress notes associated with it.
758 if (LastPrimaryDiagnosticWasSuppressed) {
759 return;
760 }
761
762 if (!LastDiag) {
763 assert(false && "Adding a note without main diagnostic");
764 IgnoreDiagnostics::log(DiagLevel, Info);
765 return;
766 }
767
768 if (!Info.getFixItHints().empty()) {
769 // A clang note with fix-it is not a separate diagnostic in clangd. We
770 // attach it as a Fix to the main diagnostic instead.
771 if (!AddFix(false /* use the note as the message */))
772 IgnoreDiagnostics::log(DiagLevel, Info);
773 } else {
774 // A clang note without fix-its corresponds to clangd::Note.
775 Note N;
776 FillDiagBase(N);
777
778 LastDiag->Notes.push_back(std::move(N));
779 }
780 }
781}
782
783void StoreDiags::flushLastDiag() {
784 if (!LastDiag)
785 return;
786 auto Finish = llvm::make_scope_exit([&, NDiags(Output.size())] {
787 if (Output.size() == NDiags) // No new diag emitted.
788 vlog("Dropped diagnostic: {0}: {1}", LastDiag->File, LastDiag->Message);
789 LastDiag.reset();
790 });
791
792 if (isExcluded(*LastDiag))
793 return;
794 // Move errors that occur from headers into main file.
795 if (!LastDiag->InsideMainFile && LastDiagLoc && LastDiagOriginallyError) {
796 if (tryMoveToMainFile(*LastDiag, *LastDiagLoc)) {
797 // Suppress multiple errors from the same inclusion.
798 if (!IncludedErrorLocations
799 .insert({LastDiag->Range.start.line,
800 LastDiag->Range.start.character})
801 .second)
802 return;
803 }
804 }
805 if (!mentionsMainFile(*LastDiag))
806 return;
807 Output.push_back(std::move(*LastDiag));
808}
809
810bool isBuiltinDiagnosticSuppressed(unsigned ID,
811 const llvm::StringSet<> &Suppress) {
812 if (const char *CodePtr = getDiagnosticCode(ID)) {
813 if (Suppress.contains(normalizeSuppressedCode(CodePtr)))
814 return true;
815 }
816 StringRef Warning = DiagnosticIDs::getWarningOptionForDiag(ID);
817 if (!Warning.empty() && Suppress.contains(Warning))
818 return true;
819 return false;
820}
821
822llvm::StringRef normalizeSuppressedCode(llvm::StringRef Code) {
823 Code.consume_front("err_");
824 Code.consume_front("-W");
825 return Code;
826}
827
828} // namespace clangd
829} // namespace clang
830