blob: 1716471cd14717e6a74d8a3a920a84644a0981b8 [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:
480/// FIXME: Sink the printing of the diagnostic message itself into this class.
481/// FIXME: Sink the printing of the include stack into this class.
482/// FIXME: Remove the TextDiagnosticPrinter as an input.
483/// FIXME: Sink the recursive printing of template instantiations into this
484/// class.
485class TextDiagnostic {
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000486 TextDiagnosticPrinter &Printer;
487 raw_ostream &OS;
488 const SourceManager &SM;
489 const LangOptions &LangOpts;
490 const DiagnosticOptions &DiagOpts;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000491
Chandler Carruth3d262182011-10-15 11:44:27 +0000492 /// \brief The location of the previous diagnostic if known.
493 ///
494 /// This will be invalid in cases where there is no (known) previous
495 /// diagnostic location, or that location itself is invalid or comes from
496 /// a different source manager than SM.
497 SourceLocation LastLoc;
498
499 /// \brief The location of the previous non-note diagnostic if known.
500 ///
501 /// Same restriction as \see LastLoc but tracks the last non-note location.
502 SourceLocation LastNonNoteLoc;
503
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000504public:
Chandler Carruth84f36192011-09-25 22:54:56 +0000505 TextDiagnostic(TextDiagnosticPrinter &Printer,
Chandler Carruth3d262182011-10-15 11:44:27 +0000506 raw_ostream &OS,
507 const SourceManager &SM,
508 const LangOptions &LangOpts,
509 const DiagnosticOptions &DiagOpts,
510 FullSourceLoc LastLoc = FullSourceLoc(),
511 FullSourceLoc LastNonNoteLoc = FullSourceLoc())
512 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
513 LastLoc(LastLoc), LastNonNoteLoc(LastNonNoteLoc) {
514 if (LastLoc.isValid() && &SM != &LastLoc.getManager())
515 this->LastLoc = SourceLocation();
516 if (LastNonNoteLoc.isValid() && &SM != &LastNonNoteLoc.getManager())
517 this->LastNonNoteLoc = SourceLocation();
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000518 }
519
Chandler Carruth3d262182011-10-15 11:44:27 +0000520 /// \brief Get the last diagnostic location emitted.
521 SourceLocation getLastLoc() const { return LastLoc; }
522
Chandler Carruth636b2502011-10-15 12:07:47 +0000523 /// \brief Get the last non-note diagnostic location emitted.
524 SourceLocation getLastNonNoteLoc() const { return LastNonNoteLoc; }
525
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000526 void Emit(SourceLocation Loc, DiagnosticsEngine::Level Level,
527 StringRef Message, ArrayRef<CharSourceRange> Ranges,
528 ArrayRef<FixItHint> FixItHints,
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000529 bool LastCaretDiagnosticWasNote = false) {
530 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
531
532 // First, if this diagnostic is not in the main file, print out the
533 // "included from" lines.
Chandler Carruth636b2502011-10-15 12:07:47 +0000534 emitIncludeStack(PLoc.getIncludeLoc(), Level);
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000535
536 uint64_t StartOfLocationInfo = OS.tell();
537
538 // Next emit the location of this particular diagnostic.
Chandler Carruth99eb7dc2011-10-15 11:09:23 +0000539 EmitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000540
541 if (DiagOpts.ShowColors)
542 OS.resetColor();
543
544 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
545 printDiagnosticMessage(OS, Level, Message,
546 OS.tell() - StartOfLocationInfo,
547 DiagOpts.MessageLength, DiagOpts.ShowColors);
548
549 // If caret diagnostics are enabled and we have location, we want to
550 // emit the caret. However, we only do this if the location moved
551 // from the last diagnostic, if the last diagnostic was a note that
552 // was part of a different warning or error diagnostic, or if the
553 // diagnostic has ranges. We don't want to emit the same caret
554 // multiple times if one loc has multiple diagnostics.
555 if (DiagOpts.ShowCarets &&
556 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
557 (LastCaretDiagnosticWasNote && Level != DiagnosticsEngine::Note))) {
558 // Get the ranges into a local array we can hack on.
559 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
560 Ranges.end());
561
562 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
563 E = FixItHints.end();
564 I != E; ++I)
565 if (I->RemoveRange.isValid())
566 MutableRanges.push_back(I->RemoveRange);
567
568 unsigned MacroDepth = 0;
569 EmitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
570 }
Chandler Carruth3d262182011-10-15 11:44:27 +0000571
572 LastLoc = Loc;
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000573 }
574
Chandler Carruth09c74642011-10-15 01:21:55 +0000575 /// \brief Emit the caret and underlining text.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000576 ///
577 /// Walks up the macro expansion stack printing the code snippet, caret,
578 /// underlines and FixItHint display as appropriate at each level. Walk is
579 /// accomplished by calling itself recursively.
580 ///
Chandler Carruth09c74642011-10-15 01:21:55 +0000581 /// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
582 /// caret diagnostics.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000583 /// FIXME: Break up massive function into logical units.
584 ///
585 /// \param Loc The location for this caret.
586 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000587 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000588 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000589 /// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruth09c74642011-10-15 01:21:55 +0000590 void EmitCaret(SourceLocation Loc,
Chandler Carruth773757a2011-09-07 01:47:09 +0000591 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000592 ArrayRef<FixItHint> Hints,
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000593 unsigned &MacroDepth,
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000594 unsigned OnMacroInst = 0) {
595 assert(!Loc.isInvalid() && "must have a valid source location here");
596
Chandler Carruth9d229f32011-09-25 06:59:38 +0000597 // If this is a file source location, directly emit the source snippet and
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000598 // caret line. Also record the macro depth reached.
599 if (Loc.isFileID()) {
600 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
601 MacroDepth = OnMacroInst;
602 EmitSnippetAndCaret(Loc, Ranges, Hints);
603 return;
604 }
Chandler Carruth9d229f32011-09-25 06:59:38 +0000605 // Otherwise recurse through each macro expansion layer.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000606
Chandler Carruth9d229f32011-09-25 06:59:38 +0000607 // When processing macros, skip over the expansions leading up to
608 // a macro argument, and trace the argument's expansion stack instead.
609 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000610
Chandler Carruth9d229f32011-09-25 06:59:38 +0000611 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000612
Chandler Carruth9d229f32011-09-25 06:59:38 +0000613 // FIXME: Map ranges?
Chandler Carruth09c74642011-10-15 01:21:55 +0000614 EmitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000615
Chandler Carruth9d229f32011-09-25 06:59:38 +0000616 // Map the location.
617 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000618
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000619 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
620 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
621 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
622 DiagOpts.MacroBacktraceLimit % 2;
623 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
624 }
625
626 // Whether to suppress printing this macro expansion.
627 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
628 OnMacroInst < MacroSkipEnd);
629
Chandler Carruth9d229f32011-09-25 06:59:38 +0000630 // Map the ranges.
631 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
632 E = Ranges.end();
633 I != E; ++I) {
634 SourceLocation Start = I->getBegin(), End = I->getEnd();
635 if (Start.isMacroID())
636 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
637 if (End.isMacroID())
638 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
639 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000640
Chandler Carruth9d229f32011-09-25 06:59:38 +0000641 if (!Suppressed) {
642 // Don't print recursive expansion notes from an expansion note.
643 Loc = SM.getSpellingLoc(Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000644
Chandler Carruth9d229f32011-09-25 06:59:38 +0000645 // Get the pretty name, according to #line directives etc.
646 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
647 if (PLoc.isInvalid())
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000648 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000649
Chandler Carruth9d229f32011-09-25 06:59:38 +0000650 // If this diagnostic is not in the main file, print out the
651 // "included from" lines.
Chandler Carruth636b2502011-10-15 12:07:47 +0000652 emitIncludeStack(PLoc.getIncludeLoc(), DiagnosticsEngine::Note);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000653
Chandler Carruth9d229f32011-09-25 06:59:38 +0000654 if (DiagOpts.ShowLocation) {
655 // Emit the file/line/column that this expansion came from.
656 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
657 if (DiagOpts.ShowColumn)
658 OS << PLoc.getColumn() << ':';
659 OS << ' ';
660 }
661 OS << "note: expanded from:\n";
662
663 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000664 return;
665 }
666
Chandler Carruth9d229f32011-09-25 06:59:38 +0000667 if (OnMacroInst == MacroSkipStart) {
668 // Tell the user that we've skipped contexts.
669 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
670 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
671 "all)\n";
672 }
673 }
674
675 /// \brief Emit a code snippet and caret line.
676 ///
677 /// This routine emits a single line's code snippet and caret line..
678 ///
679 /// \param Loc The location for the caret.
680 /// \param Ranges The underlined ranges for this code snippet.
681 /// \param Hints The FixIt hints active for this diagnostic.
682 void EmitSnippetAndCaret(SourceLocation Loc,
683 SmallVectorImpl<CharSourceRange>& Ranges,
684 ArrayRef<FixItHint> Hints) {
685 assert(!Loc.isInvalid() && "must have a valid source location here");
686 assert(Loc.isFileID() && "must have a file location here");
687
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000688 // Decompose the location into a FID/Offset pair.
689 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
690 FileID FID = LocInfo.first;
691 unsigned FileOffset = LocInfo.second;
692
693 // Get information about the buffer it points into.
694 bool Invalid = false;
695 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
696 if (Invalid)
697 return;
698
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000699 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000700 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
701 unsigned CaretEndColNo
702 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
703
704 // Rewind from the current position to the start of the line.
705 const char *TokPtr = BufStart+FileOffset;
706 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
707
708
709 // Compute the line end. Scan forward from the error position to the end of
710 // the line.
711 const char *LineEnd = TokPtr;
712 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
713 ++LineEnd;
714
715 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
716 // the source line length as currently being computed. See
717 // test/Misc/message-length.c.
718 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
719
720 // Copy the line of code into an std::string for ease of manipulation.
721 std::string SourceLine(LineStart, LineEnd);
722
723 // Create a line for the caret that is filled with spaces that is the same
724 // length as the line of source code.
725 std::string CaretLine(LineEnd-LineStart, ' ');
726
727 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000728 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
729 E = Ranges.end();
730 I != E; ++I)
Chandler Carruth97798302011-09-07 07:02:31 +0000731 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000732
733 // Next, insert the caret itself.
734 if (ColNo-1 < CaretLine.size())
735 CaretLine[ColNo-1] = '^';
736 else
737 CaretLine.push_back('^');
738
Chandler Carruthe79ddf82011-09-07 05:36:50 +0000739 ExpandTabs(SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000740
741 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
742 // to produce easily machine parsable output. Add a space before the
743 // source line and the caret to make it trivial to tell the main diagnostic
744 // line from what the user is intended to see.
745 if (DiagOpts.ShowSourceRanges) {
746 SourceLine = ' ' + SourceLine;
747 CaretLine = ' ' + CaretLine;
748 }
749
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000750 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000751 LineStart, LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000752 Hints);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000753
754 // If the source line is too long for our terminal, select only the
755 // "interesting" source region within that line.
Chandler Carruth3236f0d2011-09-25 22:31:58 +0000756 unsigned Columns = DiagOpts.MessageLength;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000757 if (Columns && SourceLine.size() > Columns)
758 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
759 CaretEndColNo, Columns);
760
761 // Finally, remove any blank spaces from the end of CaretLine.
762 while (CaretLine[CaretLine.size()-1] == ' ')
763 CaretLine.erase(CaretLine.end()-1);
764
765 // Emit what we have computed.
766 OS << SourceLine << '\n';
767
768 if (DiagOpts.ShowColors)
769 OS.changeColor(caretColor, true);
770 OS << CaretLine << '\n';
771 if (DiagOpts.ShowColors)
772 OS.resetColor();
773
774 if (!FixItInsertionLine.empty()) {
775 if (DiagOpts.ShowColors)
776 // Print fixit line in color
777 OS.changeColor(fixitColor, false);
778 if (DiagOpts.ShowSourceRanges)
779 OS << ' ';
780 OS << FixItInsertionLine << '\n';
781 if (DiagOpts.ShowColors)
782 OS.resetColor();
783 }
784
Chandler Carruthd3e83672011-09-02 06:30:30 +0000785 // Print out any parseable fixit information requested by the options.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000786 EmitParseableFixits(Hints);
Chandler Carruthd3e83672011-09-02 06:30:30 +0000787 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000788
Chandler Carruthd3e83672011-09-02 06:30:30 +0000789private:
Chandler Carruth636b2502011-10-15 12:07:47 +0000790 /// \brief Prints an include stack when appropriate for a particular
791 /// diagnostic level and location.
792 ///
793 /// This routine handles all the logic of suppressing particular include
794 /// stacks (such as those for notes) and duplicate include stacks when
795 /// repeated warnings occur within the same file. It also handles the logic
796 /// of customizing the formatting and display of the include stack.
797 ///
798 /// \param Level The diagnostic level of the message this stack pertains to.
799 /// \param Loc The include location of the current file (not the diagnostic
800 /// location).
801 void emitIncludeStack(SourceLocation Loc, DiagnosticsEngine::Level Level) {
802 // Skip redundant include stacks altogether.
803 if (LastNonNoteLoc == Loc)
804 return;
805 LastNonNoteLoc = Loc;
806
807 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
808 return;
809
810 emitIncludeStackRecursively(Loc);
811 }
812
813 /// \brief Helper to recursivly walk up the include stack and print each layer
814 /// on the way back down.
815 void emitIncludeStackRecursively(SourceLocation Loc) {
816 if (Loc.isInvalid())
817 return;
818
819 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
820 if (PLoc.isInvalid())
821 return;
822
823 // Emit the other include frames first.
824 emitIncludeStackRecursively(PLoc.getIncludeLoc());
825
826 if (DiagOpts.ShowLocation)
827 OS << "In file included from " << PLoc.getFilename()
828 << ':' << PLoc.getLine() << ":\n";
829 else
830 OS << "In included file:\n";
831 }
832
Chandler Carruth99eb7dc2011-10-15 11:09:23 +0000833 /// \brief Print out the file/line/column information and include trace.
834 ///
835 /// This method handlen the emission of the diagnostic location information.
836 /// This includes extracting as much location information as is present for
837 /// the diagnostic and printing it, as well as any include stack or source
838 /// ranges necessary.
839 void EmitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
840 DiagnosticsEngine::Level Level,
841 ArrayRef<CharSourceRange> Ranges) {
842 if (PLoc.isInvalid()) {
843 // At least print the file name if available:
844 FileID FID = SM.getFileID(Loc);
845 if (!FID.isInvalid()) {
846 const FileEntry* FE = SM.getFileEntryForID(FID);
847 if (FE && FE->getName()) {
848 OS << FE->getName();
849 if (FE->getDevice() == 0 && FE->getInode() == 0
850 && FE->getFileMode() == 0) {
851 // in PCH is a guess, but a good one:
852 OS << " (in PCH)";
853 }
854 OS << ": ";
855 }
856 }
857 return;
858 }
859 unsigned LineNo = PLoc.getLine();
860
861 if (!DiagOpts.ShowLocation)
862 return;
863
864 if (DiagOpts.ShowColors)
865 OS.changeColor(savedColor, true);
866
867 OS << PLoc.getFilename();
868 switch (DiagOpts.Format) {
869 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
870 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
871 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
872 }
873
874 if (DiagOpts.ShowColumn)
875 // Compute the column number.
876 if (unsigned ColNo = PLoc.getColumn()) {
877 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
878 OS << ',';
879 ColNo--;
880 } else
881 OS << ':';
882 OS << ColNo;
883 }
884 switch (DiagOpts.Format) {
885 case DiagnosticOptions::Clang:
886 case DiagnosticOptions::Vi: OS << ':'; break;
887 case DiagnosticOptions::Msvc: OS << ") : "; break;
888 }
889
890 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
891 FileID CaretFileID =
892 SM.getFileID(SM.getExpansionLoc(Loc));
893 bool PrintedRange = false;
894
895 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
896 RE = Ranges.end();
897 RI != RE; ++RI) {
898 // Ignore invalid ranges.
899 if (!RI->isValid()) continue;
900
901 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
902 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
903
904 // If the End location and the start location are the same and are a
905 // macro location, then the range was something that came from a
906 // macro expansion or _Pragma. If this is an object-like macro, the
907 // best we can do is to highlight the range. If this is a
908 // function-like macro, we'd also like to highlight the arguments.
909 if (B == E && RI->getEnd().isMacroID())
910 E = SM.getExpansionRange(RI->getEnd()).second;
911
912 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
913 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
914
915 // If the start or end of the range is in another file, just discard
916 // it.
917 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
918 continue;
919
920 // Add in the length of the token, so that we cover multi-char
921 // tokens.
922 unsigned TokSize = 0;
923 if (RI->isTokenRange())
924 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
925
926 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
927 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
928 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
929 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
930 << '}';
931 PrintedRange = true;
932 }
933
934 if (PrintedRange)
935 OS << ':';
936 }
937 OS << ' ';
938 }
939
Chandler Carruth97798302011-09-07 07:02:31 +0000940 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
941 void HighlightRange(const CharSourceRange &R,
942 unsigned LineNo, FileID FID,
943 const std::string &SourceLine,
944 std::string &CaretLine) {
945 assert(CaretLine.size() == SourceLine.size() &&
946 "Expect a correspondence between source and caret line!");
947 if (!R.isValid()) return;
948
949 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
950 SourceLocation End = SM.getExpansionLoc(R.getEnd());
951
952 // If the End location and the start location are the same and are a macro
953 // location, then the range was something that came from a macro expansion
954 // or _Pragma. If this is an object-like macro, the best we can do is to
955 // highlight the range. If this is a function-like macro, we'd also like to
956 // highlight the arguments.
957 if (Begin == End && R.getEnd().isMacroID())
958 End = SM.getExpansionRange(R.getEnd()).second;
959
960 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
961 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
962 return; // No intersection.
963
964 unsigned EndLineNo = SM.getExpansionLineNumber(End);
965 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
966 return; // No intersection.
967
968 // Compute the column number of the start.
969 unsigned StartColNo = 0;
970 if (StartLineNo == LineNo) {
971 StartColNo = SM.getExpansionColumnNumber(Begin);
972 if (StartColNo) --StartColNo; // Zero base the col #.
973 }
974
975 // Compute the column number of the end.
976 unsigned EndColNo = CaretLine.size();
977 if (EndLineNo == LineNo) {
978 EndColNo = SM.getExpansionColumnNumber(End);
979 if (EndColNo) {
980 --EndColNo; // Zero base the col #.
981
982 // Add in the length of the token, so that we cover multi-char tokens if
983 // this is a token range.
984 if (R.isTokenRange())
985 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
986 } else {
987 EndColNo = CaretLine.size();
988 }
989 }
990
991 assert(StartColNo <= EndColNo && "Invalid range!");
992
993 // Check that a token range does not highlight only whitespace.
994 if (R.isTokenRange()) {
995 // Pick the first non-whitespace column.
996 while (StartColNo < SourceLine.size() &&
997 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
998 ++StartColNo;
999
1000 // Pick the last non-whitespace column.
1001 if (EndColNo > SourceLine.size())
1002 EndColNo = SourceLine.size();
1003 while (EndColNo-1 &&
1004 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
1005 --EndColNo;
1006
1007 // If the start/end passed each other, then we are trying to highlight a
1008 // range that just exists in whitespace, which must be some sort of other
1009 // bug.
1010 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1011 }
1012
1013 // Fill the range with ~'s.
1014 for (unsigned i = StartColNo; i < EndColNo; ++i)
1015 CaretLine[i] = '~';
1016 }
1017
Chandler Carruth0f1006a2011-09-07 05:01:10 +00001018 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001019 const char *LineStart,
1020 const char *LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001021 ArrayRef<FixItHint> Hints) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001022 std::string FixItInsertionLine;
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001023 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001024 return FixItInsertionLine;
1025
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001026 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1027 I != E; ++I) {
1028 if (!I->CodeToInsert.empty()) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001029 // We have an insertion hint. Determine whether the inserted
1030 // code is on the same line as the caret.
1031 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001032 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0f1006a2011-09-07 05:01:10 +00001033 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001034 // Insert the new code into the line just below the code
1035 // that the user wrote.
1036 unsigned HintColNo
1037 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
1038 unsigned LastColumnModified
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001039 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001040 if (LastColumnModified > FixItInsertionLine.size())
1041 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001042 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001043 FixItInsertionLine.begin() + HintColNo - 1);
1044 } else {
1045 FixItInsertionLine.clear();
1046 break;
1047 }
1048 }
1049 }
1050
1051 if (FixItInsertionLine.empty())
1052 return FixItInsertionLine;
1053
1054 // Now that we have the entire fixit line, expand the tabs in it.
1055 // Since we don't want to insert spaces in the middle of a word,
1056 // find each word and the column it should line up with and insert
1057 // spaces until they match.
1058 unsigned FixItPos = 0;
1059 unsigned LinePos = 0;
1060 unsigned TabExpandedCol = 0;
1061 unsigned LineLength = LineEnd - LineStart;
1062
1063 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
1064 // Find the next word in the FixIt line.
1065 while (FixItPos < FixItInsertionLine.size() &&
1066 FixItInsertionLine[FixItPos] == ' ')
1067 ++FixItPos;
1068 unsigned CharDistance = FixItPos - TabExpandedCol;
1069
1070 // Walk forward in the source line, keeping track of
1071 // the tab-expanded column.
1072 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
1073 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
1074 ++TabExpandedCol;
1075 else
1076 TabExpandedCol =
1077 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
1078
1079 // Adjust the fixit line to match this column.
1080 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
1081 FixItPos = TabExpandedCol;
1082
1083 // Walk to the end of the word.
1084 while (FixItPos < FixItInsertionLine.size() &&
1085 FixItInsertionLine[FixItPos] != ' ')
1086 ++FixItPos;
1087 }
1088
1089 return FixItInsertionLine;
1090 }
1091
Chandler Carruthe79ddf82011-09-07 05:36:50 +00001092 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
1093 // Scan the source line, looking for tabs. If we find any, manually expand
1094 // them to spaces and update the CaretLine to match.
1095 for (unsigned i = 0; i != SourceLine.size(); ++i) {
1096 if (SourceLine[i] != '\t') continue;
1097
1098 // Replace this tab with at least one space.
1099 SourceLine[i] = ' ';
1100
1101 // Compute the number of spaces we need to insert.
1102 unsigned TabStop = DiagOpts.TabStop;
1103 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1104 "Invalid -ftabstop value");
1105 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
1106 assert(NumSpaces < TabStop && "Invalid computation of space amt");
1107
1108 // Insert spaces into the SourceLine.
1109 SourceLine.insert(i+1, NumSpaces, ' ');
1110
1111 // Insert spaces or ~'s into CaretLine.
1112 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
1113 }
1114 }
1115
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001116 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthd3e83672011-09-02 06:30:30 +00001117 if (!DiagOpts.ShowParseableFixits)
1118 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001119
Chandler Carruthd3e83672011-09-02 06:30:30 +00001120 // We follow FixItRewriter's example in not (yet) handling
1121 // fix-its in macros.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001122 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1123 I != E; ++I) {
1124 if (I->RemoveRange.isInvalid() ||
1125 I->RemoveRange.getBegin().isMacroID() ||
1126 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthd3e83672011-09-02 06:30:30 +00001127 return;
1128 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001129
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001130 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1131 I != E; ++I) {
1132 SourceLocation BLoc = I->RemoveRange.getBegin();
1133 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001134
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001135 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1136 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001137
Chandler Carruthd3e83672011-09-02 06:30:30 +00001138 // Adjust for token ranges.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001139 if (I->RemoveRange.isTokenRange())
1140 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001141
Chandler Carruthd3e83672011-09-02 06:30:30 +00001142 // We specifically do not do word-wrapping or tab-expansion here,
1143 // because this is supposed to be easy to parse.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001144 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001145 if (PLoc.isInvalid())
1146 break;
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001147
Chandler Carruthd3e83672011-09-02 06:30:30 +00001148 OS << "fix-it:\"";
Chandler Carruth935574d2011-09-06 22:34:33 +00001149 OS.write_escaped(PLoc.getFilename());
Chandler Carruthd3e83672011-09-02 06:30:30 +00001150 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1151 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1152 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1153 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1154 << "}:\"";
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001155 OS.write_escaped(I->CodeToInsert);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001156 OS << "\"\n";
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001157 }
1158 }
1159};
1160
1161} // end namespace
1162
Chandler Carruthcf259a42011-09-26 01:30:09 +00001163/// \brief Print the diagnostic name to a raw_ostream.
1164///
1165/// This prints the diagnostic name to a raw_ostream if it has one. It formats
1166/// the name according to the expected diagnostic message formatting:
1167/// " [diagnostic_name_here]"
1168static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
Chandler Carruthb59f9cb92011-09-26 00:37:30 +00001169 if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
1170 OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
1171}
1172
Chandler Carruthcf259a42011-09-26 01:30:09 +00001173/// \brief Print any diagnostic option information to a raw_ostream.
1174///
1175/// This implements all of the logic for adding diagnostic options to a message
1176/// (via OS). Each relevant option is comma separated and all are enclosed in
1177/// the standard bracketing: " [...]".
1178static void printDiagnosticOptions(raw_ostream &OS,
Chandler Carruth60740842011-09-26 00:44:09 +00001179 DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001180 const Diagnostic &Info,
Chandler Carruth60740842011-09-26 00:44:09 +00001181 const DiagnosticOptions &DiagOpts) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001182 bool Started = false;
Chandler Carruth60740842011-09-26 00:44:09 +00001183 if (DiagOpts.ShowOptionNames) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001184 // Handle special cases for non-warnings early.
1185 if (Info.getID() == diag::fatal_too_many_errors) {
1186 OS << " [-ferror-limit=]";
1187 return;
1188 }
1189
Daniel Dunbaraa111382011-09-29 01:01:08 +00001190 // The code below is somewhat fragile because we are essentially trying to
1191 // report to the user what happened by inferring what the diagnostic engine
1192 // did. Eventually it might make more sense to have the diagnostic engine
1193 // include some "why" information in the diagnostic.
1194
1195 // If this is a warning which has been mapped to an error by the user (as
1196 // inferred by checking whether the default mapping is to an error) then
1197 // flag it as such. Note that diagnostics could also have been mapped by a
1198 // pragma, but we don't currently have a way to distinguish this.
Chandler Carruth60740842011-09-26 00:44:09 +00001199 if (Level == DiagnosticsEngine::Error &&
Daniel Dunbaraa111382011-09-29 01:01:08 +00001200 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID()) &&
1201 !DiagnosticIDs::isDefaultMappingAsError(Info.getID())) {
1202 OS << " [-Werror";
1203 Started = true;
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001204 }
1205
1206 // If the diagnostic is an extension diagnostic and not enabled by default
1207 // then it must have been turned on with -pedantic.
1208 bool EnabledByDefault;
1209 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1210 EnabledByDefault) &&
1211 !EnabledByDefault) {
1212 OS << (Started ? "," : " [") << "-pedantic";
1213 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001214 }
1215
1216 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
1217 if (!Opt.empty()) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001218 OS << (Started ? "," : " [") << "-W" << Opt;
1219 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001220 }
1221 }
Chandler Carruth60740842011-09-26 00:44:09 +00001222
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001223 // If the user wants to see category information, include it too.
1224 if (DiagOpts.ShowCategories) {
1225 unsigned DiagCategory =
1226 DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Chandler Carruth60740842011-09-26 00:44:09 +00001227 if (DiagCategory) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001228 OS << (Started ? "," : " [");
Benjamin Kramere2125d82011-09-26 02:14:13 +00001229 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001230 if (DiagOpts.ShowCategories == 1)
Benjamin Kramere2125d82011-09-26 02:14:13 +00001231 OS << DiagCategory;
Chandler Carruth60740842011-09-26 00:44:09 +00001232 else {
1233 assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
1234 OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
1235 }
1236 }
Chandler Carruth60740842011-09-26 00:44:09 +00001237 }
Benjamin Kramere2125d82011-09-26 02:14:13 +00001238 if (Started)
1239 OS << ']';
Chandler Carruth60740842011-09-26 00:44:09 +00001240}
1241
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001242void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001243 const Diagnostic &Info) {
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001244 // Default implementation (Warnings/errors count).
1245 DiagnosticConsumer::HandleDiagnostic(Level, Info);
1246
Chandler Carruth2be992d2011-09-26 11:25:30 +00001247 // Render the diagnostic message into a temporary buffer eagerly. We'll use
1248 // this later as we print out the diagnostic to the terminal.
1249 llvm::SmallString<100> OutStr;
1250 Info.FormatDiagnostic(OutStr);
1251
1252 llvm::raw_svector_ostream DiagMessageStream(OutStr);
1253 if (DiagOpts->ShowNames)
1254 printDiagnosticName(DiagMessageStream, Info);
1255 printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
1256
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001257 // Keeps track of the the starting position of the location
1258 // information (e.g., "foo.c:10:4:") that precedes the error
1259 // message. We use this information to determine how long the
1260 // file+line+column number prefix is.
1261 uint64_t StartOfLocationInfo = OS.tell();
1262
1263 if (!Prefix.empty())
1264 OS << Prefix << ": ";
1265
Chandler Carruth2be992d2011-09-26 11:25:30 +00001266 // Use a dedicated, simpler path for diagnostics without a valid location.
Chandler Carruth577372e2011-09-26 11:38:46 +00001267 // This is important as if the location is missing, we may be emitting
1268 // diagnostics in a context that lacks language options, a source manager, or
1269 // other infrastructure necessary when emitting more rich diagnostics.
Chandler Carruth2be992d2011-09-26 11:25:30 +00001270 if (!Info.getLocation().isValid()) {
1271 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
1272 printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1273 OS.tell() - StartOfLocationInfo,
1274 DiagOpts->MessageLength, DiagOpts->ShowColors);
1275 OS.flush();
1276 return;
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001277 }
1278
Chandler Carruth577372e2011-09-26 11:38:46 +00001279 // Assert that the rest of our infrastructure is setup properly.
1280 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1281 assert(DiagOpts && "Unexpected diagnostic without options set");
1282 assert(Info.hasSourceManager() &&
1283 "Unexpected diagnostic with no source manager");
Chandler Carruth2be992d2011-09-26 11:25:30 +00001284 const SourceManager &SM = Info.getSourceManager();
Chandler Carruth3d262182011-10-15 11:44:27 +00001285 TextDiagnostic TextDiag(*this, OS, SM, *LangOpts, *DiagOpts,
Chandler Carruth636b2502011-10-15 12:07:47 +00001286 LastLoc, LastNonNoteLoc);
Chandler Carruth577372e2011-09-26 11:38:46 +00001287
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001288 TextDiag.Emit(Info.getLocation(), Level, DiagMessageStream.str(),
1289 Info.getRanges(),
1290 llvm::makeArrayRef(Info.getFixItHints(),
1291 Info.getNumFixItHints()),
Chandler Carruth3d262182011-10-15 11:44:27 +00001292 LastCaretDiagnosticWasNote);
Chandler Carruth2be992d2011-09-26 11:25:30 +00001293
Chandler Carruth3d262182011-10-15 11:44:27 +00001294 // Cache the LastLoc from the TextDiagnostic printing.
1295 LastLoc = FullSourceLoc(TextDiag.getLastLoc(), SM);
Chandler Carruth636b2502011-10-15 12:07:47 +00001296 LastNonNoteLoc = FullSourceLoc(TextDiag.getLastNonNoteLoc(), SM);
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001297 LastCaretDiagnosticWasNote = (Level == DiagnosticsEngine::Note);
Daniel Dunbar49f0e802009-09-07 23:07:56 +00001298
Chris Lattner327984f2008-11-19 06:56:25 +00001299 OS.flush();
Bill Wendling37b1dde2007-06-07 09:34:54 +00001300}
Douglas Gregord0e9e3a2011-09-29 00:38:00 +00001301
1302DiagnosticConsumer *
1303TextDiagnosticPrinter::clone(DiagnosticsEngine &Diags) const {
1304 return new TextDiagnosticPrinter(OS, *DiagOpts, /*OwnsOutputStream=*/false);
1305}