blob: 4df935bf34f4f239202e29d30e485bb1d360a957 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This diagnostic client prints out their diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000014#include "clang/Frontend/TextDiagnosticPrinter.h"
Axel Naumann04331162011-01-27 10:55:51 +000015#include "clang/Basic/FileManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Basic/SourceManager.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000017#include "clang/Frontend/DiagnosticOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Lex/Lexer.h"
Chris Lattner037fb7f2009-05-05 22:03:18 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattnera03a5b52008-11-19 06:56:25 +000020#include "llvm/Support/raw_ostream.h"
David Blaikie548f6c82011-09-23 05:57:42 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000022#include "llvm/ADT/SmallString.h"
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000023#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Chris Lattner5f9e2722011-07-23 10:55:15 +000026static const enum raw_ostream::Colors noteColor =
27 raw_ostream::BLACK;
28static const enum raw_ostream::Colors fixitColor =
29 raw_ostream::GREEN;
30static const enum raw_ostream::Colors caretColor =
31 raw_ostream::GREEN;
32static const enum raw_ostream::Colors warningColor =
33 raw_ostream::MAGENTA;
34static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
35static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
Daniel Dunbarb96b6702010-02-25 03:23:40 +000036// Used for changing only the bold attribute.
Chris Lattner5f9e2722011-07-23 10:55:15 +000037static const enum raw_ostream::Colors savedColor =
38 raw_ostream::SAVEDCOLOR;
Torok Edwin603fca72009-06-04 07:18:23 +000039
Douglas Gregorfffd93f2009-05-01 21:53:04 +000040/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Chris Lattner5f9e2722011-07-23 10:55:15 +000043TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
Daniel Dunbaraea36412009-11-11 09:38:24 +000044 const DiagnosticOptions &diags,
45 bool _OwnsOutputStream)
Chandler Carruth03efd2e2011-10-15 22:39:16 +000046 : OS(os), LangOpts(0), DiagOpts(&diags), LastLevel(),
Daniel Dunbaraea36412009-11-11 09:38:24 +000047 OwnsOutputStream(_OwnsOutputStream) {
48}
49
50TextDiagnosticPrinter::~TextDiagnosticPrinter() {
51 if (OwnsOutputStream)
52 delete &OS;
Daniel Dunbareace8742009-11-04 06:24:30 +000053}
54
Douglas Gregor47f71772009-05-01 23:32:58 +000055/// \brief When the source code line we want to print is too long for
56/// the terminal, select the "interesting" region.
57static void SelectInterestingSourceRegion(std::string &SourceLine,
58 std::string &CaretLine,
59 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +000060 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +000061 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +000062 unsigned MaxSize = std::max(SourceLine.size(),
63 std::max(CaretLine.size(),
64 FixItInsertionLine.size()));
65 if (MaxSize > SourceLine.size())
66 SourceLine.resize(MaxSize, ' ');
67 if (MaxSize > CaretLine.size())
68 CaretLine.resize(MaxSize, ' ');
69 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
70 FixItInsertionLine.resize(MaxSize, ' ');
71
Douglas Gregor47f71772009-05-01 23:32:58 +000072 // Find the slice that we need to display the full caret line
73 // correctly.
74 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
75 for (; CaretStart != CaretEnd; ++CaretStart)
76 if (!isspace(CaretLine[CaretStart]))
77 break;
78
79 for (; CaretEnd != CaretStart; --CaretEnd)
80 if (!isspace(CaretLine[CaretEnd - 1]))
81 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +000082
83 // Make sure we don't chop the string shorter than the caret token
84 // itself.
85 if (CaretEnd < EndOfCaretToken)
86 CaretEnd = EndOfCaretToken;
87
Douglas Gregor844da342009-05-03 04:33:32 +000088 // If we have a fix-it line, make sure the slice includes all of the
89 // fix-it information.
90 if (!FixItInsertionLine.empty()) {
91 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
92 for (; FixItStart != FixItEnd; ++FixItStart)
93 if (!isspace(FixItInsertionLine[FixItStart]))
94 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000095
Douglas Gregor844da342009-05-03 04:33:32 +000096 for (; FixItEnd != FixItStart; --FixItEnd)
97 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
98 break;
99
100 if (FixItStart < CaretStart)
101 CaretStart = FixItStart;
102 if (FixItEnd > CaretEnd)
103 CaretEnd = FixItEnd;
104 }
105
Douglas Gregor47f71772009-05-01 23:32:58 +0000106 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
107 // parts of the caret line. While this slice is smaller than the
108 // number of columns we have, try to grow the slice to encompass
109 // more context.
110
111 // If the end of the interesting region comes before we run out of
112 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000113 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000114 CaretStart = 0;
115
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000116 unsigned TargetColumns = Columns;
117 if (TargetColumns > 8)
118 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000119 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000120 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000121 bool ExpandedRegion = false;
122 // Move the start of the interesting region left until we've
123 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000124 if (CaretStart == 1)
125 CaretStart = 0;
126 else if (CaretStart > 1) {
127 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000128
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000129 // Skip over any whitespace we see here; we're looking for
130 // another bit of interesting text.
131 while (NewStart && isspace(SourceLine[NewStart]))
132 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000133
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000134 // Skip over this bit of "interesting" text.
135 while (NewStart && !isspace(SourceLine[NewStart]))
136 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000137
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000138 // Move up to the non-whitespace character we just saw.
139 if (NewStart)
140 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000141
142 // If we're still within our limit, update the starting
143 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000144 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000145 CaretStart = NewStart;
146 ExpandedRegion = true;
147 }
148 }
149
150 // Move the end of the interesting region right until we've
151 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000152 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000153 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000154 unsigned NewEnd = CaretEnd;
155
156 // Skip over any whitespace we see here; we're looking for
157 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000158 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000159 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000160
Douglas Gregor47f71772009-05-01 23:32:58 +0000161 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000162 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000163 ++NewEnd;
164
165 if (NewEnd - CaretStart <= TargetColumns) {
166 CaretEnd = NewEnd;
167 ExpandedRegion = true;
168 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000169 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000170
171 if (!ExpandedRegion)
172 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000173 }
174
175 // [CaretStart, CaretEnd) is the slice we want. Update the various
176 // output lines to show only this slice, with two-space padding
177 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000178 if (CaretEnd < SourceLine.size())
179 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000180 if (CaretEnd < CaretLine.size())
181 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000182 if (FixItInsertionLine.size() > CaretEnd)
183 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000184
Douglas Gregor47f71772009-05-01 23:32:58 +0000185 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000186 SourceLine.replace(0, CaretStart, " ...");
187 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000188 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000189 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000190 }
191}
192
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000193/// Look through spelling locations for a macro argument expansion, and
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000194/// if found skip to it so that we can trace the argument rather than the macros
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000195/// in which that argument is used. If no macro argument expansion is found,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000196/// don't skip anything and return the starting location.
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000197static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000198 SourceLocation StartLoc) {
199 for (SourceLocation L = StartLoc; L.isMacroID();
200 L = SM.getImmediateSpellingLoc(L)) {
Chandler Carruth96d35892011-07-26 03:03:00 +0000201 if (SM.isMacroArgExpansion(L))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000202 return L;
203 }
204
205 // Otherwise just return initial location, there's nothing to skip.
206 return StartLoc;
207}
208
209/// Gets the location of the immediate macro caller, one level up the stack
210/// toward the initial macro typed into the source.
211static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
212 SourceLocation Loc) {
213 if (!Loc.isMacroID()) return Loc;
214
215 // When we have the location of (part of) an expanded parameter, its spelling
216 // location points to the argument as typed into the macro call, and
217 // therefore is used to locate the macro caller.
Chandler Carruth96d35892011-07-26 03:03:00 +0000218 if (SM.isMacroArgExpansion(Loc))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000219 return SM.getImmediateSpellingLoc(Loc);
220
221 // Otherwise, the caller of the macro is located where this macro is
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000222 // expanded (while the spelling is part of the macro definition).
Chandler Carruth999f7392011-07-25 20:52:21 +0000223 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000224}
225
226/// Gets the location of the immediate macro callee, one level down the stack
227/// toward the leaf macro.
228static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
229 SourceLocation Loc) {
230 if (!Loc.isMacroID()) return Loc;
231
232 // When we have the location of (part of) an expanded parameter, its
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000233 // expansion location points to the unexpanded paramater reference within
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000234 // the macro definition (or callee).
Chandler Carruth96d35892011-07-26 03:03:00 +0000235 if (SM.isMacroArgExpansion(Loc))
Chandler Carruth999f7392011-07-25 20:52:21 +0000236 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000237
238 // Otherwise, the callee of the macro is located where this location was
239 // spelled inside the macro definition.
240 return SM.getImmediateSpellingLoc(Loc);
241}
242
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000243/// Get the presumed location of a diagnostic message. This computes the
244/// presumed location for the top of any macro backtrace when present.
245static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
246 SourceLocation Loc) {
247 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
248 // walk to the top of the macro call stack.
249 while (Loc.isMacroID()) {
250 Loc = skipToMacroArgExpansion(SM, Loc);
251 Loc = getImmediateMacroCallerLoc(SM, Loc);
252 }
253
254 return SM.getPresumedLoc(Loc);
255}
256
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000257/// \brief Skip over whitespace in the string, starting at the given
258/// index.
259///
260/// \returns The index of the first non-whitespace character that is
261/// greater than or equal to Idx or, if no such character exists,
262/// returns the end of the string.
263static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
264 while (Idx < Length && isspace(Str[Idx]))
265 ++Idx;
266 return Idx;
267}
268
269/// \brief If the given character is the start of some kind of
270/// balanced punctuation (e.g., quotes or parentheses), return the
271/// character that will terminate the punctuation.
272///
273/// \returns The ending punctuation character, if any, or the NULL
274/// character if the input character does not start any punctuation.
275static inline char findMatchingPunctuation(char c) {
276 switch (c) {
277 case '\'': return '\'';
278 case '`': return '\'';
279 case '"': return '"';
280 case '(': return ')';
281 case '[': return ']';
282 case '{': return '}';
283 default: break;
284 }
285
286 return 0;
287}
288
289/// \brief Find the end of the word starting at the given offset
290/// within a string.
291///
292/// \returns the index pointing one character past the end of the
293/// word.
294static unsigned findEndOfWord(unsigned Start, StringRef Str,
295 unsigned Length, unsigned Column,
296 unsigned Columns) {
297 assert(Start < Str.size() && "Invalid start position!");
298 unsigned End = Start + 1;
299
300 // If we are already at the end of the string, take that as the word.
301 if (End == Str.size())
302 return End;
303
304 // Determine if the start of the string is actually opening
305 // punctuation, e.g., a quote or parentheses.
306 char EndPunct = findMatchingPunctuation(Str[Start]);
307 if (!EndPunct) {
308 // This is a normal word. Just find the first space character.
309 while (End < Length && !isspace(Str[End]))
310 ++End;
311 return End;
312 }
313
314 // We have the start of a balanced punctuation sequence (quotes,
315 // parentheses, etc.). Determine the full sequence is.
316 llvm::SmallString<16> PunctuationEndStack;
317 PunctuationEndStack.push_back(EndPunct);
318 while (End < Length && !PunctuationEndStack.empty()) {
319 if (Str[End] == PunctuationEndStack.back())
320 PunctuationEndStack.pop_back();
321 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
322 PunctuationEndStack.push_back(SubEndPunct);
323
324 ++End;
325 }
326
327 // Find the first space character after the punctuation ended.
328 while (End < Length && !isspace(Str[End]))
329 ++End;
330
331 unsigned PunctWordLength = End - Start;
332 if (// If the word fits on this line
333 Column + PunctWordLength <= Columns ||
334 // ... or the word is "short enough" to take up the next line
335 // without too much ugly white space
336 PunctWordLength < Columns/3)
337 return End; // Take the whole thing as a single "word".
338
339 // The whole quoted/parenthesized string is too long to print as a
340 // single "word". Instead, find the "word" that starts just after
341 // the punctuation and use that end-point instead. This will recurse
342 // until it finds something small enough to consider a word.
343 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
344}
345
346/// \brief Print the given string to a stream, word-wrapping it to
347/// some number of columns in the process.
348///
349/// \param OS the stream to which the word-wrapping string will be
350/// emitted.
351/// \param Str the string to word-wrap and output.
352/// \param Columns the number of columns to word-wrap to.
353/// \param Column the column number at which the first character of \p
354/// Str will be printed. This will be non-zero when part of the first
355/// line has already been printed.
356/// \param Indentation the number of spaces to indent any lines beyond
357/// the first line.
358/// \returns true if word-wrapping was required, or false if the
359/// string fit on the first line.
360static bool printWordWrapped(raw_ostream &OS, StringRef Str,
361 unsigned Columns,
362 unsigned Column = 0,
363 unsigned Indentation = WordWrapIndentation) {
364 const unsigned Length = std::min(Str.find('\n'), Str.size());
365
366 // The string used to indent each line.
367 llvm::SmallString<16> IndentStr;
368 IndentStr.assign(Indentation, ' ');
369 bool Wrapped = false;
370 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
371 WordStart = WordEnd) {
372 // Find the beginning of the next word.
373 WordStart = skipWhitespace(WordStart, Str, Length);
374 if (WordStart == Length)
375 break;
376
377 // Find the end of this word.
378 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
379
380 // Does this word fit on the current line?
381 unsigned WordLength = WordEnd - WordStart;
382 if (Column + WordLength < Columns) {
383 // This word fits on the current line; print it there.
384 if (WordStart) {
385 OS << ' ';
386 Column += 1;
387 }
388 OS << Str.substr(WordStart, WordLength);
389 Column += WordLength;
390 continue;
391 }
392
393 // This word does not fit on the current line, so wrap to the next
394 // line.
395 OS << '\n';
396 OS.write(&IndentStr[0], Indentation);
397 OS << Str.substr(WordStart, WordLength);
398 Column = Indentation + WordLength;
399 Wrapped = true;
400 }
401
402 // Append any remaning text from the message with its existing formatting.
403 OS << Str.substr(Length);
404
405 return Wrapped;
406}
407
408static void printDiagnosticMessage(raw_ostream &OS,
409 DiagnosticsEngine::Level Level,
410 StringRef Message,
411 unsigned CurrentColumn, unsigned Columns,
412 bool ShowColors) {
413 if (ShowColors) {
414 // Print warnings, errors and fatal errors in bold, no color
415 switch (Level) {
416 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
417 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
418 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
419 default: break; //don't bold notes
420 }
421 }
422
423 if (Columns)
424 printWordWrapped(OS, Message, Columns, CurrentColumn);
425 else
426 OS << Message;
427
428 if (ShowColors)
429 OS.resetColor();
430 OS << '\n';
431}
432
Chandler Carruth50c909b2011-08-31 23:59:23 +0000433namespace {
434
Chandler Carruth18fc0022011-09-25 22:54:56 +0000435/// \brief Class to encapsulate the logic for formatting and printing a textual
436/// diagnostic message.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000437///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000438/// This class provides an interface for building and emitting a textual
439/// diagnostic, including all of the macro backtraces, caret diagnostics, FixIt
440/// Hints, and code snippets. In the presence of macros this involves
441/// a recursive process, synthesizing notes for each macro expansion.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000442///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000443/// The purpose of this class is to isolate the implementation of printing
444/// beautiful text diagnostics from any particular interfaces. The Clang
445/// DiagnosticClient is implemented through this class as is diagnostic
446/// printing coming out of libclang.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000447///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000448/// A brief worklist:
Chandler Carruth18fc0022011-09-25 22:54:56 +0000449/// FIXME: Sink the recursive printing of template instantiations into this
450/// class.
451class TextDiagnostic {
Chandler Carruth50c909b2011-08-31 23:59:23 +0000452 raw_ostream &OS;
453 const SourceManager &SM;
454 const LangOptions &LangOpts;
455 const DiagnosticOptions &DiagOpts;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000456
Chandler Carruthf54a6142011-10-15 11:44:27 +0000457 /// \brief The location of the previous diagnostic if known.
458 ///
459 /// This will be invalid in cases where there is no (known) previous
460 /// diagnostic location, or that location itself is invalid or comes from
461 /// a different source manager than SM.
462 SourceLocation LastLoc;
463
Chandler Carruthd6140402011-10-15 12:12:44 +0000464 /// \brief The location of the last include whose stack was printed if known.
Chandler Carruthf54a6142011-10-15 11:44:27 +0000465 ///
Chandler Carruthd6140402011-10-15 12:12:44 +0000466 /// Same restriction as \see LastLoc essentially, but tracking include stack
467 /// root locations rather than diagnostic locations.
468 SourceLocation LastIncludeLoc;
Chandler Carruthf54a6142011-10-15 11:44:27 +0000469
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000470 /// \brief The level of the last diagnostic emitted.
471 ///
472 /// The level of the last diagnostic emitted. Used to detect level changes
473 /// which change the amount of information displayed.
474 DiagnosticsEngine::Level LastLevel;
475
Chandler Carruth50c909b2011-08-31 23:59:23 +0000476public:
Chandler Carruth67e2d512011-10-15 12:07:49 +0000477 TextDiagnostic(raw_ostream &OS,
Chandler Carruthf54a6142011-10-15 11:44:27 +0000478 const SourceManager &SM,
479 const LangOptions &LangOpts,
480 const DiagnosticOptions &DiagOpts,
481 FullSourceLoc LastLoc = FullSourceLoc(),
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000482 FullSourceLoc LastIncludeLoc = FullSourceLoc(),
483 DiagnosticsEngine::Level LastLevel
484 = DiagnosticsEngine::Level())
Chandler Carruth67e2d512011-10-15 12:07:49 +0000485 : OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000486 LastLoc(LastLoc), LastIncludeLoc(LastIncludeLoc), LastLevel(LastLevel) {
Chandler Carruthf54a6142011-10-15 11:44:27 +0000487 if (LastLoc.isValid() && &SM != &LastLoc.getManager())
488 this->LastLoc = SourceLocation();
Chandler Carruthd6140402011-10-15 12:12:44 +0000489 if (LastIncludeLoc.isValid() && &SM != &LastIncludeLoc.getManager())
490 this->LastIncludeLoc = SourceLocation();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000491 }
492
Chandler Carruthf54a6142011-10-15 11:44:27 +0000493 /// \brief Get the last diagnostic location emitted.
494 SourceLocation getLastLoc() const { return LastLoc; }
495
Chandler Carruthd6140402011-10-15 12:12:44 +0000496 /// \brief Get the last emitted include stack location.
497 SourceLocation getLastIncludeLoc() const { return LastIncludeLoc; }
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000498
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000499 /// \brief Get the last diagnostic level.
500 DiagnosticsEngine::Level getLastLevel() const { return LastLevel; }
501
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000502 void Emit(SourceLocation Loc, DiagnosticsEngine::Level Level,
503 StringRef Message, ArrayRef<CharSourceRange> Ranges,
504 ArrayRef<FixItHint> FixItHints,
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000505 bool LastCaretDiagnosticWasNote = false) {
506 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
507
508 // First, if this diagnostic is not in the main file, print out the
509 // "included from" lines.
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000510 emitIncludeStack(PLoc.getIncludeLoc(), Level);
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000511
512 uint64_t StartOfLocationInfo = OS.tell();
513
514 // Next emit the location of this particular diagnostic.
Chandler Carruth9ed30662011-10-15 11:09:23 +0000515 EmitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000516
517 if (DiagOpts.ShowColors)
518 OS.resetColor();
519
520 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
521 printDiagnosticMessage(OS, Level, Message,
522 OS.tell() - StartOfLocationInfo,
523 DiagOpts.MessageLength, DiagOpts.ShowColors);
524
525 // If caret diagnostics are enabled and we have location, we want to
526 // emit the caret. However, we only do this if the location moved
527 // from the last diagnostic, if the last diagnostic was a note that
528 // was part of a different warning or error diagnostic, or if the
529 // diagnostic has ranges. We don't want to emit the same caret
530 // multiple times if one loc has multiple diagnostics.
531 if (DiagOpts.ShowCarets &&
532 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000533 (LastLevel == DiagnosticsEngine::Note && Level != LastLevel))) {
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000534 // Get the ranges into a local array we can hack on.
535 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
536 Ranges.end());
537
538 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
539 E = FixItHints.end();
540 I != E; ++I)
541 if (I->RemoveRange.isValid())
542 MutableRanges.push_back(I->RemoveRange);
543
544 unsigned MacroDepth = 0;
545 EmitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
546 }
Chandler Carruthf54a6142011-10-15 11:44:27 +0000547
548 LastLoc = Loc;
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000549 LastLevel = Level;
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000550 }
551
Chandler Carruthd79e4622011-10-15 01:21:55 +0000552 /// \brief Emit the caret and underlining text.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000553 ///
554 /// Walks up the macro expansion stack printing the code snippet, caret,
555 /// underlines and FixItHint display as appropriate at each level. Walk is
556 /// accomplished by calling itself recursively.
557 ///
Chandler Carruthd79e4622011-10-15 01:21:55 +0000558 /// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
559 /// caret diagnostics.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000560 /// FIXME: Break up massive function into logical units.
561 ///
562 /// \param Loc The location for this caret.
563 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000564 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000565 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000566 /// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruthd79e4622011-10-15 01:21:55 +0000567 void EmitCaret(SourceLocation Loc,
Chandler Carruth5182a182011-09-07 01:47:09 +0000568 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000569 ArrayRef<FixItHint> Hints,
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000570 unsigned &MacroDepth,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000571 unsigned OnMacroInst = 0) {
572 assert(!Loc.isInvalid() && "must have a valid source location here");
573
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000574 // If this is a file source location, directly emit the source snippet and
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000575 // caret line. Also record the macro depth reached.
576 if (Loc.isFileID()) {
577 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
578 MacroDepth = OnMacroInst;
579 EmitSnippetAndCaret(Loc, Ranges, Hints);
580 return;
581 }
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000582 // Otherwise recurse through each macro expansion layer.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000583
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000584 // When processing macros, skip over the expansions leading up to
585 // a macro argument, and trace the argument's expansion stack instead.
586 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000587
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000588 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000589
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000590 // FIXME: Map ranges?
Chandler Carruthd79e4622011-10-15 01:21:55 +0000591 EmitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000592
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000593 // Map the location.
594 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000595
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000596 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
597 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
598 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
599 DiagOpts.MacroBacktraceLimit % 2;
600 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
601 }
602
603 // Whether to suppress printing this macro expansion.
604 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
605 OnMacroInst < MacroSkipEnd);
606
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000607 // Map the ranges.
608 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
609 E = Ranges.end();
610 I != E; ++I) {
611 SourceLocation Start = I->getBegin(), End = I->getEnd();
612 if (Start.isMacroID())
613 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
614 if (End.isMacroID())
615 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
616 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000617
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000618 if (!Suppressed) {
619 // Don't print recursive expansion notes from an expansion note.
620 Loc = SM.getSpellingLoc(Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000621
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000622 // Get the pretty name, according to #line directives etc.
623 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
624 if (PLoc.isInvalid())
Chandler Carruth50c909b2011-08-31 23:59:23 +0000625 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000626
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000627 // If this diagnostic is not in the main file, print out the
628 // "included from" lines.
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000629 emitIncludeStack(PLoc.getIncludeLoc(), DiagnosticsEngine::Note);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000630
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000631 if (DiagOpts.ShowLocation) {
632 // Emit the file/line/column that this expansion came from.
633 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
634 if (DiagOpts.ShowColumn)
635 OS << PLoc.getColumn() << ':';
636 OS << ' ';
637 }
638 OS << "note: expanded from:\n";
639
640 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruth50c909b2011-08-31 23:59:23 +0000641 return;
642 }
643
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000644 if (OnMacroInst == MacroSkipStart) {
645 // Tell the user that we've skipped contexts.
646 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
647 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
648 "all)\n";
649 }
650 }
651
652 /// \brief Emit a code snippet and caret line.
653 ///
654 /// This routine emits a single line's code snippet and caret line..
655 ///
656 /// \param Loc The location for the caret.
657 /// \param Ranges The underlined ranges for this code snippet.
658 /// \param Hints The FixIt hints active for this diagnostic.
659 void EmitSnippetAndCaret(SourceLocation Loc,
660 SmallVectorImpl<CharSourceRange>& Ranges,
661 ArrayRef<FixItHint> Hints) {
662 assert(!Loc.isInvalid() && "must have a valid source location here");
663 assert(Loc.isFileID() && "must have a file location here");
664
Chandler Carruth50c909b2011-08-31 23:59:23 +0000665 // Decompose the location into a FID/Offset pair.
666 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
667 FileID FID = LocInfo.first;
668 unsigned FileOffset = LocInfo.second;
669
670 // Get information about the buffer it points into.
671 bool Invalid = false;
672 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
673 if (Invalid)
674 return;
675
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000676 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000677 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
678 unsigned CaretEndColNo
679 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
680
681 // Rewind from the current position to the start of the line.
682 const char *TokPtr = BufStart+FileOffset;
683 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
684
685
686 // Compute the line end. Scan forward from the error position to the end of
687 // the line.
688 const char *LineEnd = TokPtr;
689 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
690 ++LineEnd;
691
692 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
693 // the source line length as currently being computed. See
694 // test/Misc/message-length.c.
695 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
696
697 // Copy the line of code into an std::string for ease of manipulation.
698 std::string SourceLine(LineStart, LineEnd);
699
700 // Create a line for the caret that is filled with spaces that is the same
701 // length as the line of source code.
702 std::string CaretLine(LineEnd-LineStart, ' ');
703
704 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000705 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
706 E = Ranges.end();
707 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000708 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000709
710 // Next, insert the caret itself.
711 if (ColNo-1 < CaretLine.size())
712 CaretLine[ColNo-1] = '^';
713 else
714 CaretLine.push_back('^');
715
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000716 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000717
718 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
719 // to produce easily machine parsable output. Add a space before the
720 // source line and the caret to make it trivial to tell the main diagnostic
721 // line from what the user is intended to see.
722 if (DiagOpts.ShowSourceRanges) {
723 SourceLine = ' ' + SourceLine;
724 CaretLine = ' ' + CaretLine;
725 }
726
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000727 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000728 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000729 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000730
731 // If the source line is too long for our terminal, select only the
732 // "interesting" source region within that line.
Chandler Carruth8be5c152011-09-25 22:31:58 +0000733 unsigned Columns = DiagOpts.MessageLength;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000734 if (Columns && SourceLine.size() > Columns)
735 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
736 CaretEndColNo, Columns);
737
738 // Finally, remove any blank spaces from the end of CaretLine.
739 while (CaretLine[CaretLine.size()-1] == ' ')
740 CaretLine.erase(CaretLine.end()-1);
741
742 // Emit what we have computed.
743 OS << SourceLine << '\n';
744
745 if (DiagOpts.ShowColors)
746 OS.changeColor(caretColor, true);
747 OS << CaretLine << '\n';
748 if (DiagOpts.ShowColors)
749 OS.resetColor();
750
751 if (!FixItInsertionLine.empty()) {
752 if (DiagOpts.ShowColors)
753 // Print fixit line in color
754 OS.changeColor(fixitColor, false);
755 if (DiagOpts.ShowSourceRanges)
756 OS << ' ';
757 OS << FixItInsertionLine << '\n';
758 if (DiagOpts.ShowColors)
759 OS.resetColor();
760 }
761
Chandler Carruthcca61582011-09-02 06:30:30 +0000762 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000763 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000764 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000765
Chandler Carruth7eb84dc2011-10-15 22:49:21 +0000766 /// \brief Print the diagonstic level to a raw_ostream.
767 ///
768 /// This is a static helper that handles colorizing the level and formatting
769 /// it into an arbitrary output stream. This is used internally by the
770 /// TextDiagnostic emission code, but it can also be used directly by
771 /// consumers that don't have a source manager or other state that the full
772 /// TextDiagnostic logic requires.
773 static void printDiagnosticLevel(raw_ostream &OS,
774 DiagnosticsEngine::Level Level,
775 bool ShowColors) {
776 if (ShowColors) {
777 // Print diagnostic category in bold and color
778 switch (Level) {
779 case DiagnosticsEngine::Ignored:
780 llvm_unreachable("Invalid diagnostic type");
781 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
782 case DiagnosticsEngine::Warning:
783 OS.changeColor(warningColor, true);
784 break;
785 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
786 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
787 }
788 }
789
790 switch (Level) {
791 case DiagnosticsEngine::Ignored:
792 llvm_unreachable("Invalid diagnostic type");
793 case DiagnosticsEngine::Note: OS << "note: "; break;
794 case DiagnosticsEngine::Warning: OS << "warning: "; break;
795 case DiagnosticsEngine::Error: OS << "error: "; break;
796 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
797 }
798
799 if (ShowColors)
800 OS.resetColor();
801 }
802
Chandler Carruthcca61582011-09-02 06:30:30 +0000803private:
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000804 /// \brief Prints an include stack when appropriate for a particular
805 /// diagnostic level and location.
806 ///
807 /// This routine handles all the logic of suppressing particular include
808 /// stacks (such as those for notes) and duplicate include stacks when
809 /// repeated warnings occur within the same file. It also handles the logic
810 /// of customizing the formatting and display of the include stack.
811 ///
812 /// \param Level The diagnostic level of the message this stack pertains to.
813 /// \param Loc The include location of the current file (not the diagnostic
814 /// location).
815 void emitIncludeStack(SourceLocation Loc, DiagnosticsEngine::Level Level) {
816 // Skip redundant include stacks altogether.
Chandler Carruthd6140402011-10-15 12:12:44 +0000817 if (LastIncludeLoc == Loc)
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000818 return;
Chandler Carruthd6140402011-10-15 12:12:44 +0000819 LastIncludeLoc = Loc;
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000820
821 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
822 return;
823
824 emitIncludeStackRecursively(Loc);
825 }
826
827 /// \brief Helper to recursivly walk up the include stack and print each layer
828 /// on the way back down.
829 void emitIncludeStackRecursively(SourceLocation Loc) {
830 if (Loc.isInvalid())
831 return;
832
833 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
834 if (PLoc.isInvalid())
835 return;
836
837 // Emit the other include frames first.
838 emitIncludeStackRecursively(PLoc.getIncludeLoc());
839
840 if (DiagOpts.ShowLocation)
841 OS << "In file included from " << PLoc.getFilename()
842 << ':' << PLoc.getLine() << ":\n";
843 else
844 OS << "In included file:\n";
845 }
846
Chandler Carruth9ed30662011-10-15 11:09:23 +0000847 /// \brief Print out the file/line/column information and include trace.
848 ///
849 /// This method handlen the emission of the diagnostic location information.
850 /// This includes extracting as much location information as is present for
851 /// the diagnostic and printing it, as well as any include stack or source
852 /// ranges necessary.
853 void EmitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
854 DiagnosticsEngine::Level Level,
855 ArrayRef<CharSourceRange> Ranges) {
856 if (PLoc.isInvalid()) {
857 // At least print the file name if available:
858 FileID FID = SM.getFileID(Loc);
859 if (!FID.isInvalid()) {
860 const FileEntry* FE = SM.getFileEntryForID(FID);
861 if (FE && FE->getName()) {
862 OS << FE->getName();
863 if (FE->getDevice() == 0 && FE->getInode() == 0
864 && FE->getFileMode() == 0) {
865 // in PCH is a guess, but a good one:
866 OS << " (in PCH)";
867 }
868 OS << ": ";
869 }
870 }
871 return;
872 }
873 unsigned LineNo = PLoc.getLine();
874
875 if (!DiagOpts.ShowLocation)
876 return;
877
878 if (DiagOpts.ShowColors)
879 OS.changeColor(savedColor, true);
880
881 OS << PLoc.getFilename();
882 switch (DiagOpts.Format) {
883 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
884 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
885 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
886 }
887
888 if (DiagOpts.ShowColumn)
889 // Compute the column number.
890 if (unsigned ColNo = PLoc.getColumn()) {
891 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
892 OS << ',';
893 ColNo--;
894 } else
895 OS << ':';
896 OS << ColNo;
897 }
898 switch (DiagOpts.Format) {
899 case DiagnosticOptions::Clang:
900 case DiagnosticOptions::Vi: OS << ':'; break;
901 case DiagnosticOptions::Msvc: OS << ") : "; break;
902 }
903
904 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
905 FileID CaretFileID =
906 SM.getFileID(SM.getExpansionLoc(Loc));
907 bool PrintedRange = false;
908
909 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
910 RE = Ranges.end();
911 RI != RE; ++RI) {
912 // Ignore invalid ranges.
913 if (!RI->isValid()) continue;
914
915 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
916 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
917
918 // If the End location and the start location are the same and are a
919 // macro location, then the range was something that came from a
920 // macro expansion or _Pragma. If this is an object-like macro, the
921 // best we can do is to highlight the range. If this is a
922 // function-like macro, we'd also like to highlight the arguments.
923 if (B == E && RI->getEnd().isMacroID())
924 E = SM.getExpansionRange(RI->getEnd()).second;
925
926 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
927 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
928
929 // If the start or end of the range is in another file, just discard
930 // it.
931 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
932 continue;
933
934 // Add in the length of the token, so that we cover multi-char
935 // tokens.
936 unsigned TokSize = 0;
937 if (RI->isTokenRange())
938 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
939
940 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
941 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
942 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
943 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
944 << '}';
945 PrintedRange = true;
946 }
947
948 if (PrintedRange)
949 OS << ':';
950 }
951 OS << ' ';
952 }
953
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000954 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
955 void HighlightRange(const CharSourceRange &R,
956 unsigned LineNo, FileID FID,
957 const std::string &SourceLine,
958 std::string &CaretLine) {
959 assert(CaretLine.size() == SourceLine.size() &&
960 "Expect a correspondence between source and caret line!");
961 if (!R.isValid()) return;
962
963 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
964 SourceLocation End = SM.getExpansionLoc(R.getEnd());
965
966 // If the End location and the start location are the same and are a macro
967 // location, then the range was something that came from a macro expansion
968 // or _Pragma. If this is an object-like macro, the best we can do is to
969 // highlight the range. If this is a function-like macro, we'd also like to
970 // highlight the arguments.
971 if (Begin == End && R.getEnd().isMacroID())
972 End = SM.getExpansionRange(R.getEnd()).second;
973
974 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
975 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
976 return; // No intersection.
977
978 unsigned EndLineNo = SM.getExpansionLineNumber(End);
979 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
980 return; // No intersection.
981
982 // Compute the column number of the start.
983 unsigned StartColNo = 0;
984 if (StartLineNo == LineNo) {
985 StartColNo = SM.getExpansionColumnNumber(Begin);
986 if (StartColNo) --StartColNo; // Zero base the col #.
987 }
988
989 // Compute the column number of the end.
990 unsigned EndColNo = CaretLine.size();
991 if (EndLineNo == LineNo) {
992 EndColNo = SM.getExpansionColumnNumber(End);
993 if (EndColNo) {
994 --EndColNo; // Zero base the col #.
995
996 // Add in the length of the token, so that we cover multi-char tokens if
997 // this is a token range.
998 if (R.isTokenRange())
999 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1000 } else {
1001 EndColNo = CaretLine.size();
1002 }
1003 }
1004
1005 assert(StartColNo <= EndColNo && "Invalid range!");
1006
1007 // Check that a token range does not highlight only whitespace.
1008 if (R.isTokenRange()) {
1009 // Pick the first non-whitespace column.
1010 while (StartColNo < SourceLine.size() &&
1011 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
1012 ++StartColNo;
1013
1014 // Pick the last non-whitespace column.
1015 if (EndColNo > SourceLine.size())
1016 EndColNo = SourceLine.size();
1017 while (EndColNo-1 &&
1018 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
1019 --EndColNo;
1020
1021 // If the start/end passed each other, then we are trying to highlight a
1022 // range that just exists in whitespace, which must be some sort of other
1023 // bug.
1024 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1025 }
1026
1027 // Fill the range with ~'s.
1028 for (unsigned i = StartColNo; i < EndColNo; ++i)
1029 CaretLine[i] = '~';
1030 }
1031
Chandler Carruth0580e7d2011-09-07 05:01:10 +00001032 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +00001033 const char *LineStart,
1034 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001035 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +00001036 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001037 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +00001038 return FixItInsertionLine;
1039
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001040 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1041 I != E; ++I) {
1042 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +00001043 // We have an insertion hint. Determine whether the inserted
1044 // code is on the same line as the caret.
1045 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001046 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +00001047 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +00001048 // Insert the new code into the line just below the code
1049 // that the user wrote.
1050 unsigned HintColNo
1051 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
1052 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001053 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +00001054 if (LastColumnModified > FixItInsertionLine.size())
1055 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001056 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +00001057 FixItInsertionLine.begin() + HintColNo - 1);
1058 } else {
1059 FixItInsertionLine.clear();
1060 break;
1061 }
1062 }
1063 }
1064
1065 if (FixItInsertionLine.empty())
1066 return FixItInsertionLine;
1067
1068 // Now that we have the entire fixit line, expand the tabs in it.
1069 // Since we don't want to insert spaces in the middle of a word,
1070 // find each word and the column it should line up with and insert
1071 // spaces until they match.
1072 unsigned FixItPos = 0;
1073 unsigned LinePos = 0;
1074 unsigned TabExpandedCol = 0;
1075 unsigned LineLength = LineEnd - LineStart;
1076
1077 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
1078 // Find the next word in the FixIt line.
1079 while (FixItPos < FixItInsertionLine.size() &&
1080 FixItInsertionLine[FixItPos] == ' ')
1081 ++FixItPos;
1082 unsigned CharDistance = FixItPos - TabExpandedCol;
1083
1084 // Walk forward in the source line, keeping track of
1085 // the tab-expanded column.
1086 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
1087 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
1088 ++TabExpandedCol;
1089 else
1090 TabExpandedCol =
1091 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
1092
1093 // Adjust the fixit line to match this column.
1094 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
1095 FixItPos = TabExpandedCol;
1096
1097 // Walk to the end of the word.
1098 while (FixItPos < FixItInsertionLine.size() &&
1099 FixItInsertionLine[FixItPos] != ' ')
1100 ++FixItPos;
1101 }
1102
1103 return FixItInsertionLine;
1104 }
1105
Chandler Carruthd2156fc2011-09-07 05:36:50 +00001106 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
1107 // Scan the source line, looking for tabs. If we find any, manually expand
1108 // them to spaces and update the CaretLine to match.
1109 for (unsigned i = 0; i != SourceLine.size(); ++i) {
1110 if (SourceLine[i] != '\t') continue;
1111
1112 // Replace this tab with at least one space.
1113 SourceLine[i] = ' ';
1114
1115 // Compute the number of spaces we need to insert.
1116 unsigned TabStop = DiagOpts.TabStop;
1117 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1118 "Invalid -ftabstop value");
1119 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
1120 assert(NumSpaces < TabStop && "Invalid computation of space amt");
1121
1122 // Insert spaces into the SourceLine.
1123 SourceLine.insert(i+1, NumSpaces, ' ');
1124
1125 // Insert spaces or ~'s into CaretLine.
1126 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
1127 }
1128 }
1129
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001130 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +00001131 if (!DiagOpts.ShowParseableFixits)
1132 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +00001133
Chandler Carruthcca61582011-09-02 06:30:30 +00001134 // We follow FixItRewriter's example in not (yet) handling
1135 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001136 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1137 I != E; ++I) {
1138 if (I->RemoveRange.isInvalid() ||
1139 I->RemoveRange.getBegin().isMacroID() ||
1140 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +00001141 return;
1142 }
Chandler Carruth50c909b2011-08-31 23:59:23 +00001143
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001144 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1145 I != E; ++I) {
1146 SourceLocation BLoc = I->RemoveRange.getBegin();
1147 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +00001148
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001149 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1150 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +00001151
Chandler Carruthcca61582011-09-02 06:30:30 +00001152 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001153 if (I->RemoveRange.isTokenRange())
1154 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +00001155
Chandler Carruthcca61582011-09-02 06:30:30 +00001156 // We specifically do not do word-wrapping or tab-expansion here,
1157 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001158 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +00001159 if (PLoc.isInvalid())
1160 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +00001161
Chandler Carruthcca61582011-09-02 06:30:30 +00001162 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +00001163 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +00001164 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1165 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1166 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1167 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1168 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001169 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +00001170 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +00001171 }
1172 }
1173};
1174
1175} // end namespace
1176
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +00001177/// \brief Print the diagnostic name to a raw_ostream.
1178///
1179/// This prints the diagnostic name to a raw_ostream if it has one. It formats
1180/// the name according to the expected diagnostic message formatting:
1181/// " [diagnostic_name_here]"
1182static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
Chandler Carruth76145782011-09-26 00:37:30 +00001183 if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
1184 OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
1185}
1186
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +00001187/// \brief Print any diagnostic option information to a raw_ostream.
1188///
1189/// This implements all of the logic for adding diagnostic options to a message
1190/// (via OS). Each relevant option is comma separated and all are enclosed in
1191/// the standard bracketing: " [...]".
1192static void printDiagnosticOptions(raw_ostream &OS,
Chandler Carruth53a529e2011-09-26 00:44:09 +00001193 DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +00001194 const Diagnostic &Info,
Chandler Carruth53a529e2011-09-26 00:44:09 +00001195 const DiagnosticOptions &DiagOpts) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001196 bool Started = false;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001197 if (DiagOpts.ShowOptionNames) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001198 // Handle special cases for non-warnings early.
1199 if (Info.getID() == diag::fatal_too_many_errors) {
1200 OS << " [-ferror-limit=]";
1201 return;
1202 }
1203
Daniel Dunbar76101cf2011-09-29 01:01:08 +00001204 // The code below is somewhat fragile because we are essentially trying to
1205 // report to the user what happened by inferring what the diagnostic engine
1206 // did. Eventually it might make more sense to have the diagnostic engine
1207 // include some "why" information in the diagnostic.
1208
1209 // If this is a warning which has been mapped to an error by the user (as
1210 // inferred by checking whether the default mapping is to an error) then
1211 // flag it as such. Note that diagnostics could also have been mapped by a
1212 // pragma, but we don't currently have a way to distinguish this.
Chandler Carruth53a529e2011-09-26 00:44:09 +00001213 if (Level == DiagnosticsEngine::Error &&
Daniel Dunbar76101cf2011-09-29 01:01:08 +00001214 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID()) &&
1215 !DiagnosticIDs::isDefaultMappingAsError(Info.getID())) {
1216 OS << " [-Werror";
1217 Started = true;
Chandler Carruth253d41d2011-09-26 01:21:58 +00001218 }
1219
1220 // If the diagnostic is an extension diagnostic and not enabled by default
1221 // then it must have been turned on with -pedantic.
1222 bool EnabledByDefault;
1223 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1224 EnabledByDefault) &&
1225 !EnabledByDefault) {
1226 OS << (Started ? "," : " [") << "-pedantic";
1227 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001228 }
1229
1230 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
1231 if (!Opt.empty()) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001232 OS << (Started ? "," : " [") << "-W" << Opt;
1233 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001234 }
1235 }
Chandler Carruth53a529e2011-09-26 00:44:09 +00001236
Chandler Carruth253d41d2011-09-26 01:21:58 +00001237 // If the user wants to see category information, include it too.
1238 if (DiagOpts.ShowCategories) {
1239 unsigned DiagCategory =
1240 DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Chandler Carruth53a529e2011-09-26 00:44:09 +00001241 if (DiagCategory) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001242 OS << (Started ? "," : " [");
Benjamin Kramera65cb0c2011-09-26 02:14:13 +00001243 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001244 if (DiagOpts.ShowCategories == 1)
Benjamin Kramera65cb0c2011-09-26 02:14:13 +00001245 OS << DiagCategory;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001246 else {
1247 assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
1248 OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
1249 }
1250 }
Chandler Carruth53a529e2011-09-26 00:44:09 +00001251 }
Benjamin Kramera65cb0c2011-09-26 02:14:13 +00001252 if (Started)
1253 OS << ']';
Chandler Carruth53a529e2011-09-26 00:44:09 +00001254}
1255
Chandler Carrutha6290042011-09-26 00:26:47 +00001256void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +00001257 const Diagnostic &Info) {
Chandler Carrutha6290042011-09-26 00:26:47 +00001258 // Default implementation (Warnings/errors count).
1259 DiagnosticConsumer::HandleDiagnostic(Level, Info);
1260
Chandler Carruth0ef89882011-09-26 11:25:30 +00001261 // Render the diagnostic message into a temporary buffer eagerly. We'll use
1262 // this later as we print out the diagnostic to the terminal.
1263 llvm::SmallString<100> OutStr;
1264 Info.FormatDiagnostic(OutStr);
1265
1266 llvm::raw_svector_ostream DiagMessageStream(OutStr);
1267 if (DiagOpts->ShowNames)
1268 printDiagnosticName(DiagMessageStream, Info);
1269 printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
1270
Chandler Carrutha6290042011-09-26 00:26:47 +00001271 // Keeps track of the the starting position of the location
1272 // information (e.g., "foo.c:10:4:") that precedes the error
1273 // message. We use this information to determine how long the
1274 // file+line+column number prefix is.
1275 uint64_t StartOfLocationInfo = OS.tell();
1276
1277 if (!Prefix.empty())
1278 OS << Prefix << ": ";
1279
Chandler Carruth0ef89882011-09-26 11:25:30 +00001280 // Use a dedicated, simpler path for diagnostics without a valid location.
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001281 // This is important as if the location is missing, we may be emitting
1282 // diagnostics in a context that lacks language options, a source manager, or
1283 // other infrastructure necessary when emitting more rich diagnostics.
Chandler Carruth0ef89882011-09-26 11:25:30 +00001284 if (!Info.getLocation().isValid()) {
Chandler Carruth7eb84dc2011-10-15 22:49:21 +00001285 TextDiagnostic::printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
Chandler Carruth0ef89882011-09-26 11:25:30 +00001286 printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1287 OS.tell() - StartOfLocationInfo,
1288 DiagOpts->MessageLength, DiagOpts->ShowColors);
1289 OS.flush();
1290 return;
Chandler Carrutha6290042011-09-26 00:26:47 +00001291 }
1292
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001293 // Assert that the rest of our infrastructure is setup properly.
1294 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1295 assert(DiagOpts && "Unexpected diagnostic without options set");
1296 assert(Info.hasSourceManager() &&
1297 "Unexpected diagnostic with no source manager");
Chandler Carruth0ef89882011-09-26 11:25:30 +00001298 const SourceManager &SM = Info.getSourceManager();
Chandler Carruth67e2d512011-10-15 12:07:49 +00001299 TextDiagnostic TextDiag(OS, SM, *LangOpts, *DiagOpts,
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001300 LastLoc, LastIncludeLoc, LastLevel);
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001301
Chandler Carruth60e4a2a2011-10-15 11:09:19 +00001302 TextDiag.Emit(Info.getLocation(), Level, DiagMessageStream.str(),
1303 Info.getRanges(),
1304 llvm::makeArrayRef(Info.getFixItHints(),
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001305 Info.getNumFixItHints()));
Chandler Carruth0ef89882011-09-26 11:25:30 +00001306
Chandler Carruthf54a6142011-10-15 11:44:27 +00001307 // Cache the LastLoc from the TextDiagnostic printing.
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001308 // FIXME: Rather than this, we should persist a TextDiagnostic object across
1309 // diagnostics until the SourceManager changes. That will allow the
1310 // TextDiagnostic object to form a 'session' of output where we can
1311 // reasonably collapse redundant information.
Chandler Carruthf54a6142011-10-15 11:44:27 +00001312 LastLoc = FullSourceLoc(TextDiag.getLastLoc(), SM);
Chandler Carruthd6140402011-10-15 12:12:44 +00001313 LastIncludeLoc = FullSourceLoc(TextDiag.getLastIncludeLoc(), SM);
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001314 LastLevel = TextDiag.getLastLevel();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001315
Chris Lattnera03a5b52008-11-19 06:56:25 +00001316 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001317}
Douglas Gregoraee526e2011-09-29 00:38:00 +00001318
1319DiagnosticConsumer *
1320TextDiagnosticPrinter::clone(DiagnosticsEngine &Diags) const {
1321 return new TextDiagnosticPrinter(OS, *DiagOpts, /*OwnsOutputStream=*/false);
1322}