blob: 0afc3efbbcd43ed288dcff7c7fa2d9a32c3f17c2 [file] [log] [blame]
Bill Wendling37b1dde2007-06-07 09:34:54 +00001//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling37b1dde2007-06-07 09:34:54 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This diagnostic client prints out their diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar51adf582009-03-02 06:16:29 +000014#include "clang/Frontend/TextDiagnosticPrinter.h"
Axel Naumann63fbaed2011-01-27 10:55:51 +000015#include "clang/Basic/FileManager.h"
Bill Wendling37b1dde2007-06-07 09:34:54 +000016#include "clang/Basic/SourceManager.h"
Daniel Dunbarc2e6a472009-11-04 06:24:30 +000017#include "clang/Frontend/DiagnosticOptions.h"
Bill Wendling37b1dde2007-06-07 09:34:54 +000018#include "clang/Lex/Lexer.h"
Chris Lattnerc45529b2009-05-05 22:03:18 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattner327984f2008-11-19 06:56:25 +000020#include "llvm/Support/raw_ostream.h"
David Blaikie79000202011-09-23 05:57:42 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattner23be0672008-11-19 06:51:40 +000022#include "llvm/ADT/SmallString.h"
Douglas Gregor87f95b02009-02-26 21:00:50 +000023#include <algorithm>
Bill Wendling37b1dde2007-06-07 09:34:54 +000024using namespace clang;
25
Chris Lattner0e62c1c2011-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 Dunbaraa7d55a2010-02-25 03:23:40 +000036// Used for changing only the bold attribute.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000037static const enum raw_ostream::Colors savedColor =
38 raw_ostream::SAVEDCOLOR;
Torok Edwinc91b6e02009-06-04 07:18:23 +000039
Douglas Gregor48185532009-05-01 21:53:04 +000040/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Chris Lattner0e62c1c2011-07-23 10:55:15 +000043TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
Daniel Dunbard0c3bb02009-11-11 09:38:24 +000044 const DiagnosticOptions &diags,
45 bool _OwnsOutputStream)
Daniel Dunbarc2e6a472009-11-04 06:24:30 +000046 : OS(os), LangOpts(0), DiagOpts(&diags),
Daniel Dunbard0c3bb02009-11-11 09:38:24 +000047 LastCaretDiagnosticWasNote(0),
48 OwnsOutputStream(_OwnsOutputStream) {
49}
50
51TextDiagnosticPrinter::~TextDiagnosticPrinter() {
52 if (OwnsOutputStream)
53 delete &OS;
Daniel Dunbarc2e6a472009-11-04 06:24:30 +000054}
55
Douglas Gregorcf7b2af2009-05-01 23:32:58 +000056/// \brief When the source code line we want to print is too long for
57/// the terminal, select the "interesting" region.
58static void SelectInterestingSourceRegion(std::string &SourceLine,
59 std::string &CaretLine,
60 std::string &FixItInsertionLine,
Douglas Gregor2d69cd22009-05-04 06:27:32 +000061 unsigned EndOfCaretToken,
Douglas Gregorcf7b2af2009-05-01 23:32:58 +000062 unsigned Columns) {
Douglas Gregoraef00222010-04-16 00:23:51 +000063 unsigned MaxSize = std::max(SourceLine.size(),
64 std::max(CaretLine.size(),
65 FixItInsertionLine.size()));
66 if (MaxSize > SourceLine.size())
67 SourceLine.resize(MaxSize, ' ');
68 if (MaxSize > CaretLine.size())
69 CaretLine.resize(MaxSize, ' ');
70 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
71 FixItInsertionLine.resize(MaxSize, ' ');
72
Douglas Gregorcf7b2af2009-05-01 23:32:58 +000073 // Find the slice that we need to display the full caret line
74 // correctly.
75 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
76 for (; CaretStart != CaretEnd; ++CaretStart)
77 if (!isspace(CaretLine[CaretStart]))
78 break;
79
80 for (; CaretEnd != CaretStart; --CaretEnd)
81 if (!isspace(CaretLine[CaretEnd - 1]))
82 break;
Douglas Gregor2d69cd22009-05-04 06:27:32 +000083
84 // Make sure we don't chop the string shorter than the caret token
85 // itself.
86 if (CaretEnd < EndOfCaretToken)
87 CaretEnd = EndOfCaretToken;
88
Douglas Gregorb8c6d5d2009-05-03 04:33:32 +000089 // If we have a fix-it line, make sure the slice includes all of the
90 // fix-it information.
91 if (!FixItInsertionLine.empty()) {
92 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
93 for (; FixItStart != FixItEnd; ++FixItStart)
94 if (!isspace(FixItInsertionLine[FixItStart]))
95 break;
Daniel Dunbar49f0e802009-09-07 23:07:56 +000096
Douglas Gregorb8c6d5d2009-05-03 04:33:32 +000097 for (; FixItEnd != FixItStart; --FixItEnd)
98 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
99 break;
100
101 if (FixItStart < CaretStart)
102 CaretStart = FixItStart;
103 if (FixItEnd > CaretEnd)
104 CaretEnd = FixItEnd;
105 }
106
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000107 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
108 // parts of the caret line. While this slice is smaller than the
109 // number of columns we have, try to grow the slice to encompass
110 // more context.
111
112 // If the end of the interesting region comes before we run out of
113 // space in the terminal, start at the beginning of the line.
Douglas Gregor12c3a5c2009-05-15 18:05:24 +0000114 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000115 CaretStart = 0;
116
Douglas Gregor12c3a5c2009-05-15 18:05:24 +0000117 unsigned TargetColumns = Columns;
118 if (TargetColumns > 8)
119 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000120 unsigned SourceLength = SourceLine.size();
Douglas Gregor006fd382009-05-04 06:45:38 +0000121 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000122 bool ExpandedRegion = false;
123 // Move the start of the interesting region left until we've
124 // pulled in something else interesting.
Douglas Gregor006fd382009-05-04 06:45:38 +0000125 if (CaretStart == 1)
126 CaretStart = 0;
127 else if (CaretStart > 1) {
128 unsigned NewStart = CaretStart - 1;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000129
Douglas Gregor006fd382009-05-04 06:45:38 +0000130 // Skip over any whitespace we see here; we're looking for
131 // another bit of interesting text.
132 while (NewStart && isspace(SourceLine[NewStart]))
133 --NewStart;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000134
Douglas Gregor006fd382009-05-04 06:45:38 +0000135 // Skip over this bit of "interesting" text.
136 while (NewStart && !isspace(SourceLine[NewStart]))
137 --NewStart;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000138
Douglas Gregor006fd382009-05-04 06:45:38 +0000139 // Move up to the non-whitespace character we just saw.
140 if (NewStart)
141 ++NewStart;
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000142
143 // If we're still within our limit, update the starting
144 // position within the source/caret line.
Douglas Gregor006fd382009-05-04 06:45:38 +0000145 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000146 CaretStart = NewStart;
147 ExpandedRegion = true;
148 }
149 }
150
151 // Move the end of the interesting region right until we've
152 // pulled in something else interesting.
Daniel Dunbar6f949912009-05-03 23:04:40 +0000153 if (CaretEnd != SourceLength) {
Daniel Dunbar28a24fd2009-10-19 09:11:21 +0000154 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000155 unsigned NewEnd = CaretEnd;
156
157 // Skip over any whitespace we see here; we're looking for
158 // another bit of interesting text.
Douglas Gregor8e35e2d2009-05-18 22:09:16 +0000159 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000160 ++NewEnd;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000161
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000162 // Skip over this bit of "interesting" text.
Douglas Gregor8e35e2d2009-05-18 22:09:16 +0000163 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000164 ++NewEnd;
165
166 if (NewEnd - CaretStart <= TargetColumns) {
167 CaretEnd = NewEnd;
168 ExpandedRegion = true;
169 }
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000170 }
Daniel Dunbar6f949912009-05-03 23:04:40 +0000171
172 if (!ExpandedRegion)
173 break;
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000174 }
175
176 // [CaretStart, CaretEnd) is the slice we want. Update the various
177 // output lines to show only this slice, with two-space padding
178 // before the lines so that it looks nicer.
Douglas Gregor54c6a3b2009-05-03 04:12:51 +0000179 if (CaretEnd < SourceLine.size())
180 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregorcb516622009-05-03 15:24:25 +0000181 if (CaretEnd < CaretLine.size())
182 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000183 if (FixItInsertionLine.size() > CaretEnd)
184 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000185
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000186 if (CaretStart > 2) {
Douglas Gregor54c6a3b2009-05-03 04:12:51 +0000187 SourceLine.replace(0, CaretStart, " ...");
188 CaretLine.replace(0, CaretStart, " ");
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000189 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor54c6a3b2009-05-03 04:12:51 +0000190 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000191 }
192}
193
Chandler Carruth64d376a2011-07-14 08:20:31 +0000194/// Look through spelling locations for a macro argument expansion, and
Chandler Carruth402bb382011-07-07 23:56:36 +0000195/// if found skip to it so that we can trace the argument rather than the macros
Chandler Carruth64d376a2011-07-14 08:20:31 +0000196/// in which that argument is used. If no macro argument expansion is found,
Chandler Carruth402bb382011-07-07 23:56:36 +0000197/// don't skip anything and return the starting location.
Chandler Carruth64d376a2011-07-14 08:20:31 +0000198static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
Chandler Carruth402bb382011-07-07 23:56:36 +0000199 SourceLocation StartLoc) {
200 for (SourceLocation L = StartLoc; L.isMacroID();
201 L = SM.getImmediateSpellingLoc(L)) {
Chandler Carruthaa631532011-07-26 03:03:00 +0000202 if (SM.isMacroArgExpansion(L))
Chandler Carruth402bb382011-07-07 23:56:36 +0000203 return L;
204 }
205
206 // Otherwise just return initial location, there's nothing to skip.
207 return StartLoc;
208}
209
210/// Gets the location of the immediate macro caller, one level up the stack
211/// toward the initial macro typed into the source.
212static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
213 SourceLocation Loc) {
214 if (!Loc.isMacroID()) return Loc;
215
216 // When we have the location of (part of) an expanded parameter, its spelling
217 // location points to the argument as typed into the macro call, and
218 // therefore is used to locate the macro caller.
Chandler Carruthaa631532011-07-26 03:03:00 +0000219 if (SM.isMacroArgExpansion(Loc))
Chandler Carruth402bb382011-07-07 23:56:36 +0000220 return SM.getImmediateSpellingLoc(Loc);
221
222 // Otherwise, the caller of the macro is located where this macro is
Chandler Carruth64d376a2011-07-14 08:20:31 +0000223 // expanded (while the spelling is part of the macro definition).
Chandler Carruthca757582011-07-25 20:52:21 +0000224 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruth402bb382011-07-07 23:56:36 +0000225}
226
227/// Gets the location of the immediate macro callee, one level down the stack
228/// toward the leaf macro.
229static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
230 SourceLocation Loc) {
231 if (!Loc.isMacroID()) return Loc;
232
233 // When we have the location of (part of) an expanded parameter, its
Chandler Carruth64d376a2011-07-14 08:20:31 +0000234 // expansion location points to the unexpanded paramater reference within
Chandler Carruth402bb382011-07-07 23:56:36 +0000235 // the macro definition (or callee).
Chandler Carruthaa631532011-07-26 03:03:00 +0000236 if (SM.isMacroArgExpansion(Loc))
Chandler Carruthca757582011-07-25 20:52:21 +0000237 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruth402bb382011-07-07 23:56:36 +0000238
239 // Otherwise, the callee of the macro is located where this location was
240 // spelled inside the macro definition.
241 return SM.getImmediateSpellingLoc(Loc);
242}
243
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000244/// Get the presumed location of a diagnostic message. This computes the
245/// presumed location for the top of any macro backtrace when present.
246static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
247 SourceLocation Loc) {
248 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
249 // walk to the top of the macro call stack.
250 while (Loc.isMacroID()) {
251 Loc = skipToMacroArgExpansion(SM, Loc);
252 Loc = getImmediateMacroCallerLoc(SM, Loc);
253 }
254
255 return SM.getPresumedLoc(Loc);
256}
257
258/// \brief Print the diagonstic level to a raw_ostream.
259///
260/// Handles colorizing the level and formatting.
261static void printDiagnosticLevel(raw_ostream &OS,
262 DiagnosticsEngine::Level Level,
263 bool ShowColors) {
264 if (ShowColors) {
265 // Print diagnostic category in bold and color
266 switch (Level) {
267 case DiagnosticsEngine::Ignored:
268 llvm_unreachable("Invalid diagnostic type");
269 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
270 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
271 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
272 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
273 }
274 }
275
276 switch (Level) {
277 case DiagnosticsEngine::Ignored: llvm_unreachable("Invalid diagnostic type");
278 case DiagnosticsEngine::Note: OS << "note: "; break;
279 case DiagnosticsEngine::Warning: OS << "warning: "; break;
280 case DiagnosticsEngine::Error: OS << "error: "; break;
281 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
282 }
283
284 if (ShowColors)
285 OS.resetColor();
286}
287
288/// \brief Skip over whitespace in the string, starting at the given
289/// index.
290///
291/// \returns The index of the first non-whitespace character that is
292/// greater than or equal to Idx or, if no such character exists,
293/// returns the end of the string.
294static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
295 while (Idx < Length && isspace(Str[Idx]))
296 ++Idx;
297 return Idx;
298}
299
300/// \brief If the given character is the start of some kind of
301/// balanced punctuation (e.g., quotes or parentheses), return the
302/// character that will terminate the punctuation.
303///
304/// \returns The ending punctuation character, if any, or the NULL
305/// character if the input character does not start any punctuation.
306static inline char findMatchingPunctuation(char c) {
307 switch (c) {
308 case '\'': return '\'';
309 case '`': return '\'';
310 case '"': return '"';
311 case '(': return ')';
312 case '[': return ']';
313 case '{': return '}';
314 default: break;
315 }
316
317 return 0;
318}
319
320/// \brief Find the end of the word starting at the given offset
321/// within a string.
322///
323/// \returns the index pointing one character past the end of the
324/// word.
325static unsigned findEndOfWord(unsigned Start, StringRef Str,
326 unsigned Length, unsigned Column,
327 unsigned Columns) {
328 assert(Start < Str.size() && "Invalid start position!");
329 unsigned End = Start + 1;
330
331 // If we are already at the end of the string, take that as the word.
332 if (End == Str.size())
333 return End;
334
335 // Determine if the start of the string is actually opening
336 // punctuation, e.g., a quote or parentheses.
337 char EndPunct = findMatchingPunctuation(Str[Start]);
338 if (!EndPunct) {
339 // This is a normal word. Just find the first space character.
340 while (End < Length && !isspace(Str[End]))
341 ++End;
342 return End;
343 }
344
345 // We have the start of a balanced punctuation sequence (quotes,
346 // parentheses, etc.). Determine the full sequence is.
347 llvm::SmallString<16> PunctuationEndStack;
348 PunctuationEndStack.push_back(EndPunct);
349 while (End < Length && !PunctuationEndStack.empty()) {
350 if (Str[End] == PunctuationEndStack.back())
351 PunctuationEndStack.pop_back();
352 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
353 PunctuationEndStack.push_back(SubEndPunct);
354
355 ++End;
356 }
357
358 // Find the first space character after the punctuation ended.
359 while (End < Length && !isspace(Str[End]))
360 ++End;
361
362 unsigned PunctWordLength = End - Start;
363 if (// If the word fits on this line
364 Column + PunctWordLength <= Columns ||
365 // ... or the word is "short enough" to take up the next line
366 // without too much ugly white space
367 PunctWordLength < Columns/3)
368 return End; // Take the whole thing as a single "word".
369
370 // The whole quoted/parenthesized string is too long to print as a
371 // single "word". Instead, find the "word" that starts just after
372 // the punctuation and use that end-point instead. This will recurse
373 // until it finds something small enough to consider a word.
374 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
375}
376
377/// \brief Print the given string to a stream, word-wrapping it to
378/// some number of columns in the process.
379///
380/// \param OS the stream to which the word-wrapping string will be
381/// emitted.
382/// \param Str the string to word-wrap and output.
383/// \param Columns the number of columns to word-wrap to.
384/// \param Column the column number at which the first character of \p
385/// Str will be printed. This will be non-zero when part of the first
386/// line has already been printed.
387/// \param Indentation the number of spaces to indent any lines beyond
388/// the first line.
389/// \returns true if word-wrapping was required, or false if the
390/// string fit on the first line.
391static bool printWordWrapped(raw_ostream &OS, StringRef Str,
392 unsigned Columns,
393 unsigned Column = 0,
394 unsigned Indentation = WordWrapIndentation) {
395 const unsigned Length = std::min(Str.find('\n'), Str.size());
396
397 // The string used to indent each line.
398 llvm::SmallString<16> IndentStr;
399 IndentStr.assign(Indentation, ' ');
400 bool Wrapped = false;
401 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
402 WordStart = WordEnd) {
403 // Find the beginning of the next word.
404 WordStart = skipWhitespace(WordStart, Str, Length);
405 if (WordStart == Length)
406 break;
407
408 // Find the end of this word.
409 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
410
411 // Does this word fit on the current line?
412 unsigned WordLength = WordEnd - WordStart;
413 if (Column + WordLength < Columns) {
414 // This word fits on the current line; print it there.
415 if (WordStart) {
416 OS << ' ';
417 Column += 1;
418 }
419 OS << Str.substr(WordStart, WordLength);
420 Column += WordLength;
421 continue;
422 }
423
424 // This word does not fit on the current line, so wrap to the next
425 // line.
426 OS << '\n';
427 OS.write(&IndentStr[0], Indentation);
428 OS << Str.substr(WordStart, WordLength);
429 Column = Indentation + WordLength;
430 Wrapped = true;
431 }
432
433 // Append any remaning text from the message with its existing formatting.
434 OS << Str.substr(Length);
435
436 return Wrapped;
437}
438
439static void printDiagnosticMessage(raw_ostream &OS,
440 DiagnosticsEngine::Level Level,
441 StringRef Message,
442 unsigned CurrentColumn, unsigned Columns,
443 bool ShowColors) {
444 if (ShowColors) {
445 // Print warnings, errors and fatal errors in bold, no color
446 switch (Level) {
447 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
448 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
449 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
450 default: break; //don't bold notes
451 }
452 }
453
454 if (Columns)
455 printWordWrapped(OS, Message, Columns, CurrentColumn);
456 else
457 OS << Message;
458
459 if (ShowColors)
460 OS.resetColor();
461 OS << '\n';
462}
463
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000464namespace {
465
Chandler Carruth84f36192011-09-25 22:54:56 +0000466/// \brief Class to encapsulate the logic for formatting and printing a textual
467/// diagnostic message.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000468///
Chandler Carruth84f36192011-09-25 22:54:56 +0000469/// This class provides an interface for building and emitting a textual
470/// diagnostic, including all of the macro backtraces, caret diagnostics, FixIt
471/// Hints, and code snippets. In the presence of macros this involves
472/// a recursive process, synthesizing notes for each macro expansion.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000473///
Chandler Carruth84f36192011-09-25 22:54:56 +0000474/// The purpose of this class is to isolate the implementation of printing
475/// beautiful text diagnostics from any particular interfaces. The Clang
476/// DiagnosticClient is implemented through this class as is diagnostic
477/// printing coming out of libclang.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000478///
Chandler Carruth84f36192011-09-25 22:54:56 +0000479/// A brief worklist:
Chandler Carruth84f36192011-09-25 22:54:56 +0000480/// FIXME: Sink the recursive printing of template instantiations into this
481/// class.
482class TextDiagnostic {
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000483 raw_ostream &OS;
484 const SourceManager &SM;
485 const LangOptions &LangOpts;
486 const DiagnosticOptions &DiagOpts;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000487
Chandler Carruth3d262182011-10-15 11:44:27 +0000488 /// \brief The location of the previous diagnostic if known.
489 ///
490 /// This will be invalid in cases where there is no (known) previous
491 /// diagnostic location, or that location itself is invalid or comes from
492 /// a different source manager than SM.
493 SourceLocation LastLoc;
494
495 /// \brief The location of the previous non-note diagnostic if known.
496 ///
497 /// Same restriction as \see LastLoc but tracks the last non-note location.
498 SourceLocation LastNonNoteLoc;
499
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000500public:
Chandler Carruthc9b1c182011-10-15 12:07:49 +0000501 TextDiagnostic(raw_ostream &OS,
Chandler Carruth3d262182011-10-15 11:44:27 +0000502 const SourceManager &SM,
503 const LangOptions &LangOpts,
504 const DiagnosticOptions &DiagOpts,
505 FullSourceLoc LastLoc = FullSourceLoc(),
506 FullSourceLoc LastNonNoteLoc = FullSourceLoc())
Chandler Carruthc9b1c182011-10-15 12:07:49 +0000507 : OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
Chandler Carruth3d262182011-10-15 11:44:27 +0000508 LastLoc(LastLoc), LastNonNoteLoc(LastNonNoteLoc) {
509 if (LastLoc.isValid() && &SM != &LastLoc.getManager())
510 this->LastLoc = SourceLocation();
511 if (LastNonNoteLoc.isValid() && &SM != &LastNonNoteLoc.getManager())
512 this->LastNonNoteLoc = SourceLocation();
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000513 }
514
Chandler Carruth3d262182011-10-15 11:44:27 +0000515 /// \brief Get the last diagnostic location emitted.
516 SourceLocation getLastLoc() const { return LastLoc; }
517
Chandler Carruth636b2502011-10-15 12:07:47 +0000518 /// \brief Get the last non-note diagnostic location emitted.
519 SourceLocation getLastNonNoteLoc() const { return LastNonNoteLoc; }
520
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000521 void Emit(SourceLocation Loc, DiagnosticsEngine::Level Level,
522 StringRef Message, ArrayRef<CharSourceRange> Ranges,
523 ArrayRef<FixItHint> FixItHints,
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000524 bool LastCaretDiagnosticWasNote = false) {
525 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
526
527 // First, if this diagnostic is not in the main file, print out the
528 // "included from" lines.
Chandler Carruth636b2502011-10-15 12:07:47 +0000529 emitIncludeStack(PLoc.getIncludeLoc(), Level);
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000530
531 uint64_t StartOfLocationInfo = OS.tell();
532
533 // Next emit the location of this particular diagnostic.
Chandler Carruth99eb7dc2011-10-15 11:09:23 +0000534 EmitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000535
536 if (DiagOpts.ShowColors)
537 OS.resetColor();
538
539 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
540 printDiagnosticMessage(OS, Level, Message,
541 OS.tell() - StartOfLocationInfo,
542 DiagOpts.MessageLength, DiagOpts.ShowColors);
543
544 // If caret diagnostics are enabled and we have location, we want to
545 // emit the caret. However, we only do this if the location moved
546 // from the last diagnostic, if the last diagnostic was a note that
547 // was part of a different warning or error diagnostic, or if the
548 // diagnostic has ranges. We don't want to emit the same caret
549 // multiple times if one loc has multiple diagnostics.
550 if (DiagOpts.ShowCarets &&
551 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
552 (LastCaretDiagnosticWasNote && Level != DiagnosticsEngine::Note))) {
553 // Get the ranges into a local array we can hack on.
554 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
555 Ranges.end());
556
557 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
558 E = FixItHints.end();
559 I != E; ++I)
560 if (I->RemoveRange.isValid())
561 MutableRanges.push_back(I->RemoveRange);
562
563 unsigned MacroDepth = 0;
564 EmitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
565 }
Chandler Carruth3d262182011-10-15 11:44:27 +0000566
567 LastLoc = Loc;
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000568 }
569
Chandler Carruth09c74642011-10-15 01:21:55 +0000570 /// \brief Emit the caret and underlining text.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000571 ///
572 /// Walks up the macro expansion stack printing the code snippet, caret,
573 /// underlines and FixItHint display as appropriate at each level. Walk is
574 /// accomplished by calling itself recursively.
575 ///
Chandler Carruth09c74642011-10-15 01:21:55 +0000576 /// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
577 /// caret diagnostics.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000578 /// FIXME: Break up massive function into logical units.
579 ///
580 /// \param Loc The location for this caret.
581 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000582 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000583 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000584 /// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruth09c74642011-10-15 01:21:55 +0000585 void EmitCaret(SourceLocation Loc,
Chandler Carruth773757a2011-09-07 01:47:09 +0000586 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000587 ArrayRef<FixItHint> Hints,
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000588 unsigned &MacroDepth,
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000589 unsigned OnMacroInst = 0) {
590 assert(!Loc.isInvalid() && "must have a valid source location here");
591
Chandler Carruth9d229f32011-09-25 06:59:38 +0000592 // If this is a file source location, directly emit the source snippet and
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000593 // caret line. Also record the macro depth reached.
594 if (Loc.isFileID()) {
595 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
596 MacroDepth = OnMacroInst;
597 EmitSnippetAndCaret(Loc, Ranges, Hints);
598 return;
599 }
Chandler Carruth9d229f32011-09-25 06:59:38 +0000600 // Otherwise recurse through each macro expansion layer.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000601
Chandler Carruth9d229f32011-09-25 06:59:38 +0000602 // When processing macros, skip over the expansions leading up to
603 // a macro argument, and trace the argument's expansion stack instead.
604 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000605
Chandler Carruth9d229f32011-09-25 06:59:38 +0000606 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000607
Chandler Carruth9d229f32011-09-25 06:59:38 +0000608 // FIXME: Map ranges?
Chandler Carruth09c74642011-10-15 01:21:55 +0000609 EmitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000610
Chandler Carruth9d229f32011-09-25 06:59:38 +0000611 // Map the location.
612 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000613
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000614 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
615 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
616 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
617 DiagOpts.MacroBacktraceLimit % 2;
618 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
619 }
620
621 // Whether to suppress printing this macro expansion.
622 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
623 OnMacroInst < MacroSkipEnd);
624
Chandler Carruth9d229f32011-09-25 06:59:38 +0000625 // Map the ranges.
626 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
627 E = Ranges.end();
628 I != E; ++I) {
629 SourceLocation Start = I->getBegin(), End = I->getEnd();
630 if (Start.isMacroID())
631 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
632 if (End.isMacroID())
633 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
634 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000635
Chandler Carruth9d229f32011-09-25 06:59:38 +0000636 if (!Suppressed) {
637 // Don't print recursive expansion notes from an expansion note.
638 Loc = SM.getSpellingLoc(Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000639
Chandler Carruth9d229f32011-09-25 06:59:38 +0000640 // Get the pretty name, according to #line directives etc.
641 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
642 if (PLoc.isInvalid())
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000643 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000644
Chandler Carruth9d229f32011-09-25 06:59:38 +0000645 // If this diagnostic is not in the main file, print out the
646 // "included from" lines.
Chandler Carruth636b2502011-10-15 12:07:47 +0000647 emitIncludeStack(PLoc.getIncludeLoc(), DiagnosticsEngine::Note);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000648
Chandler Carruth9d229f32011-09-25 06:59:38 +0000649 if (DiagOpts.ShowLocation) {
650 // Emit the file/line/column that this expansion came from.
651 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
652 if (DiagOpts.ShowColumn)
653 OS << PLoc.getColumn() << ':';
654 OS << ' ';
655 }
656 OS << "note: expanded from:\n";
657
658 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000659 return;
660 }
661
Chandler Carruth9d229f32011-09-25 06:59:38 +0000662 if (OnMacroInst == MacroSkipStart) {
663 // Tell the user that we've skipped contexts.
664 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
665 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
666 "all)\n";
667 }
668 }
669
670 /// \brief Emit a code snippet and caret line.
671 ///
672 /// This routine emits a single line's code snippet and caret line..
673 ///
674 /// \param Loc The location for the caret.
675 /// \param Ranges The underlined ranges for this code snippet.
676 /// \param Hints The FixIt hints active for this diagnostic.
677 void EmitSnippetAndCaret(SourceLocation Loc,
678 SmallVectorImpl<CharSourceRange>& Ranges,
679 ArrayRef<FixItHint> Hints) {
680 assert(!Loc.isInvalid() && "must have a valid source location here");
681 assert(Loc.isFileID() && "must have a file location here");
682
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000683 // Decompose the location into a FID/Offset pair.
684 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
685 FileID FID = LocInfo.first;
686 unsigned FileOffset = LocInfo.second;
687
688 // Get information about the buffer it points into.
689 bool Invalid = false;
690 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
691 if (Invalid)
692 return;
693
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000694 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000695 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
696 unsigned CaretEndColNo
697 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
698
699 // Rewind from the current position to the start of the line.
700 const char *TokPtr = BufStart+FileOffset;
701 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
702
703
704 // Compute the line end. Scan forward from the error position to the end of
705 // the line.
706 const char *LineEnd = TokPtr;
707 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
708 ++LineEnd;
709
710 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
711 // the source line length as currently being computed. See
712 // test/Misc/message-length.c.
713 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
714
715 // Copy the line of code into an std::string for ease of manipulation.
716 std::string SourceLine(LineStart, LineEnd);
717
718 // Create a line for the caret that is filled with spaces that is the same
719 // length as the line of source code.
720 std::string CaretLine(LineEnd-LineStart, ' ');
721
722 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000723 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
724 E = Ranges.end();
725 I != E; ++I)
Chandler Carruth97798302011-09-07 07:02:31 +0000726 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000727
728 // Next, insert the caret itself.
729 if (ColNo-1 < CaretLine.size())
730 CaretLine[ColNo-1] = '^';
731 else
732 CaretLine.push_back('^');
733
Chandler Carruthe79ddf82011-09-07 05:36:50 +0000734 ExpandTabs(SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000735
736 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
737 // to produce easily machine parsable output. Add a space before the
738 // source line and the caret to make it trivial to tell the main diagnostic
739 // line from what the user is intended to see.
740 if (DiagOpts.ShowSourceRanges) {
741 SourceLine = ' ' + SourceLine;
742 CaretLine = ' ' + CaretLine;
743 }
744
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000745 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000746 LineStart, LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000747 Hints);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000748
749 // If the source line is too long for our terminal, select only the
750 // "interesting" source region within that line.
Chandler Carruth3236f0d2011-09-25 22:31:58 +0000751 unsigned Columns = DiagOpts.MessageLength;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000752 if (Columns && SourceLine.size() > Columns)
753 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
754 CaretEndColNo, Columns);
755
756 // Finally, remove any blank spaces from the end of CaretLine.
757 while (CaretLine[CaretLine.size()-1] == ' ')
758 CaretLine.erase(CaretLine.end()-1);
759
760 // Emit what we have computed.
761 OS << SourceLine << '\n';
762
763 if (DiagOpts.ShowColors)
764 OS.changeColor(caretColor, true);
765 OS << CaretLine << '\n';
766 if (DiagOpts.ShowColors)
767 OS.resetColor();
768
769 if (!FixItInsertionLine.empty()) {
770 if (DiagOpts.ShowColors)
771 // Print fixit line in color
772 OS.changeColor(fixitColor, false);
773 if (DiagOpts.ShowSourceRanges)
774 OS << ' ';
775 OS << FixItInsertionLine << '\n';
776 if (DiagOpts.ShowColors)
777 OS.resetColor();
778 }
779
Chandler Carruthd3e83672011-09-02 06:30:30 +0000780 // Print out any parseable fixit information requested by the options.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000781 EmitParseableFixits(Hints);
Chandler Carruthd3e83672011-09-02 06:30:30 +0000782 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000783
Chandler Carruthd3e83672011-09-02 06:30:30 +0000784private:
Chandler Carruth636b2502011-10-15 12:07:47 +0000785 /// \brief Prints an include stack when appropriate for a particular
786 /// diagnostic level and location.
787 ///
788 /// This routine handles all the logic of suppressing particular include
789 /// stacks (such as those for notes) and duplicate include stacks when
790 /// repeated warnings occur within the same file. It also handles the logic
791 /// of customizing the formatting and display of the include stack.
792 ///
793 /// \param Level The diagnostic level of the message this stack pertains to.
794 /// \param Loc The include location of the current file (not the diagnostic
795 /// location).
796 void emitIncludeStack(SourceLocation Loc, DiagnosticsEngine::Level Level) {
797 // Skip redundant include stacks altogether.
798 if (LastNonNoteLoc == Loc)
799 return;
800 LastNonNoteLoc = Loc;
801
802 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
803 return;
804
805 emitIncludeStackRecursively(Loc);
806 }
807
808 /// \brief Helper to recursivly walk up the include stack and print each layer
809 /// on the way back down.
810 void emitIncludeStackRecursively(SourceLocation Loc) {
811 if (Loc.isInvalid())
812 return;
813
814 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
815 if (PLoc.isInvalid())
816 return;
817
818 // Emit the other include frames first.
819 emitIncludeStackRecursively(PLoc.getIncludeLoc());
820
821 if (DiagOpts.ShowLocation)
822 OS << "In file included from " << PLoc.getFilename()
823 << ':' << PLoc.getLine() << ":\n";
824 else
825 OS << "In included file:\n";
826 }
827
Chandler Carruth99eb7dc2011-10-15 11:09:23 +0000828 /// \brief Print out the file/line/column information and include trace.
829 ///
830 /// This method handlen the emission of the diagnostic location information.
831 /// This includes extracting as much location information as is present for
832 /// the diagnostic and printing it, as well as any include stack or source
833 /// ranges necessary.
834 void EmitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
835 DiagnosticsEngine::Level Level,
836 ArrayRef<CharSourceRange> Ranges) {
837 if (PLoc.isInvalid()) {
838 // At least print the file name if available:
839 FileID FID = SM.getFileID(Loc);
840 if (!FID.isInvalid()) {
841 const FileEntry* FE = SM.getFileEntryForID(FID);
842 if (FE && FE->getName()) {
843 OS << FE->getName();
844 if (FE->getDevice() == 0 && FE->getInode() == 0
845 && FE->getFileMode() == 0) {
846 // in PCH is a guess, but a good one:
847 OS << " (in PCH)";
848 }
849 OS << ": ";
850 }
851 }
852 return;
853 }
854 unsigned LineNo = PLoc.getLine();
855
856 if (!DiagOpts.ShowLocation)
857 return;
858
859 if (DiagOpts.ShowColors)
860 OS.changeColor(savedColor, true);
861
862 OS << PLoc.getFilename();
863 switch (DiagOpts.Format) {
864 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
865 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
866 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
867 }
868
869 if (DiagOpts.ShowColumn)
870 // Compute the column number.
871 if (unsigned ColNo = PLoc.getColumn()) {
872 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
873 OS << ',';
874 ColNo--;
875 } else
876 OS << ':';
877 OS << ColNo;
878 }
879 switch (DiagOpts.Format) {
880 case DiagnosticOptions::Clang:
881 case DiagnosticOptions::Vi: OS << ':'; break;
882 case DiagnosticOptions::Msvc: OS << ") : "; break;
883 }
884
885 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
886 FileID CaretFileID =
887 SM.getFileID(SM.getExpansionLoc(Loc));
888 bool PrintedRange = false;
889
890 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
891 RE = Ranges.end();
892 RI != RE; ++RI) {
893 // Ignore invalid ranges.
894 if (!RI->isValid()) continue;
895
896 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
897 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
898
899 // If the End location and the start location are the same and are a
900 // macro location, then the range was something that came from a
901 // macro expansion or _Pragma. If this is an object-like macro, the
902 // best we can do is to highlight the range. If this is a
903 // function-like macro, we'd also like to highlight the arguments.
904 if (B == E && RI->getEnd().isMacroID())
905 E = SM.getExpansionRange(RI->getEnd()).second;
906
907 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
908 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
909
910 // If the start or end of the range is in another file, just discard
911 // it.
912 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
913 continue;
914
915 // Add in the length of the token, so that we cover multi-char
916 // tokens.
917 unsigned TokSize = 0;
918 if (RI->isTokenRange())
919 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
920
921 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
922 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
923 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
924 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
925 << '}';
926 PrintedRange = true;
927 }
928
929 if (PrintedRange)
930 OS << ':';
931 }
932 OS << ' ';
933 }
934
Chandler Carruth97798302011-09-07 07:02:31 +0000935 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
936 void HighlightRange(const CharSourceRange &R,
937 unsigned LineNo, FileID FID,
938 const std::string &SourceLine,
939 std::string &CaretLine) {
940 assert(CaretLine.size() == SourceLine.size() &&
941 "Expect a correspondence between source and caret line!");
942 if (!R.isValid()) return;
943
944 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
945 SourceLocation End = SM.getExpansionLoc(R.getEnd());
946
947 // If the End location and the start location are the same and are a macro
948 // location, then the range was something that came from a macro expansion
949 // or _Pragma. If this is an object-like macro, the best we can do is to
950 // highlight the range. If this is a function-like macro, we'd also like to
951 // highlight the arguments.
952 if (Begin == End && R.getEnd().isMacroID())
953 End = SM.getExpansionRange(R.getEnd()).second;
954
955 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
956 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
957 return; // No intersection.
958
959 unsigned EndLineNo = SM.getExpansionLineNumber(End);
960 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
961 return; // No intersection.
962
963 // Compute the column number of the start.
964 unsigned StartColNo = 0;
965 if (StartLineNo == LineNo) {
966 StartColNo = SM.getExpansionColumnNumber(Begin);
967 if (StartColNo) --StartColNo; // Zero base the col #.
968 }
969
970 // Compute the column number of the end.
971 unsigned EndColNo = CaretLine.size();
972 if (EndLineNo == LineNo) {
973 EndColNo = SM.getExpansionColumnNumber(End);
974 if (EndColNo) {
975 --EndColNo; // Zero base the col #.
976
977 // Add in the length of the token, so that we cover multi-char tokens if
978 // this is a token range.
979 if (R.isTokenRange())
980 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
981 } else {
982 EndColNo = CaretLine.size();
983 }
984 }
985
986 assert(StartColNo <= EndColNo && "Invalid range!");
987
988 // Check that a token range does not highlight only whitespace.
989 if (R.isTokenRange()) {
990 // Pick the first non-whitespace column.
991 while (StartColNo < SourceLine.size() &&
992 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
993 ++StartColNo;
994
995 // Pick the last non-whitespace column.
996 if (EndColNo > SourceLine.size())
997 EndColNo = SourceLine.size();
998 while (EndColNo-1 &&
999 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
1000 --EndColNo;
1001
1002 // If the start/end passed each other, then we are trying to highlight a
1003 // range that just exists in whitespace, which must be some sort of other
1004 // bug.
1005 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1006 }
1007
1008 // Fill the range with ~'s.
1009 for (unsigned i = StartColNo; i < EndColNo; ++i)
1010 CaretLine[i] = '~';
1011 }
1012
Chandler Carruth0f1006a2011-09-07 05:01:10 +00001013 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001014 const char *LineStart,
1015 const char *LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001016 ArrayRef<FixItHint> Hints) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001017 std::string FixItInsertionLine;
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001018 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001019 return FixItInsertionLine;
1020
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001021 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1022 I != E; ++I) {
1023 if (!I->CodeToInsert.empty()) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001024 // We have an insertion hint. Determine whether the inserted
1025 // code is on the same line as the caret.
1026 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001027 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0f1006a2011-09-07 05:01:10 +00001028 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001029 // Insert the new code into the line just below the code
1030 // that the user wrote.
1031 unsigned HintColNo
1032 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
1033 unsigned LastColumnModified
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001034 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001035 if (LastColumnModified > FixItInsertionLine.size())
1036 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001037 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001038 FixItInsertionLine.begin() + HintColNo - 1);
1039 } else {
1040 FixItInsertionLine.clear();
1041 break;
1042 }
1043 }
1044 }
1045
1046 if (FixItInsertionLine.empty())
1047 return FixItInsertionLine;
1048
1049 // Now that we have the entire fixit line, expand the tabs in it.
1050 // Since we don't want to insert spaces in the middle of a word,
1051 // find each word and the column it should line up with and insert
1052 // spaces until they match.
1053 unsigned FixItPos = 0;
1054 unsigned LinePos = 0;
1055 unsigned TabExpandedCol = 0;
1056 unsigned LineLength = LineEnd - LineStart;
1057
1058 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
1059 // Find the next word in the FixIt line.
1060 while (FixItPos < FixItInsertionLine.size() &&
1061 FixItInsertionLine[FixItPos] == ' ')
1062 ++FixItPos;
1063 unsigned CharDistance = FixItPos - TabExpandedCol;
1064
1065 // Walk forward in the source line, keeping track of
1066 // the tab-expanded column.
1067 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
1068 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
1069 ++TabExpandedCol;
1070 else
1071 TabExpandedCol =
1072 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
1073
1074 // Adjust the fixit line to match this column.
1075 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
1076 FixItPos = TabExpandedCol;
1077
1078 // Walk to the end of the word.
1079 while (FixItPos < FixItInsertionLine.size() &&
1080 FixItInsertionLine[FixItPos] != ' ')
1081 ++FixItPos;
1082 }
1083
1084 return FixItInsertionLine;
1085 }
1086
Chandler Carruthe79ddf82011-09-07 05:36:50 +00001087 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
1088 // Scan the source line, looking for tabs. If we find any, manually expand
1089 // them to spaces and update the CaretLine to match.
1090 for (unsigned i = 0; i != SourceLine.size(); ++i) {
1091 if (SourceLine[i] != '\t') continue;
1092
1093 // Replace this tab with at least one space.
1094 SourceLine[i] = ' ';
1095
1096 // Compute the number of spaces we need to insert.
1097 unsigned TabStop = DiagOpts.TabStop;
1098 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1099 "Invalid -ftabstop value");
1100 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
1101 assert(NumSpaces < TabStop && "Invalid computation of space amt");
1102
1103 // Insert spaces into the SourceLine.
1104 SourceLine.insert(i+1, NumSpaces, ' ');
1105
1106 // Insert spaces or ~'s into CaretLine.
1107 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
1108 }
1109 }
1110
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001111 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthd3e83672011-09-02 06:30:30 +00001112 if (!DiagOpts.ShowParseableFixits)
1113 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001114
Chandler Carruthd3e83672011-09-02 06:30:30 +00001115 // We follow FixItRewriter's example in not (yet) handling
1116 // fix-its in macros.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001117 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1118 I != E; ++I) {
1119 if (I->RemoveRange.isInvalid() ||
1120 I->RemoveRange.getBegin().isMacroID() ||
1121 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthd3e83672011-09-02 06:30:30 +00001122 return;
1123 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001124
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001125 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1126 I != E; ++I) {
1127 SourceLocation BLoc = I->RemoveRange.getBegin();
1128 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001129
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001130 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1131 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001132
Chandler Carruthd3e83672011-09-02 06:30:30 +00001133 // Adjust for token ranges.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001134 if (I->RemoveRange.isTokenRange())
1135 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001136
Chandler Carruthd3e83672011-09-02 06:30:30 +00001137 // We specifically do not do word-wrapping or tab-expansion here,
1138 // because this is supposed to be easy to parse.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001139 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001140 if (PLoc.isInvalid())
1141 break;
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001142
Chandler Carruthd3e83672011-09-02 06:30:30 +00001143 OS << "fix-it:\"";
Chandler Carruth935574d2011-09-06 22:34:33 +00001144 OS.write_escaped(PLoc.getFilename());
Chandler Carruthd3e83672011-09-02 06:30:30 +00001145 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1146 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1147 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1148 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1149 << "}:\"";
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001150 OS.write_escaped(I->CodeToInsert);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001151 OS << "\"\n";
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001152 }
1153 }
1154};
1155
1156} // end namespace
1157
Chandler Carruthcf259a42011-09-26 01:30:09 +00001158/// \brief Print the diagnostic name to a raw_ostream.
1159///
1160/// This prints the diagnostic name to a raw_ostream if it has one. It formats
1161/// the name according to the expected diagnostic message formatting:
1162/// " [diagnostic_name_here]"
1163static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
Chandler Carruthb59f9cb92011-09-26 00:37:30 +00001164 if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
1165 OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
1166}
1167
Chandler Carruthcf259a42011-09-26 01:30:09 +00001168/// \brief Print any diagnostic option information to a raw_ostream.
1169///
1170/// This implements all of the logic for adding diagnostic options to a message
1171/// (via OS). Each relevant option is comma separated and all are enclosed in
1172/// the standard bracketing: " [...]".
1173static void printDiagnosticOptions(raw_ostream &OS,
Chandler Carruth60740842011-09-26 00:44:09 +00001174 DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001175 const Diagnostic &Info,
Chandler Carruth60740842011-09-26 00:44:09 +00001176 const DiagnosticOptions &DiagOpts) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001177 bool Started = false;
Chandler Carruth60740842011-09-26 00:44:09 +00001178 if (DiagOpts.ShowOptionNames) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001179 // Handle special cases for non-warnings early.
1180 if (Info.getID() == diag::fatal_too_many_errors) {
1181 OS << " [-ferror-limit=]";
1182 return;
1183 }
1184
Daniel Dunbaraa111382011-09-29 01:01:08 +00001185 // The code below is somewhat fragile because we are essentially trying to
1186 // report to the user what happened by inferring what the diagnostic engine
1187 // did. Eventually it might make more sense to have the diagnostic engine
1188 // include some "why" information in the diagnostic.
1189
1190 // If this is a warning which has been mapped to an error by the user (as
1191 // inferred by checking whether the default mapping is to an error) then
1192 // flag it as such. Note that diagnostics could also have been mapped by a
1193 // pragma, but we don't currently have a way to distinguish this.
Chandler Carruth60740842011-09-26 00:44:09 +00001194 if (Level == DiagnosticsEngine::Error &&
Daniel Dunbaraa111382011-09-29 01:01:08 +00001195 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID()) &&
1196 !DiagnosticIDs::isDefaultMappingAsError(Info.getID())) {
1197 OS << " [-Werror";
1198 Started = true;
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001199 }
1200
1201 // If the diagnostic is an extension diagnostic and not enabled by default
1202 // then it must have been turned on with -pedantic.
1203 bool EnabledByDefault;
1204 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1205 EnabledByDefault) &&
1206 !EnabledByDefault) {
1207 OS << (Started ? "," : " [") << "-pedantic";
1208 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001209 }
1210
1211 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
1212 if (!Opt.empty()) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001213 OS << (Started ? "," : " [") << "-W" << Opt;
1214 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001215 }
1216 }
Chandler Carruth60740842011-09-26 00:44:09 +00001217
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001218 // If the user wants to see category information, include it too.
1219 if (DiagOpts.ShowCategories) {
1220 unsigned DiagCategory =
1221 DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Chandler Carruth60740842011-09-26 00:44:09 +00001222 if (DiagCategory) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001223 OS << (Started ? "," : " [");
Benjamin Kramere2125d82011-09-26 02:14:13 +00001224 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001225 if (DiagOpts.ShowCategories == 1)
Benjamin Kramere2125d82011-09-26 02:14:13 +00001226 OS << DiagCategory;
Chandler Carruth60740842011-09-26 00:44:09 +00001227 else {
1228 assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
1229 OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
1230 }
1231 }
Chandler Carruth60740842011-09-26 00:44:09 +00001232 }
Benjamin Kramere2125d82011-09-26 02:14:13 +00001233 if (Started)
1234 OS << ']';
Chandler Carruth60740842011-09-26 00:44:09 +00001235}
1236
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001237void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001238 const Diagnostic &Info) {
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001239 // Default implementation (Warnings/errors count).
1240 DiagnosticConsumer::HandleDiagnostic(Level, Info);
1241
Chandler Carruth2be992d2011-09-26 11:25:30 +00001242 // Render the diagnostic message into a temporary buffer eagerly. We'll use
1243 // this later as we print out the diagnostic to the terminal.
1244 llvm::SmallString<100> OutStr;
1245 Info.FormatDiagnostic(OutStr);
1246
1247 llvm::raw_svector_ostream DiagMessageStream(OutStr);
1248 if (DiagOpts->ShowNames)
1249 printDiagnosticName(DiagMessageStream, Info);
1250 printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
1251
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001252 // Keeps track of the the starting position of the location
1253 // information (e.g., "foo.c:10:4:") that precedes the error
1254 // message. We use this information to determine how long the
1255 // file+line+column number prefix is.
1256 uint64_t StartOfLocationInfo = OS.tell();
1257
1258 if (!Prefix.empty())
1259 OS << Prefix << ": ";
1260
Chandler Carruth2be992d2011-09-26 11:25:30 +00001261 // Use a dedicated, simpler path for diagnostics without a valid location.
Chandler Carruth577372e2011-09-26 11:38:46 +00001262 // This is important as if the location is missing, we may be emitting
1263 // diagnostics in a context that lacks language options, a source manager, or
1264 // other infrastructure necessary when emitting more rich diagnostics.
Chandler Carruth2be992d2011-09-26 11:25:30 +00001265 if (!Info.getLocation().isValid()) {
1266 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
1267 printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1268 OS.tell() - StartOfLocationInfo,
1269 DiagOpts->MessageLength, DiagOpts->ShowColors);
1270 OS.flush();
1271 return;
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001272 }
1273
Chandler Carruth577372e2011-09-26 11:38:46 +00001274 // Assert that the rest of our infrastructure is setup properly.
1275 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1276 assert(DiagOpts && "Unexpected diagnostic without options set");
1277 assert(Info.hasSourceManager() &&
1278 "Unexpected diagnostic with no source manager");
Chandler Carruth2be992d2011-09-26 11:25:30 +00001279 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthc9b1c182011-10-15 12:07:49 +00001280 TextDiagnostic TextDiag(OS, SM, *LangOpts, *DiagOpts,
Chandler Carruth636b2502011-10-15 12:07:47 +00001281 LastLoc, LastNonNoteLoc);
Chandler Carruth577372e2011-09-26 11:38:46 +00001282
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001283 TextDiag.Emit(Info.getLocation(), Level, DiagMessageStream.str(),
1284 Info.getRanges(),
1285 llvm::makeArrayRef(Info.getFixItHints(),
1286 Info.getNumFixItHints()),
Chandler Carruth3d262182011-10-15 11:44:27 +00001287 LastCaretDiagnosticWasNote);
Chandler Carruth2be992d2011-09-26 11:25:30 +00001288
Chandler Carruth3d262182011-10-15 11:44:27 +00001289 // Cache the LastLoc from the TextDiagnostic printing.
1290 LastLoc = FullSourceLoc(TextDiag.getLastLoc(), SM);
Chandler Carruth636b2502011-10-15 12:07:47 +00001291 LastNonNoteLoc = FullSourceLoc(TextDiag.getLastNonNoteLoc(), SM);
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001292 LastCaretDiagnosticWasNote = (Level == DiagnosticsEngine::Note);
Daniel Dunbar49f0e802009-09-07 23:07:56 +00001293
Chris Lattner327984f2008-11-19 06:56:25 +00001294 OS.flush();
Bill Wendling37b1dde2007-06-07 09:34:54 +00001295}
Douglas Gregord0e9e3a2011-09-29 00:38:00 +00001296
1297DiagnosticConsumer *
1298TextDiagnosticPrinter::clone(DiagnosticsEngine &Diags) const {
1299 return new TextDiagnosticPrinter(OS, *DiagOpts, /*OwnsOutputStream=*/false);
1300}