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