clang  6.0.0svn
TextDiagnosticPrinter.cpp
Go to the documentation of this file.
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 
18 #include "clang/Lex/Lexer.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <algorithm>
23 using namespace clang;
24 
26  DiagnosticOptions *diags,
27  bool _OwnsOutputStream)
28  : OS(os), DiagOpts(diags),
29  OwnsOutputStream(_OwnsOutputStream) {
30 }
31 
33  if (OwnsOutputStream)
34  delete &OS;
35 }
36 
38  const Preprocessor *PP) {
39  // Build the TextDiagnostic utility.
40  TextDiag.reset(new TextDiagnostic(OS, LO, &*DiagOpts));
41 }
42 
44  TextDiag.reset();
45 }
46 
47 /// \brief Print any diagnostic option information to a raw_ostream.
48 ///
49 /// This implements all of the logic for adding diagnostic options to a message
50 /// (via OS). Each relevant option is comma separated and all are enclosed in
51 /// the standard bracketing: " [...]".
52 static void printDiagnosticOptions(raw_ostream &OS,
54  const Diagnostic &Info,
55  const DiagnosticOptions &DiagOpts) {
56  bool Started = false;
57  if (DiagOpts.ShowOptionNames) {
58  // Handle special cases for non-warnings early.
59  if (Info.getID() == diag::fatal_too_many_errors) {
60  OS << " [-ferror-limit=]";
61  return;
62  }
63 
64  // The code below is somewhat fragile because we are essentially trying to
65  // report to the user what happened by inferring what the diagnostic engine
66  // did. Eventually it might make more sense to have the diagnostic engine
67  // include some "why" information in the diagnostic.
68 
69  // If this is a warning which has been mapped to an error by the user (as
70  // inferred by checking whether the default mapping is to an error) then
71  // flag it as such. Note that diagnostics could also have been mapped by a
72  // pragma, but we don't currently have a way to distinguish this.
73  if (Level == DiagnosticsEngine::Error &&
76  OS << " [-Werror";
77  Started = true;
78  }
79 
80  StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
81  if (!Opt.empty()) {
82  OS << (Started ? "," : " [")
83  << (Level == DiagnosticsEngine::Remark ? "-R" : "-W") << Opt;
84  StringRef OptValue = Info.getDiags()->getFlagValue();
85  if (!OptValue.empty())
86  OS << "=" << OptValue;
87  Started = true;
88  }
89  }
90 
91  // If the user wants to see category information, include it too.
92  if (DiagOpts.ShowCategories) {
93  unsigned DiagCategory =
95  if (DiagCategory) {
96  OS << (Started ? "," : " [");
97  Started = true;
98  if (DiagOpts.ShowCategories == 1)
99  OS << DiagCategory;
100  else {
101  assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
102  OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
103  }
104  }
105  }
106  if (Started)
107  OS << ']';
108 }
109 
111  const Diagnostic &Info) {
112  // Default implementation (Warnings/errors count).
114 
115  // Render the diagnostic message into a temporary buffer eagerly. We'll use
116  // this later as we print out the diagnostic to the terminal.
117  SmallString<100> OutStr;
118  Info.FormatDiagnostic(OutStr);
119 
120  llvm::raw_svector_ostream DiagMessageStream(OutStr);
121  printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
122 
123  // Keeps track of the starting position of the location
124  // information (e.g., "foo.c:10:4:") that precedes the error
125  // message. We use this information to determine how long the
126  // file+line+column number prefix is.
127  uint64_t StartOfLocationInfo = OS.tell();
128 
129  if (!Prefix.empty())
130  OS << Prefix << ": ";
131 
132  // Use a dedicated, simpler path for diagnostics without a valid location.
133  // This is important as if the location is missing, we may be emitting
134  // diagnostics in a context that lacks language options, a source manager, or
135  // other infrastructure necessary when emitting more rich diagnostics.
136  if (!Info.getLocation().isValid()) {
137  TextDiagnostic::printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
138  DiagOpts->CLFallbackMode);
139  TextDiagnostic::printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
140  OS.tell() - StartOfLocationInfo,
141  DiagOpts->MessageLength,
142  DiagOpts->ShowColors);
143  OS.flush();
144  return;
145  }
146 
147  // Assert that the rest of our infrastructure is setup properly.
148  assert(DiagOpts && "Unexpected diagnostic without options set");
149  assert(Info.hasSourceManager() &&
150  "Unexpected diagnostic with no source manager");
151  assert(TextDiag && "Unexpected diagnostic outside source file processing");
152 
153  TextDiag->emitDiagnostic(
154  FullSourceLoc(Info.getLocation(), Info.getSourceManager()), Level,
155  DiagMessageStream.str(), Info.getRanges(), Info.getFixItHints());
156 
157  OS.flush();
158 }
static unsigned getCategoryNumberForDiag(unsigned DiagID)
Return the category number that a specified DiagID belongs to, or 0 if no category.
Defines the SourceManager interface.
static StringRef getCategoryNameFromID(unsigned CategoryID)
Given a category ID, return the name of the category.
bool hasSourceManager() const
Definition: Diagnostic.h:1239
unsigned getID() const
Definition: Diagnostic.h:1237
const DiagnosticsEngine * getDiags() const
Definition: Diagnostic.h:1236
Class to encapsulate the logic for formatting and printing a textual diagnostic message.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
StringRef getFlagValue() const
Return the value associated with this diagnostic flag.
Definition: Diagnostic.h:797
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1238
void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override
Callback to inform the diagnostic client that processing of a source file is beginning.
static bool isBuiltinWarningOrExtension(unsigned DiagID)
Return true if the unmapped diagnostic levelof the specified diagnostic ID is a Warning or Extension...
static void printDiagnosticOptions(raw_ostream &OS, DiagnosticsEngine::Level Level, const Diagnostic &Info, const DiagnosticOptions &DiagOpts)
Print any diagnostic option information to a raw_ostream.
void HandleDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info) override
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
static StringRef getWarningOptionForDiag(unsigned DiagID)
Return the lowest-level warning option that enables the specified diagnostic.
void EndSourceFile() override
Callback to inform the diagnostic client that processing of a source file has ended.
Options for controlling the compiler diagnostics engine.
static void printDiagnosticLevel(raw_ostream &OS, DiagnosticsEngine::Level Level, bool ShowColors, bool CLFallbackMode=false)
Print the diagonstic level to a raw_ostream.
static void printDiagnosticMessage(raw_ostream &OS, bool IsSupplemental, StringRef Message, unsigned CurrentColumn, unsigned Columns, bool ShowColors)
Pretty-print a diagnostic message to a raw_ostream.
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
Definition: Diagnostic.cpp:435
SourceManager & getSourceManager() const
Definition: Diagnostic.h:1240
TextDiagnosticPrinter(raw_ostream &os, DiagnosticOptions *diags, bool OwnsOutputStream=false)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
static bool isDefaultMappingAsError(unsigned DiagID)
Return true if the specified diagnostic is mapped to errors by default.
ArrayRef< CharSourceRange > getRanges() const
Return an array reference for this diagnostic&#39;s ranges.
Definition: Diagnostic.h:1315
ArrayRef< FixItHint > getFixItHints() const
Definition: Diagnostic.h:1328
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:150
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1227
A SourceLocation and its associated SourceManager.
void FormatDiagnostic(SmallVectorImpl< char > &OutStr) const
Format this diagnostic into a string, substituting the formal arguments into the %0 slots...
Definition: Diagnostic.cpp:667
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127