TextDiagnosticPrinter.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. //===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This diagnostic client prints out their diagnostic messages.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/TextDiagnosticPrinter.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Frontend/DiagnosticOptions.h"
  17. #include "clang/Frontend/TextDiagnostic.h"
  18. #include "clang/Lex/Lexer.h"
  19. #include "llvm/Support/MemoryBuffer.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include <algorithm>
  24. using namespace clang;
  25. TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
  26. const DiagnosticOptions &diags,
  27. bool _OwnsOutputStream)
  28. : OS(os), LangOpts(0), DiagOpts(&diags), SM(0),
  29. OwnsOutputStream(_OwnsOutputStream) {
  30. }
  31. TextDiagnosticPrinter::~TextDiagnosticPrinter() {
  32. if (OwnsOutputStream)
  33. delete &OS;
  34. }
  35. void TextDiagnosticPrinter::BeginSourceFile(const LangOptions &LO,
  36. const Preprocessor *PP) {
  37. LangOpts = &LO;
  38. }
  39. void TextDiagnosticPrinter::EndSourceFile() {
  40. LangOpts = 0;
  41. TextDiag.reset(0);
  42. }
  43. /// \brief Print the diagnostic name to a raw_ostream.
  44. ///
  45. /// This prints the diagnostic name to a raw_ostream if it has one. It formats
  46. /// the name according to the expected diagnostic message formatting:
  47. /// " [diagnostic_name_here]"
  48. static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
  49. if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
  50. OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
  51. }
  52. /// \brief Print any diagnostic option information to a raw_ostream.
  53. ///
  54. /// This implements all of the logic for adding diagnostic options to a message
  55. /// (via OS). Each relevant option is comma separated and all are enclosed in
  56. /// the standard bracketing: " [...]".
  57. static void printDiagnosticOptions(raw_ostream &OS,
  58. DiagnosticsEngine::Level Level,
  59. const Diagnostic &Info,
  60. const DiagnosticOptions &DiagOpts) {
  61. bool Started = false;
  62. if (DiagOpts.ShowOptionNames) {
  63. // Handle special cases for non-warnings early.
  64. if (Info.getID() == diag::fatal_too_many_errors) {
  65. OS << " [-ferror-limit=]";
  66. return;
  67. }
  68. // The code below is somewhat fragile because we are essentially trying to
  69. // report to the user what happened by inferring what the diagnostic engine
  70. // did. Eventually it might make more sense to have the diagnostic engine
  71. // include some "why" information in the diagnostic.
  72. // If this is a warning which has been mapped to an error by the user (as
  73. // inferred by checking whether the default mapping is to an error) then
  74. // flag it as such. Note that diagnostics could also have been mapped by a
  75. // pragma, but we don't currently have a way to distinguish this.
  76. if (Level == DiagnosticsEngine::Error &&
  77. DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID()) &&
  78. !DiagnosticIDs::isDefaultMappingAsError(Info.getID())) {
  79. OS << " [-Werror";
  80. Started = true;
  81. }
  82. // If the diagnostic is an extension diagnostic and not enabled by default
  83. // then it must have been turned on with -pedantic.
  84. bool EnabledByDefault;
  85. if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
  86. EnabledByDefault) &&
  87. !EnabledByDefault) {
  88. OS << (Started ? "," : " [") << "-pedantic";
  89. Started = true;
  90. }
  91. StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
  92. if (!Opt.empty()) {
  93. OS << (Started ? "," : " [") << "-W" << Opt;
  94. Started = true;
  95. }
  96. }
  97. // If the user wants to see category information, include it too.
  98. if (DiagOpts.ShowCategories) {
  99. unsigned DiagCategory =
  100. DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
  101. if (DiagCategory) {
  102. OS << (Started ? "," : " [");
  103. Started = true;
  104. if (DiagOpts.ShowCategories == 1)
  105. OS << DiagCategory;
  106. else {
  107. assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
  108. OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
  109. }
  110. }
  111. }
  112. if (Started)
  113. OS << ']';
  114. }
  115. void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
  116. const Diagnostic &Info) {
  117. // Default implementation (Warnings/errors count).
  118. DiagnosticConsumer::HandleDiagnostic(Level, Info);
  119. // Render the diagnostic message into a temporary buffer eagerly. We'll use
  120. // this later as we print out the diagnostic to the terminal.
  121. SmallString<100> OutStr;
  122. Info.FormatDiagnostic(OutStr);
  123. llvm::raw_svector_ostream DiagMessageStream(OutStr);
  124. if (DiagOpts->ShowNames)
  125. printDiagnosticName(DiagMessageStream, Info);
  126. printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
  127. // Keeps track of the the starting position of the location
  128. // information (e.g., "foo.c:10:4:") that precedes the error
  129. // message. We use this information to determine how long the
  130. // file+line+column number prefix is.
  131. uint64_t StartOfLocationInfo = OS.tell();
  132. if (!Prefix.empty())
  133. OS << Prefix << ": ";
  134. // Use a dedicated, simpler path for diagnostics without a valid location.
  135. // This is important as if the location is missing, we may be emitting
  136. // diagnostics in a context that lacks language options, a source manager, or
  137. // other infrastructure necessary when emitting more rich diagnostics.
  138. if (!Info.getLocation().isValid()) {
  139. TextDiagnostic::printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
  140. TextDiagnostic::printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
  141. OS.tell() - StartOfLocationInfo,
  142. DiagOpts->MessageLength,
  143. DiagOpts->ShowColors);
  144. OS.flush();
  145. return;
  146. }
  147. // Assert that the rest of our infrastructure is setup properly.
  148. assert(LangOpts && "Unexpected diagnostic outside source file processing");
  149. assert(DiagOpts && "Unexpected diagnostic without options set");
  150. assert(Info.hasSourceManager() &&
  151. "Unexpected diagnostic with no source manager");
  152. // Rebuild the TextDiagnostic utility if missing or the source manager has
  153. // changed.
  154. if (!TextDiag || SM != &Info.getSourceManager()) {
  155. SM = &Info.getSourceManager();
  156. TextDiag.reset(new TextDiagnostic(OS, *SM, *LangOpts, *DiagOpts));
  157. }
  158. TextDiag->emitDiagnostic(Info.getLocation(), Level, DiagMessageStream.str(),
  159. Info.getRanges(),
  160. llvm::makeArrayRef(Info.getFixItHints(),
  161. Info.getNumFixItHints()));
  162. OS.flush();
  163. }
  164. DiagnosticConsumer *
  165. TextDiagnosticPrinter::clone(DiagnosticsEngine &Diags) const {
  166. return new TextDiagnosticPrinter(OS, *DiagOpts, /*OwnsOutputStream=*/false);
  167. }