blob: 8593e22f101f8c5859b17154450daab8fdc808c3 [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
Chandler Carruth153a7bb2011-08-31 23:59:19 +000056/// \brief Helper to recursivly walk up the include stack and print each layer
57/// on the way back down.
58static void PrintIncludeStackRecursively(raw_ostream &OS,
59 const SourceManager &SM,
60 SourceLocation Loc,
61 bool ShowLocation) {
62 if (Loc.isInvalid())
63 return;
Chris Lattnerdc5c0552007-07-20 16:37:10 +000064
Chris Lattnerf1ca7d32009-01-27 07:57:44 +000065 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregor453b0122010-11-12 07:15:47 +000066 if (PLoc.isInvalid())
67 return;
Chris Lattner92b29b2f2009-04-21 03:57:54 +000068
Chandler Carruth153a7bb2011-08-31 23:59:19 +000069 // Print out the other include frames first.
70 PrintIncludeStackRecursively(OS, SM, PLoc.getIncludeLoc(), ShowLocation);
71
72 if (ShowLocation)
Chris Lattner92b29b2f2009-04-21 03:57:54 +000073 OS << "In file included from " << PLoc.getFilename()
74 << ':' << PLoc.getLine() << ":\n";
75 else
76 OS << "In included file:\n";
Bill Wendling37b1dde2007-06-07 09:34:54 +000077}
78
Chandler Carruth153a7bb2011-08-31 23:59:19 +000079/// \brief Prints an include stack when appropriate for a particular diagnostic
80/// level and location.
81///
82/// This routine handles all the logic of suppressing particular include stacks
83/// (such as those for notes) and duplicate include stacks when repeated
84/// warnings occur within the same file. It also handles the logic of
85/// customizing the formatting and display of the include stack.
86///
87/// \param Level The diagnostic level of the message this stack pertains to.
88/// \param Loc The include location of the current file (not the diagnostic
89/// location).
David Blaikie9c902b52011-09-25 23:23:43 +000090void TextDiagnosticPrinter::PrintIncludeStack(DiagnosticsEngine::Level Level,
Chandler Carruth153a7bb2011-08-31 23:59:19 +000091 SourceLocation Loc,
92 const SourceManager &SM) {
93 // Skip redundant include stacks altogether.
Chandler Carruth3d262182011-10-15 11:44:27 +000094 if (LastNonNoteLoc == Loc)
Chandler Carruth153a7bb2011-08-31 23:59:19 +000095 return;
Chandler Carruth3d262182011-10-15 11:44:27 +000096 LastNonNoteLoc = FullSourceLoc(Loc, SM);
Chandler Carruth153a7bb2011-08-31 23:59:19 +000097
David Blaikie9c902b52011-09-25 23:23:43 +000098 if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
Chandler Carruth153a7bb2011-08-31 23:59:19 +000099 return;
100
101 PrintIncludeStackRecursively(OS, SM, Loc, DiagOpts->ShowLocation);
102}
103
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000104/// \brief When the source code line we want to print is too long for
105/// the terminal, select the "interesting" region.
106static void SelectInterestingSourceRegion(std::string &SourceLine,
107 std::string &CaretLine,
108 std::string &FixItInsertionLine,
Douglas Gregor2d69cd22009-05-04 06:27:32 +0000109 unsigned EndOfCaretToken,
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000110 unsigned Columns) {
Douglas Gregoraef00222010-04-16 00:23:51 +0000111 unsigned MaxSize = std::max(SourceLine.size(),
112 std::max(CaretLine.size(),
113 FixItInsertionLine.size()));
114 if (MaxSize > SourceLine.size())
115 SourceLine.resize(MaxSize, ' ');
116 if (MaxSize > CaretLine.size())
117 CaretLine.resize(MaxSize, ' ');
118 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
119 FixItInsertionLine.resize(MaxSize, ' ');
120
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000121 // Find the slice that we need to display the full caret line
122 // correctly.
123 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
124 for (; CaretStart != CaretEnd; ++CaretStart)
125 if (!isspace(CaretLine[CaretStart]))
126 break;
127
128 for (; CaretEnd != CaretStart; --CaretEnd)
129 if (!isspace(CaretLine[CaretEnd - 1]))
130 break;
Douglas Gregor2d69cd22009-05-04 06:27:32 +0000131
132 // Make sure we don't chop the string shorter than the caret token
133 // itself.
134 if (CaretEnd < EndOfCaretToken)
135 CaretEnd = EndOfCaretToken;
136
Douglas Gregorb8c6d5d2009-05-03 04:33:32 +0000137 // If we have a fix-it line, make sure the slice includes all of the
138 // fix-it information.
139 if (!FixItInsertionLine.empty()) {
140 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
141 for (; FixItStart != FixItEnd; ++FixItStart)
142 if (!isspace(FixItInsertionLine[FixItStart]))
143 break;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000144
Douglas Gregorb8c6d5d2009-05-03 04:33:32 +0000145 for (; FixItEnd != FixItStart; --FixItEnd)
146 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
147 break;
148
149 if (FixItStart < CaretStart)
150 CaretStart = FixItStart;
151 if (FixItEnd > CaretEnd)
152 CaretEnd = FixItEnd;
153 }
154
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000155 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
156 // parts of the caret line. While this slice is smaller than the
157 // number of columns we have, try to grow the slice to encompass
158 // more context.
159
160 // If the end of the interesting region comes before we run out of
161 // space in the terminal, start at the beginning of the line.
Douglas Gregor12c3a5c2009-05-15 18:05:24 +0000162 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000163 CaretStart = 0;
164
Douglas Gregor12c3a5c2009-05-15 18:05:24 +0000165 unsigned TargetColumns = Columns;
166 if (TargetColumns > 8)
167 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000168 unsigned SourceLength = SourceLine.size();
Douglas Gregor006fd382009-05-04 06:45:38 +0000169 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000170 bool ExpandedRegion = false;
171 // Move the start of the interesting region left until we've
172 // pulled in something else interesting.
Douglas Gregor006fd382009-05-04 06:45:38 +0000173 if (CaretStart == 1)
174 CaretStart = 0;
175 else if (CaretStart > 1) {
176 unsigned NewStart = CaretStart - 1;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000177
Douglas Gregor006fd382009-05-04 06:45:38 +0000178 // Skip over any whitespace we see here; we're looking for
179 // another bit of interesting text.
180 while (NewStart && isspace(SourceLine[NewStart]))
181 --NewStart;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000182
Douglas Gregor006fd382009-05-04 06:45:38 +0000183 // Skip over this bit of "interesting" text.
184 while (NewStart && !isspace(SourceLine[NewStart]))
185 --NewStart;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000186
Douglas Gregor006fd382009-05-04 06:45:38 +0000187 // Move up to the non-whitespace character we just saw.
188 if (NewStart)
189 ++NewStart;
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000190
191 // If we're still within our limit, update the starting
192 // position within the source/caret line.
Douglas Gregor006fd382009-05-04 06:45:38 +0000193 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000194 CaretStart = NewStart;
195 ExpandedRegion = true;
196 }
197 }
198
199 // Move the end of the interesting region right until we've
200 // pulled in something else interesting.
Daniel Dunbar6f949912009-05-03 23:04:40 +0000201 if (CaretEnd != SourceLength) {
Daniel Dunbar28a24fd2009-10-19 09:11:21 +0000202 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000203 unsigned NewEnd = CaretEnd;
204
205 // Skip over any whitespace we see here; we're looking for
206 // another bit of interesting text.
Douglas Gregor8e35e2d2009-05-18 22:09:16 +0000207 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000208 ++NewEnd;
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000209
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000210 // Skip over this bit of "interesting" text.
Douglas Gregor8e35e2d2009-05-18 22:09:16 +0000211 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000212 ++NewEnd;
213
214 if (NewEnd - CaretStart <= TargetColumns) {
215 CaretEnd = NewEnd;
216 ExpandedRegion = true;
217 }
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000218 }
Daniel Dunbar6f949912009-05-03 23:04:40 +0000219
220 if (!ExpandedRegion)
221 break;
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000222 }
223
224 // [CaretStart, CaretEnd) is the slice we want. Update the various
225 // output lines to show only this slice, with two-space padding
226 // before the lines so that it looks nicer.
Douglas Gregor54c6a3b2009-05-03 04:12:51 +0000227 if (CaretEnd < SourceLine.size())
228 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregorcb516622009-05-03 15:24:25 +0000229 if (CaretEnd < CaretLine.size())
230 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000231 if (FixItInsertionLine.size() > CaretEnd)
232 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbar49f0e802009-09-07 23:07:56 +0000233
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000234 if (CaretStart > 2) {
Douglas Gregor54c6a3b2009-05-03 04:12:51 +0000235 SourceLine.replace(0, CaretStart, " ...");
236 CaretLine.replace(0, CaretStart, " ");
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000237 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor54c6a3b2009-05-03 04:12:51 +0000238 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregorcf7b2af2009-05-01 23:32:58 +0000239 }
240}
241
Chandler Carruth64d376a2011-07-14 08:20:31 +0000242/// Look through spelling locations for a macro argument expansion, and
Chandler Carruth402bb382011-07-07 23:56:36 +0000243/// if found skip to it so that we can trace the argument rather than the macros
Chandler Carruth64d376a2011-07-14 08:20:31 +0000244/// in which that argument is used. If no macro argument expansion is found,
Chandler Carruth402bb382011-07-07 23:56:36 +0000245/// don't skip anything and return the starting location.
Chandler Carruth64d376a2011-07-14 08:20:31 +0000246static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
Chandler Carruth402bb382011-07-07 23:56:36 +0000247 SourceLocation StartLoc) {
248 for (SourceLocation L = StartLoc; L.isMacroID();
249 L = SM.getImmediateSpellingLoc(L)) {
Chandler Carruthaa631532011-07-26 03:03:00 +0000250 if (SM.isMacroArgExpansion(L))
Chandler Carruth402bb382011-07-07 23:56:36 +0000251 return L;
252 }
253
254 // Otherwise just return initial location, there's nothing to skip.
255 return StartLoc;
256}
257
258/// Gets the location of the immediate macro caller, one level up the stack
259/// toward the initial macro typed into the source.
260static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
261 SourceLocation Loc) {
262 if (!Loc.isMacroID()) return Loc;
263
264 // When we have the location of (part of) an expanded parameter, its spelling
265 // location points to the argument as typed into the macro call, and
266 // therefore is used to locate the macro caller.
Chandler Carruthaa631532011-07-26 03:03:00 +0000267 if (SM.isMacroArgExpansion(Loc))
Chandler Carruth402bb382011-07-07 23:56:36 +0000268 return SM.getImmediateSpellingLoc(Loc);
269
270 // Otherwise, the caller of the macro is located where this macro is
Chandler Carruth64d376a2011-07-14 08:20:31 +0000271 // expanded (while the spelling is part of the macro definition).
Chandler Carruthca757582011-07-25 20:52:21 +0000272 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruth402bb382011-07-07 23:56:36 +0000273}
274
275/// Gets the location of the immediate macro callee, one level down the stack
276/// toward the leaf macro.
277static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
278 SourceLocation Loc) {
279 if (!Loc.isMacroID()) return Loc;
280
281 // When we have the location of (part of) an expanded parameter, its
Chandler Carruth64d376a2011-07-14 08:20:31 +0000282 // expansion location points to the unexpanded paramater reference within
Chandler Carruth402bb382011-07-07 23:56:36 +0000283 // the macro definition (or callee).
Chandler Carruthaa631532011-07-26 03:03:00 +0000284 if (SM.isMacroArgExpansion(Loc))
Chandler Carruthca757582011-07-25 20:52:21 +0000285 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruth402bb382011-07-07 23:56:36 +0000286
287 // Otherwise, the callee of the macro is located where this location was
288 // spelled inside the macro definition.
289 return SM.getImmediateSpellingLoc(Loc);
290}
291
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000292/// Get the presumed location of a diagnostic message. This computes the
293/// presumed location for the top of any macro backtrace when present.
294static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
295 SourceLocation Loc) {
296 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
297 // walk to the top of the macro call stack.
298 while (Loc.isMacroID()) {
299 Loc = skipToMacroArgExpansion(SM, Loc);
300 Loc = getImmediateMacroCallerLoc(SM, Loc);
301 }
302
303 return SM.getPresumedLoc(Loc);
304}
305
306/// \brief Print the diagonstic level to a raw_ostream.
307///
308/// Handles colorizing the level and formatting.
309static void printDiagnosticLevel(raw_ostream &OS,
310 DiagnosticsEngine::Level Level,
311 bool ShowColors) {
312 if (ShowColors) {
313 // Print diagnostic category in bold and color
314 switch (Level) {
315 case DiagnosticsEngine::Ignored:
316 llvm_unreachable("Invalid diagnostic type");
317 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
318 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
319 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
320 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
321 }
322 }
323
324 switch (Level) {
325 case DiagnosticsEngine::Ignored: llvm_unreachable("Invalid diagnostic type");
326 case DiagnosticsEngine::Note: OS << "note: "; break;
327 case DiagnosticsEngine::Warning: OS << "warning: "; break;
328 case DiagnosticsEngine::Error: OS << "error: "; break;
329 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
330 }
331
332 if (ShowColors)
333 OS.resetColor();
334}
335
336/// \brief Skip over whitespace in the string, starting at the given
337/// index.
338///
339/// \returns The index of the first non-whitespace character that is
340/// greater than or equal to Idx or, if no such character exists,
341/// returns the end of the string.
342static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
343 while (Idx < Length && isspace(Str[Idx]))
344 ++Idx;
345 return Idx;
346}
347
348/// \brief If the given character is the start of some kind of
349/// balanced punctuation (e.g., quotes or parentheses), return the
350/// character that will terminate the punctuation.
351///
352/// \returns The ending punctuation character, if any, or the NULL
353/// character if the input character does not start any punctuation.
354static inline char findMatchingPunctuation(char c) {
355 switch (c) {
356 case '\'': return '\'';
357 case '`': return '\'';
358 case '"': return '"';
359 case '(': return ')';
360 case '[': return ']';
361 case '{': return '}';
362 default: break;
363 }
364
365 return 0;
366}
367
368/// \brief Find the end of the word starting at the given offset
369/// within a string.
370///
371/// \returns the index pointing one character past the end of the
372/// word.
373static unsigned findEndOfWord(unsigned Start, StringRef Str,
374 unsigned Length, unsigned Column,
375 unsigned Columns) {
376 assert(Start < Str.size() && "Invalid start position!");
377 unsigned End = Start + 1;
378
379 // If we are already at the end of the string, take that as the word.
380 if (End == Str.size())
381 return End;
382
383 // Determine if the start of the string is actually opening
384 // punctuation, e.g., a quote or parentheses.
385 char EndPunct = findMatchingPunctuation(Str[Start]);
386 if (!EndPunct) {
387 // This is a normal word. Just find the first space character.
388 while (End < Length && !isspace(Str[End]))
389 ++End;
390 return End;
391 }
392
393 // We have the start of a balanced punctuation sequence (quotes,
394 // parentheses, etc.). Determine the full sequence is.
395 llvm::SmallString<16> PunctuationEndStack;
396 PunctuationEndStack.push_back(EndPunct);
397 while (End < Length && !PunctuationEndStack.empty()) {
398 if (Str[End] == PunctuationEndStack.back())
399 PunctuationEndStack.pop_back();
400 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
401 PunctuationEndStack.push_back(SubEndPunct);
402
403 ++End;
404 }
405
406 // Find the first space character after the punctuation ended.
407 while (End < Length && !isspace(Str[End]))
408 ++End;
409
410 unsigned PunctWordLength = End - Start;
411 if (// If the word fits on this line
412 Column + PunctWordLength <= Columns ||
413 // ... or the word is "short enough" to take up the next line
414 // without too much ugly white space
415 PunctWordLength < Columns/3)
416 return End; // Take the whole thing as a single "word".
417
418 // The whole quoted/parenthesized string is too long to print as a
419 // single "word". Instead, find the "word" that starts just after
420 // the punctuation and use that end-point instead. This will recurse
421 // until it finds something small enough to consider a word.
422 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
423}
424
425/// \brief Print the given string to a stream, word-wrapping it to
426/// some number of columns in the process.
427///
428/// \param OS the stream to which the word-wrapping string will be
429/// emitted.
430/// \param Str the string to word-wrap and output.
431/// \param Columns the number of columns to word-wrap to.
432/// \param Column the column number at which the first character of \p
433/// Str will be printed. This will be non-zero when part of the first
434/// line has already been printed.
435/// \param Indentation the number of spaces to indent any lines beyond
436/// the first line.
437/// \returns true if word-wrapping was required, or false if the
438/// string fit on the first line.
439static bool printWordWrapped(raw_ostream &OS, StringRef Str,
440 unsigned Columns,
441 unsigned Column = 0,
442 unsigned Indentation = WordWrapIndentation) {
443 const unsigned Length = std::min(Str.find('\n'), Str.size());
444
445 // The string used to indent each line.
446 llvm::SmallString<16> IndentStr;
447 IndentStr.assign(Indentation, ' ');
448 bool Wrapped = false;
449 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
450 WordStart = WordEnd) {
451 // Find the beginning of the next word.
452 WordStart = skipWhitespace(WordStart, Str, Length);
453 if (WordStart == Length)
454 break;
455
456 // Find the end of this word.
457 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
458
459 // Does this word fit on the current line?
460 unsigned WordLength = WordEnd - WordStart;
461 if (Column + WordLength < Columns) {
462 // This word fits on the current line; print it there.
463 if (WordStart) {
464 OS << ' ';
465 Column += 1;
466 }
467 OS << Str.substr(WordStart, WordLength);
468 Column += WordLength;
469 continue;
470 }
471
472 // This word does not fit on the current line, so wrap to the next
473 // line.
474 OS << '\n';
475 OS.write(&IndentStr[0], Indentation);
476 OS << Str.substr(WordStart, WordLength);
477 Column = Indentation + WordLength;
478 Wrapped = true;
479 }
480
481 // Append any remaning text from the message with its existing formatting.
482 OS << Str.substr(Length);
483
484 return Wrapped;
485}
486
487static void printDiagnosticMessage(raw_ostream &OS,
488 DiagnosticsEngine::Level Level,
489 StringRef Message,
490 unsigned CurrentColumn, unsigned Columns,
491 bool ShowColors) {
492 if (ShowColors) {
493 // Print warnings, errors and fatal errors in bold, no color
494 switch (Level) {
495 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
496 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
497 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
498 default: break; //don't bold notes
499 }
500 }
501
502 if (Columns)
503 printWordWrapped(OS, Message, Columns, CurrentColumn);
504 else
505 OS << Message;
506
507 if (ShowColors)
508 OS.resetColor();
509 OS << '\n';
510}
511
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000512namespace {
513
Chandler Carruth84f36192011-09-25 22:54:56 +0000514/// \brief Class to encapsulate the logic for formatting and printing a textual
515/// diagnostic message.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000516///
Chandler Carruth84f36192011-09-25 22:54:56 +0000517/// This class provides an interface for building and emitting a textual
518/// diagnostic, including all of the macro backtraces, caret diagnostics, FixIt
519/// Hints, and code snippets. In the presence of macros this involves
520/// a recursive process, synthesizing notes for each macro expansion.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000521///
Chandler Carruth84f36192011-09-25 22:54:56 +0000522/// The purpose of this class is to isolate the implementation of printing
523/// beautiful text diagnostics from any particular interfaces. The Clang
524/// DiagnosticClient is implemented through this class as is diagnostic
525/// printing coming out of libclang.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000526///
Chandler Carruth84f36192011-09-25 22:54:56 +0000527/// A brief worklist:
528/// FIXME: Sink the printing of the diagnostic message itself into this class.
529/// FIXME: Sink the printing of the include stack into this class.
530/// FIXME: Remove the TextDiagnosticPrinter as an input.
531/// FIXME: Sink the recursive printing of template instantiations into this
532/// class.
533class TextDiagnostic {
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000534 TextDiagnosticPrinter &Printer;
535 raw_ostream &OS;
536 const SourceManager &SM;
537 const LangOptions &LangOpts;
538 const DiagnosticOptions &DiagOpts;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000539
Chandler Carruth3d262182011-10-15 11:44:27 +0000540 /// \brief The location of the previous diagnostic if known.
541 ///
542 /// This will be invalid in cases where there is no (known) previous
543 /// diagnostic location, or that location itself is invalid or comes from
544 /// a different source manager than SM.
545 SourceLocation LastLoc;
546
547 /// \brief The location of the previous non-note diagnostic if known.
548 ///
549 /// Same restriction as \see LastLoc but tracks the last non-note location.
550 SourceLocation LastNonNoteLoc;
551
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000552public:
Chandler Carruth84f36192011-09-25 22:54:56 +0000553 TextDiagnostic(TextDiagnosticPrinter &Printer,
Chandler Carruth3d262182011-10-15 11:44:27 +0000554 raw_ostream &OS,
555 const SourceManager &SM,
556 const LangOptions &LangOpts,
557 const DiagnosticOptions &DiagOpts,
558 FullSourceLoc LastLoc = FullSourceLoc(),
559 FullSourceLoc LastNonNoteLoc = FullSourceLoc())
560 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
561 LastLoc(LastLoc), LastNonNoteLoc(LastNonNoteLoc) {
562 if (LastLoc.isValid() && &SM != &LastLoc.getManager())
563 this->LastLoc = SourceLocation();
564 if (LastNonNoteLoc.isValid() && &SM != &LastNonNoteLoc.getManager())
565 this->LastNonNoteLoc = SourceLocation();
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000566 }
567
Chandler Carruth3d262182011-10-15 11:44:27 +0000568 /// \brief Get the last diagnostic location emitted.
569 SourceLocation getLastLoc() const { return LastLoc; }
570
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000571 void Emit(SourceLocation Loc, DiagnosticsEngine::Level Level,
572 StringRef Message, ArrayRef<CharSourceRange> Ranges,
573 ArrayRef<FixItHint> FixItHints,
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000574 bool LastCaretDiagnosticWasNote = false) {
575 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
576
577 // First, if this diagnostic is not in the main file, print out the
578 // "included from" lines.
579 Printer.PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
580
581 uint64_t StartOfLocationInfo = OS.tell();
582
583 // Next emit the location of this particular diagnostic.
Chandler Carruth99eb7dc2011-10-15 11:09:23 +0000584 EmitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000585
586 if (DiagOpts.ShowColors)
587 OS.resetColor();
588
589 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
590 printDiagnosticMessage(OS, Level, Message,
591 OS.tell() - StartOfLocationInfo,
592 DiagOpts.MessageLength, DiagOpts.ShowColors);
593
594 // If caret diagnostics are enabled and we have location, we want to
595 // emit the caret. However, we only do this if the location moved
596 // from the last diagnostic, if the last diagnostic was a note that
597 // was part of a different warning or error diagnostic, or if the
598 // diagnostic has ranges. We don't want to emit the same caret
599 // multiple times if one loc has multiple diagnostics.
600 if (DiagOpts.ShowCarets &&
601 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
602 (LastCaretDiagnosticWasNote && Level != DiagnosticsEngine::Note))) {
603 // Get the ranges into a local array we can hack on.
604 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
605 Ranges.end());
606
607 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
608 E = FixItHints.end();
609 I != E; ++I)
610 if (I->RemoveRange.isValid())
611 MutableRanges.push_back(I->RemoveRange);
612
613 unsigned MacroDepth = 0;
614 EmitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
615 }
Chandler Carruth3d262182011-10-15 11:44:27 +0000616
617 LastLoc = Loc;
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000618 }
619
Chandler Carruth09c74642011-10-15 01:21:55 +0000620 /// \brief Emit the caret and underlining text.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000621 ///
622 /// Walks up the macro expansion stack printing the code snippet, caret,
623 /// underlines and FixItHint display as appropriate at each level. Walk is
624 /// accomplished by calling itself recursively.
625 ///
Chandler Carruth09c74642011-10-15 01:21:55 +0000626 /// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
627 /// caret diagnostics.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000628 /// FIXME: Break up massive function into logical units.
629 ///
630 /// \param Loc The location for this caret.
631 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000632 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000633 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000634 /// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruth09c74642011-10-15 01:21:55 +0000635 void EmitCaret(SourceLocation Loc,
Chandler Carruth773757a2011-09-07 01:47:09 +0000636 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000637 ArrayRef<FixItHint> Hints,
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000638 unsigned &MacroDepth,
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000639 unsigned OnMacroInst = 0) {
640 assert(!Loc.isInvalid() && "must have a valid source location here");
641
Chandler Carruth9d229f32011-09-25 06:59:38 +0000642 // If this is a file source location, directly emit the source snippet and
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000643 // caret line. Also record the macro depth reached.
644 if (Loc.isFileID()) {
645 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
646 MacroDepth = OnMacroInst;
647 EmitSnippetAndCaret(Loc, Ranges, Hints);
648 return;
649 }
Chandler Carruth9d229f32011-09-25 06:59:38 +0000650 // Otherwise recurse through each macro expansion layer.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000651
Chandler Carruth9d229f32011-09-25 06:59:38 +0000652 // When processing macros, skip over the expansions leading up to
653 // a macro argument, and trace the argument's expansion stack instead.
654 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000655
Chandler Carruth9d229f32011-09-25 06:59:38 +0000656 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000657
Chandler Carruth9d229f32011-09-25 06:59:38 +0000658 // FIXME: Map ranges?
Chandler Carruth09c74642011-10-15 01:21:55 +0000659 EmitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000660
Chandler Carruth9d229f32011-09-25 06:59:38 +0000661 // Map the location.
662 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000663
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000664 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
665 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
666 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
667 DiagOpts.MacroBacktraceLimit % 2;
668 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
669 }
670
671 // Whether to suppress printing this macro expansion.
672 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
673 OnMacroInst < MacroSkipEnd);
674
Chandler Carruth9d229f32011-09-25 06:59:38 +0000675 // Map the ranges.
676 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
677 E = Ranges.end();
678 I != E; ++I) {
679 SourceLocation Start = I->getBegin(), End = I->getEnd();
680 if (Start.isMacroID())
681 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
682 if (End.isMacroID())
683 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
684 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000685
Chandler Carruth9d229f32011-09-25 06:59:38 +0000686 if (!Suppressed) {
687 // Don't print recursive expansion notes from an expansion note.
688 Loc = SM.getSpellingLoc(Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000689
Chandler Carruth9d229f32011-09-25 06:59:38 +0000690 // Get the pretty name, according to #line directives etc.
691 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
692 if (PLoc.isInvalid())
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000693 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000694
Chandler Carruth9d229f32011-09-25 06:59:38 +0000695 // If this diagnostic is not in the main file, print out the
696 // "included from" lines.
David Blaikie9c902b52011-09-25 23:23:43 +0000697 Printer.PrintIncludeStack(DiagnosticsEngine::Note, PLoc.getIncludeLoc(),
698 SM);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000699
Chandler Carruth9d229f32011-09-25 06:59:38 +0000700 if (DiagOpts.ShowLocation) {
701 // Emit the file/line/column that this expansion came from.
702 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
703 if (DiagOpts.ShowColumn)
704 OS << PLoc.getColumn() << ':';
705 OS << ' ';
706 }
707 OS << "note: expanded from:\n";
708
709 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000710 return;
711 }
712
Chandler Carruth9d229f32011-09-25 06:59:38 +0000713 if (OnMacroInst == MacroSkipStart) {
714 // Tell the user that we've skipped contexts.
715 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
716 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
717 "all)\n";
718 }
719 }
720
721 /// \brief Emit a code snippet and caret line.
722 ///
723 /// This routine emits a single line's code snippet and caret line..
724 ///
725 /// \param Loc The location for the caret.
726 /// \param Ranges The underlined ranges for this code snippet.
727 /// \param Hints The FixIt hints active for this diagnostic.
728 void EmitSnippetAndCaret(SourceLocation Loc,
729 SmallVectorImpl<CharSourceRange>& Ranges,
730 ArrayRef<FixItHint> Hints) {
731 assert(!Loc.isInvalid() && "must have a valid source location here");
732 assert(Loc.isFileID() && "must have a file location here");
733
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000734 // Decompose the location into a FID/Offset pair.
735 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
736 FileID FID = LocInfo.first;
737 unsigned FileOffset = LocInfo.second;
738
739 // Get information about the buffer it points into.
740 bool Invalid = false;
741 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
742 if (Invalid)
743 return;
744
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000745 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000746 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
747 unsigned CaretEndColNo
748 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
749
750 // Rewind from the current position to the start of the line.
751 const char *TokPtr = BufStart+FileOffset;
752 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
753
754
755 // Compute the line end. Scan forward from the error position to the end of
756 // the line.
757 const char *LineEnd = TokPtr;
758 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
759 ++LineEnd;
760
761 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
762 // the source line length as currently being computed. See
763 // test/Misc/message-length.c.
764 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
765
766 // Copy the line of code into an std::string for ease of manipulation.
767 std::string SourceLine(LineStart, LineEnd);
768
769 // Create a line for the caret that is filled with spaces that is the same
770 // length as the line of source code.
771 std::string CaretLine(LineEnd-LineStart, ' ');
772
773 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000774 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
775 E = Ranges.end();
776 I != E; ++I)
Chandler Carruth97798302011-09-07 07:02:31 +0000777 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000778
779 // Next, insert the caret itself.
780 if (ColNo-1 < CaretLine.size())
781 CaretLine[ColNo-1] = '^';
782 else
783 CaretLine.push_back('^');
784
Chandler Carruthe79ddf82011-09-07 05:36:50 +0000785 ExpandTabs(SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000786
787 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
788 // to produce easily machine parsable output. Add a space before the
789 // source line and the caret to make it trivial to tell the main diagnostic
790 // line from what the user is intended to see.
791 if (DiagOpts.ShowSourceRanges) {
792 SourceLine = ' ' + SourceLine;
793 CaretLine = ' ' + CaretLine;
794 }
795
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000796 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000797 LineStart, LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000798 Hints);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000799
800 // If the source line is too long for our terminal, select only the
801 // "interesting" source region within that line.
Chandler Carruth3236f0d2011-09-25 22:31:58 +0000802 unsigned Columns = DiagOpts.MessageLength;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000803 if (Columns && SourceLine.size() > Columns)
804 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
805 CaretEndColNo, Columns);
806
807 // Finally, remove any blank spaces from the end of CaretLine.
808 while (CaretLine[CaretLine.size()-1] == ' ')
809 CaretLine.erase(CaretLine.end()-1);
810
811 // Emit what we have computed.
812 OS << SourceLine << '\n';
813
814 if (DiagOpts.ShowColors)
815 OS.changeColor(caretColor, true);
816 OS << CaretLine << '\n';
817 if (DiagOpts.ShowColors)
818 OS.resetColor();
819
820 if (!FixItInsertionLine.empty()) {
821 if (DiagOpts.ShowColors)
822 // Print fixit line in color
823 OS.changeColor(fixitColor, false);
824 if (DiagOpts.ShowSourceRanges)
825 OS << ' ';
826 OS << FixItInsertionLine << '\n';
827 if (DiagOpts.ShowColors)
828 OS.resetColor();
829 }
830
Chandler Carruthd3e83672011-09-02 06:30:30 +0000831 // Print out any parseable fixit information requested by the options.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000832 EmitParseableFixits(Hints);
Chandler Carruthd3e83672011-09-02 06:30:30 +0000833 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000834
Chandler Carruthd3e83672011-09-02 06:30:30 +0000835private:
Chandler Carruth99eb7dc2011-10-15 11:09:23 +0000836 /// \brief Print out the file/line/column information and include trace.
837 ///
838 /// This method handlen the emission of the diagnostic location information.
839 /// This includes extracting as much location information as is present for
840 /// the diagnostic and printing it, as well as any include stack or source
841 /// ranges necessary.
842 void EmitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
843 DiagnosticsEngine::Level Level,
844 ArrayRef<CharSourceRange> Ranges) {
845 if (PLoc.isInvalid()) {
846 // At least print the file name if available:
847 FileID FID = SM.getFileID(Loc);
848 if (!FID.isInvalid()) {
849 const FileEntry* FE = SM.getFileEntryForID(FID);
850 if (FE && FE->getName()) {
851 OS << FE->getName();
852 if (FE->getDevice() == 0 && FE->getInode() == 0
853 && FE->getFileMode() == 0) {
854 // in PCH is a guess, but a good one:
855 OS << " (in PCH)";
856 }
857 OS << ": ";
858 }
859 }
860 return;
861 }
862 unsigned LineNo = PLoc.getLine();
863
864 if (!DiagOpts.ShowLocation)
865 return;
866
867 if (DiagOpts.ShowColors)
868 OS.changeColor(savedColor, true);
869
870 OS << PLoc.getFilename();
871 switch (DiagOpts.Format) {
872 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
873 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
874 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
875 }
876
877 if (DiagOpts.ShowColumn)
878 // Compute the column number.
879 if (unsigned ColNo = PLoc.getColumn()) {
880 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
881 OS << ',';
882 ColNo--;
883 } else
884 OS << ':';
885 OS << ColNo;
886 }
887 switch (DiagOpts.Format) {
888 case DiagnosticOptions::Clang:
889 case DiagnosticOptions::Vi: OS << ':'; break;
890 case DiagnosticOptions::Msvc: OS << ") : "; break;
891 }
892
893 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
894 FileID CaretFileID =
895 SM.getFileID(SM.getExpansionLoc(Loc));
896 bool PrintedRange = false;
897
898 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
899 RE = Ranges.end();
900 RI != RE; ++RI) {
901 // Ignore invalid ranges.
902 if (!RI->isValid()) continue;
903
904 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
905 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
906
907 // If the End location and the start location are the same and are a
908 // macro location, then the range was something that came from a
909 // macro expansion or _Pragma. If this is an object-like macro, the
910 // best we can do is to highlight the range. If this is a
911 // function-like macro, we'd also like to highlight the arguments.
912 if (B == E && RI->getEnd().isMacroID())
913 E = SM.getExpansionRange(RI->getEnd()).second;
914
915 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
916 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
917
918 // If the start or end of the range is in another file, just discard
919 // it.
920 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
921 continue;
922
923 // Add in the length of the token, so that we cover multi-char
924 // tokens.
925 unsigned TokSize = 0;
926 if (RI->isTokenRange())
927 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
928
929 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
930 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
931 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
932 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
933 << '}';
934 PrintedRange = true;
935 }
936
937 if (PrintedRange)
938 OS << ':';
939 }
940 OS << ' ';
941 }
942
Chandler Carruth97798302011-09-07 07:02:31 +0000943 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
944 void HighlightRange(const CharSourceRange &R,
945 unsigned LineNo, FileID FID,
946 const std::string &SourceLine,
947 std::string &CaretLine) {
948 assert(CaretLine.size() == SourceLine.size() &&
949 "Expect a correspondence between source and caret line!");
950 if (!R.isValid()) return;
951
952 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
953 SourceLocation End = SM.getExpansionLoc(R.getEnd());
954
955 // If the End location and the start location are the same and are a macro
956 // location, then the range was something that came from a macro expansion
957 // or _Pragma. If this is an object-like macro, the best we can do is to
958 // highlight the range. If this is a function-like macro, we'd also like to
959 // highlight the arguments.
960 if (Begin == End && R.getEnd().isMacroID())
961 End = SM.getExpansionRange(R.getEnd()).second;
962
963 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
964 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
965 return; // No intersection.
966
967 unsigned EndLineNo = SM.getExpansionLineNumber(End);
968 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
969 return; // No intersection.
970
971 // Compute the column number of the start.
972 unsigned StartColNo = 0;
973 if (StartLineNo == LineNo) {
974 StartColNo = SM.getExpansionColumnNumber(Begin);
975 if (StartColNo) --StartColNo; // Zero base the col #.
976 }
977
978 // Compute the column number of the end.
979 unsigned EndColNo = CaretLine.size();
980 if (EndLineNo == LineNo) {
981 EndColNo = SM.getExpansionColumnNumber(End);
982 if (EndColNo) {
983 --EndColNo; // Zero base the col #.
984
985 // Add in the length of the token, so that we cover multi-char tokens if
986 // this is a token range.
987 if (R.isTokenRange())
988 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
989 } else {
990 EndColNo = CaretLine.size();
991 }
992 }
993
994 assert(StartColNo <= EndColNo && "Invalid range!");
995
996 // Check that a token range does not highlight only whitespace.
997 if (R.isTokenRange()) {
998 // Pick the first non-whitespace column.
999 while (StartColNo < SourceLine.size() &&
1000 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
1001 ++StartColNo;
1002
1003 // Pick the last non-whitespace column.
1004 if (EndColNo > SourceLine.size())
1005 EndColNo = SourceLine.size();
1006 while (EndColNo-1 &&
1007 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
1008 --EndColNo;
1009
1010 // If the start/end passed each other, then we are trying to highlight a
1011 // range that just exists in whitespace, which must be some sort of other
1012 // bug.
1013 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1014 }
1015
1016 // Fill the range with ~'s.
1017 for (unsigned i = StartColNo; i < EndColNo; ++i)
1018 CaretLine[i] = '~';
1019 }
1020
Chandler Carruth0f1006a2011-09-07 05:01:10 +00001021 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001022 const char *LineStart,
1023 const char *LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001024 ArrayRef<FixItHint> Hints) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001025 std::string FixItInsertionLine;
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001026 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001027 return FixItInsertionLine;
1028
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001029 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1030 I != E; ++I) {
1031 if (!I->CodeToInsert.empty()) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001032 // We have an insertion hint. Determine whether the inserted
1033 // code is on the same line as the caret.
1034 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001035 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0f1006a2011-09-07 05:01:10 +00001036 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001037 // Insert the new code into the line just below the code
1038 // that the user wrote.
1039 unsigned HintColNo
1040 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
1041 unsigned LastColumnModified
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001042 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001043 if (LastColumnModified > FixItInsertionLine.size())
1044 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001045 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +00001046 FixItInsertionLine.begin() + HintColNo - 1);
1047 } else {
1048 FixItInsertionLine.clear();
1049 break;
1050 }
1051 }
1052 }
1053
1054 if (FixItInsertionLine.empty())
1055 return FixItInsertionLine;
1056
1057 // Now that we have the entire fixit line, expand the tabs in it.
1058 // Since we don't want to insert spaces in the middle of a word,
1059 // find each word and the column it should line up with and insert
1060 // spaces until they match.
1061 unsigned FixItPos = 0;
1062 unsigned LinePos = 0;
1063 unsigned TabExpandedCol = 0;
1064 unsigned LineLength = LineEnd - LineStart;
1065
1066 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
1067 // Find the next word in the FixIt line.
1068 while (FixItPos < FixItInsertionLine.size() &&
1069 FixItInsertionLine[FixItPos] == ' ')
1070 ++FixItPos;
1071 unsigned CharDistance = FixItPos - TabExpandedCol;
1072
1073 // Walk forward in the source line, keeping track of
1074 // the tab-expanded column.
1075 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
1076 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
1077 ++TabExpandedCol;
1078 else
1079 TabExpandedCol =
1080 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
1081
1082 // Adjust the fixit line to match this column.
1083 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
1084 FixItPos = TabExpandedCol;
1085
1086 // Walk to the end of the word.
1087 while (FixItPos < FixItInsertionLine.size() &&
1088 FixItInsertionLine[FixItPos] != ' ')
1089 ++FixItPos;
1090 }
1091
1092 return FixItInsertionLine;
1093 }
1094
Chandler Carruthe79ddf82011-09-07 05:36:50 +00001095 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
1096 // Scan the source line, looking for tabs. If we find any, manually expand
1097 // them to spaces and update the CaretLine to match.
1098 for (unsigned i = 0; i != SourceLine.size(); ++i) {
1099 if (SourceLine[i] != '\t') continue;
1100
1101 // Replace this tab with at least one space.
1102 SourceLine[i] = ' ';
1103
1104 // Compute the number of spaces we need to insert.
1105 unsigned TabStop = DiagOpts.TabStop;
1106 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1107 "Invalid -ftabstop value");
1108 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
1109 assert(NumSpaces < TabStop && "Invalid computation of space amt");
1110
1111 // Insert spaces into the SourceLine.
1112 SourceLine.insert(i+1, NumSpaces, ' ');
1113
1114 // Insert spaces or ~'s into CaretLine.
1115 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
1116 }
1117 }
1118
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001119 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthd3e83672011-09-02 06:30:30 +00001120 if (!DiagOpts.ShowParseableFixits)
1121 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001122
Chandler Carruthd3e83672011-09-02 06:30:30 +00001123 // We follow FixItRewriter's example in not (yet) handling
1124 // fix-its in macros.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001125 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1126 I != E; ++I) {
1127 if (I->RemoveRange.isInvalid() ||
1128 I->RemoveRange.getBegin().isMacroID() ||
1129 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthd3e83672011-09-02 06:30:30 +00001130 return;
1131 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001132
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001133 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1134 I != E; ++I) {
1135 SourceLocation BLoc = I->RemoveRange.getBegin();
1136 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001137
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001138 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1139 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001140
Chandler Carruthd3e83672011-09-02 06:30:30 +00001141 // Adjust for token ranges.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001142 if (I->RemoveRange.isTokenRange())
1143 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001144
Chandler Carruthd3e83672011-09-02 06:30:30 +00001145 // We specifically do not do word-wrapping or tab-expansion here,
1146 // because this is supposed to be easy to parse.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001147 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001148 if (PLoc.isInvalid())
1149 break;
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001150
Chandler Carruthd3e83672011-09-02 06:30:30 +00001151 OS << "fix-it:\"";
Chandler Carruth935574d2011-09-06 22:34:33 +00001152 OS.write_escaped(PLoc.getFilename());
Chandler Carruthd3e83672011-09-02 06:30:30 +00001153 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1154 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1155 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1156 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1157 << "}:\"";
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001158 OS.write_escaped(I->CodeToInsert);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001159 OS << "\"\n";
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001160 }
1161 }
1162};
1163
1164} // end namespace
1165
Chandler Carruthcf259a42011-09-26 01:30:09 +00001166/// \brief Print the diagnostic name to a raw_ostream.
1167///
1168/// This prints the diagnostic name to a raw_ostream if it has one. It formats
1169/// the name according to the expected diagnostic message formatting:
1170/// " [diagnostic_name_here]"
1171static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
Chandler Carruthb59f9cb92011-09-26 00:37:30 +00001172 if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
1173 OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
1174}
1175
Chandler Carruthcf259a42011-09-26 01:30:09 +00001176/// \brief Print any diagnostic option information to a raw_ostream.
1177///
1178/// This implements all of the logic for adding diagnostic options to a message
1179/// (via OS). Each relevant option is comma separated and all are enclosed in
1180/// the standard bracketing: " [...]".
1181static void printDiagnosticOptions(raw_ostream &OS,
Chandler Carruth60740842011-09-26 00:44:09 +00001182 DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001183 const Diagnostic &Info,
Chandler Carruth60740842011-09-26 00:44:09 +00001184 const DiagnosticOptions &DiagOpts) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001185 bool Started = false;
Chandler Carruth60740842011-09-26 00:44:09 +00001186 if (DiagOpts.ShowOptionNames) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001187 // Handle special cases for non-warnings early.
1188 if (Info.getID() == diag::fatal_too_many_errors) {
1189 OS << " [-ferror-limit=]";
1190 return;
1191 }
1192
Daniel Dunbaraa111382011-09-29 01:01:08 +00001193 // The code below is somewhat fragile because we are essentially trying to
1194 // report to the user what happened by inferring what the diagnostic engine
1195 // did. Eventually it might make more sense to have the diagnostic engine
1196 // include some "why" information in the diagnostic.
1197
1198 // If this is a warning which has been mapped to an error by the user (as
1199 // inferred by checking whether the default mapping is to an error) then
1200 // flag it as such. Note that diagnostics could also have been mapped by a
1201 // pragma, but we don't currently have a way to distinguish this.
Chandler Carruth60740842011-09-26 00:44:09 +00001202 if (Level == DiagnosticsEngine::Error &&
Daniel Dunbaraa111382011-09-29 01:01:08 +00001203 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID()) &&
1204 !DiagnosticIDs::isDefaultMappingAsError(Info.getID())) {
1205 OS << " [-Werror";
1206 Started = true;
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001207 }
1208
1209 // If the diagnostic is an extension diagnostic and not enabled by default
1210 // then it must have been turned on with -pedantic.
1211 bool EnabledByDefault;
1212 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1213 EnabledByDefault) &&
1214 !EnabledByDefault) {
1215 OS << (Started ? "," : " [") << "-pedantic";
1216 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001217 }
1218
1219 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
1220 if (!Opt.empty()) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001221 OS << (Started ? "," : " [") << "-W" << Opt;
1222 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001223 }
1224 }
Chandler Carruth60740842011-09-26 00:44:09 +00001225
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001226 // If the user wants to see category information, include it too.
1227 if (DiagOpts.ShowCategories) {
1228 unsigned DiagCategory =
1229 DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Chandler Carruth60740842011-09-26 00:44:09 +00001230 if (DiagCategory) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001231 OS << (Started ? "," : " [");
Benjamin Kramere2125d82011-09-26 02:14:13 +00001232 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001233 if (DiagOpts.ShowCategories == 1)
Benjamin Kramere2125d82011-09-26 02:14:13 +00001234 OS << DiagCategory;
Chandler Carruth60740842011-09-26 00:44:09 +00001235 else {
1236 assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
1237 OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
1238 }
1239 }
Chandler Carruth60740842011-09-26 00:44:09 +00001240 }
Benjamin Kramere2125d82011-09-26 02:14:13 +00001241 if (Started)
1242 OS << ']';
Chandler Carruth60740842011-09-26 00:44:09 +00001243}
1244
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001245void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001246 const Diagnostic &Info) {
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001247 // Default implementation (Warnings/errors count).
1248 DiagnosticConsumer::HandleDiagnostic(Level, Info);
1249
Chandler Carruth2be992d2011-09-26 11:25:30 +00001250 // Render the diagnostic message into a temporary buffer eagerly. We'll use
1251 // this later as we print out the diagnostic to the terminal.
1252 llvm::SmallString<100> OutStr;
1253 Info.FormatDiagnostic(OutStr);
1254
1255 llvm::raw_svector_ostream DiagMessageStream(OutStr);
1256 if (DiagOpts->ShowNames)
1257 printDiagnosticName(DiagMessageStream, Info);
1258 printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
1259
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001260 // Keeps track of the the starting position of the location
1261 // information (e.g., "foo.c:10:4:") that precedes the error
1262 // message. We use this information to determine how long the
1263 // file+line+column number prefix is.
1264 uint64_t StartOfLocationInfo = OS.tell();
1265
1266 if (!Prefix.empty())
1267 OS << Prefix << ": ";
1268
Chandler Carruth2be992d2011-09-26 11:25:30 +00001269 // Use a dedicated, simpler path for diagnostics without a valid location.
Chandler Carruth577372e2011-09-26 11:38:46 +00001270 // This is important as if the location is missing, we may be emitting
1271 // diagnostics in a context that lacks language options, a source manager, or
1272 // other infrastructure necessary when emitting more rich diagnostics.
Chandler Carruth2be992d2011-09-26 11:25:30 +00001273 if (!Info.getLocation().isValid()) {
1274 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
1275 printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1276 OS.tell() - StartOfLocationInfo,
1277 DiagOpts->MessageLength, DiagOpts->ShowColors);
1278 OS.flush();
1279 return;
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001280 }
1281
Chandler Carruth577372e2011-09-26 11:38:46 +00001282 // Assert that the rest of our infrastructure is setup properly.
1283 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1284 assert(DiagOpts && "Unexpected diagnostic without options set");
1285 assert(Info.hasSourceManager() &&
1286 "Unexpected diagnostic with no source manager");
Chandler Carruth2be992d2011-09-26 11:25:30 +00001287 const SourceManager &SM = Info.getSourceManager();
Chandler Carruth3d262182011-10-15 11:44:27 +00001288 TextDiagnostic TextDiag(*this, OS, SM, *LangOpts, *DiagOpts,
1289 LastNonNoteLoc, LastLoc);
Chandler Carruth577372e2011-09-26 11:38:46 +00001290
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001291 TextDiag.Emit(Info.getLocation(), Level, DiagMessageStream.str(),
1292 Info.getRanges(),
1293 llvm::makeArrayRef(Info.getFixItHints(),
1294 Info.getNumFixItHints()),
Chandler Carruth3d262182011-10-15 11:44:27 +00001295 LastCaretDiagnosticWasNote);
Chandler Carruth2be992d2011-09-26 11:25:30 +00001296
Chandler Carruth3d262182011-10-15 11:44:27 +00001297 // Cache the LastLoc from the TextDiagnostic printing.
1298 LastLoc = FullSourceLoc(TextDiag.getLastLoc(), SM);
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001299 LastCaretDiagnosticWasNote = (Level == DiagnosticsEngine::Note);
Daniel Dunbar49f0e802009-09-07 23:07:56 +00001300
Chris Lattner327984f2008-11-19 06:56:25 +00001301 OS.flush();
Bill Wendling37b1dde2007-06-07 09:34:54 +00001302}
Douglas Gregord0e9e3a2011-09-29 00:38:00 +00001303
1304DiagnosticConsumer *
1305TextDiagnosticPrinter::clone(DiagnosticsEngine &Diags) const {
1306 return new TextDiagnosticPrinter(OS, *DiagOpts, /*OwnsOutputStream=*/false);
1307}