clang-tools  12.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"
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 
39 namespace clang {
40 namespace clangd {
41 namespace {
42 
43 const 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 
66 bool 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 
79 bool 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!
89 bool 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.
100 Range 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.
126 const 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 instantation location
190 // In both cases, add the original header location as a note.
191 bool 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 
217 bool isInsideMainFile(const clang::Diagnostic &D) {
218  if (!D.hasSourceManager())
219  return false;
220 
221  return clangd::isInsideMainFile(D.getLocation(), D.getSourceManager());
222 }
223 
224 bool isNote(DiagnosticsEngine::Level L) {
225  return L == DiagnosticsEngine::Note || L == DiagnosticsEngine::Remark;
226 }
227 
228 llvm::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";
237  return "warning";
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
257 void 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.
280 std::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
296 std::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.
313 std::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 
329 llvm::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 
338 llvm::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 
348 llvm::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 
370 CodeAction toCodeAction(const Fix &F, const URIForFile &File) {
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 
381  const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts,
382  llvm::function_ref<void(clangd::Diagnostic, llvm::ArrayRef<Fix>)> OutFn) {
383  clangd::Diagnostic Main;
384  Main.severity = getSeverity(D.Severity);
385 
386  // Main diagnostic should always refer to a range inside main file. If a
387  // diagnostic made it so for, it means either itself or one of its notes is
388  // inside main file.
389  if (D.InsideMainFile) {
390  Main.range = D.Range;
391  } else {
392  auto It =
393  llvm::find_if(D.Notes, [](const Note &N) { return N.InsideMainFile; });
394  assert(It != D.Notes.end() &&
395  "neither the main diagnostic nor notes are inside main file");
396  Main.range = It->Range;
397  }
398 
399  Main.code = D.Name;
400  switch (D.Source) {
401  case Diag::Clang:
402  Main.source = "clang";
403  break;
404  case Diag::ClangTidy:
405  Main.source = "clang-tidy";
406  break;
407  case Diag::Unknown:
408  break;
409  }
410  if (Opts.EmbedFixesInDiagnostics) {
411  Main.codeActions.emplace();
412  for (const auto &Fix : D.Fixes)
413  Main.codeActions->push_back(toCodeAction(Fix, File));
414  if (Main.codeActions->size() == 1)
415  Main.codeActions->front().isPreferred = true;
416  }
417  if (Opts.SendDiagnosticCategory && !D.Category.empty())
418  Main.category = D.Category;
419 
420  Main.message = mainMessage(D, Opts);
421  if (Opts.EmitRelatedLocations) {
422  Main.relatedInformation.emplace();
423  for (auto &Note : D.Notes) {
424  if (!Note.AbsFile) {
425  vlog("Dropping note from unknown file: {0}", Note);
426  continue;
427  }
429  RelInfo.location.range = Note.Range;
430  RelInfo.location.uri =
431  URIForFile::canonicalize(*Note.AbsFile, File.file());
432  RelInfo.message = noteMessage(D, Note, Opts);
433  Main.relatedInformation->push_back(std::move(RelInfo));
434  }
435  }
436  OutFn(std::move(Main), D.Fixes);
437 
438  // If we didn't emit the notes as relatedLocations, emit separate diagnostics
439  // so the user can find the locations easily.
440  if (!Opts.EmitRelatedLocations)
441  for (auto &Note : D.Notes) {
442  if (!Note.InsideMainFile)
443  continue;
444  clangd::Diagnostic Res;
445  Res.severity = getSeverity(Note.Severity);
446  Res.range = Note.Range;
447  Res.message = noteMessage(D, Note, Opts);
448  OutFn(std::move(Res), llvm::ArrayRef<Fix>());
449  }
450 }
451 
452 int getSeverity(DiagnosticsEngine::Level L) {
453  switch (L) {
454  case DiagnosticsEngine::Remark:
455  return 4;
456  case DiagnosticsEngine::Note:
457  return 3;
459  return 2;
460  case DiagnosticsEngine::Fatal:
462  return 1;
463  case DiagnosticsEngine::Ignored:
464  return 0;
465  }
466  llvm_unreachable("Unknown diagnostic level!");
467 }
468 
469 std::vector<Diag> StoreDiags::take(const clang::tidy::ClangTidyContext *Tidy) {
470  // Do not forget to emit a pending diagnostic if there is one.
471  flushLastDiag();
472 
473  // Fill in name/source now that we have all the context needed to map them.
474  for (auto &Diag : Output) {
475  if (const char *ClangDiag = getDiagnosticCode(Diag.ID)) {
476  // Warnings controlled by -Wfoo are better recognized by that name.
477  StringRef Warning = DiagnosticIDs::getWarningOptionForDiag(Diag.ID);
478  if (!Warning.empty()) {
479  Diag.Name = ("-W" + Warning).str();
480  } else {
481  StringRef Name(ClangDiag);
482  // Almost always an error, with a name like err_enum_class_reference.
483  // Drop the err_ prefix for brevity.
484  Name.consume_front("err_");
485  Diag.Name = std::string(Name);
486  }
488  continue;
489  }
490  if (Tidy != nullptr) {
491  std::string TidyDiag = Tidy->getCheckName(Diag.ID);
492  if (!TidyDiag.empty()) {
493  Diag.Name = std::move(TidyDiag);
495  // clang-tidy bakes the name into diagnostic messages. Strip it out.
496  // It would be much nicer to make clang-tidy not do this.
497  auto CleanMessage = [&](std::string &Msg) {
498  StringRef Rest(Msg);
499  if (Rest.consume_back("]") && Rest.consume_back(Diag.Name) &&
500  Rest.consume_back(" ["))
501  Msg.resize(Rest.size());
502  };
503  CleanMessage(Diag.Message);
504  for (auto &Note : Diag.Notes)
505  CleanMessage(Note.Message);
506  for (auto &Fix : Diag.Fixes)
507  CleanMessage(Fix.Message);
508  continue;
509  }
510  }
511  }
512  // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
513  // duplicated messages due to various reasons (e.g. the check doesn't handle
514  // template instantiations well; clang-tidy alias checks).
515  std::set<std::pair<Range, std::string>> SeenDiags;
516  llvm::erase_if(Output, [&](const Diag& D) {
517  return !SeenDiags.emplace(D.Range, D.Message).second;
518  });
519  return std::move(Output);
520 }
521 
522 void StoreDiags::BeginSourceFile(const LangOptions &Opts,
523  const Preprocessor *PP) {
524  LangOpts = Opts;
525  if (PP) {
526  OrigSrcMgr = &PP->getSourceManager();
527  }
528 }
529 
531  flushLastDiag();
532  LangOpts = None;
533  OrigSrcMgr = nullptr;
534 }
535 
536 /// Sanitizes a piece for presenting it in a synthesized fix message. Ensures
537 /// the result is not too large and does not contain newlines.
538 static void writeCodeToFixMessage(llvm::raw_ostream &OS, llvm::StringRef Code) {
539  constexpr unsigned MaxLen = 50;
540 
541  // Only show the first line if there are many.
542  llvm::StringRef R = Code.split('\n').first;
543  // Shorten the message if it's too long.
544  R = R.take_front(MaxLen);
545 
546  OS << R;
547  if (R.size() != Code.size())
548  OS << "…";
549 }
550 
551 /// Fills \p D with all information, except the location-related bits.
552 /// Also note that ID and Name are not part of clangd::DiagBase and should be
553 /// set elsewhere.
554 static void fillNonLocationData(DiagnosticsEngine::Level DiagLevel,
555  const clang::Diagnostic &Info,
556  clangd::DiagBase &D) {
557  llvm::SmallString<64> Message;
558  Info.FormatDiagnostic(Message);
559 
560  D.Message = std::string(Message.str());
561  D.Severity = DiagLevel;
562  D.Category = DiagnosticIDs::getCategoryNameFromID(
563  DiagnosticIDs::getCategoryNumberForDiag(Info.getID()))
564  .str();
565 }
566 
567 void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
568  const clang::Diagnostic &Info) {
569  // If the diagnostic was generated for a different SourceManager, skip it.
570  // This happens when a module is imported and needs to be implicitly built.
571  // The compilation of that module will use the same StoreDiags, but different
572  // SourceManager.
573  if (OrigSrcMgr && Info.hasSourceManager() &&
574  OrigSrcMgr != &Info.getSourceManager()) {
575  IgnoreDiagnostics::log(DiagLevel, Info);
576  return;
577  }
578 
579  DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
580  bool OriginallyError =
581  Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
582  Info.getID());
583 
584  if (Info.getLocation().isInvalid()) {
585  // Handle diagnostics coming from command-line arguments. The source manager
586  // is *not* available at this point, so we cannot use it.
587  if (!OriginallyError) {
588  IgnoreDiagnostics::log(DiagLevel, Info);
589  return; // non-errors add too much noise, do not show them.
590  }
591 
592  flushLastDiag();
593 
594  LastDiag = Diag();
595  LastDiagLoc.reset();
596  LastDiagOriginallyError = OriginallyError;
597  LastDiag->ID = Info.getID();
598  fillNonLocationData(DiagLevel, Info, *LastDiag);
599  LastDiag->InsideMainFile = true;
600  // Put it at the start of the main file, for a lack of a better place.
601  LastDiag->Range.start = Position{0, 0};
602  LastDiag->Range.end = Position{0, 0};
603  return;
604  }
605 
606  if (!LangOpts || !Info.hasSourceManager()) {
607  IgnoreDiagnostics::log(DiagLevel, Info);
608  return;
609  }
610 
611  bool InsideMainFile = isInsideMainFile(Info);
612  SourceManager &SM = Info.getSourceManager();
613 
614  auto FillDiagBase = [&](DiagBase &D) {
615  fillNonLocationData(DiagLevel, Info, D);
616 
617  D.InsideMainFile = InsideMainFile;
618  D.Range = diagnosticRange(Info, *LangOpts);
619  D.File = std::string(SM.getFilename(Info.getLocation()));
621  SM.getFileEntryForID(SM.getFileID(Info.getLocation())), SM);
622  D.ID = Info.getID();
623  return D;
624  };
625 
626  auto AddFix = [&](bool SyntheticMessage) -> bool {
627  assert(!Info.getFixItHints().empty() &&
628  "diagnostic does not have attached fix-its");
629  if (!InsideMainFile)
630  return false;
631 
632  // Copy as we may modify the ranges.
633  auto FixIts = Info.getFixItHints().vec();
634  llvm::SmallVector<TextEdit, 1> Edits;
635  for (auto &FixIt : FixIts) {
636  // Allow fixits within a single macro-arg expansion to be applied.
637  // This can be incorrect if the argument is expanded multiple times in
638  // different contexts. Hopefully this is rare!
639  if (FixIt.RemoveRange.getBegin().isMacroID() &&
640  FixIt.RemoveRange.getEnd().isMacroID() &&
641  SM.getFileID(FixIt.RemoveRange.getBegin()) ==
642  SM.getFileID(FixIt.RemoveRange.getEnd())) {
643  FixIt.RemoveRange = CharSourceRange(
644  {SM.getTopMacroCallerLoc(FixIt.RemoveRange.getBegin()),
645  SM.getTopMacroCallerLoc(FixIt.RemoveRange.getEnd())},
646  FixIt.RemoveRange.isTokenRange());
647  }
648  // Otherwise, follow clang's behavior: no fixits in macros.
649  if (FixIt.RemoveRange.getBegin().isMacroID() ||
650  FixIt.RemoveRange.getEnd().isMacroID())
651  return false;
652  if (!isInsideMainFile(FixIt.RemoveRange.getBegin(), SM))
653  return false;
654  Edits.push_back(toTextEdit(FixIt, SM, *LangOpts));
655  }
656 
657  llvm::SmallString<64> Message;
658  // If requested and possible, create a message like "change 'foo' to 'bar'".
659  if (SyntheticMessage && FixIts.size() == 1) {
660  const auto &FixIt = FixIts.front();
661  bool Invalid = false;
662  llvm::StringRef Remove =
663  Lexer::getSourceText(FixIt.RemoveRange, SM, *LangOpts, &Invalid);
664  llvm::StringRef Insert = FixIt.CodeToInsert;
665  if (!Invalid) {
666  llvm::raw_svector_ostream M(Message);
667  if (!Remove.empty() && !Insert.empty()) {
668  M << "change '";
669  writeCodeToFixMessage(M, Remove);
670  M << "' to '";
671  writeCodeToFixMessage(M, Insert);
672  M << "'";
673  } else if (!Remove.empty()) {
674  M << "remove '";
675  writeCodeToFixMessage(M, Remove);
676  M << "'";
677  } else if (!Insert.empty()) {
678  M << "insert '";
679  writeCodeToFixMessage(M, Insert);
680  M << "'";
681  }
682  // Don't allow source code to inject newlines into diagnostics.
683  std::replace(Message.begin(), Message.end(), '\n', ' ');
684  }
685  }
686  if (Message.empty()) // either !SyntheticMessage, or we failed to make one.
687  Info.FormatDiagnostic(Message);
688  LastDiag->Fixes.push_back(
689  Fix{std::string(Message.str()), std::move(Edits)});
690  return true;
691  };
692 
693  if (!isNote(DiagLevel)) {
694  // Handle the new main diagnostic.
695  flushLastDiag();
696 
697  if (Adjuster) {
698  DiagLevel = Adjuster(DiagLevel, Info);
699  if (DiagLevel == DiagnosticsEngine::Ignored) {
700  LastPrimaryDiagnosticWasSuppressed = true;
701  return;
702  }
703  }
704  LastPrimaryDiagnosticWasSuppressed = false;
705 
706  LastDiag = Diag();
707  FillDiagBase(*LastDiag);
708  LastDiagLoc.emplace(Info.getLocation(), Info.getSourceManager());
709  LastDiagOriginallyError = OriginallyError;
710 
711  if (!Info.getFixItHints().empty())
712  AddFix(true /* try to invent a message instead of repeating the diag */);
713  if (Fixer) {
714  auto ExtraFixes = Fixer(DiagLevel, Info);
715  LastDiag->Fixes.insert(LastDiag->Fixes.end(), ExtraFixes.begin(),
716  ExtraFixes.end());
717  }
718  } else {
719  // Handle a note to an existing diagnostic.
720 
721  // If a diagnostic was suppressed due to the suppression filter,
722  // also suppress notes associated with it.
723  if (LastPrimaryDiagnosticWasSuppressed) {
724  return;
725  }
726 
727  if (!LastDiag) {
728  assert(false && "Adding a note without main diagnostic");
729  IgnoreDiagnostics::log(DiagLevel, Info);
730  return;
731  }
732 
733  if (!Info.getFixItHints().empty()) {
734  // A clang note with fix-it is not a separate diagnostic in clangd. We
735  // attach it as a Fix to the main diagnostic instead.
736  if (!AddFix(false /* use the note as the message */))
737  IgnoreDiagnostics::log(DiagLevel, Info);
738  } else {
739  // A clang note without fix-its corresponds to clangd::Note.
740  Note N;
741  FillDiagBase(N);
742 
743  LastDiag->Notes.push_back(std::move(N));
744  }
745  }
746 }
747 
748 void StoreDiags::flushLastDiag() {
749  if (!LastDiag)
750  return;
751  auto Finish = llvm::make_scope_exit([&, NDiags(Output.size())] {
752  if (Output.size() == NDiags) // No new diag emitted.
753  vlog("Dropped diagnostic: {0}: {1}", LastDiag->File, LastDiag->Message);
754  LastDiag.reset();
755  });
756 
757  if (isExcluded(*LastDiag))
758  return;
759  // Move errors that occur from headers into main file.
760  if (!LastDiag->InsideMainFile && LastDiagLoc && LastDiagOriginallyError) {
761  if (tryMoveToMainFile(*LastDiag, *LastDiagLoc)) {
762  // Suppress multiple errors from the same inclusion.
763  if (!IncludedErrorLocations
764  .insert({LastDiag->Range.start.line,
765  LastDiag->Range.start.character})
766  .second)
767  return;
768  }
769  }
770  if (!mentionsMainFile(*LastDiag))
771  return;
772  Output.push_back(std::move(*LastDiag));
773 }
774 
775 } // namespace clangd
776 } // namespace clang
std::string code
The diagnostic&#39;s code. Can be omitted.
Definition: Protocol.h:816
std::string Code
static void log(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info)
Definition: Compiler.cpp:21
Position start
The range&#39;s start position.
Definition: Protocol.h:178
bool EmbedFixesInDiagnostics
If true, Clangd uses an LSP extension to embed the fixes with the diagnostics that are sent to the cl...
Definition: Diagnostics.h:35
Contains basic information about a diagnostic.
Definition: Diagnostics.h:54
CodeAction toCodeAction(const Fix &F, const URIForFile &File)
Convert from Fix to LSP CodeAction.
llvm::Optional< std::vector< CodeAction > > codeActions
Clangd extension: code actions related to this diagnostic.
Definition: Protocol.h:838
llvm::Optional< std::string > kind
The kind of the code action.
Definition: Protocol.h:959
std::string title
A short, human-readable, title for this code action.
Definition: Protocol.h:955
Location location
The location of this related diagnostic information.
Definition: Protocol.h:800
Represents a related message and source code location for a diagnostic.
Definition: Protocol.h:798
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
Definition: SourceCode.cpp:417
A code action represents a change that can be performed in code, e.g.
Definition: Protocol.h:953
URIForFile uri
The text document&#39;s URI.
Definition: Protocol.h:204
llvm::Optional< WorkspaceEdit > edit
The workspace edit this code action performs.
Definition: Protocol.h:975
Documents should not be synced at all.
SourceLocation Loc
void vlog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:73
std::string Name
Definition: Diagnostics.h:87
static std::string replace(llvm::StringRef Haystack, llvm::StringRef Needle, llvm::StringRef Repl)
Definition: TestIndex.cpp:30
A top-level diagnostic that may have Notes and Fixes.
Definition: Diagnostics.h:86
std::string uri() const
Definition: Protocol.h:98
std::string Message
Message for the fix-it.
Definition: Diagnostics.h:75
std::vector< Fix > Fixes
Alternative fixes for this diagnostic, one should be chosen.
Definition: Diagnostics.h:97
std::string source
A human-readable string describing the source of this diagnostic, e.g.
Definition: Protocol.h:820
llvm::SmallVector< TextEdit, 1 > Edits
TextEdits from clang&#39;s fix-its. Must be non-empty.
Definition: Diagnostics.h:77
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
Definition: SourceCode.cpp:546
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.
int getSeverity(DiagnosticsEngine::Level L)
Convert from clang diagnostic level to LSP severity.
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) override
DiagnosticCallback Diagnostic
llvm::unique_function< void()> Action
llvm::Optional< std::string > category
The diagnostic&#39;s category.
Definition: Protocol.h:833
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:163
clangd::Range Range
Definition: Diagnostics.h:62
DiagnosticsEngine::Level Severity
Definition: Diagnostics.h:63
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition: Protocol.cpp:33
static constexpr llvm::StringLiteral Name
void BeginSourceFile(const LangOptions &Opts, const Preprocessor *PP) override
std::string message
The message of this related diagnostic information.
Definition: Protocol.h:802
Represents a single fix-it that editor can apply to fix the error.
Definition: Diagnostics.h:73
Position Pos
Definition: SourceCode.cpp:650
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
Definition: SourceCode.cpp:216
An information message.
static void fillNonLocationData(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info, clangd::DiagBase &D)
Fills D with all information, except the location-related bits.
enum clang::clangd::Diag::@5 Source
int line
Line position in a document (zero-based).
Definition: Protocol.h:149
int character
Character offset on a line in a document (zero-based).
Definition: Protocol.h:154
std::vector< Note > Notes
Elaborate on the problem, usually pointing to a related piece of code.
Definition: Diagnostics.h:95
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::string message
The diagnostic&#39;s message.
Definition: Protocol.h:823
bool EmitRelatedLocations
If true, Clangd uses the relatedInformation field to include other locations (in particular attached ...
Definition: Diagnostics.h:40
CharSourceRange Range
SourceRange for the file name.
const google::protobuf::Message & M
Definition: Server.cpp:255
static const llvm::StringLiteral QUICKFIX_KIND
Definition: Protocol.h:960
llvm::Optional< std::string > getCanonicalPath(const FileEntry *F, const SourceManager &SourceMgr)
Get the canonical path of F.
Definition: SourceCode.cpp:507
std::string getCheckName(unsigned DiagnosticID) const
Returns the name of the clang-tidy check which produced this diagnostic ID.
int severity
The diagnostic&#39;s severity.
Definition: Protocol.h:813
bool SendDiagnosticCategory
If true, Clangd uses an LSP extension to send the diagnostic&#39;s category to the client.
Definition: Diagnostics.h:46
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void EndSourceFile() override
llvm::Optional< FixItHint > FixIt
Range range
The range at which the message applies.
Definition: Protocol.h:809
static cl::opt< bool > Fix("fix", cl::desc(R"( Apply suggested fixes. Without -fix-errors clang-tidy will bail out if any compilation errors were found. )"), cl::init(false), cl::cat(ClangTidyCategory))
Position end
The range&#39;s end position.
Definition: Protocol.h:181
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
A set of edits generated for a single file.
Definition: SourceCode.h:180
std::vector< Diag > take(const clang::tidy::ClangTidyContext *Tidy=nullptr)
llvm::Optional< std::vector< DiagnosticRelatedInformation > > relatedInformation
An array of related diagnostic information, e.g.
Definition: Protocol.h:827
static void writeCodeToFixMessage(llvm::raw_ostream &OS, llvm::StringRef Code)
Sanitizes a piece for presenting it in a synthesized fix message.
llvm::Optional< std::string > AbsFile
Definition: Diagnostics.h:60
static char ID
Definition: Logger.cpp:74
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:466
llvm::StringRef file() const
Retrieves absolute path to the file.
Definition: Protocol.h:95