blob: 9ae368c6c9e61b32674ccf1d6acac135a14a4b85 [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
Chandler Carruth50c909b2011-08-31 23:59:23 +0000408namespace {
409
Chandler Carruth18fc0022011-09-25 22:54:56 +0000410/// \brief Class to encapsulate the logic for formatting and printing a textual
411/// diagnostic message.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000412///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000413/// This class provides an interface for building and emitting a textual
414/// diagnostic, including all of the macro backtraces, caret diagnostics, FixIt
415/// Hints, and code snippets. In the presence of macros this involves
416/// a recursive process, synthesizing notes for each macro expansion.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000417///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000418/// The purpose of this class is to isolate the implementation of printing
419/// beautiful text diagnostics from any particular interfaces. The Clang
420/// DiagnosticClient is implemented through this class as is diagnostic
421/// printing coming out of libclang.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000422///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000423/// A brief worklist:
Chandler Carruth18fc0022011-09-25 22:54:56 +0000424/// FIXME: Sink the recursive printing of template instantiations into this
425/// class.
426class TextDiagnostic {
Chandler Carruth50c909b2011-08-31 23:59:23 +0000427 raw_ostream &OS;
428 const SourceManager &SM;
429 const LangOptions &LangOpts;
430 const DiagnosticOptions &DiagOpts;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000431
Chandler Carruthf54a6142011-10-15 11:44:27 +0000432 /// \brief The location of the previous diagnostic if known.
433 ///
434 /// This will be invalid in cases where there is no (known) previous
435 /// diagnostic location, or that location itself is invalid or comes from
436 /// a different source manager than SM.
437 SourceLocation LastLoc;
438
Chandler Carruthd6140402011-10-15 12:12:44 +0000439 /// \brief The location of the last include whose stack was printed if known.
Chandler Carruthf54a6142011-10-15 11:44:27 +0000440 ///
Chandler Carruthd6140402011-10-15 12:12:44 +0000441 /// Same restriction as \see LastLoc essentially, but tracking include stack
442 /// root locations rather than diagnostic locations.
443 SourceLocation LastIncludeLoc;
Chandler Carruthf54a6142011-10-15 11:44:27 +0000444
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000445 /// \brief The level of the last diagnostic emitted.
446 ///
447 /// The level of the last diagnostic emitted. Used to detect level changes
448 /// which change the amount of information displayed.
449 DiagnosticsEngine::Level LastLevel;
450
Chandler Carruth50c909b2011-08-31 23:59:23 +0000451public:
Chandler Carruth67e2d512011-10-15 12:07:49 +0000452 TextDiagnostic(raw_ostream &OS,
Chandler Carruthf54a6142011-10-15 11:44:27 +0000453 const SourceManager &SM,
454 const LangOptions &LangOpts,
455 const DiagnosticOptions &DiagOpts,
456 FullSourceLoc LastLoc = FullSourceLoc(),
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000457 FullSourceLoc LastIncludeLoc = FullSourceLoc(),
458 DiagnosticsEngine::Level LastLevel
459 = DiagnosticsEngine::Level())
Chandler Carruth67e2d512011-10-15 12:07:49 +0000460 : OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000461 LastLoc(LastLoc), LastIncludeLoc(LastIncludeLoc), LastLevel(LastLevel) {
Chandler Carruthf54a6142011-10-15 11:44:27 +0000462 if (LastLoc.isValid() && &SM != &LastLoc.getManager())
463 this->LastLoc = SourceLocation();
Chandler Carruthd6140402011-10-15 12:12:44 +0000464 if (LastIncludeLoc.isValid() && &SM != &LastIncludeLoc.getManager())
465 this->LastIncludeLoc = SourceLocation();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000466 }
467
Chandler Carruthf54a6142011-10-15 11:44:27 +0000468 /// \brief Get the last diagnostic location emitted.
469 SourceLocation getLastLoc() const { return LastLoc; }
470
Chandler Carruthd6140402011-10-15 12:12:44 +0000471 /// \brief Get the last emitted include stack location.
472 SourceLocation getLastIncludeLoc() const { return LastIncludeLoc; }
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000473
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000474 /// \brief Get the last diagnostic level.
475 DiagnosticsEngine::Level getLastLevel() const { return LastLevel; }
476
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000477 void Emit(SourceLocation Loc, DiagnosticsEngine::Level Level,
478 StringRef Message, ArrayRef<CharSourceRange> Ranges,
479 ArrayRef<FixItHint> FixItHints,
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000480 bool LastCaretDiagnosticWasNote = false) {
481 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
482
483 // First, if this diagnostic is not in the main file, print out the
484 // "included from" lines.
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000485 emitIncludeStack(PLoc.getIncludeLoc(), Level);
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000486
487 uint64_t StartOfLocationInfo = OS.tell();
488
489 // Next emit the location of this particular diagnostic.
Chandler Carruth9ed30662011-10-15 11:09:23 +0000490 EmitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000491
492 if (DiagOpts.ShowColors)
493 OS.resetColor();
494
495 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
496 printDiagnosticMessage(OS, Level, Message,
497 OS.tell() - StartOfLocationInfo,
498 DiagOpts.MessageLength, DiagOpts.ShowColors);
499
500 // If caret diagnostics are enabled and we have location, we want to
501 // emit the caret. However, we only do this if the location moved
502 // from the last diagnostic, if the last diagnostic was a note that
503 // was part of a different warning or error diagnostic, or if the
504 // diagnostic has ranges. We don't want to emit the same caret
505 // multiple times if one loc has multiple diagnostics.
506 if (DiagOpts.ShowCarets &&
507 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000508 (LastLevel == DiagnosticsEngine::Note && Level != LastLevel))) {
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000509 // Get the ranges into a local array we can hack on.
510 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
511 Ranges.end());
512
513 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
514 E = FixItHints.end();
515 I != E; ++I)
516 if (I->RemoveRange.isValid())
517 MutableRanges.push_back(I->RemoveRange);
518
519 unsigned MacroDepth = 0;
520 EmitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
521 }
Chandler Carruthf54a6142011-10-15 11:44:27 +0000522
523 LastLoc = Loc;
Chandler Carruth03efd2e2011-10-15 22:39:16 +0000524 LastLevel = Level;
Chandler Carruth60e4a2a2011-10-15 11:09:19 +0000525 }
526
Chandler Carruthd79e4622011-10-15 01:21:55 +0000527 /// \brief Emit the caret and underlining text.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000528 ///
529 /// Walks up the macro expansion stack printing the code snippet, caret,
530 /// underlines and FixItHint display as appropriate at each level. Walk is
531 /// accomplished by calling itself recursively.
532 ///
Chandler Carruthd79e4622011-10-15 01:21:55 +0000533 /// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
534 /// caret diagnostics.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000535 /// FIXME: Break up massive function into logical units.
536 ///
537 /// \param Loc The location for this caret.
538 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000539 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000540 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000541 /// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruthd79e4622011-10-15 01:21:55 +0000542 void EmitCaret(SourceLocation Loc,
Chandler Carruth5182a182011-09-07 01:47:09 +0000543 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000544 ArrayRef<FixItHint> Hints,
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000545 unsigned &MacroDepth,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000546 unsigned OnMacroInst = 0) {
547 assert(!Loc.isInvalid() && "must have a valid source location here");
548
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000549 // If this is a file source location, directly emit the source snippet and
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000550 // caret line. Also record the macro depth reached.
551 if (Loc.isFileID()) {
552 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
553 MacroDepth = OnMacroInst;
554 EmitSnippetAndCaret(Loc, Ranges, Hints);
555 return;
556 }
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000557 // Otherwise recurse through each macro expansion layer.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000558
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000559 // When processing macros, skip over the expansions leading up to
560 // a macro argument, and trace the argument's expansion stack instead.
561 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000562
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000563 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000564
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000565 // FIXME: Map ranges?
Chandler Carruthd79e4622011-10-15 01:21:55 +0000566 EmitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000567
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000568 // Map the location.
569 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000570
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000571 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
572 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
573 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
574 DiagOpts.MacroBacktraceLimit % 2;
575 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
576 }
577
578 // Whether to suppress printing this macro expansion.
579 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
580 OnMacroInst < MacroSkipEnd);
581
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000582 // Map the ranges.
583 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
584 E = Ranges.end();
585 I != E; ++I) {
586 SourceLocation Start = I->getBegin(), End = I->getEnd();
587 if (Start.isMacroID())
588 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
589 if (End.isMacroID())
590 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
591 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000592
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000593 if (!Suppressed) {
594 // Don't print recursive expansion notes from an expansion note.
595 Loc = SM.getSpellingLoc(Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000596
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000597 // Get the pretty name, according to #line directives etc.
598 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
599 if (PLoc.isInvalid())
Chandler Carruth50c909b2011-08-31 23:59:23 +0000600 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000601
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000602 // If this diagnostic is not in the main file, print out the
603 // "included from" lines.
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000604 emitIncludeStack(PLoc.getIncludeLoc(), DiagnosticsEngine::Note);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000605
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000606 if (DiagOpts.ShowLocation) {
607 // Emit the file/line/column that this expansion came from.
608 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
609 if (DiagOpts.ShowColumn)
610 OS << PLoc.getColumn() << ':';
611 OS << ' ';
612 }
613 OS << "note: expanded from:\n";
614
615 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruth50c909b2011-08-31 23:59:23 +0000616 return;
617 }
618
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000619 if (OnMacroInst == MacroSkipStart) {
620 // Tell the user that we've skipped contexts.
621 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
622 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
623 "all)\n";
624 }
625 }
626
627 /// \brief Emit a code snippet and caret line.
628 ///
629 /// This routine emits a single line's code snippet and caret line..
630 ///
631 /// \param Loc The location for the caret.
632 /// \param Ranges The underlined ranges for this code snippet.
633 /// \param Hints The FixIt hints active for this diagnostic.
634 void EmitSnippetAndCaret(SourceLocation Loc,
635 SmallVectorImpl<CharSourceRange>& Ranges,
636 ArrayRef<FixItHint> Hints) {
637 assert(!Loc.isInvalid() && "must have a valid source location here");
638 assert(Loc.isFileID() && "must have a file location here");
639
Chandler Carruth50c909b2011-08-31 23:59:23 +0000640 // Decompose the location into a FID/Offset pair.
641 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
642 FileID FID = LocInfo.first;
643 unsigned FileOffset = LocInfo.second;
644
645 // Get information about the buffer it points into.
646 bool Invalid = false;
647 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
648 if (Invalid)
649 return;
650
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000651 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000652 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
653 unsigned CaretEndColNo
654 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
655
656 // Rewind from the current position to the start of the line.
657 const char *TokPtr = BufStart+FileOffset;
658 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
659
660
661 // Compute the line end. Scan forward from the error position to the end of
662 // the line.
663 const char *LineEnd = TokPtr;
664 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
665 ++LineEnd;
666
667 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
668 // the source line length as currently being computed. See
669 // test/Misc/message-length.c.
670 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
671
672 // Copy the line of code into an std::string for ease of manipulation.
673 std::string SourceLine(LineStart, LineEnd);
674
675 // Create a line for the caret that is filled with spaces that is the same
676 // length as the line of source code.
677 std::string CaretLine(LineEnd-LineStart, ' ');
678
679 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000680 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
681 E = Ranges.end();
682 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000683 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000684
685 // Next, insert the caret itself.
686 if (ColNo-1 < CaretLine.size())
687 CaretLine[ColNo-1] = '^';
688 else
689 CaretLine.push_back('^');
690
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000691 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000692
693 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
694 // to produce easily machine parsable output. Add a space before the
695 // source line and the caret to make it trivial to tell the main diagnostic
696 // line from what the user is intended to see.
697 if (DiagOpts.ShowSourceRanges) {
698 SourceLine = ' ' + SourceLine;
699 CaretLine = ' ' + CaretLine;
700 }
701
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000702 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000703 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000704 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000705
706 // If the source line is too long for our terminal, select only the
707 // "interesting" source region within that line.
Chandler Carruth8be5c152011-09-25 22:31:58 +0000708 unsigned Columns = DiagOpts.MessageLength;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000709 if (Columns && SourceLine.size() > Columns)
710 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
711 CaretEndColNo, Columns);
712
713 // Finally, remove any blank spaces from the end of CaretLine.
714 while (CaretLine[CaretLine.size()-1] == ' ')
715 CaretLine.erase(CaretLine.end()-1);
716
717 // Emit what we have computed.
718 OS << SourceLine << '\n';
719
720 if (DiagOpts.ShowColors)
721 OS.changeColor(caretColor, true);
722 OS << CaretLine << '\n';
723 if (DiagOpts.ShowColors)
724 OS.resetColor();
725
726 if (!FixItInsertionLine.empty()) {
727 if (DiagOpts.ShowColors)
728 // Print fixit line in color
729 OS.changeColor(fixitColor, false);
730 if (DiagOpts.ShowSourceRanges)
731 OS << ' ';
732 OS << FixItInsertionLine << '\n';
733 if (DiagOpts.ShowColors)
734 OS.resetColor();
735 }
736
Chandler Carruthcca61582011-09-02 06:30:30 +0000737 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000738 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000739 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000740
Chandler Carruth7eb84dc2011-10-15 22:49:21 +0000741 /// \brief Print the diagonstic level to a raw_ostream.
742 ///
743 /// This is a static helper that handles colorizing the level and formatting
744 /// it into an arbitrary output stream. This is used internally by the
745 /// TextDiagnostic emission code, but it can also be used directly by
746 /// consumers that don't have a source manager or other state that the full
747 /// TextDiagnostic logic requires.
748 static void printDiagnosticLevel(raw_ostream &OS,
749 DiagnosticsEngine::Level Level,
750 bool ShowColors) {
751 if (ShowColors) {
752 // Print diagnostic category in bold and color
753 switch (Level) {
754 case DiagnosticsEngine::Ignored:
755 llvm_unreachable("Invalid diagnostic type");
756 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
757 case DiagnosticsEngine::Warning:
758 OS.changeColor(warningColor, true);
759 break;
760 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
761 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
762 }
763 }
764
765 switch (Level) {
766 case DiagnosticsEngine::Ignored:
767 llvm_unreachable("Invalid diagnostic type");
768 case DiagnosticsEngine::Note: OS << "note: "; break;
769 case DiagnosticsEngine::Warning: OS << "warning: "; break;
770 case DiagnosticsEngine::Error: OS << "error: "; break;
771 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
772 }
773
774 if (ShowColors)
775 OS.resetColor();
776 }
777
Chandler Carruth1f3839e2011-10-15 22:57:29 +0000778 /// \brief Pretty-print a diagnostic message to a raw_ostream.
779 ///
780 /// This is a static helper to handle the line wrapping, colorizing, and
781 /// rendering of a diagnostic message to a particular ostream. It is
782 /// publically visible so that clients which do not have sufficient state to
783 /// build a complete TextDiagnostic object can still get consistent
784 /// formatting of their diagnostic messages.
785 ///
786 /// \param OS Where the message is printed
787 /// \param Level Used to colorizing the message
788 /// \param Message The text actually printed
789 /// \param CurrentColumn The starting column of the first line, accounting
790 /// for any prefix.
791 /// \param Columns The number of columns to use in line-wrapping, 0 disables
792 /// all line-wrapping.
793 /// \param ShowColors Enable colorizing of the message.
794 static void printDiagnosticMessage(raw_ostream &OS,
795 DiagnosticsEngine::Level Level,
796 StringRef Message,
797 unsigned CurrentColumn, unsigned Columns,
798 bool ShowColors) {
799 if (ShowColors) {
800 // Print warnings, errors and fatal errors in bold, no color
801 switch (Level) {
802 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
803 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
804 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
805 default: break; //don't bold notes
806 }
807 }
808
809 if (Columns)
810 printWordWrapped(OS, Message, Columns, CurrentColumn);
811 else
812 OS << Message;
813
814 if (ShowColors)
815 OS.resetColor();
816 OS << '\n';
817 }
818
Chandler Carruthcca61582011-09-02 06:30:30 +0000819private:
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000820 /// \brief Prints an include stack when appropriate for a particular
821 /// diagnostic level and location.
822 ///
823 /// This routine handles all the logic of suppressing particular include
824 /// stacks (such as those for notes) and duplicate include stacks when
825 /// repeated warnings occur within the same file. It also handles the logic
826 /// of customizing the formatting and display of the include stack.
827 ///
828 /// \param Level The diagnostic level of the message this stack pertains to.
829 /// \param Loc The include location of the current file (not the diagnostic
830 /// location).
831 void emitIncludeStack(SourceLocation Loc, DiagnosticsEngine::Level Level) {
832 // Skip redundant include stacks altogether.
Chandler Carruthd6140402011-10-15 12:12:44 +0000833 if (LastIncludeLoc == Loc)
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000834 return;
Chandler Carruthd6140402011-10-15 12:12:44 +0000835 LastIncludeLoc = Loc;
Chandler Carruthcae9ab12011-10-15 12:07:47 +0000836
837 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
838 return;
839
840 emitIncludeStackRecursively(Loc);
841 }
842
843 /// \brief Helper to recursivly walk up the include stack and print each layer
844 /// on the way back down.
845 void emitIncludeStackRecursively(SourceLocation Loc) {
846 if (Loc.isInvalid())
847 return;
848
849 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
850 if (PLoc.isInvalid())
851 return;
852
853 // Emit the other include frames first.
854 emitIncludeStackRecursively(PLoc.getIncludeLoc());
855
856 if (DiagOpts.ShowLocation)
857 OS << "In file included from " << PLoc.getFilename()
858 << ':' << PLoc.getLine() << ":\n";
859 else
860 OS << "In included file:\n";
861 }
862
Chandler Carruth9ed30662011-10-15 11:09:23 +0000863 /// \brief Print out the file/line/column information and include trace.
864 ///
865 /// This method handlen the emission of the diagnostic location information.
866 /// This includes extracting as much location information as is present for
867 /// the diagnostic and printing it, as well as any include stack or source
868 /// ranges necessary.
869 void EmitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
870 DiagnosticsEngine::Level Level,
871 ArrayRef<CharSourceRange> Ranges) {
872 if (PLoc.isInvalid()) {
873 // At least print the file name if available:
874 FileID FID = SM.getFileID(Loc);
875 if (!FID.isInvalid()) {
876 const FileEntry* FE = SM.getFileEntryForID(FID);
877 if (FE && FE->getName()) {
878 OS << FE->getName();
879 if (FE->getDevice() == 0 && FE->getInode() == 0
880 && FE->getFileMode() == 0) {
881 // in PCH is a guess, but a good one:
882 OS << " (in PCH)";
883 }
884 OS << ": ";
885 }
886 }
887 return;
888 }
889 unsigned LineNo = PLoc.getLine();
890
891 if (!DiagOpts.ShowLocation)
892 return;
893
894 if (DiagOpts.ShowColors)
895 OS.changeColor(savedColor, true);
896
897 OS << PLoc.getFilename();
898 switch (DiagOpts.Format) {
899 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
900 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
901 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
902 }
903
904 if (DiagOpts.ShowColumn)
905 // Compute the column number.
906 if (unsigned ColNo = PLoc.getColumn()) {
907 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
908 OS << ',';
909 ColNo--;
910 } else
911 OS << ':';
912 OS << ColNo;
913 }
914 switch (DiagOpts.Format) {
915 case DiagnosticOptions::Clang:
916 case DiagnosticOptions::Vi: OS << ':'; break;
917 case DiagnosticOptions::Msvc: OS << ") : "; break;
918 }
919
920 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
921 FileID CaretFileID =
922 SM.getFileID(SM.getExpansionLoc(Loc));
923 bool PrintedRange = false;
924
925 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
926 RE = Ranges.end();
927 RI != RE; ++RI) {
928 // Ignore invalid ranges.
929 if (!RI->isValid()) continue;
930
931 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
932 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
933
934 // If the End location and the start location are the same and are a
935 // macro location, then the range was something that came from a
936 // macro expansion or _Pragma. If this is an object-like macro, the
937 // best we can do is to highlight the range. If this is a
938 // function-like macro, we'd also like to highlight the arguments.
939 if (B == E && RI->getEnd().isMacroID())
940 E = SM.getExpansionRange(RI->getEnd()).second;
941
942 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
943 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
944
945 // If the start or end of the range is in another file, just discard
946 // it.
947 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
948 continue;
949
950 // Add in the length of the token, so that we cover multi-char
951 // tokens.
952 unsigned TokSize = 0;
953 if (RI->isTokenRange())
954 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
955
956 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
957 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
958 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
959 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
960 << '}';
961 PrintedRange = true;
962 }
963
964 if (PrintedRange)
965 OS << ':';
966 }
967 OS << ' ';
968 }
969
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000970 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
971 void HighlightRange(const CharSourceRange &R,
972 unsigned LineNo, FileID FID,
973 const std::string &SourceLine,
974 std::string &CaretLine) {
975 assert(CaretLine.size() == SourceLine.size() &&
976 "Expect a correspondence between source and caret line!");
977 if (!R.isValid()) return;
978
979 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
980 SourceLocation End = SM.getExpansionLoc(R.getEnd());
981
982 // If the End location and the start location are the same and are a macro
983 // location, then the range was something that came from a macro expansion
984 // or _Pragma. If this is an object-like macro, the best we can do is to
985 // highlight the range. If this is a function-like macro, we'd also like to
986 // highlight the arguments.
987 if (Begin == End && R.getEnd().isMacroID())
988 End = SM.getExpansionRange(R.getEnd()).second;
989
990 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
991 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
992 return; // No intersection.
993
994 unsigned EndLineNo = SM.getExpansionLineNumber(End);
995 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
996 return; // No intersection.
997
998 // Compute the column number of the start.
999 unsigned StartColNo = 0;
1000 if (StartLineNo == LineNo) {
1001 StartColNo = SM.getExpansionColumnNumber(Begin);
1002 if (StartColNo) --StartColNo; // Zero base the col #.
1003 }
1004
1005 // Compute the column number of the end.
1006 unsigned EndColNo = CaretLine.size();
1007 if (EndLineNo == LineNo) {
1008 EndColNo = SM.getExpansionColumnNumber(End);
1009 if (EndColNo) {
1010 --EndColNo; // Zero base the col #.
1011
1012 // Add in the length of the token, so that we cover multi-char tokens if
1013 // this is a token range.
1014 if (R.isTokenRange())
1015 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1016 } else {
1017 EndColNo = CaretLine.size();
1018 }
1019 }
1020
1021 assert(StartColNo <= EndColNo && "Invalid range!");
1022
1023 // Check that a token range does not highlight only whitespace.
1024 if (R.isTokenRange()) {
1025 // Pick the first non-whitespace column.
1026 while (StartColNo < SourceLine.size() &&
1027 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
1028 ++StartColNo;
1029
1030 // Pick the last non-whitespace column.
1031 if (EndColNo > SourceLine.size())
1032 EndColNo = SourceLine.size();
1033 while (EndColNo-1 &&
1034 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
1035 --EndColNo;
1036
1037 // If the start/end passed each other, then we are trying to highlight a
1038 // range that just exists in whitespace, which must be some sort of other
1039 // bug.
1040 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1041 }
1042
1043 // Fill the range with ~'s.
1044 for (unsigned i = StartColNo; i < EndColNo; ++i)
1045 CaretLine[i] = '~';
1046 }
1047
Chandler Carruth0580e7d2011-09-07 05:01:10 +00001048 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +00001049 const char *LineStart,
1050 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001051 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +00001052 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001053 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +00001054 return FixItInsertionLine;
1055
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001056 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1057 I != E; ++I) {
1058 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +00001059 // We have an insertion hint. Determine whether the inserted
1060 // code is on the same line as the caret.
1061 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001062 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +00001063 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +00001064 // Insert the new code into the line just below the code
1065 // that the user wrote.
1066 unsigned HintColNo
1067 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
1068 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001069 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +00001070 if (LastColumnModified > FixItInsertionLine.size())
1071 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001072 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +00001073 FixItInsertionLine.begin() + HintColNo - 1);
1074 } else {
1075 FixItInsertionLine.clear();
1076 break;
1077 }
1078 }
1079 }
1080
1081 if (FixItInsertionLine.empty())
1082 return FixItInsertionLine;
1083
1084 // Now that we have the entire fixit line, expand the tabs in it.
1085 // Since we don't want to insert spaces in the middle of a word,
1086 // find each word and the column it should line up with and insert
1087 // spaces until they match.
1088 unsigned FixItPos = 0;
1089 unsigned LinePos = 0;
1090 unsigned TabExpandedCol = 0;
1091 unsigned LineLength = LineEnd - LineStart;
1092
1093 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
1094 // Find the next word in the FixIt line.
1095 while (FixItPos < FixItInsertionLine.size() &&
1096 FixItInsertionLine[FixItPos] == ' ')
1097 ++FixItPos;
1098 unsigned CharDistance = FixItPos - TabExpandedCol;
1099
1100 // Walk forward in the source line, keeping track of
1101 // the tab-expanded column.
1102 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
1103 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
1104 ++TabExpandedCol;
1105 else
1106 TabExpandedCol =
1107 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
1108
1109 // Adjust the fixit line to match this column.
1110 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
1111 FixItPos = TabExpandedCol;
1112
1113 // Walk to the end of the word.
1114 while (FixItPos < FixItInsertionLine.size() &&
1115 FixItInsertionLine[FixItPos] != ' ')
1116 ++FixItPos;
1117 }
1118
1119 return FixItInsertionLine;
1120 }
1121
Chandler Carruthd2156fc2011-09-07 05:36:50 +00001122 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
1123 // Scan the source line, looking for tabs. If we find any, manually expand
1124 // them to spaces and update the CaretLine to match.
1125 for (unsigned i = 0; i != SourceLine.size(); ++i) {
1126 if (SourceLine[i] != '\t') continue;
1127
1128 // Replace this tab with at least one space.
1129 SourceLine[i] = ' ';
1130
1131 // Compute the number of spaces we need to insert.
1132 unsigned TabStop = DiagOpts.TabStop;
1133 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1134 "Invalid -ftabstop value");
1135 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
1136 assert(NumSpaces < TabStop && "Invalid computation of space amt");
1137
1138 // Insert spaces into the SourceLine.
1139 SourceLine.insert(i+1, NumSpaces, ' ');
1140
1141 // Insert spaces or ~'s into CaretLine.
1142 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
1143 }
1144 }
1145
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001146 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +00001147 if (!DiagOpts.ShowParseableFixits)
1148 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +00001149
Chandler Carruthcca61582011-09-02 06:30:30 +00001150 // We follow FixItRewriter's example in not (yet) handling
1151 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001152 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1153 I != E; ++I) {
1154 if (I->RemoveRange.isInvalid() ||
1155 I->RemoveRange.getBegin().isMacroID() ||
1156 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +00001157 return;
1158 }
Chandler Carruth50c909b2011-08-31 23:59:23 +00001159
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001160 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1161 I != E; ++I) {
1162 SourceLocation BLoc = I->RemoveRange.getBegin();
1163 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +00001164
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001165 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1166 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +00001167
Chandler Carruthcca61582011-09-02 06:30:30 +00001168 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001169 if (I->RemoveRange.isTokenRange())
1170 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +00001171
Chandler Carruthcca61582011-09-02 06:30:30 +00001172 // We specifically do not do word-wrapping or tab-expansion here,
1173 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001174 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +00001175 if (PLoc.isInvalid())
1176 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +00001177
Chandler Carruthcca61582011-09-02 06:30:30 +00001178 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +00001179 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +00001180 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1181 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1182 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1183 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1184 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001185 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +00001186 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +00001187 }
1188 }
1189};
1190
1191} // end namespace
1192
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +00001193/// \brief Print the diagnostic name to a raw_ostream.
1194///
1195/// This prints the diagnostic name to a raw_ostream if it has one. It formats
1196/// the name according to the expected diagnostic message formatting:
1197/// " [diagnostic_name_here]"
1198static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
Chandler Carruth76145782011-09-26 00:37:30 +00001199 if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
1200 OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
1201}
1202
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +00001203/// \brief Print any diagnostic option information to a raw_ostream.
1204///
1205/// This implements all of the logic for adding diagnostic options to a message
1206/// (via OS). Each relevant option is comma separated and all are enclosed in
1207/// the standard bracketing: " [...]".
1208static void printDiagnosticOptions(raw_ostream &OS,
Chandler Carruth53a529e2011-09-26 00:44:09 +00001209 DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +00001210 const Diagnostic &Info,
Chandler Carruth53a529e2011-09-26 00:44:09 +00001211 const DiagnosticOptions &DiagOpts) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001212 bool Started = false;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001213 if (DiagOpts.ShowOptionNames) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001214 // Handle special cases for non-warnings early.
1215 if (Info.getID() == diag::fatal_too_many_errors) {
1216 OS << " [-ferror-limit=]";
1217 return;
1218 }
1219
Daniel Dunbar76101cf2011-09-29 01:01:08 +00001220 // The code below is somewhat fragile because we are essentially trying to
1221 // report to the user what happened by inferring what the diagnostic engine
1222 // did. Eventually it might make more sense to have the diagnostic engine
1223 // include some "why" information in the diagnostic.
1224
1225 // If this is a warning which has been mapped to an error by the user (as
1226 // inferred by checking whether the default mapping is to an error) then
1227 // flag it as such. Note that diagnostics could also have been mapped by a
1228 // pragma, but we don't currently have a way to distinguish this.
Chandler Carruth53a529e2011-09-26 00:44:09 +00001229 if (Level == DiagnosticsEngine::Error &&
Daniel Dunbar76101cf2011-09-29 01:01:08 +00001230 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID()) &&
1231 !DiagnosticIDs::isDefaultMappingAsError(Info.getID())) {
1232 OS << " [-Werror";
1233 Started = true;
Chandler Carruth253d41d2011-09-26 01:21:58 +00001234 }
1235
1236 // If the diagnostic is an extension diagnostic and not enabled by default
1237 // then it must have been turned on with -pedantic.
1238 bool EnabledByDefault;
1239 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1240 EnabledByDefault) &&
1241 !EnabledByDefault) {
1242 OS << (Started ? "," : " [") << "-pedantic";
1243 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001244 }
1245
1246 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
1247 if (!Opt.empty()) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001248 OS << (Started ? "," : " [") << "-W" << Opt;
1249 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001250 }
1251 }
Chandler Carruth53a529e2011-09-26 00:44:09 +00001252
Chandler Carruth253d41d2011-09-26 01:21:58 +00001253 // If the user wants to see category information, include it too.
1254 if (DiagOpts.ShowCategories) {
1255 unsigned DiagCategory =
1256 DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Chandler Carruth53a529e2011-09-26 00:44:09 +00001257 if (DiagCategory) {
Chandler Carruth253d41d2011-09-26 01:21:58 +00001258 OS << (Started ? "," : " [");
Benjamin Kramera65cb0c2011-09-26 02:14:13 +00001259 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001260 if (DiagOpts.ShowCategories == 1)
Benjamin Kramera65cb0c2011-09-26 02:14:13 +00001261 OS << DiagCategory;
Chandler Carruth53a529e2011-09-26 00:44:09 +00001262 else {
1263 assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
1264 OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
1265 }
1266 }
Chandler Carruth53a529e2011-09-26 00:44:09 +00001267 }
Benjamin Kramera65cb0c2011-09-26 02:14:13 +00001268 if (Started)
1269 OS << ']';
Chandler Carruth53a529e2011-09-26 00:44:09 +00001270}
1271
Chandler Carrutha6290042011-09-26 00:26:47 +00001272void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +00001273 const Diagnostic &Info) {
Chandler Carrutha6290042011-09-26 00:26:47 +00001274 // Default implementation (Warnings/errors count).
1275 DiagnosticConsumer::HandleDiagnostic(Level, Info);
1276
Chandler Carruth0ef89882011-09-26 11:25:30 +00001277 // Render the diagnostic message into a temporary buffer eagerly. We'll use
1278 // this later as we print out the diagnostic to the terminal.
1279 llvm::SmallString<100> OutStr;
1280 Info.FormatDiagnostic(OutStr);
1281
1282 llvm::raw_svector_ostream DiagMessageStream(OutStr);
1283 if (DiagOpts->ShowNames)
1284 printDiagnosticName(DiagMessageStream, Info);
1285 printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
1286
Chandler Carrutha6290042011-09-26 00:26:47 +00001287 // Keeps track of the the starting position of the location
1288 // information (e.g., "foo.c:10:4:") that precedes the error
1289 // message. We use this information to determine how long the
1290 // file+line+column number prefix is.
1291 uint64_t StartOfLocationInfo = OS.tell();
1292
1293 if (!Prefix.empty())
1294 OS << Prefix << ": ";
1295
Chandler Carruth0ef89882011-09-26 11:25:30 +00001296 // Use a dedicated, simpler path for diagnostics without a valid location.
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001297 // This is important as if the location is missing, we may be emitting
1298 // diagnostics in a context that lacks language options, a source manager, or
1299 // other infrastructure necessary when emitting more rich diagnostics.
Chandler Carruth0ef89882011-09-26 11:25:30 +00001300 if (!Info.getLocation().isValid()) {
Chandler Carruth7eb84dc2011-10-15 22:49:21 +00001301 TextDiagnostic::printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
Chandler Carruth1f3839e2011-10-15 22:57:29 +00001302 TextDiagnostic::printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1303 OS.tell() - StartOfLocationInfo,
1304 DiagOpts->MessageLength,
1305 DiagOpts->ShowColors);
Chandler Carruth0ef89882011-09-26 11:25:30 +00001306 OS.flush();
1307 return;
Chandler Carrutha6290042011-09-26 00:26:47 +00001308 }
1309
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001310 // Assert that the rest of our infrastructure is setup properly.
1311 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1312 assert(DiagOpts && "Unexpected diagnostic without options set");
1313 assert(Info.hasSourceManager() &&
1314 "Unexpected diagnostic with no source manager");
Chandler Carruth0ef89882011-09-26 11:25:30 +00001315 const SourceManager &SM = Info.getSourceManager();
Chandler Carruth67e2d512011-10-15 12:07:49 +00001316 TextDiagnostic TextDiag(OS, SM, *LangOpts, *DiagOpts,
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001317 LastLoc, LastIncludeLoc, LastLevel);
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001318
Chandler Carruth60e4a2a2011-10-15 11:09:19 +00001319 TextDiag.Emit(Info.getLocation(), Level, DiagMessageStream.str(),
1320 Info.getRanges(),
1321 llvm::makeArrayRef(Info.getFixItHints(),
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001322 Info.getNumFixItHints()));
Chandler Carruth0ef89882011-09-26 11:25:30 +00001323
Chandler Carruthf54a6142011-10-15 11:44:27 +00001324 // Cache the LastLoc from the TextDiagnostic printing.
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001325 // FIXME: Rather than this, we should persist a TextDiagnostic object across
1326 // diagnostics until the SourceManager changes. That will allow the
1327 // TextDiagnostic object to form a 'session' of output where we can
1328 // reasonably collapse redundant information.
Chandler Carruthf54a6142011-10-15 11:44:27 +00001329 LastLoc = FullSourceLoc(TextDiag.getLastLoc(), SM);
Chandler Carruthd6140402011-10-15 12:12:44 +00001330 LastIncludeLoc = FullSourceLoc(TextDiag.getLastIncludeLoc(), SM);
Chandler Carruth03efd2e2011-10-15 22:39:16 +00001331 LastLevel = TextDiag.getLastLevel();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001332
Chris Lattnera03a5b52008-11-19 06:56:25 +00001333 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001334}
Douglas Gregoraee526e2011-09-29 00:38:00 +00001335
1336DiagnosticConsumer *
1337TextDiagnosticPrinter::clone(DiagnosticsEngine &Diags) const {
1338 return new TextDiagnosticPrinter(OS, *DiagOpts, /*OwnsOutputStream=*/false);
1339}